blob: 3adbbd7373642511593aa2f999e5711aa7ebfd69 [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);
Christian Heimes985ecdc2013-11-20 11:46:18 +0100107extern void _PyHash_Fini(void);
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100108extern int _PyTraceMalloc_Init(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +0000109
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000110#ifdef WITH_THREAD
111extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
112extern void _PyGILState_Fini(void);
113#endif /* WITH_THREAD */
114
Guido van Rossum82598051997-03-05 00:20:32 +0000115int Py_DebugFlag; /* Needed by parser.c */
116int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000117int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000118int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200119int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000120int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000121int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000122int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000123int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000124int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000125int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000126int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000127int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100128int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200129int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000130
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200131PyThreadState *_Py_Finalizing = NULL;
132
Christian Heimes49e61802013-10-22 10:22:29 +0200133/* Hack to force loading of object files */
134int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
135 PyOS_mystrnicmp; /* Python/pystrcmp.o */
136
Christian Heimes33fe8092008-04-13 13:53:33 +0000137/* PyModule_GetWarningsModule is no longer necessary as of 2.6
138since _warnings is builtin. This API should not be used. */
139PyObject *
140PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000143}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000144
Guido van Rossum25ce5661997-08-02 03:10:38 +0000145static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000146
Thomas Wouters7e474022000-07-16 12:04:32 +0000147/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000148
149int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000150Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000153}
154
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000155/* Helper to allow an embedding application to override the normal
156 * mechanism that attempts to figure out an appropriate IO encoding
157 */
158
159static char *_Py_StandardStreamEncoding = NULL;
160static char *_Py_StandardStreamErrors = NULL;
161
162int
163Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
164{
165 if (Py_IsInitialized()) {
166 /* This is too late to have any effect */
167 return -1;
168 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000169 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
170 * initialised yet.
171 *
172 * However, the raw memory allocators are initialised appropriately
173 * as C static variables, so _PyMem_RawStrdup is OK even though
174 * Py_Initialize hasn't been called yet.
175 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000176 if (encoding) {
177 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
178 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000179 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000180 }
181 }
182 if (errors) {
183 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
184 if (!_Py_StandardStreamErrors) {
185 if (_Py_StandardStreamEncoding) {
186 PyMem_RawFree(_Py_StandardStreamEncoding);
187 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000188 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000189 }
190 }
191 return 0;
192}
193
Guido van Rossum25ce5661997-08-02 03:10:38 +0000194/* Global initializations. Can be undone by Py_Finalize(). Don't
195 call this twice without an intervening Py_Finalize() call. When
196 initializations fail, a fatal error is issued and the function does
197 not return. On return, the first thread and interpreter state have
198 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000199
Guido van Rossum25ce5661997-08-02 03:10:38 +0000200 Locking: you must hold the interpreter lock while calling this.
201 (If the lock has not yet been initialized, that's equivalent to
202 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000203
Guido van Rossum25ce5661997-08-02 03:10:38 +0000204*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000205
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000206static int
207add_flag(int flag, const char *envs)
208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 int env = atoi(envs);
210 if (flag < env)
211 flag = env;
212 if (flag < 1)
213 flag = 1;
214 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000215}
216
Christian Heimes5833a2f2008-10-30 21:40:04 +0000217static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000218get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000219{
Victor Stinner94908bb2010-08-18 21:23:25 +0000220 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000221 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000222
Victor Stinner94908bb2010-08-18 21:23:25 +0000223 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (!codec)
225 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000226
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200227 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 Py_CLEAR(codec);
229 if (!name)
230 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000231
Victor Stinner94908bb2010-08-18 21:23:25 +0000232 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100233 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000234 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200235 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000237 if (name_str == NULL) {
238 PyErr_NoMemory();
239 return NULL;
240 }
241 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000242
243error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000245 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000247}
Victor Stinner94908bb2010-08-18 21:23:25 +0000248
Victor Stinner94908bb2010-08-18 21:23:25 +0000249static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200250get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000251{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200252#ifdef MS_WINDOWS
253 char codepage[100];
254 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
255 return get_codec_name(codepage);
256#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000257 char* codeset = nl_langinfo(CODESET);
258 if (!codeset || codeset[0] == '\0') {
259 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
260 return NULL;
261 }
262 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200263#else
264 PyErr_SetNone(PyExc_NotImplementedError);
265 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000266#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200267}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000268
Brett Cannonfd074152012-04-14 14:10:13 -0400269static void
270import_init(PyInterpreterState *interp, PyObject *sysmod)
271{
272 PyObject *importlib;
273 PyObject *impmod;
274 PyObject *sys_modules;
275 PyObject *value;
276
277 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400278 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
279 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
280 }
281 else if (Py_VerboseFlag) {
282 PySys_FormatStderr("import _frozen_importlib # frozen\n");
283 }
284 importlib = PyImport_AddModule("_frozen_importlib");
285 if (importlib == NULL) {
286 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
287 "sys.modules");
288 }
289 interp->importlib = importlib;
290 Py_INCREF(interp->importlib);
291
292 /* Install _importlib as __import__ */
293 impmod = PyInit_imp();
294 if (impmod == NULL) {
295 Py_FatalError("Py_Initialize: can't import imp");
296 }
297 else if (Py_VerboseFlag) {
298 PySys_FormatStderr("import imp # builtin\n");
299 }
300 sys_modules = PyImport_GetModuleDict();
301 if (Py_VerboseFlag) {
302 PySys_FormatStderr("import sys # builtin\n");
303 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400304 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
305 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400306 }
307
Brett Cannone0d88a12012-04-25 20:54:04 -0400308 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400309 if (value == NULL) {
310 PyErr_Print();
311 Py_FatalError("Py_Initialize: importlib install failed");
312 }
313 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400314 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400315
316 _PyImportZip_Init();
317}
318
319
Guido van Rossuma027efa1997-05-05 20:56:21 +0000320void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200321_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 PyInterpreterState *interp;
324 PyThreadState *tstate;
325 PyObject *bimod, *sysmod, *pstderr;
326 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (initialized)
330 return;
331 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200332 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000333
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000334#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* Set up the LC_CTYPE locale, so we can obtain
336 the locale's charset without having to switch
337 locales. */
338 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000339#endif
340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
342 Py_DebugFlag = add_flag(Py_DebugFlag, p);
343 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
344 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
345 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
346 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
347 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
348 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100349 /* The variable is only tested for existence here; _PyRandom_Init will
350 check its value further. */
351 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
352 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
353
354 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 interp = PyInterpreterState_New();
357 if (interp == NULL)
358 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 tstate = PyThreadState_New(interp);
361 if (tstate == NULL)
362 Py_FatalError("Py_Initialize: can't make first thread");
363 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000364
Victor Stinner6961bd62010-08-17 22:26:51 +0000365#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000366 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
367 destroying the GIL might fail when it is being referenced from
368 another running thread (see issue #9901).
369 Instead we destroy the previously created GIL here, which ensures
370 that we can call Py_Initialize / Py_Finalize multiple times. */
371 _PyEval_FiniThreads();
372
373 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000374 _PyGILState_Init(interp, tstate);
375#endif /* WITH_THREAD */
376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (!_PyFrame_Init())
380 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (!_PyLong_Init())
383 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (!PyByteArray_Init())
386 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000387
Victor Stinner1c8f0592013-07-22 22:24:54 +0200388 if (!_PyFloat_Init())
389 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 interp->modules = PyDict_New();
392 if (interp->modules == NULL)
393 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200396 if (_PyUnicode_Init() < 0)
397 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200398 if (_PyStructSequence_Init() < 0)
399 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 bimod = _PyBuiltin_Init();
402 if (bimod == NULL)
403 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000404 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 interp->builtins = PyModule_GetDict(bimod);
406 if (interp->builtins == NULL)
407 Py_FatalError("Py_Initialize: can't initialize builtins dict");
408 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400411 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 sysmod = _PySys_Init();
414 if (sysmod == NULL)
415 Py_FatalError("Py_Initialize: can't initialize sys");
416 interp->sysdict = PyModule_GetDict(sysmod);
417 if (interp->sysdict == NULL)
418 Py_FatalError("Py_Initialize: can't initialize sys dict");
419 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000420 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PySys_SetPath(Py_GetPath());
422 PyDict_SetItemString(interp->sysdict, "modules",
423 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* Set up a preliminary stderr printer until we have enough
426 infrastructure for the io module in place. */
427 pstderr = PyFile_NewStdPrinter(fileno(stderr));
428 if (pstderr == NULL)
429 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100430 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000432 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000437
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000438 /* Initialize _warnings. */
439 _PyWarnings_Init();
440
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200441 if (!install_importlib)
442 return;
443
Brett Cannonfd074152012-04-14 14:10:13 -0400444 import_init(interp, sysmod);
445
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200446 /* initialize the faulthandler module */
447 if (_PyFaulthandler_Init())
448 Py_FatalError("Py_Initialize: can't initialize faulthandler");
449
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000450 _PyTime_Init();
451
Victor Stinner793b5312011-04-27 00:24:21 +0200452 if (initfsencoding(interp) < 0)
453 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (install_sigs)
456 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000457
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100458 if (_PyTraceMalloc_Init() < 0)
459 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
460
Nick Coghlan85e729e2012-07-15 18:09:52 +1000461 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 if (initstdio() < 0)
463 Py_FatalError(
464 "Py_Initialize: can't initialize sys standard streams");
465
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000466 /* Initialize warnings. */
467 if (PySys_HasWarnOptions()) {
468 PyObject *warnings_module = PyImport_ImportModule("warnings");
469 if (warnings_module == NULL) {
470 fprintf(stderr, "'import warnings' failed; traceback:\n");
471 PyErr_Print();
472 }
473 Py_XDECREF(warnings_module);
474 }
475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 if (!Py_NoSiteFlag)
477 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000478}
479
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000480void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200481Py_InitializeEx(int install_sigs)
482{
483 _Py_InitializeEx_Private(install_sigs, 1);
484}
485
486void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000487Py_Initialize(void)
488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000490}
491
492
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000493#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000494extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000495#endif
496
Guido van Rossume8432ac2007-07-09 15:04:50 +0000497/* Flush stdout and stderr */
498
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100499static int
500file_is_closed(PyObject *fobj)
501{
502 int r;
503 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
504 if (tmp == NULL) {
505 PyErr_Clear();
506 return 0;
507 }
508 r = PyObject_IsTrue(tmp);
509 Py_DECREF(tmp);
510 if (r < 0)
511 PyErr_Clear();
512 return r > 0;
513}
514
Neal Norwitz2bad9702007-08-27 06:19:22 +0000515static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000516flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000517{
Victor Stinnerbd303c12013-11-07 23:07:29 +0100518 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
519 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000521
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100522 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200523 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000525 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 else
527 Py_DECREF(tmp);
528 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000529
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100530 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200531 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (tmp == NULL)
533 PyErr_Clear();
534 else
535 Py_DECREF(tmp);
536 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000537}
538
Guido van Rossum25ce5661997-08-02 03:10:38 +0000539/* Undo the effect of Py_Initialize().
540
541 Beware: if multiple interpreter and/or thread states exist, these
542 are not wiped out; only the current thread and interpreter state
543 are deleted. But since everything else is deleted, those other
544 interpreter and thread states should no longer be used.
545
546 (XXX We should do better, e.g. wipe out all interpreters and
547 threads.)
548
549 Locking: as above.
550
551*/
552
553void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000554Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyInterpreterState *interp;
557 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (!initialized)
560 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 /* The interpreter is still entirely intact at this point, and the
565 * exit funcs may be relying on that. In particular, if some thread
566 * or exit func is still waiting to do an import, the import machinery
567 * expects Py_IsInitialized() to return true. So don't say the
568 * interpreter is uninitialized until after the exit funcs have run.
569 * Note that Threading.py uses an exit func to do a join on all the
570 * threads created thru it, so this also protects pending imports in
571 * the threads created via Threading.
572 */
573 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* Get current thread state and interpreter pointer */
576 tstate = PyThreadState_GET();
577 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000578
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200579 /* Remaining threads (e.g. daemon threads) will automatically exit
580 after taking the GIL (in PyEval_RestoreThread()). */
581 _Py_Finalizing = tstate;
582 initialized = 0;
583
Victor Stinner45956b92013-11-12 16:37:55 +0100584 /* Destroy the state of all threads except of the current thread: in
585 practice, only daemon threads should still be alive. Clear frames of
586 other threads to call objects destructor. Destructors will be called in
587 the current Python thread. Since _Py_Finalizing has been set, no other
588 Python threads can lock the GIL at this point (if they try, they will
Victor Stinnerdcf17f82013-11-12 17:18:51 +0100589 exit immediately). */
Victor Stinner45956b92013-11-12 16:37:55 +0100590 _PyThreadState_DeleteExcept(tstate);
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 /* Collect garbage. This may call finalizers; it's nice to call these
593 * before all modules are destroyed.
594 * XXX If a __del__ or weakref callback is triggered here, and tries to
595 * XXX import a module, bad things can happen, because Python no
596 * XXX longer believes it's initialized.
597 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
598 * XXX is easy to provoke that way. I've also seen, e.g.,
599 * XXX Exception exceptions.ImportError: 'No module named sha'
600 * XXX in <function callback at 0x008F5718> ignored
601 * XXX but I'm unclear on exactly how that one happens. In any case,
602 * XXX I haven't seen a real-life report of either of these.
603 */
604 PyGC_Collect();
Victor Stinner45956b92013-11-12 16:37:55 +0100605
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000606#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 /* With COUNT_ALLOCS, it helps to run GC multiple times:
608 each collection might release some types from the type
609 list, so they become garbage. */
610 while (PyGC_Collect() > 0)
611 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000612#endif
Victor Stinner45956b92013-11-12 16:37:55 +0100613
614 /* Flush stdout+stderr */
615 flush_std_files();
616
617 /* Disable signal handling */
618 PyOS_FiniInterrupts();
619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 /* Destroy all modules */
621 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 /* Flush stdout+stderr (again, in case more was printed) */
624 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100627 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 * XXX This is disabled because it caused too many problems. If
629 * XXX a __del__ or weakref callback triggers here, Python code has
630 * XXX a hard time running, because even the sys module has been
631 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
632 * XXX One symptom is a sequence of information-free messages
633 * XXX coming from threads (if a __del__ or callback is invoked,
634 * XXX other threads can execute too, and any exception they encounter
635 * XXX triggers a comedy of errors as subsystem after subsystem
636 * XXX fails to find what it *expects* to find in sys to help report
637 * XXX the exception and consequent unexpected failures). I've also
638 * XXX seen segfaults then, after adding print statements to the
639 * XXX Python code getting called.
640 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000641#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000643#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
646 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000647
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200648 /* Cleanup typeobject.c's internal caches. */
649 _PyType_Fini();
650
Victor Stinner024e37a2011-03-31 01:31:06 +0200651 /* unload faulthandler module */
652 _PyFaulthandler_Fini();
653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000655#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000657#endif
Christian Heimes985ecdc2013-11-20 11:46:18 +0100658 /* dump hash stats */
659 _PyHash_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000662
Tim Peters9cf25ce2003-04-17 15:21:01 +0000663#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 /* Display all objects still alive -- this can invoke arbitrary
665 * __repr__ overrides, so requires a mostly-intact interpreter.
666 * Alas, a lot of stuff may still be alive now that will be cleaned
667 * up later.
668 */
669 if (Py_GETENV("PYTHONDUMPREFS"))
670 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000671#endif /* Py_TRACE_REFS */
672
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200673 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 /* Now we decref the exception classes. After this point nothing
677 can raise an exception. That's okay, because each Fini() method
678 below has been checked to make sure no exceptions are ever
679 raised.
680 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 /* Sundry finalizers */
685 PyMethod_Fini();
686 PyFrame_Fini();
687 PyCFunction_Fini();
688 PyTuple_Fini();
689 PyList_Fini();
690 PySet_Fini();
691 PyBytes_Fini();
692 PyByteArray_Fini();
693 PyLong_Fini();
694 PyFloat_Fini();
695 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100696 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200697 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200698 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Cleanup Unicode implementation */
701 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000704 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200705 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 Py_FileSystemDefaultEncoding = NULL;
707 }
Christian Heimesc8967002007-11-30 10:18:26 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 /* XXX Still allocated:
710 - various static ad-hoc pointers to interned strings
711 - int and float free list blocks
712 - whatever various modules and libraries allocate
713 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000716
Victor Stinner51fa4582013-07-07 15:50:49 +0200717 /* Cleanup auto-thread-state */
718#ifdef WITH_THREAD
719 _PyGILState_Fini();
720#endif /* WITH_THREAD */
721
722 /* Delete current thread. After this, many C API calls become crashy. */
723 PyThreadState_Swap(NULL);
724 PyInterpreterState_Delete(interp);
725
Tim Peters269b2a62003-04-17 19:52:29 +0000726#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 /* Display addresses (& refcnts) of all objects still alive.
728 * An address can be used to find the repr of the object, printed
729 * above by _Py_PrintReferences.
730 */
731 if (Py_GETENV("PYTHONDUMPREFS"))
732 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000733#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000734#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400736 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000737#endif
738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000740}
741
742/* Create and initialize a new interpreter and thread, and return the
743 new thread. This requires that Py_Initialize() has been called
744 first.
745
746 Unsuccessful initialization yields a NULL pointer. Note that *no*
747 exception information is available even in this case -- the
748 exception information is held in the thread, and there is no
749 thread.
750
751 Locking: as above.
752
753*/
754
755PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000756Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyInterpreterState *interp;
759 PyThreadState *tstate, *save_tstate;
760 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (!initialized)
763 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 interp = PyInterpreterState_New();
766 if (interp == NULL)
767 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 tstate = PyThreadState_New(interp);
770 if (tstate == NULL) {
771 PyInterpreterState_Delete(interp);
772 return NULL;
773 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000780
Victor Stinner49d3f252010-10-17 01:24:53 +0000781 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (bimod != NULL) {
783 interp->builtins = PyModule_GetDict(bimod);
784 if (interp->builtins == NULL)
785 goto handle_error;
786 Py_INCREF(interp->builtins);
787 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400790 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000791
Victor Stinner49d3f252010-10-17 01:24:53 +0000792 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 if (bimod != NULL && sysmod != NULL) {
794 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 interp->sysdict = PyModule_GetDict(sysmod);
797 if (interp->sysdict == NULL)
798 goto handle_error;
799 Py_INCREF(interp->sysdict);
800 PySys_SetPath(Py_GetPath());
801 PyDict_SetItemString(interp->sysdict, "modules",
802 interp->modules);
803 /* Set up a preliminary stderr printer until we have enough
804 infrastructure for the io module in place. */
805 pstderr = PyFile_NewStdPrinter(fileno(stderr));
806 if (pstderr == NULL)
807 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100808 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000810 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200813
Brett Cannonfd074152012-04-14 14:10:13 -0400814 import_init(interp, sysmod);
815
Victor Stinner793b5312011-04-27 00:24:21 +0200816 if (initfsencoding(interp) < 0)
817 goto handle_error;
818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (initstdio() < 0)
820 Py_FatalError(
821 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000822 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (!Py_NoSiteFlag)
824 initsite();
825 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (!PyErr_Occurred())
828 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000829
Thomas Wouters89f507f2006-12-13 04:49:30 +0000830handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000832
Victor Stinnerc40a3502011-04-27 00:20:27 +0200833 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyThreadState_Clear(tstate);
835 PyThreadState_Swap(save_tstate);
836 PyThreadState_Delete(tstate);
837 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000840}
841
842/* Delete an interpreter and its last thread. This requires that the
843 given thread state is current, that the thread has no remaining
844 frames, and that it is its interpreter's only remaining thread.
845 It is a fatal error to violate these constraints.
846
847 (Py_Finalize() doesn't have these constraints -- it zaps
848 everything, regardless.)
849
850 Locking: as above.
851
852*/
853
854void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000855Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (tstate != PyThreadState_GET())
860 Py_FatalError("Py_EndInterpreter: thread is not current");
861 if (tstate->frame != NULL)
862 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200863
864 wait_for_thread_shutdown();
865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (tstate != interp->tstate_head || tstate->next != NULL)
867 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyImport_Cleanup();
870 PyInterpreterState_Clear(interp);
871 PyThreadState_Swap(NULL);
872 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000873}
874
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200875#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000876static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200877#else
878static wchar_t *progname = L"python3";
879#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000880
881void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000882Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (pn && *pn)
885 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000886}
887
Martin v. Löwis790465f2008-04-05 20:41:37 +0000888wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000889Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000892}
893
Martin v. Löwis790465f2008-04-05 20:41:37 +0000894static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200895static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000896
897void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000898Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000901}
902
Martin v. Löwis790465f2008-04-05 20:41:37 +0000903wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000904Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 wchar_t *home = default_home;
907 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
908 char* chome = Py_GETENV("PYTHONHOME");
909 if (chome) {
Victor Stinner2f5bbc62013-11-15 17:09:24 +0100910 size_t size = Py_ARRAY_LENGTH(env_home);
911 size_t r = mbstowcs(env_home, chome, size);
912 if (r != (size_t)-1 && r < size)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 home = env_home;
914 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 }
917 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000918}
919
Guido van Rossum6135a871995-01-09 17:53:26 +0000920/* Create __main__ module */
921
922static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000923initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000924{
Brett Cannon13853a62013-05-04 17:37:09 -0400925 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 m = PyImport_AddModule("__main__");
927 if (m == NULL)
928 Py_FatalError("can't create __main__ module");
929 d = PyModule_GetDict(m);
930 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
931 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000932 if (bimod == NULL) {
933 Py_FatalError("Failed to retrieve builtins module");
934 }
935 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
936 Py_FatalError("Failed to initialize __main__.__builtins__");
937 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 Py_DECREF(bimod);
939 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000940 /* Main is a little special - imp.is_builtin("__main__") will return
941 * False, but BuiltinImporter is still the most appropriate initial
942 * setting for its __loader__ attribute. A more suitable value will
943 * be set if __main__ gets further initialized later in the startup
944 * process.
945 */
Brett Cannon13853a62013-05-04 17:37:09 -0400946 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400947 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000948 PyObject *loader = PyObject_GetAttrString(interp->importlib,
949 "BuiltinImporter");
950 if (loader == NULL) {
951 Py_FatalError("Failed to retrieve BuiltinImporter");
952 }
953 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
954 Py_FatalError("Failed to initialize __main__.__loader__");
955 }
956 Py_DECREF(loader);
957 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000958}
959
Victor Stinner793b5312011-04-27 00:24:21 +0200960static int
961initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000962{
963 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000964
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200965 if (Py_FileSystemDefaultEncoding == NULL)
966 {
967 Py_FileSystemDefaultEncoding = get_locale_encoding();
968 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000969 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000970
Victor Stinnere4743092010-10-19 00:05:51 +0000971 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200972 interp->fscodec_initialized = 1;
973 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000974 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000975
976 /* the encoding is mbcs, utf-8 or ascii */
977 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
978 if (!codec) {
979 /* Such error can only occurs in critical situations: no more
980 * memory, import a module of the standard library failed,
981 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200982 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000983 }
Victor Stinner793b5312011-04-27 00:24:21 +0200984 Py_DECREF(codec);
985 interp->fscodec_initialized = 1;
986 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000987}
988
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000989/* Import the site module (not into __main__ though) */
990
991static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000992initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyObject *m;
995 m = PyImport_ImportModule("site");
996 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200997 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 PyErr_Print();
999 Py_Finalize();
1000 exit(1);
1001 }
1002 else {
1003 Py_DECREF(m);
1004 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001005}
1006
Antoine Pitrou05608432009-01-09 18:53:14 +00001007static PyObject*
1008create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 int fd, int write_mode, char* name,
1010 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +00001011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1013 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001014 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 PyObject *line_buffering;
1016 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001017 _Py_IDENTIFIER(open);
1018 _Py_IDENTIFIER(isatty);
1019 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001020 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 /* stdin is always opened in buffered mode, first because it shouldn't
1023 make a difference in common use cases, second because TextIOWrapper
1024 depends on the presence of a read1() method which only exists on
1025 buffered streams.
1026 */
1027 if (Py_UnbufferedStdioFlag && write_mode)
1028 buffering = 0;
1029 else
1030 buffering = -1;
1031 if (write_mode)
1032 mode = "wb";
1033 else
1034 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001035 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1036 fd, mode, buffering,
1037 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 if (buf == NULL)
1039 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001042 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001043 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (raw == NULL)
1045 goto error;
1046 }
1047 else {
1048 raw = buf;
1049 Py_INCREF(raw);
1050 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001053 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001055 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (res == NULL)
1057 goto error;
1058 isatty = PyObject_IsTrue(res);
1059 Py_DECREF(res);
1060 if (isatty == -1)
1061 goto error;
1062 if (isatty || Py_UnbufferedStdioFlag)
1063 line_buffering = Py_True;
1064 else
1065 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 Py_CLEAR(raw);
1068 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001069
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001070#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001071 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1072 newlines to "\n".
1073 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1074 newline = NULL;
1075#else
1076 /* sys.stdin: split lines at "\n".
1077 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1078 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001079#endif
1080
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001081 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1082 buf, encoding, errors,
1083 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 Py_CLEAR(buf);
1085 if (stream == NULL)
1086 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (write_mode)
1089 mode = "w";
1090 else
1091 mode = "r";
1092 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001093 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 goto error;
1095 Py_CLEAR(text);
1096 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001097
1098error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 Py_XDECREF(buf);
1100 Py_XDECREF(stream);
1101 Py_XDECREF(text);
1102 Py_XDECREF(raw);
1103 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001104}
1105
Antoine Pitrou11942a52011-11-28 19:08:36 +01001106static int
1107is_valid_fd(int fd)
1108{
1109 int dummy_fd;
1110 if (fd < 0 || !_PyVerify_fd(fd))
1111 return 0;
1112 dummy_fd = dup(fd);
1113 if (dummy_fd < 0)
1114 return 0;
1115 close(dummy_fd);
1116 return 1;
1117}
1118
Georg Brandl1a3284e2007-12-02 09:40:06 +00001119/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001120static int
1121initstdio(void)
1122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 PyObject *iomod = NULL, *wrapper;
1124 PyObject *bimod = NULL;
1125 PyObject *m;
1126 PyObject *std = NULL;
1127 int status = 0, fd;
1128 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001129 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 /* Hack to avoid a nasty recursion issue when Python is invoked
1132 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1133 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1134 goto error;
1135 }
1136 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1139 goto error;
1140 }
1141 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (!(bimod = PyImport_ImportModule("builtins"))) {
1144 goto error;
1145 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (!(iomod = PyImport_ImportModule("io"))) {
1148 goto error;
1149 }
1150 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1151 goto error;
1152 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 /* Set builtins.open */
1155 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001156 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 goto error;
1158 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001159 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001160
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001161 encoding = _Py_StandardStreamEncoding;
1162 errors = _Py_StandardStreamErrors;
1163 if (!encoding || !errors) {
1164 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1165 if (pythonioencoding) {
1166 char *err;
1167 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1168 if (pythonioencoding == NULL) {
1169 PyErr_NoMemory();
1170 goto error;
1171 }
1172 err = strchr(pythonioencoding, ':');
1173 if (err) {
1174 *err = '\0';
1175 err++;
1176 if (*err && !errors) {
1177 errors = err;
1178 }
1179 }
1180 if (*pythonioencoding && !encoding) {
1181 encoding = pythonioencoding;
1182 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001183 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 /* Set sys.stdin */
1187 fd = fileno(stdin);
1188 /* Under some conditions stdin, stdout and stderr may not be connected
1189 * and fileno() may point to an invalid file descriptor. For example
1190 * GUI apps don't have valid standard streams by default.
1191 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001192 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 std = Py_None;
1194 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 }
1196 else {
1197 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1198 if (std == NULL)
1199 goto error;
1200 } /* if (fd < 0) */
1201 PySys_SetObject("__stdin__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001202 _PySys_SetObjectId(&PyId_stdin, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 /* Set sys.stdout */
1206 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001207 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 std = Py_None;
1209 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 }
1211 else {
1212 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1213 if (std == NULL)
1214 goto error;
1215 } /* if (fd < 0) */
1216 PySys_SetObject("__stdout__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001217 _PySys_SetObjectId(&PyId_stdout, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001219
Guido van Rossum98297ee2007-11-06 21:34:58 +00001220#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 /* Set sys.stderr, replaces the preliminary stderr */
1222 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001223 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 std = Py_None;
1225 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 }
1227 else {
1228 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1229 if (std == NULL)
1230 goto error;
1231 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 /* Same as hack above, pre-import stderr's codec to avoid recursion
1234 when import.c tries to write to stderr in verbose mode. */
1235 encoding_attr = PyObject_GetAttrString(std, "encoding");
1236 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001237 const char * std_encoding;
1238 std_encoding = _PyUnicode_AsString(encoding_attr);
1239 if (std_encoding != NULL) {
1240 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001241 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001243 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 }
1245 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001246
Victor Stinnerba308832013-07-22 23:55:19 +02001247 if (PySys_SetObject("__stderr__", std) < 0) {
1248 Py_DECREF(std);
1249 goto error;
1250 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001251 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
Victor Stinnerba308832013-07-22 23:55:19 +02001252 Py_DECREF(std);
1253 goto error;
1254 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001256#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001259 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 status = -1;
1261 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001262
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001263 /* We won't need them anymore. */
1264 if (_Py_StandardStreamEncoding) {
1265 PyMem_RawFree(_Py_StandardStreamEncoding);
1266 _Py_StandardStreamEncoding = NULL;
1267 }
1268 if (_Py_StandardStreamErrors) {
1269 PyMem_RawFree(_Py_StandardStreamErrors);
1270 _Py_StandardStreamErrors = NULL;
1271 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001272 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 Py_XDECREF(bimod);
1274 Py_XDECREF(iomod);
1275 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001276}
1277
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001278/* Parse input from a file and execute it */
1279
1280int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001281PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (filename == NULL)
1285 filename = "???";
1286 if (Py_FdIsInteractive(fp, filename)) {
1287 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1288 if (closeit)
1289 fclose(fp);
1290 return err;
1291 }
1292 else
1293 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001294}
1295
1296int
Victor Stinner95701bd2013-11-06 18:41:07 +01001297PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001298{
Victor Stinner95701bd2013-11-06 18:41:07 +01001299 PyObject *filename, *v;
1300 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001302
Victor Stinner95701bd2013-11-06 18:41:07 +01001303 filename = PyUnicode_DecodeFSDefault(filename_str);
1304 if (filename == NULL) {
1305 PyErr_Print();
1306 return -1;
1307 }
1308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (flags == NULL) {
1310 flags = &local_flags;
1311 local_flags.cf_flags = 0;
1312 }
Victor Stinner09054372013-11-06 22:41:44 +01001313 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001315 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 Py_XDECREF(v);
1317 }
Victor Stinner09054372013-11-06 22:41:44 +01001318 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001320 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 Py_XDECREF(v);
1322 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001323 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001325 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001327 if (ret == E_EOF) {
1328 err = 0;
1329 break;
1330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /*
1332 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001333 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 */
1335 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001336 Py_DECREF(filename);
1337 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001338}
1339
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001340/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001341static int PARSER_FLAGS(PyCompilerFlags *flags)
1342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 int parser_flags = 0;
1344 if (!flags)
1345 return 0;
1346 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1347 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1348 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1349 parser_flags |= PyPARSE_IGNORE_COOKIE;
1350 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1351 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1352 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001353}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001354
Thomas Wouters89f507f2006-12-13 04:49:30 +00001355#if 0
1356/* Keep an example of flags with future keyword support. */
1357#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1359 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1360 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1361 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001362#endif
1363
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001364int
Victor Stinner95701bd2013-11-06 18:41:07 +01001365PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001366{
Victor Stinner95701bd2013-11-06 18:41:07 +01001367 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 mod_ty mod;
1369 PyArena *arena;
1370 char *ps1 = "", *ps2 = "", *enc = NULL;
1371 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001372 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001373 _Py_IDENTIFIER(__main__);
1374
1375 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1376 if (mod_name == NULL) {
1377 PyErr_Print();
1378 return -1;
1379 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001382 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +01001383 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001384 if (v && v != Py_None) {
1385 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1386 if (oenc)
1387 enc = _PyUnicode_AsString(oenc);
1388 if (!enc)
1389 PyErr_Clear();
1390 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 }
Victor Stinner09054372013-11-06 22:41:44 +01001392 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (v != NULL) {
1394 v = PyObject_Str(v);
1395 if (v == NULL)
1396 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001397 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001399 if (ps1 == NULL) {
1400 PyErr_Clear();
1401 ps1 = "";
1402 }
1403 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 }
Victor Stinner09054372013-11-06 22:41:44 +01001405 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (w != NULL) {
1407 w = PyObject_Str(w);
1408 if (w == NULL)
1409 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001410 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001412 if (ps2 == NULL) {
1413 PyErr_Clear();
1414 ps2 = "";
1415 }
1416 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 }
1418 arena = PyArena_New();
1419 if (arena == NULL) {
1420 Py_XDECREF(v);
1421 Py_XDECREF(w);
1422 Py_XDECREF(oenc);
1423 return -1;
1424 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001425 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1426 Py_single_input, ps1, ps2,
1427 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 Py_XDECREF(v);
1429 Py_XDECREF(w);
1430 Py_XDECREF(oenc);
1431 if (mod == NULL) {
1432 PyArena_Free(arena);
1433 if (errcode == E_EOF) {
1434 PyErr_Clear();
1435 return E_EOF;
1436 }
1437 PyErr_Print();
1438 return -1;
1439 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001440 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (m == NULL) {
1442 PyArena_Free(arena);
1443 return -1;
1444 }
1445 d = PyModule_GetDict(m);
1446 v = run_mod(mod, filename, d, d, flags, arena);
1447 PyArena_Free(arena);
1448 flush_io();
1449 if (v == NULL) {
1450 PyErr_Print();
1451 return -1;
1452 }
1453 Py_DECREF(v);
1454 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001455}
1456
Victor Stinner95701bd2013-11-06 18:41:07 +01001457int
1458PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1459{
1460 PyObject *filename;
1461 int res;
1462
1463 filename = PyUnicode_DecodeFSDefault(filename_str);
1464 if (filename == NULL) {
1465 PyErr_Print();
1466 return -1;
1467 }
1468 res = PyRun_InteractiveOneObject(fp, filename, flags);
1469 Py_DECREF(filename);
1470 return res;
1471}
1472
1473
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001474/* Check whether a file maybe a pyc file: Look at the extension,
1475 the file type, and, if we may close it, at the first few bytes. */
1476
1477static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001478maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1481 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 /* Only look into the file if we are allowed to close it, since
1484 it then should also be seekable. */
1485 if (closeit) {
1486 /* Read only two bytes of the magic. If the file was opened in
1487 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1488 be read as they are on disk. */
1489 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1490 unsigned char buf[2];
1491 /* Mess: In case of -x, the stream is NOT at its start now,
1492 and ungetc() was used to push back the first newline,
1493 which makes the current stream position formally undefined,
1494 and a x-platform nightmare.
1495 Unfortunately, we have no direct way to know whether -x
1496 was specified. So we use a terrible hack: if the current
1497 stream position is not 0, we assume -x was specified, and
1498 give up. Bug 132850 on SourceForge spells out the
1499 hopelessness of trying anything else (fseek and ftell
1500 don't work predictably x-platform for text-mode files).
1501 */
1502 int ispyc = 0;
1503 if (ftell(fp) == 0) {
1504 if (fread(buf, 1, 2, fp) == 2 &&
1505 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1506 ispyc = 1;
1507 rewind(fp);
1508 }
1509 return ispyc;
1510 }
1511 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001512}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001513
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001514static int
1515set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001516{
1517 PyInterpreterState *interp;
1518 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001519 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001520 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001521
1522 filename_obj = PyUnicode_DecodeFSDefault(filename);
1523 if (filename_obj == NULL)
1524 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001525 /* Get current thread state and interpreter pointer */
1526 tstate = PyThreadState_GET();
1527 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001528 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1529 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001530 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001531 return -1;
1532 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001533 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001534 Py_DECREF(loader_type);
1535 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001536 return -1;
1537 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001538 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1539 result = -1;
1540 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001541 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001542 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001543}
1544
1545int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001546PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 PyObject *m, *d, *v;
1550 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001551 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001552 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 m = PyImport_AddModule("__main__");
1555 if (m == NULL)
1556 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001557 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 d = PyModule_GetDict(m);
1559 if (PyDict_GetItemString(d, "__file__") == NULL) {
1560 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001561 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001563 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1565 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001566 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001568 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1569 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001570 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001571 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 set_file_name = 1;
1573 Py_DECREF(f);
1574 }
1575 len = strlen(filename);
1576 ext = filename + len - (len > 4 ? 4 : 0);
1577 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001578 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 /* Try to run a pyc file. First, re-open in binary */
1580 if (closeit)
1581 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001582 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 goto done;
1585 }
1586 /* Turn on optimization if a .pyo file is given */
1587 if (strcmp(ext, ".pyo") == 0)
1588 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001589
1590 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1591 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1592 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001593 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001594 goto done;
1595 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001596 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1597 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001599 /* When running from stdin, leave __main__.__loader__ alone */
1600 if (strcmp(filename, "<stdin>") != 0 &&
1601 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1602 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1603 ret = -1;
1604 goto done;
1605 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1607 closeit, flags);
1608 }
1609 flush_io();
1610 if (v == NULL) {
1611 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 goto done;
1613 }
1614 Py_DECREF(v);
1615 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001616 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1618 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001619 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001621}
1622
1623int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001624PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 PyObject *m, *d, *v;
1627 m = PyImport_AddModule("__main__");
1628 if (m == NULL)
1629 return -1;
1630 d = PyModule_GetDict(m);
1631 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1632 if (v == NULL) {
1633 PyErr_Print();
1634 return -1;
1635 }
1636 Py_DECREF(v);
1637 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001638}
1639
Barry Warsaw035574d1997-08-29 22:07:17 +00001640static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001641parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
1642 int *lineno, int *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 long hold;
1645 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001646 _Py_IDENTIFIER(msg);
1647 _Py_IDENTIFIER(filename);
1648 _Py_IDENTIFIER(lineno);
1649 _Py_IDENTIFIER(offset);
1650 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001651
Benjamin Peterson80d50422012-04-03 00:30:38 -04001652 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001653 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001656 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001657 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001659
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001660 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001661 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001663 if (v == Py_None) {
1664 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001665 *filename = _PyUnicode_FromId(&PyId_string);
1666 if (*filename == NULL)
1667 goto finally;
1668 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001669 }
1670 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001671 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001672 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001673
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001674 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001675 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 goto finally;
1677 hold = PyLong_AsLong(v);
1678 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (hold < 0 && PyErr_Occurred())
1680 goto finally;
1681 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001682
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001683 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001684 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 goto finally;
1686 if (v == Py_None) {
1687 *offset = -1;
1688 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 } else {
1690 hold = PyLong_AsLong(v);
1691 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (hold < 0 && PyErr_Occurred())
1693 goto finally;
1694 *offset = (int)hold;
1695 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001696
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001697 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001698 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001700 if (v == Py_None) {
1701 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001703 }
1704 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001705 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001706 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001708
1709finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001710 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001711 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001713}
1714
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001715void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001716PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001719}
1720
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001721static void
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001722print_error_text(PyObject *f, int offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001723{
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001724 char *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 char *nl;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001726
1727 text = _PyUnicode_AsString(text_obj);
1728 if (text == NULL)
1729 return;
1730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001732 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1733 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 for (;;) {
1735 nl = strchr(text, '\n');
1736 if (nl == NULL || nl-text >= offset)
1737 break;
1738 offset -= (int)(nl+1-text);
1739 text = nl+1;
1740 }
1741 while (*text == ' ' || *text == '\t') {
1742 text++;
1743 offset--;
1744 }
1745 }
1746 PyFile_WriteString(" ", f);
1747 PyFile_WriteString(text, f);
1748 if (*text == '\0' || text[strlen(text)-1] != '\n')
1749 PyFile_WriteString("\n", f);
1750 if (offset == -1)
1751 return;
1752 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001753 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001756}
1757
Guido van Rossum66e8e862001-03-23 17:54:43 +00001758static void
1759handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 PyObject *exception, *value, *tb;
1762 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 if (Py_InspectFlag)
1765 /* Don't exit if -i flag was given. This flag is set to 0
1766 * when entering interactive mode for inspecting. */
1767 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 PyErr_Fetch(&exception, &value, &tb);
1770 fflush(stdout);
1771 if (value == NULL || value == Py_None)
1772 goto done;
1773 if (PyExceptionInstance_Check(value)) {
1774 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001775 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001776 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (code) {
1778 Py_DECREF(value);
1779 value = code;
1780 if (value == Py_None)
1781 goto done;
1782 }
1783 /* If we failed to dig out the 'code' attribute,
1784 just let the else clause below print the error. */
1785 }
1786 if (PyLong_Check(value))
1787 exitcode = (int)PyLong_AsLong(value);
1788 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001789 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner7126dbc2010-05-21 23:45:42 +00001790 if (sys_stderr != NULL && sys_stderr != Py_None) {
1791 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1792 } else {
1793 PyObject_Print(value, stderr, Py_PRINT_RAW);
1794 fflush(stderr);
1795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 PySys_WriteStderr("\n");
1797 exitcode = 1;
1798 }
Tim Peterscf615b52003-04-19 18:47:02 +00001799 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 /* Restore and clear the exception info, in order to properly decref
1801 * the exception, value, and traceback. If we just exit instead,
1802 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1803 * some finalizers from running.
1804 */
1805 PyErr_Restore(exception, value, tb);
1806 PyErr_Clear();
1807 Py_Exit(exitcode);
1808 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001809}
1810
1811void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001812PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1817 handle_system_exit();
1818 }
1819 PyErr_Fetch(&exception, &v, &tb);
1820 if (exception == NULL)
1821 return;
1822 PyErr_NormalizeException(&exception, &v, &tb);
1823 if (tb == NULL) {
1824 tb = Py_None;
1825 Py_INCREF(tb);
1826 }
1827 PyException_SetTraceback(v, tb);
1828 if (exception == NULL)
1829 return;
1830 /* Now we know v != NULL too */
1831 if (set_sys_last_vars) {
Victor Stinner09054372013-11-06 22:41:44 +01001832 _PySys_SetObjectId(&PyId_last_type, exception);
1833 _PySys_SetObjectId(&PyId_last_value, v);
1834 _PySys_SetObjectId(&PyId_last_traceback, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 }
Victor Stinner09054372013-11-06 22:41:44 +01001836 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 if (hook) {
1838 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1839 PyObject *result = PyEval_CallObject(hook, args);
1840 if (result == NULL) {
1841 PyObject *exception2, *v2, *tb2;
1842 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1843 handle_system_exit();
1844 }
1845 PyErr_Fetch(&exception2, &v2, &tb2);
1846 PyErr_NormalizeException(&exception2, &v2, &tb2);
1847 /* It should not be possible for exception2 or v2
1848 to be NULL. However PyErr_Display() can't
1849 tolerate NULLs, so just be safe. */
1850 if (exception2 == NULL) {
1851 exception2 = Py_None;
1852 Py_INCREF(exception2);
1853 }
1854 if (v2 == NULL) {
1855 v2 = Py_None;
1856 Py_INCREF(v2);
1857 }
1858 fflush(stdout);
1859 PySys_WriteStderr("Error in sys.excepthook:\n");
1860 PyErr_Display(exception2, v2, tb2);
1861 PySys_WriteStderr("\nOriginal exception was:\n");
1862 PyErr_Display(exception, v, tb);
1863 Py_DECREF(exception2);
1864 Py_DECREF(v2);
1865 Py_XDECREF(tb2);
1866 }
1867 Py_XDECREF(result);
1868 Py_XDECREF(args);
1869 } else {
1870 PySys_WriteStderr("sys.excepthook is missing\n");
1871 PyErr_Display(exception, v, tb);
1872 }
1873 Py_XDECREF(exception);
1874 Py_XDECREF(v);
1875 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001876}
1877
Benjamin Petersone6528212008-07-15 15:32:09 +00001878static void
1879print_exception(PyObject *f, PyObject *value)
1880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 int err = 0;
1882 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001883 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if (!PyExceptionInstance_Check(value)) {
1886 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1887 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1888 PyFile_WriteString(" found\n", f);
1889 return;
1890 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 Py_INCREF(value);
1893 fflush(stdout);
1894 type = (PyObject *) Py_TYPE(value);
1895 tb = PyException_GetTraceback(value);
1896 if (tb && tb != Py_None)
1897 err = PyTraceBack_Print(tb, f);
1898 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001899 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001901 PyObject *message, *filename, *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 int lineno, offset;
1903 if (!parse_syntax_error(value, &message, &filename,
1904 &lineno, &offset, &text))
1905 PyErr_Clear();
1906 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001907 PyObject *line;
1908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 Py_DECREF(value);
1910 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001911
1912 line = PyUnicode_FromFormat(" File \"%U\", line %d\n",
1913 filename, lineno);
1914 Py_DECREF(filename);
1915 if (line != NULL) {
1916 PyFile_WriteObject(line, f, Py_PRINT_RAW);
1917 Py_DECREF(line);
1918 }
1919
1920 if (text != NULL) {
1921 print_error_text(f, offset, text);
1922 Py_DECREF(text);
1923 }
1924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 /* Can't be bothered to check all those
1926 PyFile_WriteString() calls */
1927 if (PyErr_Occurred())
1928 err = -1;
1929 }
1930 }
1931 if (err) {
1932 /* Don't do anything else */
1933 }
1934 else {
1935 PyObject* moduleName;
1936 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001937 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 assert(PyExceptionClass_Check(type));
1939 className = PyExceptionClass_Name(type);
1940 if (className != NULL) {
1941 char *dot = strrchr(className, '.');
1942 if (dot != NULL)
1943 className = dot+1;
1944 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001945
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001946 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1948 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001949 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 err = PyFile_WriteString("<unknown>", f);
1951 }
1952 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001953 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 {
Victor Stinner937114f2013-11-07 00:12:30 +01001955 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 err += PyFile_WriteString(".", f);
1957 }
1958 Py_DECREF(moduleName);
1959 }
1960 if (err == 0) {
1961 if (className == NULL)
1962 err = PyFile_WriteString("<unknown>", f);
1963 else
1964 err = PyFile_WriteString(className, f);
1965 }
1966 }
1967 if (err == 0 && (value != Py_None)) {
1968 PyObject *s = PyObject_Str(value);
1969 /* only print colon if the str() of the
1970 object is not the empty string
1971 */
1972 if (s == NULL)
1973 err = -1;
1974 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001975 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 err = PyFile_WriteString(": ", f);
1977 if (err == 0)
1978 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1979 Py_XDECREF(s);
1980 }
1981 /* try to write a newline in any case */
1982 err += PyFile_WriteString("\n", f);
1983 Py_XDECREF(tb);
1984 Py_DECREF(value);
1985 /* If an error happened here, don't show it.
1986 XXX This is wrong, but too many callers rely on this behavior. */
1987 if (err != 0)
1988 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001989}
1990
1991static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 "\nThe above exception was the direct cause "
1993 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001994
1995static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 "\nDuring handling of the above exception, "
1997 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001998
1999static void
2000print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
2001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 int err = 0, res;
2003 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 if (seen != NULL) {
2006 /* Exception chaining */
2007 if (PySet_Add(seen, value) == -1)
2008 PyErr_Clear();
2009 else if (PyExceptionInstance_Check(value)) {
2010 cause = PyException_GetCause(value);
2011 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002012 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 res = PySet_Contains(seen, cause);
2014 if (res == -1)
2015 PyErr_Clear();
2016 if (res == 0) {
2017 print_exception_recursive(
2018 f, cause, seen);
2019 err |= PyFile_WriteString(
2020 cause_message, f);
2021 }
2022 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002023 else if (context &&
2024 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 res = PySet_Contains(seen, context);
2026 if (res == -1)
2027 PyErr_Clear();
2028 if (res == 0) {
2029 print_exception_recursive(
2030 f, context, seen);
2031 err |= PyFile_WriteString(
2032 context_message, f);
2033 }
2034 }
2035 Py_XDECREF(context);
2036 Py_XDECREF(cause);
2037 }
2038 }
2039 print_exception(f, value);
2040 if (err != 0)
2041 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002042}
2043
Thomas Wouters477c8d52006-05-27 19:21:47 +00002044void
2045PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 PyObject *seen;
Victor Stinnerbd303c12013-11-07 23:07:29 +01002048 PyObject *f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002049 if (PyExceptionInstance_Check(value)
2050 && tb != NULL && PyTraceBack_Check(tb)) {
2051 /* Put the traceback on the exception, otherwise it won't get
2052 displayed. See issue #18776. */
2053 PyObject *cur_tb = PyException_GetTraceback(value);
2054 if (cur_tb == NULL)
2055 PyException_SetTraceback(value, tb);
2056 else
2057 Py_DECREF(cur_tb);
2058 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 if (f == Py_None) {
2060 /* pass */
2061 }
2062 else if (f == NULL) {
2063 _PyObject_Dump(value);
2064 fprintf(stderr, "lost sys.stderr\n");
2065 }
2066 else {
2067 /* We choose to ignore seen being possibly NULL, and report
2068 at least the main exception (it could be a MemoryError).
2069 */
2070 seen = PySet_New(NULL);
2071 if (seen == NULL)
2072 PyErr_Clear();
2073 print_exception_recursive(f, value, seen);
2074 Py_XDECREF(seen);
2075 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002076}
2077
Guido van Rossum82598051997-03-05 00:20:32 +00002078PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002079PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 PyObject *ret = NULL;
2083 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002084 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01002085 PyObject *filename;
2086
2087 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2088 if (filename == NULL)
2089 return NULL;
2090
2091 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (arena == NULL)
2093 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002094
Victor Stinner95701bd2013-11-06 18:41:07 +01002095 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002097 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 PyArena_Free(arena);
2099 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002100}
2101
2102PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002103PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002105{
Victor Stinner95701bd2013-11-06 18:41:07 +01002106 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002108 PyArena *arena = NULL;
2109 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002110
Victor Stinner95701bd2013-11-06 18:41:07 +01002111 filename = PyUnicode_DecodeFSDefault(filename_str);
2112 if (filename == NULL)
2113 goto exit;
2114
2115 arena = PyArena_New();
2116 if (arena == NULL)
2117 goto exit;
2118
2119 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2120 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (closeit)
2122 fclose(fp);
2123 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002124 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 }
2126 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002127
2128exit:
2129 Py_XDECREF(filename);
2130 if (arena != NULL)
2131 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002133}
2134
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002135static void
2136flush_io(void)
2137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 PyObject *f, *r;
2139 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 /* Save the current exception */
2142 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002143
Victor Stinnerbd303c12013-11-07 23:07:29 +01002144 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002146 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 if (r)
2148 Py_DECREF(r);
2149 else
2150 PyErr_Clear();
2151 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01002152 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002154 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 if (r)
2156 Py_DECREF(r);
2157 else
2158 PyErr_Clear();
2159 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002162}
2163
Guido van Rossum82598051997-03-05 00:20:32 +00002164static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002165run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2166 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 PyCodeObject *co;
2169 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002170 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (co == NULL)
2172 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002173 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 Py_DECREF(co);
2175 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002176}
2177
Guido van Rossum82598051997-03-05 00:20:32 +00002178static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002179run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 PyCodeObject *co;
2183 PyObject *v;
2184 long magic;
2185 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 magic = PyMarshal_ReadLongFromFile(fp);
2188 if (magic != PyImport_GetMagicNumber()) {
2189 PyErr_SetString(PyExc_RuntimeError,
2190 "Bad magic number in .pyc file");
2191 return NULL;
2192 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002193 /* Skip mtime and size */
2194 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 (void) PyMarshal_ReadLongFromFile(fp);
2196 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 if (v == NULL || !PyCode_Check(v)) {
2198 Py_XDECREF(v);
2199 PyErr_SetString(PyExc_RuntimeError,
2200 "Bad code object in .pyc file");
2201 return NULL;
2202 }
2203 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002204 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 if (v && flags)
2206 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2207 Py_DECREF(co);
2208 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002209}
2210
Guido van Rossum82598051997-03-05 00:20:32 +00002211PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002212Py_CompileStringObject(const char *str, PyObject *filename, int start,
2213 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 PyCodeObject *co;
2216 mod_ty mod;
2217 PyArena *arena = PyArena_New();
2218 if (arena == NULL)
2219 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002220
Victor Stinner14e461d2013-08-26 22:28:21 +02002221 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 if (mod == NULL) {
2223 PyArena_Free(arena);
2224 return NULL;
2225 }
2226 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2227 PyObject *result = PyAST_mod2obj(mod);
2228 PyArena_Free(arena);
2229 return result;
2230 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002231 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 PyArena_Free(arena);
2233 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002234}
2235
Victor Stinner14e461d2013-08-26 22:28:21 +02002236PyObject *
2237Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2238 PyCompilerFlags *flags, int optimize)
2239{
2240 PyObject *filename, *co;
2241 filename = PyUnicode_DecodeFSDefault(filename_str);
2242 if (filename == NULL)
2243 return NULL;
2244 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2245 Py_DECREF(filename);
2246 return co;
2247}
2248
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002249/* For use in Py_LIMITED_API */
2250#undef Py_CompileString
2251PyObject *
2252PyCompileString(const char *str, const char *filename, int start)
2253{
2254 return Py_CompileStringFlags(str, filename, start, NULL);
2255}
2256
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002257struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002258Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 struct symtable *st;
2261 mod_ty mod;
2262 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002263 PyArena *arena;
2264
2265 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (arena == NULL)
2267 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002270 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (mod == NULL) {
2272 PyArena_Free(arena);
2273 return NULL;
2274 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002275 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyArena_Free(arena);
2277 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002278}
2279
Victor Stinner14e461d2013-08-26 22:28:21 +02002280struct symtable *
2281Py_SymtableString(const char *str, const char *filename_str, int start)
2282{
2283 PyObject *filename;
2284 struct symtable *st;
2285
2286 filename = PyUnicode_DecodeFSDefault(filename_str);
2287 if (filename == NULL)
2288 return NULL;
2289 st = Py_SymtableStringObject(str, filename, start);
2290 Py_DECREF(filename);
2291 return st;
2292}
2293
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294/* Preferred access to parser is through AST. */
2295mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002296PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2297 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 mod_ty mod;
2300 PyCompilerFlags localflags;
2301 perrdetail err;
2302 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002303
Victor Stinner14e461d2013-08-26 22:28:21 +02002304 node *n = PyParser_ParseStringObject(s, filename,
2305 &_PyParser_Grammar, start, &err,
2306 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 if (flags == NULL) {
2308 localflags.cf_flags = 0;
2309 flags = &localflags;
2310 }
2311 if (n) {
2312 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002313 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 }
2316 else {
2317 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002318 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002320 err_free(&err);
2321 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322}
2323
2324mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002325PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2326 PyCompilerFlags *flags, PyArena *arena)
2327{
2328 PyObject *filename;
2329 mod_ty mod;
2330 filename = PyUnicode_DecodeFSDefault(filename_str);
2331 if (filename == NULL)
2332 return NULL;
2333 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2334 Py_DECREF(filename);
2335 return mod;
2336}
2337
2338mod_ty
2339PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2340 int start, char *ps1,
2341 char *ps2, PyCompilerFlags *flags, int *errcode,
2342 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 mod_ty mod;
2345 PyCompilerFlags localflags;
2346 perrdetail err;
2347 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002348
Victor Stinner14e461d2013-08-26 22:28:21 +02002349 node *n = PyParser_ParseFileObject(fp, filename, enc,
2350 &_PyParser_Grammar,
2351 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 if (flags == NULL) {
2353 localflags.cf_flags = 0;
2354 flags = &localflags;
2355 }
2356 if (n) {
2357 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002358 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 }
2361 else {
2362 err_input(&err);
2363 if (errcode)
2364 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002365 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002367 err_free(&err);
2368 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369}
2370
Victor Stinner14e461d2013-08-26 22:28:21 +02002371mod_ty
2372PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2373 int start, char *ps1,
2374 char *ps2, PyCompilerFlags *flags, int *errcode,
2375 PyArena *arena)
2376{
2377 mod_ty mod;
2378 PyObject *filename;
2379 filename = PyUnicode_DecodeFSDefault(filename_str);
2380 if (filename == NULL)
2381 return NULL;
2382 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2383 flags, errcode, arena);
2384 Py_DECREF(filename);
2385 return mod;
2386}
2387
Guido van Rossuma110aa61994-08-29 12:50:44 +00002388/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002389
Guido van Rossuma110aa61994-08-29 12:50:44 +00002390node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002391PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 perrdetail err;
2394 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2395 &_PyParser_Grammar,
2396 start, NULL, NULL, &err, flags);
2397 if (n == NULL)
2398 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002399 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002402}
2403
Guido van Rossuma110aa61994-08-29 12:50:44 +00002404/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002405
Guido van Rossuma110aa61994-08-29 12:50:44 +00002406node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002407PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 perrdetail err;
2410 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2411 start, &err, flags);
2412 if (n == NULL)
2413 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002414 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002416}
2417
2418node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002419PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 perrdetail err;
2423 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2424 &_PyParser_Grammar, start, &err, flags);
2425 if (n == NULL)
2426 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002427 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002429}
2430
2431node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002432PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002435}
2436
Guido van Rossum66ebd912003-04-17 16:02:26 +00002437/* May want to move a more generalized form of this to parsetok.c or
2438 even parser modules. */
2439
2440void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002441PyParser_ClearError(perrdetail *err)
2442{
2443 err_free(err);
2444}
2445
2446void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002447PyParser_SetError(perrdetail *err)
2448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002450}
2451
Victor Stinner7f2fee32011-04-05 00:39:01 +02002452static void
2453err_free(perrdetail *err)
2454{
2455 Py_CLEAR(err->filename);
2456}
2457
Guido van Rossuma110aa61994-08-29 12:50:44 +00002458/* Set the error appropriate to the given input error code (see errcode.h) */
2459
2460static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002461err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 PyObject *v, *w, *errtype, *errtext;
2464 PyObject *msg_obj = NULL;
2465 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 errtype = PyExc_SyntaxError;
2468 switch (err->error) {
2469 case E_ERROR:
2470 return;
2471 case E_SYNTAX:
2472 errtype = PyExc_IndentationError;
2473 if (err->expected == INDENT)
2474 msg = "expected an indented block";
2475 else if (err->token == INDENT)
2476 msg = "unexpected indent";
2477 else if (err->token == DEDENT)
2478 msg = "unexpected unindent";
2479 else {
2480 errtype = PyExc_SyntaxError;
2481 msg = "invalid syntax";
2482 }
2483 break;
2484 case E_TOKEN:
2485 msg = "invalid token";
2486 break;
2487 case E_EOFS:
2488 msg = "EOF while scanning triple-quoted string literal";
2489 break;
2490 case E_EOLS:
2491 msg = "EOL while scanning string literal";
2492 break;
2493 case E_INTR:
2494 if (!PyErr_Occurred())
2495 PyErr_SetNone(PyExc_KeyboardInterrupt);
2496 goto cleanup;
2497 case E_NOMEM:
2498 PyErr_NoMemory();
2499 goto cleanup;
2500 case E_EOF:
2501 msg = "unexpected EOF while parsing";
2502 break;
2503 case E_TABSPACE:
2504 errtype = PyExc_TabError;
2505 msg = "inconsistent use of tabs and spaces in indentation";
2506 break;
2507 case E_OVERFLOW:
2508 msg = "expression too long";
2509 break;
2510 case E_DEDENT:
2511 errtype = PyExc_IndentationError;
2512 msg = "unindent does not match any outer indentation level";
2513 break;
2514 case E_TOODEEP:
2515 errtype = PyExc_IndentationError;
2516 msg = "too many levels of indentation";
2517 break;
2518 case E_DECODE: {
2519 PyObject *type, *value, *tb;
2520 PyErr_Fetch(&type, &value, &tb);
2521 msg = "unknown decode error";
2522 if (value != NULL)
2523 msg_obj = PyObject_Str(value);
2524 Py_XDECREF(type);
2525 Py_XDECREF(value);
2526 Py_XDECREF(tb);
2527 break;
2528 }
2529 case E_LINECONT:
2530 msg = "unexpected character after line continuation character";
2531 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 case E_IDENTIFIER:
2534 msg = "invalid character in identifier";
2535 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002536 case E_BADSINGLE:
2537 msg = "multiple statements found while compiling a single statement";
2538 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 default:
2540 fprintf(stderr, "error=%d\n", err->error);
2541 msg = "unknown parsing error";
2542 break;
2543 }
2544 /* err->text may not be UTF-8 in case of decoding errors.
2545 Explicitly convert to an object. */
2546 if (!err->text) {
2547 errtext = Py_None;
2548 Py_INCREF(Py_None);
2549 } else {
2550 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2551 "replace");
2552 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002553 v = Py_BuildValue("(OiiN)", err->filename,
2554 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 if (v != NULL) {
2556 if (msg_obj)
2557 w = Py_BuildValue("(OO)", msg_obj, v);
2558 else
2559 w = Py_BuildValue("(sO)", msg, v);
2560 } else
2561 w = NULL;
2562 Py_XDECREF(v);
2563 PyErr_SetObject(errtype, w);
2564 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002565cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 Py_XDECREF(msg_obj);
2567 if (err->text != NULL) {
2568 PyObject_FREE(err->text);
2569 err->text = NULL;
2570 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002571}
2572
2573/* Print fatal error message and abort */
2574
2575void
Tim Peters7c321a82002-07-09 02:57:01 +00002576Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002577{
Victor Stinner024e37a2011-03-31 01:31:06 +02002578 const int fd = fileno(stderr);
2579 PyThreadState *tstate;
2580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 fprintf(stderr, "Fatal Python error: %s\n", msg);
2582 fflush(stderr); /* it helps in Windows debug build */
2583 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002584 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002586 else {
2587 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2588 if (tstate != NULL) {
2589 fputc('\n', stderr);
2590 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002591 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002592 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002593 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002594 }
2595
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002596#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 {
2598 size_t len = strlen(msg);
2599 WCHAR* buffer;
2600 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 /* Convert the message to wchar_t. This uses a simple one-to-one
2603 conversion, assuming that the this error message actually uses ASCII
2604 only. If this ceases to be true, we will have to convert. */
2605 buffer = alloca( (len+1) * (sizeof *buffer));
2606 for( i=0; i<=len; ++i)
2607 buffer[i] = msg[i];
2608 OutputDebugStringW(L"Fatal Python error: ");
2609 OutputDebugStringW(buffer);
2610 OutputDebugStringW(L"\n");
2611 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002612#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002614#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002615#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002617}
2618
2619/* Clean up and exit */
2620
Guido van Rossuma110aa61994-08-29 12:50:44 +00002621#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002622#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002623#endif
2624
Collin Winter670e6922007-03-21 02:57:17 +00002625static void (*pyexitfunc)(void) = NULL;
2626/* For the atexit module. */
2627void _Py_PyAtExit(void (*func)(void))
2628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002630}
2631
2632static void
2633call_py_exitfuncs(void)
2634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 if (pyexitfunc == NULL)
2636 return;
Collin Winter670e6922007-03-21 02:57:17 +00002637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 (*pyexitfunc)();
2639 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002640}
2641
Antoine Pitrou011bd622009-10-20 21:52:47 +00002642/* Wait until threading._shutdown completes, provided
2643 the threading module was imported in the first place.
2644 The shutdown routine will wait until all non-daemon
2645 "threading" threads have completed. */
2646static void
2647wait_for_thread_shutdown(void)
2648{
2649#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002650 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 PyObject *result;
2652 PyThreadState *tstate = PyThreadState_GET();
2653 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2654 "threading");
2655 if (threading == NULL) {
2656 /* threading not imported */
2657 PyErr_Clear();
2658 return;
2659 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002660 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 if (result == NULL) {
2662 PyErr_WriteUnraisable(threading);
2663 }
2664 else {
2665 Py_DECREF(result);
2666 }
2667 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002668#endif
2669}
2670
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002671#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002672static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002673static int nexitfuncs = 0;
2674
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002675int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 if (nexitfuncs >= NEXITFUNCS)
2678 return -1;
2679 exitfuncs[nexitfuncs++] = func;
2680 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002681}
2682
Guido van Rossumcc283f51997-08-05 02:22:03 +00002683static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002684call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 while (nexitfuncs > 0)
2687 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 fflush(stdout);
2690 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002691}
2692
2693void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002694Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002699}
2700
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002701static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002702initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002703{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002704#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002706#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002707#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002709#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002710#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002712#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002714 if (PyErr_Occurred()) {
2715 Py_FatalError("Py_Initialize: can't import signal");
2716 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002717}
2718
Guido van Rossum7433b121997-02-14 19:45:36 +00002719
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002720/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2721 *
2722 * All of the code in this function must only use async-signal-safe functions,
2723 * listed at `man 7 signal` or
2724 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2725 */
2726void
2727_Py_RestoreSignals(void)
2728{
2729#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002731#endif
2732#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002734#endif
2735#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002737#endif
2738}
2739
2740
Guido van Rossum7433b121997-02-14 19:45:36 +00002741/*
2742 * The file descriptor fd is considered ``interactive'' if either
2743 * a) isatty(fd) is TRUE, or
2744 * b) the -i flag was given, and the filename associated with
2745 * the descriptor is NULL or "<stdin>" or "???".
2746 */
2747int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002748Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 if (isatty((int)fileno(fp)))
2751 return 1;
2752 if (!Py_InteractiveFlag)
2753 return 0;
2754 return (filename == NULL) ||
2755 (strcmp(filename, "<stdin>") == 0) ||
2756 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002757}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002758
2759
Tim Petersd08e3822003-04-17 15:24:21 +00002760#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002761#if defined(WIN32) && defined(_MSC_VER)
2762
2763/* Stack checking for Microsoft C */
2764
2765#include <malloc.h>
2766#include <excpt.h>
2767
Fred Drakee8de31c2000-08-31 05:38:39 +00002768/*
2769 * Return non-zero when we run out of memory on the stack; zero otherwise.
2770 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002771int
Fred Drake399739f2000-08-31 05:52:44 +00002772PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 __try {
2775 /* alloca throws a stack overflow exception if there's
2776 not enough space left on the stack */
2777 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2778 return 0;
2779 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2780 EXCEPTION_EXECUTE_HANDLER :
2781 EXCEPTION_CONTINUE_SEARCH) {
2782 int errcode = _resetstkoflw();
2783 if (errcode == 0)
2784 {
2785 Py_FatalError("Could not reset the stack!");
2786 }
2787 }
2788 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002789}
2790
2791#endif /* WIN32 && _MSC_VER */
2792
2793/* Alternate implementations can be added here... */
2794
2795#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002796
2797
2798/* Wrappers around sigaction() or signal(). */
2799
2800PyOS_sighandler_t
2801PyOS_getsig(int sig)
2802{
2803#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 struct sigaction context;
2805 if (sigaction(sig, NULL, &context) == -1)
2806 return SIG_ERR;
2807 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002808#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002810/* Special signal handling for the secure CRT in Visual Studio 2005 */
2811#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 switch (sig) {
2813 /* Only these signals are valid */
2814 case SIGINT:
2815 case SIGILL:
2816 case SIGFPE:
2817 case SIGSEGV:
2818 case SIGTERM:
2819 case SIGBREAK:
2820 case SIGABRT:
2821 break;
2822 /* Don't call signal() with other values or it will assert */
2823 default:
2824 return SIG_ERR;
2825 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002826#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 handler = signal(sig, SIG_IGN);
2828 if (handler != SIG_ERR)
2829 signal(sig, handler);
2830 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002831#endif
2832}
2833
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002834/*
2835 * All of the code in this function must only use async-signal-safe functions,
2836 * listed at `man 7 signal` or
2837 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2838 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002839PyOS_sighandler_t
2840PyOS_setsig(int sig, PyOS_sighandler_t handler)
2841{
2842#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 /* Some code in Modules/signalmodule.c depends on sigaction() being
2844 * used here if HAVE_SIGACTION is defined. Fix that if this code
2845 * changes to invalidate that assumption.
2846 */
2847 struct sigaction context, ocontext;
2848 context.sa_handler = handler;
2849 sigemptyset(&context.sa_mask);
2850 context.sa_flags = 0;
2851 if (sigaction(sig, &context, &ocontext) == -1)
2852 return SIG_ERR;
2853 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002854#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 PyOS_sighandler_t oldhandler;
2856 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002857#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002859#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002861#endif
2862}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863
2864/* Deprecated C API functions still provided for binary compatiblity */
2865
2866#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002867PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871}
2872
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002873#undef PyParser_SimpleParseString
2874PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875PyParser_SimpleParseString(const char *str, int start)
2876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002879
2880#undef PyRun_AnyFile
2881PyAPI_FUNC(int)
2882PyRun_AnyFile(FILE *fp, const char *name)
2883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002885}
2886
2887#undef PyRun_AnyFileEx
2888PyAPI_FUNC(int)
2889PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002892}
2893
2894#undef PyRun_AnyFileFlags
2895PyAPI_FUNC(int)
2896PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002899}
2900
2901#undef PyRun_File
2902PyAPI_FUNC(PyObject *)
2903PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002906}
2907
2908#undef PyRun_FileEx
2909PyAPI_FUNC(PyObject *)
2910PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002913}
2914
2915#undef PyRun_FileFlags
2916PyAPI_FUNC(PyObject *)
2917PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002921}
2922
2923#undef PyRun_SimpleFile
2924PyAPI_FUNC(int)
2925PyRun_SimpleFile(FILE *f, const char *p)
2926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002928}
2929
2930#undef PyRun_SimpleFileEx
2931PyAPI_FUNC(int)
2932PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002935}
2936
2937
2938#undef PyRun_String
2939PyAPI_FUNC(PyObject *)
2940PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002943}
2944
2945#undef PyRun_SimpleString
2946PyAPI_FUNC(int)
2947PyRun_SimpleString(const char *s)
2948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002950}
2951
2952#undef Py_CompileString
2953PyAPI_FUNC(PyObject *)
2954Py_CompileString(const char *str, const char *p, int s)
2955{
Georg Brandl8334fd92010-12-04 10:26:46 +00002956 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2957}
2958
2959#undef Py_CompileStringFlags
2960PyAPI_FUNC(PyObject *)
2961Py_CompileStringFlags(const char *str, const char *p, int s,
2962 PyCompilerFlags *flags)
2963{
2964 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002965}
2966
2967#undef PyRun_InteractiveOne
2968PyAPI_FUNC(int)
2969PyRun_InteractiveOne(FILE *f, const char *p)
2970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002972}
2973
2974#undef PyRun_InteractiveLoop
2975PyAPI_FUNC(int)
2976PyRun_InteractiveLoop(FILE *f, const char *p)
2977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002979}
2980
2981#ifdef __cplusplus
2982}
2983#endif