blob: e427be3174bff83aaf75fc2c44ecca6ba3633dea [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 Stinner3f36a572013-11-12 21:39:02 +010040_Py_IDENTIFIER(flush);
Victor Stinnerbd303c12013-11-07 23:07:29 +010041_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010042_Py_IDENTIFIER(last_type);
43_Py_IDENTIFIER(last_value);
Victor Stinner3f36a572013-11-12 21:39:02 +010044_Py_IDENTIFIER(name);
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(ps1);
46_Py_IDENTIFIER(ps2);
47_Py_IDENTIFIER(stdin);
48_Py_IDENTIFIER(stdout);
49_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010050_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010051
Ezio Melotti1f8898a2013-03-26 01:59:56 +020052#ifdef Py_REF_DEBUG
Antoine Pitrou208ac5c2013-04-24 20:17:53 +020053static
54void _print_total_refs(void) {
Victor Stinner4ee41c52013-11-06 18:28:21 +010055 PyObject *xoptions, *value;
56 _Py_IDENTIFIER(showrefcount);
57
Ezio Melotti1f8898a2013-03-26 01:59:56 +020058 xoptions = PySys_GetXOptions();
59 if (xoptions == NULL)
60 return;
Victor Stinner4ee41c52013-11-06 18:28:21 +010061 value = _PyDict_GetItemId(xoptions, &PyId_showrefcount);
Ezio Melotti1f8898a2013-03-26 01:59:56 +020062 if (value == Py_True)
63 fprintf(stderr,
64 "[%" PY_FORMAT_SIZE_T "d refs, "
65 "%" PY_FORMAT_SIZE_T "d blocks]\n",
66 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
67}
68#endif
69
Neal Norwitz4281cef2006-03-04 19:58:13 +000070#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000071#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000072#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020073#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000074#endif
75
76#ifdef __cplusplus
77extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000078#endif
79
Martin v. Löwis790465f2008-04-05 20:41:37 +000080extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000081
Guido van Rossum82598051997-03-05 00:20:32 +000082extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000083
Guido van Rossumb73cc041993-11-01 16:28:59 +000084/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100085static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020086static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000087static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000088static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000089static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010090static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000092static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000094static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020095static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000096static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000097static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000098static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000099static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +0200100extern int _PyUnicode_Init(void);
Victor Stinner26f91992013-07-17 01:22:45 +0200101extern int _PyStructSequence_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000102extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000103extern int _PyLong_Init(void);
104extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +0200105extern int _PyFaulthandler_Init(void);
106extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +0000107
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000108#ifdef WITH_THREAD
109extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
110extern void _PyGILState_Fini(void);
111#endif /* WITH_THREAD */
112
Guido van Rossum82598051997-03-05 00:20:32 +0000113int Py_DebugFlag; /* Needed by parser.c */
114int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000115int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000116int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200117int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000118int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000119int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000120int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000121int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000122int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000123int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000124int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000125int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100126int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200127int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000128
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200129PyThreadState *_Py_Finalizing = NULL;
130
Christian Heimes49e61802013-10-22 10:22:29 +0200131/* Hack to force loading of object files */
132int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
133 PyOS_mystrnicmp; /* Python/pystrcmp.o */
134
Christian Heimes33fe8092008-04-13 13:53:33 +0000135/* PyModule_GetWarningsModule is no longer necessary as of 2.6
136since _warnings is builtin. This API should not be used. */
137PyObject *
138PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000141}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000142
Guido van Rossum25ce5661997-08-02 03:10:38 +0000143static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000144
Thomas Wouters7e474022000-07-16 12:04:32 +0000145/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000146
147int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000148Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000151}
152
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000153/* Helper to allow an embedding application to override the normal
154 * mechanism that attempts to figure out an appropriate IO encoding
155 */
156
157static char *_Py_StandardStreamEncoding = NULL;
158static char *_Py_StandardStreamErrors = NULL;
159
160int
161Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
162{
163 if (Py_IsInitialized()) {
164 /* This is too late to have any effect */
165 return -1;
166 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000167 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
168 * initialised yet.
169 *
170 * However, the raw memory allocators are initialised appropriately
171 * as C static variables, so _PyMem_RawStrdup is OK even though
172 * Py_Initialize hasn't been called yet.
173 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000174 if (encoding) {
175 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
176 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000177 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000178 }
179 }
180 if (errors) {
181 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
182 if (!_Py_StandardStreamErrors) {
183 if (_Py_StandardStreamEncoding) {
184 PyMem_RawFree(_Py_StandardStreamEncoding);
185 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000186 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000187 }
188 }
189 return 0;
190}
191
Guido van Rossum25ce5661997-08-02 03:10:38 +0000192/* Global initializations. Can be undone by Py_Finalize(). Don't
193 call this twice without an intervening Py_Finalize() call. When
194 initializations fail, a fatal error is issued and the function does
195 not return. On return, the first thread and interpreter state have
196 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000197
Guido van Rossum25ce5661997-08-02 03:10:38 +0000198 Locking: you must hold the interpreter lock while calling this.
199 (If the lock has not yet been initialized, that's equivalent to
200 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000201
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000203
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000204static int
205add_flag(int flag, const char *envs)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 int env = atoi(envs);
208 if (flag < env)
209 flag = env;
210 if (flag < 1)
211 flag = 1;
212 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000213}
214
Christian Heimes5833a2f2008-10-30 21:40:04 +0000215static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000216get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000217{
Victor Stinner94908bb2010-08-18 21:23:25 +0000218 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000219 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000220
Victor Stinner94908bb2010-08-18 21:23:25 +0000221 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 if (!codec)
223 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000224
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200225 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_CLEAR(codec);
227 if (!name)
228 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000229
Victor Stinner94908bb2010-08-18 21:23:25 +0000230 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100231 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000232 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200233 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000235 if (name_str == NULL) {
236 PyErr_NoMemory();
237 return NULL;
238 }
239 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000240
241error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000243 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000245}
Victor Stinner94908bb2010-08-18 21:23:25 +0000246
Victor Stinner94908bb2010-08-18 21:23:25 +0000247static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200248get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000249{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200250#ifdef MS_WINDOWS
251 char codepage[100];
252 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
253 return get_codec_name(codepage);
254#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000255 char* codeset = nl_langinfo(CODESET);
256 if (!codeset || codeset[0] == '\0') {
257 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
258 return NULL;
259 }
260 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200261#else
262 PyErr_SetNone(PyExc_NotImplementedError);
263 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000264#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200265}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000266
Brett Cannonfd074152012-04-14 14:10:13 -0400267static void
268import_init(PyInterpreterState *interp, PyObject *sysmod)
269{
270 PyObject *importlib;
271 PyObject *impmod;
272 PyObject *sys_modules;
273 PyObject *value;
274
275 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400276 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
277 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
278 }
279 else if (Py_VerboseFlag) {
280 PySys_FormatStderr("import _frozen_importlib # frozen\n");
281 }
282 importlib = PyImport_AddModule("_frozen_importlib");
283 if (importlib == NULL) {
284 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
285 "sys.modules");
286 }
287 interp->importlib = importlib;
288 Py_INCREF(interp->importlib);
289
290 /* Install _importlib as __import__ */
291 impmod = PyInit_imp();
292 if (impmod == NULL) {
293 Py_FatalError("Py_Initialize: can't import imp");
294 }
295 else if (Py_VerboseFlag) {
296 PySys_FormatStderr("import imp # builtin\n");
297 }
298 sys_modules = PyImport_GetModuleDict();
299 if (Py_VerboseFlag) {
300 PySys_FormatStderr("import sys # builtin\n");
301 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400302 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
303 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400304 }
305
Brett Cannone0d88a12012-04-25 20:54:04 -0400306 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400307 if (value == NULL) {
308 PyErr_Print();
309 Py_FatalError("Py_Initialize: importlib install failed");
310 }
311 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400312 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400313
314 _PyImportZip_Init();
315}
316
317
Guido van Rossuma027efa1997-05-05 20:56:21 +0000318void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200319_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 PyInterpreterState *interp;
322 PyThreadState *tstate;
323 PyObject *bimod, *sysmod, *pstderr;
324 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 if (initialized)
328 return;
329 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200330 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000331
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000332#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 /* Set up the LC_CTYPE locale, so we can obtain
334 the locale's charset without having to switch
335 locales. */
336 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000337#endif
338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
340 Py_DebugFlag = add_flag(Py_DebugFlag, p);
341 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
342 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
343 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
344 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
345 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
346 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100347 /* The variable is only tested for existence here; _PyRandom_Init will
348 check its value further. */
349 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
350 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
351
352 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 interp = PyInterpreterState_New();
355 if (interp == NULL)
356 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 tstate = PyThreadState_New(interp);
359 if (tstate == NULL)
360 Py_FatalError("Py_Initialize: can't make first thread");
361 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000362
Victor Stinner6961bd62010-08-17 22:26:51 +0000363#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000364 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
365 destroying the GIL might fail when it is being referenced from
366 another running thread (see issue #9901).
367 Instead we destroy the previously created GIL here, which ensures
368 that we can call Py_Initialize / Py_Finalize multiple times. */
369 _PyEval_FiniThreads();
370
371 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000372 _PyGILState_Init(interp, tstate);
373#endif /* WITH_THREAD */
374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 if (!_PyFrame_Init())
378 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 if (!_PyLong_Init())
381 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 if (!PyByteArray_Init())
384 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000385
Victor Stinner1c8f0592013-07-22 22:24:54 +0200386 if (!_PyFloat_Init())
387 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 interp->modules = PyDict_New();
390 if (interp->modules == NULL)
391 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200394 if (_PyUnicode_Init() < 0)
395 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200396 if (_PyStructSequence_Init() < 0)
397 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 bimod = _PyBuiltin_Init();
400 if (bimod == NULL)
401 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000402 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 interp->builtins = PyModule_GetDict(bimod);
404 if (interp->builtins == NULL)
405 Py_FatalError("Py_Initialize: can't initialize builtins dict");
406 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400409 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 sysmod = _PySys_Init();
412 if (sysmod == NULL)
413 Py_FatalError("Py_Initialize: can't initialize sys");
414 interp->sysdict = PyModule_GetDict(sysmod);
415 if (interp->sysdict == NULL)
416 Py_FatalError("Py_Initialize: can't initialize sys dict");
417 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000418 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 PySys_SetPath(Py_GetPath());
420 PyDict_SetItemString(interp->sysdict, "modules",
421 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* Set up a preliminary stderr printer until we have enough
424 infrastructure for the io module in place. */
425 pstderr = PyFile_NewStdPrinter(fileno(stderr));
426 if (pstderr == NULL)
427 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100428 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000430 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000435
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000436 /* Initialize _warnings. */
437 _PyWarnings_Init();
438
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200439 if (!install_importlib)
440 return;
441
Brett Cannonfd074152012-04-14 14:10:13 -0400442 import_init(interp, sysmod);
443
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200444 /* initialize the faulthandler module */
445 if (_PyFaulthandler_Init())
446 Py_FatalError("Py_Initialize: can't initialize faulthandler");
447
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000448 _PyTime_Init();
449
Victor Stinner793b5312011-04-27 00:24:21 +0200450 if (initfsencoding(interp) < 0)
451 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (install_sigs)
454 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000455
Nick Coghlan85e729e2012-07-15 18:09:52 +1000456 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 if (initstdio() < 0)
458 Py_FatalError(
459 "Py_Initialize: can't initialize sys standard streams");
460
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000461 /* Initialize warnings. */
462 if (PySys_HasWarnOptions()) {
463 PyObject *warnings_module = PyImport_ImportModule("warnings");
464 if (warnings_module == NULL) {
465 fprintf(stderr, "'import warnings' failed; traceback:\n");
466 PyErr_Print();
467 }
468 Py_XDECREF(warnings_module);
469 }
470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (!Py_NoSiteFlag)
472 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000473}
474
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000475void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200476Py_InitializeEx(int install_sigs)
477{
478 _Py_InitializeEx_Private(install_sigs, 1);
479}
480
481void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000482Py_Initialize(void)
483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000485}
486
487
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000488#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000489extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000490#endif
491
Guido van Rossume8432ac2007-07-09 15:04:50 +0000492/* Flush stdout and stderr */
493
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100494static int
495file_is_closed(PyObject *fobj)
496{
497 int r;
498 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
499 if (tmp == NULL) {
500 PyErr_Clear();
501 return 0;
502 }
503 r = PyObject_IsTrue(tmp);
504 Py_DECREF(tmp);
505 if (r < 0)
506 PyErr_Clear();
507 return r > 0;
508}
509
Neal Norwitz2bad9702007-08-27 06:19:22 +0000510static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000511flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000512{
Victor Stinnerbd303c12013-11-07 23:07:29 +0100513 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
514 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyObject *tmp;
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
Victor Stinner45956b92013-11-12 16:37:55 +0100579 /* Destroy the state of all threads except of the current thread: in
580 practice, only daemon threads should still be alive. Clear frames of
581 other threads to call objects destructor. Destructors will be called in
582 the current Python thread. Since _Py_Finalizing has been set, no other
583 Python threads can lock the GIL at this point (if they try, they will
Victor Stinnerdcf17f82013-11-12 17:18:51 +0100584 exit immediately). */
Victor Stinner45956b92013-11-12 16:37:55 +0100585 _PyThreadState_DeleteExcept(tstate);
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 /* Collect garbage. This may call finalizers; it's nice to call these
588 * before all modules are destroyed.
589 * XXX If a __del__ or weakref callback is triggered here, and tries to
590 * XXX import a module, bad things can happen, because Python no
591 * XXX longer believes it's initialized.
592 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
593 * XXX is easy to provoke that way. I've also seen, e.g.,
594 * XXX Exception exceptions.ImportError: 'No module named sha'
595 * XXX in <function callback at 0x008F5718> ignored
596 * XXX but I'm unclear on exactly how that one happens. In any case,
597 * XXX I haven't seen a real-life report of either of these.
598 */
599 PyGC_Collect();
Victor Stinner45956b92013-11-12 16:37:55 +0100600
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 /* With COUNT_ALLOCS, it helps to run GC multiple times:
603 each collection might release some types from the type
604 list, so they become garbage. */
605 while (PyGC_Collect() > 0)
606 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000607#endif
Victor Stinner45956b92013-11-12 16:37:55 +0100608
609 /* Flush stdout+stderr */
610 flush_std_files();
611
612 /* Disable signal handling */
613 PyOS_FiniInterrupts();
614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 /* Destroy all modules */
616 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 /* Flush stdout+stderr (again, in case more was printed) */
619 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100622 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 * XXX This is disabled because it caused too many problems. If
624 * XXX a __del__ or weakref callback triggers here, Python code has
625 * XXX a hard time running, because even the sys module has been
626 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
627 * XXX One symptom is a sequence of information-free messages
628 * XXX coming from threads (if a __del__ or callback is invoked,
629 * XXX other threads can execute too, and any exception they encounter
630 * XXX triggers a comedy of errors as subsystem after subsystem
631 * XXX fails to find what it *expects* to find in sys to help report
632 * XXX the exception and consequent unexpected failures). I've also
633 * XXX seen segfaults then, after adding print statements to the
634 * XXX Python code getting called.
635 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000636#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000638#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
641 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000642
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200643 /* Cleanup typeobject.c's internal caches. */
644 _PyType_Fini();
645
Victor Stinner024e37a2011-03-31 01:31:06 +0200646 /* unload faulthandler module */
647 _PyFaulthandler_Fini();
648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000650#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000652#endif
653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000655
Tim Peters9cf25ce2003-04-17 15:21:01 +0000656#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* Display all objects still alive -- this can invoke arbitrary
658 * __repr__ overrides, so requires a mostly-intact interpreter.
659 * Alas, a lot of stuff may still be alive now that will be cleaned
660 * up later.
661 */
662 if (Py_GETENV("PYTHONDUMPREFS"))
663 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000664#endif /* Py_TRACE_REFS */
665
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200666 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 /* Now we decref the exception classes. After this point nothing
670 can raise an exception. That's okay, because each Fini() method
671 below has been checked to make sure no exceptions are ever
672 raised.
673 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 /* Sundry finalizers */
678 PyMethod_Fini();
679 PyFrame_Fini();
680 PyCFunction_Fini();
681 PyTuple_Fini();
682 PyList_Fini();
683 PySet_Fini();
684 PyBytes_Fini();
685 PyByteArray_Fini();
686 PyLong_Fini();
687 PyFloat_Fini();
688 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100689 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200690 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200691 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 /* Cleanup Unicode implementation */
694 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000697 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200698 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 Py_FileSystemDefaultEncoding = NULL;
700 }
Christian Heimesc8967002007-11-30 10:18:26 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 /* XXX Still allocated:
703 - various static ad-hoc pointers to interned strings
704 - int and float free list blocks
705 - whatever various modules and libraries allocate
706 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000709
Victor Stinner51fa4582013-07-07 15:50:49 +0200710 /* Cleanup auto-thread-state */
711#ifdef WITH_THREAD
712 _PyGILState_Fini();
713#endif /* WITH_THREAD */
714
715 /* Delete current thread. After this, many C API calls become crashy. */
716 PyThreadState_Swap(NULL);
717 PyInterpreterState_Delete(interp);
718
Tim Peters269b2a62003-04-17 19:52:29 +0000719#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 /* Display addresses (& refcnts) of all objects still alive.
721 * An address can be used to find the repr of the object, printed
722 * above by _Py_PrintReferences.
723 */
724 if (Py_GETENV("PYTHONDUMPREFS"))
725 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000726#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000727#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400729 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000730#endif
731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000733}
734
735/* Create and initialize a new interpreter and thread, and return the
736 new thread. This requires that Py_Initialize() has been called
737 first.
738
739 Unsuccessful initialization yields a NULL pointer. Note that *no*
740 exception information is available even in this case -- the
741 exception information is held in the thread, and there is no
742 thread.
743
744 Locking: as above.
745
746*/
747
748PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000749Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyInterpreterState *interp;
752 PyThreadState *tstate, *save_tstate;
753 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (!initialized)
756 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 interp = PyInterpreterState_New();
759 if (interp == NULL)
760 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 tstate = PyThreadState_New(interp);
763 if (tstate == NULL) {
764 PyInterpreterState_Delete(interp);
765 return NULL;
766 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000773
Victor Stinner49d3f252010-10-17 01:24:53 +0000774 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 if (bimod != NULL) {
776 interp->builtins = PyModule_GetDict(bimod);
777 if (interp->builtins == NULL)
778 goto handle_error;
779 Py_INCREF(interp->builtins);
780 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400783 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000784
Victor Stinner49d3f252010-10-17 01:24:53 +0000785 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (bimod != NULL && sysmod != NULL) {
787 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 interp->sysdict = PyModule_GetDict(sysmod);
790 if (interp->sysdict == NULL)
791 goto handle_error;
792 Py_INCREF(interp->sysdict);
793 PySys_SetPath(Py_GetPath());
794 PyDict_SetItemString(interp->sysdict, "modules",
795 interp->modules);
796 /* Set up a preliminary stderr printer until we have enough
797 infrastructure for the io module in place. */
798 pstderr = PyFile_NewStdPrinter(fileno(stderr));
799 if (pstderr == NULL)
800 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100801 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000803 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200806
Brett Cannonfd074152012-04-14 14:10:13 -0400807 import_init(interp, sysmod);
808
Victor Stinner793b5312011-04-27 00:24:21 +0200809 if (initfsencoding(interp) < 0)
810 goto handle_error;
811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (initstdio() < 0)
813 Py_FatalError(
814 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000815 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (!Py_NoSiteFlag)
817 initsite();
818 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (!PyErr_Occurred())
821 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000822
Thomas Wouters89f507f2006-12-13 04:49:30 +0000823handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000825
Victor Stinnerc40a3502011-04-27 00:20:27 +0200826 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyThreadState_Clear(tstate);
828 PyThreadState_Swap(save_tstate);
829 PyThreadState_Delete(tstate);
830 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000833}
834
835/* Delete an interpreter and its last thread. This requires that the
836 given thread state is current, that the thread has no remaining
837 frames, and that it is its interpreter's only remaining thread.
838 It is a fatal error to violate these constraints.
839
840 (Py_Finalize() doesn't have these constraints -- it zaps
841 everything, regardless.)
842
843 Locking: as above.
844
845*/
846
847void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000848Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (tstate != PyThreadState_GET())
853 Py_FatalError("Py_EndInterpreter: thread is not current");
854 if (tstate->frame != NULL)
855 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200856
857 wait_for_thread_shutdown();
858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (tstate != interp->tstate_head || tstate->next != NULL)
860 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyImport_Cleanup();
863 PyInterpreterState_Clear(interp);
864 PyThreadState_Swap(NULL);
865 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000866}
867
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200868#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000869static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200870#else
871static wchar_t *progname = L"python3";
872#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000873
874void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000875Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (pn && *pn)
878 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000879}
880
Martin v. Löwis790465f2008-04-05 20:41:37 +0000881wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000882Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000885}
886
Martin v. Löwis790465f2008-04-05 20:41:37 +0000887static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200888static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000889
890void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000891Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000894}
895
Martin v. Löwis790465f2008-04-05 20:41:37 +0000896wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000897Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 wchar_t *home = default_home;
900 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
901 char* chome = Py_GETENV("PYTHONHOME");
902 if (chome) {
Victor Stinner2f5bbc62013-11-15 17:09:24 +0100903 size_t size = Py_ARRAY_LENGTH(env_home);
904 size_t r = mbstowcs(env_home, chome, size);
905 if (r != (size_t)-1 && r < size)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 home = env_home;
907 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 }
910 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000911}
912
Guido van Rossum6135a871995-01-09 17:53:26 +0000913/* Create __main__ module */
914
915static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000916initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000917{
Brett Cannon13853a62013-05-04 17:37:09 -0400918 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 m = PyImport_AddModule("__main__");
920 if (m == NULL)
921 Py_FatalError("can't create __main__ module");
922 d = PyModule_GetDict(m);
923 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
924 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000925 if (bimod == NULL) {
926 Py_FatalError("Failed to retrieve builtins module");
927 }
928 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
929 Py_FatalError("Failed to initialize __main__.__builtins__");
930 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 Py_DECREF(bimod);
932 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000933 /* Main is a little special - imp.is_builtin("__main__") will return
934 * False, but BuiltinImporter is still the most appropriate initial
935 * setting for its __loader__ attribute. A more suitable value will
936 * be set if __main__ gets further initialized later in the startup
937 * process.
938 */
Brett Cannon13853a62013-05-04 17:37:09 -0400939 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400940 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000941 PyObject *loader = PyObject_GetAttrString(interp->importlib,
942 "BuiltinImporter");
943 if (loader == NULL) {
944 Py_FatalError("Failed to retrieve BuiltinImporter");
945 }
946 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
947 Py_FatalError("Failed to initialize __main__.__loader__");
948 }
949 Py_DECREF(loader);
950 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000951}
952
Victor Stinner793b5312011-04-27 00:24:21 +0200953static int
954initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000955{
956 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000957
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200958 if (Py_FileSystemDefaultEncoding == NULL)
959 {
960 Py_FileSystemDefaultEncoding = get_locale_encoding();
961 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000962 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000963
Victor Stinnere4743092010-10-19 00:05:51 +0000964 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200965 interp->fscodec_initialized = 1;
966 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000967 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000968
969 /* the encoding is mbcs, utf-8 or ascii */
970 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
971 if (!codec) {
972 /* Such error can only occurs in critical situations: no more
973 * memory, import a module of the standard library failed,
974 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200975 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000976 }
Victor Stinner793b5312011-04-27 00:24:21 +0200977 Py_DECREF(codec);
978 interp->fscodec_initialized = 1;
979 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000980}
981
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000982/* Import the site module (not into __main__ though) */
983
984static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000985initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 PyObject *m;
988 m = PyImport_ImportModule("site");
989 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200990 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyErr_Print();
992 Py_Finalize();
993 exit(1);
994 }
995 else {
996 Py_DECREF(m);
997 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000998}
999
Antoine Pitrou05608432009-01-09 18:53:14 +00001000static PyObject*
1001create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 int fd, int write_mode, char* name,
1003 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +00001004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1006 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001007 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 PyObject *line_buffering;
1009 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001010 _Py_IDENTIFIER(open);
1011 _Py_IDENTIFIER(isatty);
1012 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001013 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 /* stdin is always opened in buffered mode, first because it shouldn't
1016 make a difference in common use cases, second because TextIOWrapper
1017 depends on the presence of a read1() method which only exists on
1018 buffered streams.
1019 */
1020 if (Py_UnbufferedStdioFlag && write_mode)
1021 buffering = 0;
1022 else
1023 buffering = -1;
1024 if (write_mode)
1025 mode = "wb";
1026 else
1027 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001028 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1029 fd, mode, buffering,
1030 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (buf == NULL)
1032 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001035 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001036 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 if (raw == NULL)
1038 goto error;
1039 }
1040 else {
1041 raw = buf;
1042 Py_INCREF(raw);
1043 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001046 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001048 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (res == NULL)
1050 goto error;
1051 isatty = PyObject_IsTrue(res);
1052 Py_DECREF(res);
1053 if (isatty == -1)
1054 goto error;
1055 if (isatty || Py_UnbufferedStdioFlag)
1056 line_buffering = Py_True;
1057 else
1058 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 Py_CLEAR(raw);
1061 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001062
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001063#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001064 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1065 newlines to "\n".
1066 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1067 newline = NULL;
1068#else
1069 /* sys.stdin: split lines at "\n".
1070 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1071 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001072#endif
1073
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001074 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1075 buf, encoding, errors,
1076 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 Py_CLEAR(buf);
1078 if (stream == NULL)
1079 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (write_mode)
1082 mode = "w";
1083 else
1084 mode = "r";
1085 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001086 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 goto error;
1088 Py_CLEAR(text);
1089 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001090
1091error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 Py_XDECREF(buf);
1093 Py_XDECREF(stream);
1094 Py_XDECREF(text);
1095 Py_XDECREF(raw);
1096 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001097}
1098
Antoine Pitrou11942a52011-11-28 19:08:36 +01001099static int
1100is_valid_fd(int fd)
1101{
1102 int dummy_fd;
1103 if (fd < 0 || !_PyVerify_fd(fd))
1104 return 0;
1105 dummy_fd = dup(fd);
1106 if (dummy_fd < 0)
1107 return 0;
1108 close(dummy_fd);
1109 return 1;
1110}
1111
Georg Brandl1a3284e2007-12-02 09:40:06 +00001112/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001113static int
1114initstdio(void)
1115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 PyObject *iomod = NULL, *wrapper;
1117 PyObject *bimod = NULL;
1118 PyObject *m;
1119 PyObject *std = NULL;
1120 int status = 0, fd;
1121 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001122 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* Hack to avoid a nasty recursion issue when Python is invoked
1125 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1126 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1127 goto error;
1128 }
1129 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1132 goto error;
1133 }
1134 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (!(bimod = PyImport_ImportModule("builtins"))) {
1137 goto error;
1138 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 if (!(iomod = PyImport_ImportModule("io"))) {
1141 goto error;
1142 }
1143 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1144 goto error;
1145 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 /* Set builtins.open */
1148 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001149 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 goto error;
1151 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001152 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001153
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001154 encoding = _Py_StandardStreamEncoding;
1155 errors = _Py_StandardStreamErrors;
1156 if (!encoding || !errors) {
1157 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1158 if (pythonioencoding) {
1159 char *err;
1160 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1161 if (pythonioencoding == NULL) {
1162 PyErr_NoMemory();
1163 goto error;
1164 }
1165 err = strchr(pythonioencoding, ':');
1166 if (err) {
1167 *err = '\0';
1168 err++;
1169 if (*err && !errors) {
1170 errors = err;
1171 }
1172 }
1173 if (*pythonioencoding && !encoding) {
1174 encoding = pythonioencoding;
1175 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001176 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 /* Set sys.stdin */
1180 fd = fileno(stdin);
1181 /* Under some conditions stdin, stdout and stderr may not be connected
1182 * and fileno() may point to an invalid file descriptor. For example
1183 * GUI apps don't have valid standard streams by default.
1184 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001185 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 std = Py_None;
1187 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 }
1189 else {
1190 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1191 if (std == NULL)
1192 goto error;
1193 } /* if (fd < 0) */
1194 PySys_SetObject("__stdin__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001195 _PySys_SetObjectId(&PyId_stdin, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 /* Set sys.stdout */
1199 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001200 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 std = Py_None;
1202 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 }
1204 else {
1205 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1206 if (std == NULL)
1207 goto error;
1208 } /* if (fd < 0) */
1209 PySys_SetObject("__stdout__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001210 _PySys_SetObjectId(&PyId_stdout, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001212
Guido van Rossum98297ee2007-11-06 21:34:58 +00001213#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 /* Set sys.stderr, replaces the preliminary stderr */
1215 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001216 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 std = Py_None;
1218 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 }
1220 else {
1221 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1222 if (std == NULL)
1223 goto error;
1224 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 /* Same as hack above, pre-import stderr's codec to avoid recursion
1227 when import.c tries to write to stderr in verbose mode. */
1228 encoding_attr = PyObject_GetAttrString(std, "encoding");
1229 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001230 const char * std_encoding;
1231 std_encoding = _PyUnicode_AsString(encoding_attr);
1232 if (std_encoding != NULL) {
1233 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001234 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001236 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 }
1238 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001239
Victor Stinnerba308832013-07-22 23:55:19 +02001240 if (PySys_SetObject("__stderr__", std) < 0) {
1241 Py_DECREF(std);
1242 goto error;
1243 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001244 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
Victor Stinnerba308832013-07-22 23:55:19 +02001245 Py_DECREF(std);
1246 goto error;
1247 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001249#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001252 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 status = -1;
1254 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001255
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001256 /* We won't need them anymore. */
1257 if (_Py_StandardStreamEncoding) {
1258 PyMem_RawFree(_Py_StandardStreamEncoding);
1259 _Py_StandardStreamEncoding = NULL;
1260 }
1261 if (_Py_StandardStreamErrors) {
1262 PyMem_RawFree(_Py_StandardStreamErrors);
1263 _Py_StandardStreamErrors = NULL;
1264 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001265 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 Py_XDECREF(bimod);
1267 Py_XDECREF(iomod);
1268 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001269}
1270
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001271/* Parse input from a file and execute it */
1272
1273int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001274PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (filename == NULL)
1278 filename = "???";
1279 if (Py_FdIsInteractive(fp, filename)) {
1280 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1281 if (closeit)
1282 fclose(fp);
1283 return err;
1284 }
1285 else
1286 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001287}
1288
1289int
Victor Stinner95701bd2013-11-06 18:41:07 +01001290PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001291{
Victor Stinner95701bd2013-11-06 18:41:07 +01001292 PyObject *filename, *v;
1293 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001295
Victor Stinner95701bd2013-11-06 18:41:07 +01001296 filename = PyUnicode_DecodeFSDefault(filename_str);
1297 if (filename == NULL) {
1298 PyErr_Print();
1299 return -1;
1300 }
1301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (flags == NULL) {
1303 flags = &local_flags;
1304 local_flags.cf_flags = 0;
1305 }
Victor Stinner09054372013-11-06 22:41:44 +01001306 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001308 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 Py_XDECREF(v);
1310 }
Victor Stinner09054372013-11-06 22:41:44 +01001311 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001313 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 Py_XDECREF(v);
1315 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001316 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001318 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001320 if (ret == E_EOF) {
1321 err = 0;
1322 break;
1323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 /*
1325 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001326 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 */
1328 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001329 Py_DECREF(filename);
1330 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001331}
1332
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001333/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001334static int PARSER_FLAGS(PyCompilerFlags *flags)
1335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 int parser_flags = 0;
1337 if (!flags)
1338 return 0;
1339 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1340 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1341 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1342 parser_flags |= PyPARSE_IGNORE_COOKIE;
1343 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1344 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1345 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001346}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001347
Thomas Wouters89f507f2006-12-13 04:49:30 +00001348#if 0
1349/* Keep an example of flags with future keyword support. */
1350#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1352 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1353 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1354 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001355#endif
1356
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001357int
Victor Stinner95701bd2013-11-06 18:41:07 +01001358PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001359{
Victor Stinner95701bd2013-11-06 18:41:07 +01001360 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 mod_ty mod;
1362 PyArena *arena;
1363 char *ps1 = "", *ps2 = "", *enc = NULL;
1364 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001365 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001366 _Py_IDENTIFIER(__main__);
1367
1368 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1369 if (mod_name == NULL) {
1370 PyErr_Print();
1371 return -1;
1372 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001375 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +01001376 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001377 if (v && v != Py_None) {
1378 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1379 if (oenc)
1380 enc = _PyUnicode_AsString(oenc);
1381 if (!enc)
1382 PyErr_Clear();
1383 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 }
Victor Stinner09054372013-11-06 22:41:44 +01001385 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 if (v != NULL) {
1387 v = PyObject_Str(v);
1388 if (v == NULL)
1389 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001390 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001392 if (ps1 == NULL) {
1393 PyErr_Clear();
1394 ps1 = "";
1395 }
1396 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 }
Victor Stinner09054372013-11-06 22:41:44 +01001398 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 if (w != NULL) {
1400 w = PyObject_Str(w);
1401 if (w == NULL)
1402 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001403 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001405 if (ps2 == NULL) {
1406 PyErr_Clear();
1407 ps2 = "";
1408 }
1409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 }
1411 arena = PyArena_New();
1412 if (arena == NULL) {
1413 Py_XDECREF(v);
1414 Py_XDECREF(w);
1415 Py_XDECREF(oenc);
1416 return -1;
1417 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001418 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1419 Py_single_input, ps1, ps2,
1420 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 Py_XDECREF(v);
1422 Py_XDECREF(w);
1423 Py_XDECREF(oenc);
1424 if (mod == NULL) {
1425 PyArena_Free(arena);
1426 if (errcode == E_EOF) {
1427 PyErr_Clear();
1428 return E_EOF;
1429 }
1430 PyErr_Print();
1431 return -1;
1432 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001433 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (m == NULL) {
1435 PyArena_Free(arena);
1436 return -1;
1437 }
1438 d = PyModule_GetDict(m);
1439 v = run_mod(mod, filename, d, d, flags, arena);
1440 PyArena_Free(arena);
1441 flush_io();
1442 if (v == NULL) {
1443 PyErr_Print();
1444 return -1;
1445 }
1446 Py_DECREF(v);
1447 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001448}
1449
Victor Stinner95701bd2013-11-06 18:41:07 +01001450int
1451PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1452{
1453 PyObject *filename;
1454 int res;
1455
1456 filename = PyUnicode_DecodeFSDefault(filename_str);
1457 if (filename == NULL) {
1458 PyErr_Print();
1459 return -1;
1460 }
1461 res = PyRun_InteractiveOneObject(fp, filename, flags);
1462 Py_DECREF(filename);
1463 return res;
1464}
1465
1466
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001467/* Check whether a file maybe a pyc file: Look at the extension,
1468 the file type, and, if we may close it, at the first few bytes. */
1469
1470static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001471maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1474 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 /* Only look into the file if we are allowed to close it, since
1477 it then should also be seekable. */
1478 if (closeit) {
1479 /* Read only two bytes of the magic. If the file was opened in
1480 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1481 be read as they are on disk. */
1482 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1483 unsigned char buf[2];
1484 /* Mess: In case of -x, the stream is NOT at its start now,
1485 and ungetc() was used to push back the first newline,
1486 which makes the current stream position formally undefined,
1487 and a x-platform nightmare.
1488 Unfortunately, we have no direct way to know whether -x
1489 was specified. So we use a terrible hack: if the current
1490 stream position is not 0, we assume -x was specified, and
1491 give up. Bug 132850 on SourceForge spells out the
1492 hopelessness of trying anything else (fseek and ftell
1493 don't work predictably x-platform for text-mode files).
1494 */
1495 int ispyc = 0;
1496 if (ftell(fp) == 0) {
1497 if (fread(buf, 1, 2, fp) == 2 &&
1498 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1499 ispyc = 1;
1500 rewind(fp);
1501 }
1502 return ispyc;
1503 }
1504 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001505}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001506
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001507static int
1508set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001509{
1510 PyInterpreterState *interp;
1511 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001512 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001513 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001514
1515 filename_obj = PyUnicode_DecodeFSDefault(filename);
1516 if (filename_obj == NULL)
1517 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001518 /* Get current thread state and interpreter pointer */
1519 tstate = PyThreadState_GET();
1520 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001521 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1522 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001523 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001524 return -1;
1525 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001526 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001527 Py_DECREF(loader_type);
1528 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001529 return -1;
1530 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001531 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1532 result = -1;
1533 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001534 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001535 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001536}
1537
1538int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001539PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 PyObject *m, *d, *v;
1543 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001544 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001545 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 m = PyImport_AddModule("__main__");
1548 if (m == NULL)
1549 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001550 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 d = PyModule_GetDict(m);
1552 if (PyDict_GetItemString(d, "__file__") == NULL) {
1553 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001554 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001556 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1558 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001559 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001561 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1562 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001563 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001564 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 set_file_name = 1;
1566 Py_DECREF(f);
1567 }
1568 len = strlen(filename);
1569 ext = filename + len - (len > 4 ? 4 : 0);
1570 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001571 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 /* Try to run a pyc file. First, re-open in binary */
1573 if (closeit)
1574 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001575 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 goto done;
1578 }
1579 /* Turn on optimization if a .pyo file is given */
1580 if (strcmp(ext, ".pyo") == 0)
1581 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001582
1583 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1584 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1585 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001586 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001587 goto done;
1588 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001589 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1590 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001592 /* When running from stdin, leave __main__.__loader__ alone */
1593 if (strcmp(filename, "<stdin>") != 0 &&
1594 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1595 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1596 ret = -1;
1597 goto done;
1598 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1600 closeit, flags);
1601 }
1602 flush_io();
1603 if (v == NULL) {
1604 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 goto done;
1606 }
1607 Py_DECREF(v);
1608 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001609 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1611 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001612 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001614}
1615
1616int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001617PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 PyObject *m, *d, *v;
1620 m = PyImport_AddModule("__main__");
1621 if (m == NULL)
1622 return -1;
1623 d = PyModule_GetDict(m);
1624 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1625 if (v == NULL) {
1626 PyErr_Print();
1627 return -1;
1628 }
1629 Py_DECREF(v);
1630 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001631}
1632
Barry Warsaw035574d1997-08-29 22:07:17 +00001633static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001634parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
1635 int *lineno, int *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 long hold;
1638 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001639 _Py_IDENTIFIER(msg);
1640 _Py_IDENTIFIER(filename);
1641 _Py_IDENTIFIER(lineno);
1642 _Py_IDENTIFIER(offset);
1643 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001644
Benjamin Peterson80d50422012-04-03 00:30:38 -04001645 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001646 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001649 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001650 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001652
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001653 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001654 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001656 if (v == Py_None) {
1657 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001658 *filename = _PyUnicode_FromId(&PyId_string);
1659 if (*filename == NULL)
1660 goto finally;
1661 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001662 }
1663 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001664 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001665 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001666
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001667 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001668 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 goto finally;
1670 hold = PyLong_AsLong(v);
1671 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (hold < 0 && PyErr_Occurred())
1673 goto finally;
1674 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001675
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001676 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001677 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 goto finally;
1679 if (v == Py_None) {
1680 *offset = -1;
1681 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 } else {
1683 hold = PyLong_AsLong(v);
1684 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (hold < 0 && PyErr_Occurred())
1686 goto finally;
1687 *offset = (int)hold;
1688 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001689
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001690 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001691 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001693 if (v == Py_None) {
1694 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001696 }
1697 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001698 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001699 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001701
1702finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001703 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001704 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001706}
1707
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001708void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001709PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001712}
1713
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001714static void
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001715print_error_text(PyObject *f, int offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001716{
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001717 char *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 char *nl;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001719
1720 text = _PyUnicode_AsString(text_obj);
1721 if (text == NULL)
1722 return;
1723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001725 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1726 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 for (;;) {
1728 nl = strchr(text, '\n');
1729 if (nl == NULL || nl-text >= offset)
1730 break;
1731 offset -= (int)(nl+1-text);
1732 text = nl+1;
1733 }
1734 while (*text == ' ' || *text == '\t') {
1735 text++;
1736 offset--;
1737 }
1738 }
1739 PyFile_WriteString(" ", f);
1740 PyFile_WriteString(text, f);
1741 if (*text == '\0' || text[strlen(text)-1] != '\n')
1742 PyFile_WriteString("\n", f);
1743 if (offset == -1)
1744 return;
1745 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001746 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001749}
1750
Guido van Rossum66e8e862001-03-23 17:54:43 +00001751static void
1752handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyObject *exception, *value, *tb;
1755 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (Py_InspectFlag)
1758 /* Don't exit if -i flag was given. This flag is set to 0
1759 * when entering interactive mode for inspecting. */
1760 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyErr_Fetch(&exception, &value, &tb);
1763 fflush(stdout);
1764 if (value == NULL || value == Py_None)
1765 goto done;
1766 if (PyExceptionInstance_Check(value)) {
1767 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001768 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001769 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (code) {
1771 Py_DECREF(value);
1772 value = code;
1773 if (value == Py_None)
1774 goto done;
1775 }
1776 /* If we failed to dig out the 'code' attribute,
1777 just let the else clause below print the error. */
1778 }
1779 if (PyLong_Check(value))
1780 exitcode = (int)PyLong_AsLong(value);
1781 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001782 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner7126dbc2010-05-21 23:45:42 +00001783 if (sys_stderr != NULL && sys_stderr != Py_None) {
1784 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1785 } else {
1786 PyObject_Print(value, stderr, Py_PRINT_RAW);
1787 fflush(stderr);
1788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 PySys_WriteStderr("\n");
1790 exitcode = 1;
1791 }
Tim Peterscf615b52003-04-19 18:47:02 +00001792 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 /* Restore and clear the exception info, in order to properly decref
1794 * the exception, value, and traceback. If we just exit instead,
1795 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1796 * some finalizers from running.
1797 */
1798 PyErr_Restore(exception, value, tb);
1799 PyErr_Clear();
1800 Py_Exit(exitcode);
1801 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001802}
1803
1804void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001805PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1810 handle_system_exit();
1811 }
1812 PyErr_Fetch(&exception, &v, &tb);
1813 if (exception == NULL)
1814 return;
1815 PyErr_NormalizeException(&exception, &v, &tb);
1816 if (tb == NULL) {
1817 tb = Py_None;
1818 Py_INCREF(tb);
1819 }
1820 PyException_SetTraceback(v, tb);
1821 if (exception == NULL)
1822 return;
1823 /* Now we know v != NULL too */
1824 if (set_sys_last_vars) {
Victor Stinner09054372013-11-06 22:41:44 +01001825 _PySys_SetObjectId(&PyId_last_type, exception);
1826 _PySys_SetObjectId(&PyId_last_value, v);
1827 _PySys_SetObjectId(&PyId_last_traceback, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 }
Victor Stinner09054372013-11-06 22:41:44 +01001829 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 if (hook) {
1831 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1832 PyObject *result = PyEval_CallObject(hook, args);
1833 if (result == NULL) {
1834 PyObject *exception2, *v2, *tb2;
1835 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1836 handle_system_exit();
1837 }
1838 PyErr_Fetch(&exception2, &v2, &tb2);
1839 PyErr_NormalizeException(&exception2, &v2, &tb2);
1840 /* It should not be possible for exception2 or v2
1841 to be NULL. However PyErr_Display() can't
1842 tolerate NULLs, so just be safe. */
1843 if (exception2 == NULL) {
1844 exception2 = Py_None;
1845 Py_INCREF(exception2);
1846 }
1847 if (v2 == NULL) {
1848 v2 = Py_None;
1849 Py_INCREF(v2);
1850 }
1851 fflush(stdout);
1852 PySys_WriteStderr("Error in sys.excepthook:\n");
1853 PyErr_Display(exception2, v2, tb2);
1854 PySys_WriteStderr("\nOriginal exception was:\n");
1855 PyErr_Display(exception, v, tb);
1856 Py_DECREF(exception2);
1857 Py_DECREF(v2);
1858 Py_XDECREF(tb2);
1859 }
1860 Py_XDECREF(result);
1861 Py_XDECREF(args);
1862 } else {
1863 PySys_WriteStderr("sys.excepthook is missing\n");
1864 PyErr_Display(exception, v, tb);
1865 }
1866 Py_XDECREF(exception);
1867 Py_XDECREF(v);
1868 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001869}
1870
Benjamin Petersone6528212008-07-15 15:32:09 +00001871static void
1872print_exception(PyObject *f, PyObject *value)
1873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 int err = 0;
1875 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001876 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (!PyExceptionInstance_Check(value)) {
1879 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1880 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1881 PyFile_WriteString(" found\n", f);
1882 return;
1883 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 Py_INCREF(value);
1886 fflush(stdout);
1887 type = (PyObject *) Py_TYPE(value);
1888 tb = PyException_GetTraceback(value);
1889 if (tb && tb != Py_None)
1890 err = PyTraceBack_Print(tb, f);
1891 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001892 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001894 PyObject *message, *filename, *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 int lineno, offset;
1896 if (!parse_syntax_error(value, &message, &filename,
1897 &lineno, &offset, &text))
1898 PyErr_Clear();
1899 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001900 PyObject *line;
1901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 Py_DECREF(value);
1903 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001904
1905 line = PyUnicode_FromFormat(" File \"%U\", line %d\n",
1906 filename, lineno);
1907 Py_DECREF(filename);
1908 if (line != NULL) {
1909 PyFile_WriteObject(line, f, Py_PRINT_RAW);
1910 Py_DECREF(line);
1911 }
1912
1913 if (text != NULL) {
1914 print_error_text(f, offset, text);
1915 Py_DECREF(text);
1916 }
1917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 /* Can't be bothered to check all those
1919 PyFile_WriteString() calls */
1920 if (PyErr_Occurred())
1921 err = -1;
1922 }
1923 }
1924 if (err) {
1925 /* Don't do anything else */
1926 }
1927 else {
1928 PyObject* moduleName;
1929 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001930 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 assert(PyExceptionClass_Check(type));
1932 className = PyExceptionClass_Name(type);
1933 if (className != NULL) {
1934 char *dot = strrchr(className, '.');
1935 if (dot != NULL)
1936 className = dot+1;
1937 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001938
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001939 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1941 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001942 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 err = PyFile_WriteString("<unknown>", f);
1944 }
1945 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001946 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 {
Victor Stinner937114f2013-11-07 00:12:30 +01001948 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 err += PyFile_WriteString(".", f);
1950 }
1951 Py_DECREF(moduleName);
1952 }
1953 if (err == 0) {
1954 if (className == NULL)
1955 err = PyFile_WriteString("<unknown>", f);
1956 else
1957 err = PyFile_WriteString(className, f);
1958 }
1959 }
1960 if (err == 0 && (value != Py_None)) {
1961 PyObject *s = PyObject_Str(value);
1962 /* only print colon if the str() of the
1963 object is not the empty string
1964 */
1965 if (s == NULL)
1966 err = -1;
1967 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001968 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 err = PyFile_WriteString(": ", f);
1970 if (err == 0)
1971 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1972 Py_XDECREF(s);
1973 }
1974 /* try to write a newline in any case */
1975 err += PyFile_WriteString("\n", f);
1976 Py_XDECREF(tb);
1977 Py_DECREF(value);
1978 /* If an error happened here, don't show it.
1979 XXX This is wrong, but too many callers rely on this behavior. */
1980 if (err != 0)
1981 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001982}
1983
1984static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 "\nThe above exception was the direct cause "
1986 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001987
1988static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 "\nDuring handling of the above exception, "
1990 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001991
1992static void
1993print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 int err = 0, res;
1996 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 if (seen != NULL) {
1999 /* Exception chaining */
2000 if (PySet_Add(seen, value) == -1)
2001 PyErr_Clear();
2002 else if (PyExceptionInstance_Check(value)) {
2003 cause = PyException_GetCause(value);
2004 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002005 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 res = PySet_Contains(seen, cause);
2007 if (res == -1)
2008 PyErr_Clear();
2009 if (res == 0) {
2010 print_exception_recursive(
2011 f, cause, seen);
2012 err |= PyFile_WriteString(
2013 cause_message, f);
2014 }
2015 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002016 else if (context &&
2017 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 res = PySet_Contains(seen, context);
2019 if (res == -1)
2020 PyErr_Clear();
2021 if (res == 0) {
2022 print_exception_recursive(
2023 f, context, seen);
2024 err |= PyFile_WriteString(
2025 context_message, f);
2026 }
2027 }
2028 Py_XDECREF(context);
2029 Py_XDECREF(cause);
2030 }
2031 }
2032 print_exception(f, value);
2033 if (err != 0)
2034 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002035}
2036
Thomas Wouters477c8d52006-05-27 19:21:47 +00002037void
2038PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 PyObject *seen;
Victor Stinnerbd303c12013-11-07 23:07:29 +01002041 PyObject *f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002042 if (PyExceptionInstance_Check(value)
2043 && tb != NULL && PyTraceBack_Check(tb)) {
2044 /* Put the traceback on the exception, otherwise it won't get
2045 displayed. See issue #18776. */
2046 PyObject *cur_tb = PyException_GetTraceback(value);
2047 if (cur_tb == NULL)
2048 PyException_SetTraceback(value, tb);
2049 else
2050 Py_DECREF(cur_tb);
2051 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (f == Py_None) {
2053 /* pass */
2054 }
2055 else if (f == NULL) {
2056 _PyObject_Dump(value);
2057 fprintf(stderr, "lost sys.stderr\n");
2058 }
2059 else {
2060 /* We choose to ignore seen being possibly NULL, and report
2061 at least the main exception (it could be a MemoryError).
2062 */
2063 seen = PySet_New(NULL);
2064 if (seen == NULL)
2065 PyErr_Clear();
2066 print_exception_recursive(f, value, seen);
2067 Py_XDECREF(seen);
2068 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002069}
2070
Guido van Rossum82598051997-03-05 00:20:32 +00002071PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002072PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 PyObject *ret = NULL;
2076 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002077 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01002078 PyObject *filename;
2079
2080 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2081 if (filename == NULL)
2082 return NULL;
2083
2084 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 if (arena == NULL)
2086 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002087
Victor Stinner95701bd2013-11-06 18:41:07 +01002088 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002090 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 PyArena_Free(arena);
2092 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002093}
2094
2095PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002096PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002098{
Victor Stinner95701bd2013-11-06 18:41:07 +01002099 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002101 PyArena *arena = NULL;
2102 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002103
Victor Stinner95701bd2013-11-06 18:41:07 +01002104 filename = PyUnicode_DecodeFSDefault(filename_str);
2105 if (filename == NULL)
2106 goto exit;
2107
2108 arena = PyArena_New();
2109 if (arena == NULL)
2110 goto exit;
2111
2112 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2113 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 if (closeit)
2115 fclose(fp);
2116 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002117 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 }
2119 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002120
2121exit:
2122 Py_XDECREF(filename);
2123 if (arena != NULL)
2124 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002126}
2127
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002128static void
2129flush_io(void)
2130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 PyObject *f, *r;
2132 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 /* Save the current exception */
2135 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002136
Victor Stinnerbd303c12013-11-07 23:07:29 +01002137 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002139 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (r)
2141 Py_DECREF(r);
2142 else
2143 PyErr_Clear();
2144 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01002145 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002147 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (r)
2149 Py_DECREF(r);
2150 else
2151 PyErr_Clear();
2152 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002155}
2156
Guido van Rossum82598051997-03-05 00:20:32 +00002157static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002158run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2159 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyCodeObject *co;
2162 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002163 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (co == NULL)
2165 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002166 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 Py_DECREF(co);
2168 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002169}
2170
Guido van Rossum82598051997-03-05 00:20:32 +00002171static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002172run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 PyCodeObject *co;
2176 PyObject *v;
2177 long magic;
2178 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 magic = PyMarshal_ReadLongFromFile(fp);
2181 if (magic != PyImport_GetMagicNumber()) {
2182 PyErr_SetString(PyExc_RuntimeError,
2183 "Bad magic number in .pyc file");
2184 return NULL;
2185 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002186 /* Skip mtime and size */
2187 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 (void) PyMarshal_ReadLongFromFile(fp);
2189 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (v == NULL || !PyCode_Check(v)) {
2191 Py_XDECREF(v);
2192 PyErr_SetString(PyExc_RuntimeError,
2193 "Bad code object in .pyc file");
2194 return NULL;
2195 }
2196 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002197 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 if (v && flags)
2199 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2200 Py_DECREF(co);
2201 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002202}
2203
Guido van Rossum82598051997-03-05 00:20:32 +00002204PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002205Py_CompileStringObject(const char *str, PyObject *filename, int start,
2206 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 PyCodeObject *co;
2209 mod_ty mod;
2210 PyArena *arena = PyArena_New();
2211 if (arena == NULL)
2212 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002213
Victor Stinner14e461d2013-08-26 22:28:21 +02002214 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (mod == NULL) {
2216 PyArena_Free(arena);
2217 return NULL;
2218 }
2219 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2220 PyObject *result = PyAST_mod2obj(mod);
2221 PyArena_Free(arena);
2222 return result;
2223 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002224 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 PyArena_Free(arena);
2226 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002227}
2228
Victor Stinner14e461d2013-08-26 22:28:21 +02002229PyObject *
2230Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2231 PyCompilerFlags *flags, int optimize)
2232{
2233 PyObject *filename, *co;
2234 filename = PyUnicode_DecodeFSDefault(filename_str);
2235 if (filename == NULL)
2236 return NULL;
2237 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2238 Py_DECREF(filename);
2239 return co;
2240}
2241
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002242/* For use in Py_LIMITED_API */
2243#undef Py_CompileString
2244PyObject *
2245PyCompileString(const char *str, const char *filename, int start)
2246{
2247 return Py_CompileStringFlags(str, filename, start, NULL);
2248}
2249
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002250struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002251Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 struct symtable *st;
2254 mod_ty mod;
2255 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002256 PyArena *arena;
2257
2258 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 if (arena == NULL)
2260 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002263 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (mod == NULL) {
2265 PyArena_Free(arena);
2266 return NULL;
2267 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002268 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 PyArena_Free(arena);
2270 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002271}
2272
Victor Stinner14e461d2013-08-26 22:28:21 +02002273struct symtable *
2274Py_SymtableString(const char *str, const char *filename_str, int start)
2275{
2276 PyObject *filename;
2277 struct symtable *st;
2278
2279 filename = PyUnicode_DecodeFSDefault(filename_str);
2280 if (filename == NULL)
2281 return NULL;
2282 st = Py_SymtableStringObject(str, filename, start);
2283 Py_DECREF(filename);
2284 return st;
2285}
2286
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287/* Preferred access to parser is through AST. */
2288mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002289PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2290 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 mod_ty mod;
2293 PyCompilerFlags localflags;
2294 perrdetail err;
2295 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002296
Victor Stinner14e461d2013-08-26 22:28:21 +02002297 node *n = PyParser_ParseStringObject(s, filename,
2298 &_PyParser_Grammar, start, &err,
2299 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 if (flags == NULL) {
2301 localflags.cf_flags = 0;
2302 flags = &localflags;
2303 }
2304 if (n) {
2305 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002306 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 }
2309 else {
2310 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002311 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002313 err_free(&err);
2314 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315}
2316
2317mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002318PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2319 PyCompilerFlags *flags, PyArena *arena)
2320{
2321 PyObject *filename;
2322 mod_ty mod;
2323 filename = PyUnicode_DecodeFSDefault(filename_str);
2324 if (filename == NULL)
2325 return NULL;
2326 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2327 Py_DECREF(filename);
2328 return mod;
2329}
2330
2331mod_ty
2332PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2333 int start, char *ps1,
2334 char *ps2, PyCompilerFlags *flags, int *errcode,
2335 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 mod_ty mod;
2338 PyCompilerFlags localflags;
2339 perrdetail err;
2340 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002341
Victor Stinner14e461d2013-08-26 22:28:21 +02002342 node *n = PyParser_ParseFileObject(fp, filename, enc,
2343 &_PyParser_Grammar,
2344 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 if (flags == NULL) {
2346 localflags.cf_flags = 0;
2347 flags = &localflags;
2348 }
2349 if (n) {
2350 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002351 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 }
2354 else {
2355 err_input(&err);
2356 if (errcode)
2357 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002358 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002360 err_free(&err);
2361 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362}
2363
Victor Stinner14e461d2013-08-26 22:28:21 +02002364mod_ty
2365PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2366 int start, char *ps1,
2367 char *ps2, PyCompilerFlags *flags, int *errcode,
2368 PyArena *arena)
2369{
2370 mod_ty mod;
2371 PyObject *filename;
2372 filename = PyUnicode_DecodeFSDefault(filename_str);
2373 if (filename == NULL)
2374 return NULL;
2375 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2376 flags, errcode, arena);
2377 Py_DECREF(filename);
2378 return mod;
2379}
2380
Guido van Rossuma110aa61994-08-29 12:50:44 +00002381/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002382
Guido van Rossuma110aa61994-08-29 12:50:44 +00002383node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002384PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 perrdetail err;
2387 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2388 &_PyParser_Grammar,
2389 start, NULL, NULL, &err, flags);
2390 if (n == NULL)
2391 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002392 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002395}
2396
Guido van Rossuma110aa61994-08-29 12:50:44 +00002397/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002398
Guido van Rossuma110aa61994-08-29 12:50:44 +00002399node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002400PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 perrdetail err;
2403 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2404 start, &err, flags);
2405 if (n == NULL)
2406 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002407 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002409}
2410
2411node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002412PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 perrdetail err;
2416 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2417 &_PyParser_Grammar, start, &err, flags);
2418 if (n == NULL)
2419 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002420 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002422}
2423
2424node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002425PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002428}
2429
Guido van Rossum66ebd912003-04-17 16:02:26 +00002430/* May want to move a more generalized form of this to parsetok.c or
2431 even parser modules. */
2432
2433void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002434PyParser_ClearError(perrdetail *err)
2435{
2436 err_free(err);
2437}
2438
2439void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002440PyParser_SetError(perrdetail *err)
2441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002443}
2444
Victor Stinner7f2fee32011-04-05 00:39:01 +02002445static void
2446err_free(perrdetail *err)
2447{
2448 Py_CLEAR(err->filename);
2449}
2450
Guido van Rossuma110aa61994-08-29 12:50:44 +00002451/* Set the error appropriate to the given input error code (see errcode.h) */
2452
2453static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002454err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 PyObject *v, *w, *errtype, *errtext;
2457 PyObject *msg_obj = NULL;
2458 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 errtype = PyExc_SyntaxError;
2461 switch (err->error) {
2462 case E_ERROR:
2463 return;
2464 case E_SYNTAX:
2465 errtype = PyExc_IndentationError;
2466 if (err->expected == INDENT)
2467 msg = "expected an indented block";
2468 else if (err->token == INDENT)
2469 msg = "unexpected indent";
2470 else if (err->token == DEDENT)
2471 msg = "unexpected unindent";
2472 else {
2473 errtype = PyExc_SyntaxError;
2474 msg = "invalid syntax";
2475 }
2476 break;
2477 case E_TOKEN:
2478 msg = "invalid token";
2479 break;
2480 case E_EOFS:
2481 msg = "EOF while scanning triple-quoted string literal";
2482 break;
2483 case E_EOLS:
2484 msg = "EOL while scanning string literal";
2485 break;
2486 case E_INTR:
2487 if (!PyErr_Occurred())
2488 PyErr_SetNone(PyExc_KeyboardInterrupt);
2489 goto cleanup;
2490 case E_NOMEM:
2491 PyErr_NoMemory();
2492 goto cleanup;
2493 case E_EOF:
2494 msg = "unexpected EOF while parsing";
2495 break;
2496 case E_TABSPACE:
2497 errtype = PyExc_TabError;
2498 msg = "inconsistent use of tabs and spaces in indentation";
2499 break;
2500 case E_OVERFLOW:
2501 msg = "expression too long";
2502 break;
2503 case E_DEDENT:
2504 errtype = PyExc_IndentationError;
2505 msg = "unindent does not match any outer indentation level";
2506 break;
2507 case E_TOODEEP:
2508 errtype = PyExc_IndentationError;
2509 msg = "too many levels of indentation";
2510 break;
2511 case E_DECODE: {
2512 PyObject *type, *value, *tb;
2513 PyErr_Fetch(&type, &value, &tb);
2514 msg = "unknown decode error";
2515 if (value != NULL)
2516 msg_obj = PyObject_Str(value);
2517 Py_XDECREF(type);
2518 Py_XDECREF(value);
2519 Py_XDECREF(tb);
2520 break;
2521 }
2522 case E_LINECONT:
2523 msg = "unexpected character after line continuation character";
2524 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 case E_IDENTIFIER:
2527 msg = "invalid character in identifier";
2528 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002529 case E_BADSINGLE:
2530 msg = "multiple statements found while compiling a single statement";
2531 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 default:
2533 fprintf(stderr, "error=%d\n", err->error);
2534 msg = "unknown parsing error";
2535 break;
2536 }
2537 /* err->text may not be UTF-8 in case of decoding errors.
2538 Explicitly convert to an object. */
2539 if (!err->text) {
2540 errtext = Py_None;
2541 Py_INCREF(Py_None);
2542 } else {
2543 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2544 "replace");
2545 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002546 v = Py_BuildValue("(OiiN)", err->filename,
2547 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 if (v != NULL) {
2549 if (msg_obj)
2550 w = Py_BuildValue("(OO)", msg_obj, v);
2551 else
2552 w = Py_BuildValue("(sO)", msg, v);
2553 } else
2554 w = NULL;
2555 Py_XDECREF(v);
2556 PyErr_SetObject(errtype, w);
2557 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002558cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 Py_XDECREF(msg_obj);
2560 if (err->text != NULL) {
2561 PyObject_FREE(err->text);
2562 err->text = NULL;
2563 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002564}
2565
2566/* Print fatal error message and abort */
2567
2568void
Tim Peters7c321a82002-07-09 02:57:01 +00002569Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002570{
Victor Stinner024e37a2011-03-31 01:31:06 +02002571 const int fd = fileno(stderr);
2572 PyThreadState *tstate;
2573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 fprintf(stderr, "Fatal Python error: %s\n", msg);
2575 fflush(stderr); /* it helps in Windows debug build */
2576 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002577 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002579 else {
2580 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2581 if (tstate != NULL) {
2582 fputc('\n', stderr);
2583 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002584 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002585 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002586 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002587 }
2588
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002589#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 {
2591 size_t len = strlen(msg);
2592 WCHAR* buffer;
2593 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 /* Convert the message to wchar_t. This uses a simple one-to-one
2596 conversion, assuming that the this error message actually uses ASCII
2597 only. If this ceases to be true, we will have to convert. */
2598 buffer = alloca( (len+1) * (sizeof *buffer));
2599 for( i=0; i<=len; ++i)
2600 buffer[i] = msg[i];
2601 OutputDebugStringW(L"Fatal Python error: ");
2602 OutputDebugStringW(buffer);
2603 OutputDebugStringW(L"\n");
2604 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002605#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002607#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002608#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002610}
2611
2612/* Clean up and exit */
2613
Guido van Rossuma110aa61994-08-29 12:50:44 +00002614#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002615#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002616#endif
2617
Collin Winter670e6922007-03-21 02:57:17 +00002618static void (*pyexitfunc)(void) = NULL;
2619/* For the atexit module. */
2620void _Py_PyAtExit(void (*func)(void))
2621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002623}
2624
2625static void
2626call_py_exitfuncs(void)
2627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 if (pyexitfunc == NULL)
2629 return;
Collin Winter670e6922007-03-21 02:57:17 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 (*pyexitfunc)();
2632 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002633}
2634
Antoine Pitrou011bd622009-10-20 21:52:47 +00002635/* Wait until threading._shutdown completes, provided
2636 the threading module was imported in the first place.
2637 The shutdown routine will wait until all non-daemon
2638 "threading" threads have completed. */
2639static void
2640wait_for_thread_shutdown(void)
2641{
2642#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002643 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 PyObject *result;
2645 PyThreadState *tstate = PyThreadState_GET();
2646 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2647 "threading");
2648 if (threading == NULL) {
2649 /* threading not imported */
2650 PyErr_Clear();
2651 return;
2652 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002653 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 if (result == NULL) {
2655 PyErr_WriteUnraisable(threading);
2656 }
2657 else {
2658 Py_DECREF(result);
2659 }
2660 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002661#endif
2662}
2663
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002664#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002665static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002666static int nexitfuncs = 0;
2667
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002668int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 if (nexitfuncs >= NEXITFUNCS)
2671 return -1;
2672 exitfuncs[nexitfuncs++] = func;
2673 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002674}
2675
Guido van Rossumcc283f51997-08-05 02:22:03 +00002676static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002677call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 while (nexitfuncs > 0)
2680 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 fflush(stdout);
2683 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002684}
2685
2686void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002687Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002692}
2693
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002694static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002695initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002696{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002697#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002699#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002700#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002702#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002703#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002705#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002707 if (PyErr_Occurred()) {
2708 Py_FatalError("Py_Initialize: can't import signal");
2709 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002710}
2711
Guido van Rossum7433b121997-02-14 19:45:36 +00002712
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002713/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2714 *
2715 * All of the code in this function must only use async-signal-safe functions,
2716 * listed at `man 7 signal` or
2717 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2718 */
2719void
2720_Py_RestoreSignals(void)
2721{
2722#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002724#endif
2725#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002727#endif
2728#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002730#endif
2731}
2732
2733
Guido van Rossum7433b121997-02-14 19:45:36 +00002734/*
2735 * The file descriptor fd is considered ``interactive'' if either
2736 * a) isatty(fd) is TRUE, or
2737 * b) the -i flag was given, and the filename associated with
2738 * the descriptor is NULL or "<stdin>" or "???".
2739 */
2740int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002741Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 if (isatty((int)fileno(fp)))
2744 return 1;
2745 if (!Py_InteractiveFlag)
2746 return 0;
2747 return (filename == NULL) ||
2748 (strcmp(filename, "<stdin>") == 0) ||
2749 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002750}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002751
2752
Tim Petersd08e3822003-04-17 15:24:21 +00002753#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002754#if defined(WIN32) && defined(_MSC_VER)
2755
2756/* Stack checking for Microsoft C */
2757
2758#include <malloc.h>
2759#include <excpt.h>
2760
Fred Drakee8de31c2000-08-31 05:38:39 +00002761/*
2762 * Return non-zero when we run out of memory on the stack; zero otherwise.
2763 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002764int
Fred Drake399739f2000-08-31 05:52:44 +00002765PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 __try {
2768 /* alloca throws a stack overflow exception if there's
2769 not enough space left on the stack */
2770 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2771 return 0;
2772 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2773 EXCEPTION_EXECUTE_HANDLER :
2774 EXCEPTION_CONTINUE_SEARCH) {
2775 int errcode = _resetstkoflw();
2776 if (errcode == 0)
2777 {
2778 Py_FatalError("Could not reset the stack!");
2779 }
2780 }
2781 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002782}
2783
2784#endif /* WIN32 && _MSC_VER */
2785
2786/* Alternate implementations can be added here... */
2787
2788#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002789
2790
2791/* Wrappers around sigaction() or signal(). */
2792
2793PyOS_sighandler_t
2794PyOS_getsig(int sig)
2795{
2796#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 struct sigaction context;
2798 if (sigaction(sig, NULL, &context) == -1)
2799 return SIG_ERR;
2800 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002801#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002803/* Special signal handling for the secure CRT in Visual Studio 2005 */
2804#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 switch (sig) {
2806 /* Only these signals are valid */
2807 case SIGINT:
2808 case SIGILL:
2809 case SIGFPE:
2810 case SIGSEGV:
2811 case SIGTERM:
2812 case SIGBREAK:
2813 case SIGABRT:
2814 break;
2815 /* Don't call signal() with other values or it will assert */
2816 default:
2817 return SIG_ERR;
2818 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002819#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 handler = signal(sig, SIG_IGN);
2821 if (handler != SIG_ERR)
2822 signal(sig, handler);
2823 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002824#endif
2825}
2826
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002827/*
2828 * All of the code in this function must only use async-signal-safe functions,
2829 * listed at `man 7 signal` or
2830 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2831 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002832PyOS_sighandler_t
2833PyOS_setsig(int sig, PyOS_sighandler_t handler)
2834{
2835#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 /* Some code in Modules/signalmodule.c depends on sigaction() being
2837 * used here if HAVE_SIGACTION is defined. Fix that if this code
2838 * changes to invalidate that assumption.
2839 */
2840 struct sigaction context, ocontext;
2841 context.sa_handler = handler;
2842 sigemptyset(&context.sa_mask);
2843 context.sa_flags = 0;
2844 if (sigaction(sig, &context, &ocontext) == -1)
2845 return SIG_ERR;
2846 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002847#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 PyOS_sighandler_t oldhandler;
2849 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002850#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002852#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002854#endif
2855}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856
2857/* Deprecated C API functions still provided for binary compatiblity */
2858
2859#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002860PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864}
2865
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002866#undef PyParser_SimpleParseString
2867PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868PyParser_SimpleParseString(const char *str, int start)
2869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002872
2873#undef PyRun_AnyFile
2874PyAPI_FUNC(int)
2875PyRun_AnyFile(FILE *fp, const char *name)
2876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002878}
2879
2880#undef PyRun_AnyFileEx
2881PyAPI_FUNC(int)
2882PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002885}
2886
2887#undef PyRun_AnyFileFlags
2888PyAPI_FUNC(int)
2889PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002892}
2893
2894#undef PyRun_File
2895PyAPI_FUNC(PyObject *)
2896PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002899}
2900
2901#undef PyRun_FileEx
2902PyAPI_FUNC(PyObject *)
2903PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002906}
2907
2908#undef PyRun_FileFlags
2909PyAPI_FUNC(PyObject *)
2910PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002914}
2915
2916#undef PyRun_SimpleFile
2917PyAPI_FUNC(int)
2918PyRun_SimpleFile(FILE *f, const char *p)
2919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002921}
2922
2923#undef PyRun_SimpleFileEx
2924PyAPI_FUNC(int)
2925PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002928}
2929
2930
2931#undef PyRun_String
2932PyAPI_FUNC(PyObject *)
2933PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002936}
2937
2938#undef PyRun_SimpleString
2939PyAPI_FUNC(int)
2940PyRun_SimpleString(const char *s)
2941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002943}
2944
2945#undef Py_CompileString
2946PyAPI_FUNC(PyObject *)
2947Py_CompileString(const char *str, const char *p, int s)
2948{
Georg Brandl8334fd92010-12-04 10:26:46 +00002949 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2950}
2951
2952#undef Py_CompileStringFlags
2953PyAPI_FUNC(PyObject *)
2954Py_CompileStringFlags(const char *str, const char *p, int s,
2955 PyCompilerFlags *flags)
2956{
2957 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002958}
2959
2960#undef PyRun_InteractiveOne
2961PyAPI_FUNC(int)
2962PyRun_InteractiveOne(FILE *f, const char *p)
2963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002965}
2966
2967#undef PyRun_InteractiveLoop
2968PyAPI_FUNC(int)
2969PyRun_InteractiveLoop(FILE *f, const char *p)
2970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002972}
2973
2974#ifdef __cplusplus
2975}
2976#endif