blob: 751008ac303f5f748fefbd0b6bc52377f60663b5 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Ezio Melotti1f8898a2013-03-26 01:59:56 +020038#ifdef Py_REF_DEBUG
39void _print_total_refs() {
40 PyObject *xoptions, *key, *value;
41 xoptions = PySys_GetXOptions();
42 if (xoptions == NULL)
43 return;
44 key = PyUnicode_FromString("showrefcount");
45 if (key == NULL)
46 return;
47 value = PyDict_GetItem(xoptions, key);
48 Py_DECREF(key);
49 if (value == Py_True)
50 fprintf(stderr,
51 "[%" PY_FORMAT_SIZE_T "d refs, "
52 "%" PY_FORMAT_SIZE_T "d blocks]\n",
53 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
54}
55#endif
56
Neal Norwitz4281cef2006-03-04 19:58:13 +000057#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000059#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020060#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061#endif
62
63#ifdef __cplusplus
64extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000065#endif
66
Martin v. Löwis790465f2008-04-05 20:41:37 +000067extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000068
Guido van Rossum82598051997-03-05 00:20:32 +000069extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000070
Guido van Rossumb73cc041993-11-01 16:28:59 +000071/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100072static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020073static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000074static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000075static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000076static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000077static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000079static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000081static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020082static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000083static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000084static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000085static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000086static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020087extern int _PyUnicode_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000088extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000089extern int _PyLong_Init(void);
90extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020091extern int _PyFaulthandler_Init(void);
92extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000093
Mark Hammond8d98d2c2003-04-19 15:41:53 +000094#ifdef WITH_THREAD
95extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
96extern void _PyGILState_Fini(void);
97#endif /* WITH_THREAD */
98
Guido van Rossum82598051997-03-05 00:20:32 +000099int Py_DebugFlag; /* Needed by parser.c */
100int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000101int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000102int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200103int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000104int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000105int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000106int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000107int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000108int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000109int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000110int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000111int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100112int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000113
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200114PyThreadState *_Py_Finalizing = NULL;
115
Christian Heimes33fe8092008-04-13 13:53:33 +0000116/* PyModule_GetWarningsModule is no longer necessary as of 2.6
117since _warnings is builtin. This API should not be used. */
118PyObject *
119PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000122}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000123
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000125
Thomas Wouters7e474022000-07-16 12:04:32 +0000126/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000127
128int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000129Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000132}
133
Guido van Rossum25ce5661997-08-02 03:10:38 +0000134/* Global initializations. Can be undone by Py_Finalize(). Don't
135 call this twice without an intervening Py_Finalize() call. When
136 initializations fail, a fatal error is issued and the function does
137 not return. On return, the first thread and interpreter state have
138 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000139
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140 Locking: you must hold the interpreter lock while calling this.
141 (If the lock has not yet been initialized, that's equivalent to
142 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000143
Guido van Rossum25ce5661997-08-02 03:10:38 +0000144*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000145
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000146static int
147add_flag(int flag, const char *envs)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 int env = atoi(envs);
150 if (flag < env)
151 flag = env;
152 if (flag < 1)
153 flag = 1;
154 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000155}
156
Christian Heimes5833a2f2008-10-30 21:40:04 +0000157static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000158get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000159{
Victor Stinner94908bb2010-08-18 21:23:25 +0000160 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000161 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200162 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000163
Victor Stinner94908bb2010-08-18 21:23:25 +0000164 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 if (!codec)
166 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000167
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200168 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 Py_CLEAR(codec);
170 if (!name)
171 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000172
Victor Stinner94908bb2010-08-18 21:23:25 +0000173 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100174 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000175 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000176 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000178 if (name_str == NULL) {
179 PyErr_NoMemory();
180 return NULL;
181 }
182 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000183
184error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000186 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000188}
Victor Stinner94908bb2010-08-18 21:23:25 +0000189
Victor Stinner94908bb2010-08-18 21:23:25 +0000190static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200191get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000192{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200193#ifdef MS_WINDOWS
194 char codepage[100];
195 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
196 return get_codec_name(codepage);
197#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000198 char* codeset = nl_langinfo(CODESET);
199 if (!codeset || codeset[0] == '\0') {
200 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
201 return NULL;
202 }
203 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200204#else
205 PyErr_SetNone(PyExc_NotImplementedError);
206 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000207#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200208}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000209
Brett Cannonfd074152012-04-14 14:10:13 -0400210static void
211import_init(PyInterpreterState *interp, PyObject *sysmod)
212{
213 PyObject *importlib;
214 PyObject *impmod;
215 PyObject *sys_modules;
216 PyObject *value;
217
218 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400219 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
220 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
221 }
222 else if (Py_VerboseFlag) {
223 PySys_FormatStderr("import _frozen_importlib # frozen\n");
224 }
225 importlib = PyImport_AddModule("_frozen_importlib");
226 if (importlib == NULL) {
227 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
228 "sys.modules");
229 }
230 interp->importlib = importlib;
231 Py_INCREF(interp->importlib);
232
233 /* Install _importlib as __import__ */
234 impmod = PyInit_imp();
235 if (impmod == NULL) {
236 Py_FatalError("Py_Initialize: can't import imp");
237 }
238 else if (Py_VerboseFlag) {
239 PySys_FormatStderr("import imp # builtin\n");
240 }
241 sys_modules = PyImport_GetModuleDict();
242 if (Py_VerboseFlag) {
243 PySys_FormatStderr("import sys # builtin\n");
244 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400245 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
246 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400247 }
248
Brett Cannone0d88a12012-04-25 20:54:04 -0400249 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400250 if (value == NULL) {
251 PyErr_Print();
252 Py_FatalError("Py_Initialize: importlib install failed");
253 }
254 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400255 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400256
257 _PyImportZip_Init();
258}
259
260
Guido van Rossuma027efa1997-05-05 20:56:21 +0000261void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200262_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 PyInterpreterState *interp;
265 PyThreadState *tstate;
266 PyObject *bimod, *sysmod, *pstderr;
267 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 if (initialized)
271 return;
272 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200273 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000274
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000275#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* Set up the LC_CTYPE locale, so we can obtain
277 the locale's charset without having to switch
278 locales. */
279 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000280#endif
281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
283 Py_DebugFlag = add_flag(Py_DebugFlag, p);
284 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
285 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
286 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
287 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
288 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
289 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100290 /* The variable is only tested for existence here; _PyRandom_Init will
291 check its value further. */
292 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
293 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
294
295 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 interp = PyInterpreterState_New();
298 if (interp == NULL)
299 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 tstate = PyThreadState_New(interp);
302 if (tstate == NULL)
303 Py_FatalError("Py_Initialize: can't make first thread");
304 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000305
Victor Stinner6961bd62010-08-17 22:26:51 +0000306#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000307 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
308 destroying the GIL might fail when it is being referenced from
309 another running thread (see issue #9901).
310 Instead we destroy the previously created GIL here, which ensures
311 that we can call Py_Initialize / Py_Finalize multiple times. */
312 _PyEval_FiniThreads();
313
314 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000315 _PyGILState_Init(interp, tstate);
316#endif /* WITH_THREAD */
317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (!_PyFrame_Init())
321 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (!_PyLong_Init())
324 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (!PyByteArray_Init())
327 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 interp->modules = PyDict_New();
332 if (interp->modules == NULL)
333 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200336 if (_PyUnicode_Init() < 0)
337 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 bimod = _PyBuiltin_Init();
340 if (bimod == NULL)
341 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000342 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 interp->builtins = PyModule_GetDict(bimod);
344 if (interp->builtins == NULL)
345 Py_FatalError("Py_Initialize: can't initialize builtins dict");
346 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400349 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 sysmod = _PySys_Init();
352 if (sysmod == NULL)
353 Py_FatalError("Py_Initialize: can't initialize sys");
354 interp->sysdict = PyModule_GetDict(sysmod);
355 if (interp->sysdict == NULL)
356 Py_FatalError("Py_Initialize: can't initialize sys dict");
357 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000358 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 PySys_SetPath(Py_GetPath());
360 PyDict_SetItemString(interp->sysdict, "modules",
361 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 /* Set up a preliminary stderr printer until we have enough
364 infrastructure for the io module in place. */
365 pstderr = PyFile_NewStdPrinter(fileno(stderr));
366 if (pstderr == NULL)
367 Py_FatalError("Py_Initialize: can't set preliminary stderr");
368 PySys_SetObject("stderr", pstderr);
369 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000370 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000375
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000376 /* Initialize _warnings. */
377 _PyWarnings_Init();
378
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200379 if (!install_importlib)
380 return;
381
Brett Cannonfd074152012-04-14 14:10:13 -0400382 import_init(interp, sysmod);
383
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200384 /* initialize the faulthandler module */
385 if (_PyFaulthandler_Init())
386 Py_FatalError("Py_Initialize: can't initialize faulthandler");
387
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000388 _PyTime_Init();
389
Victor Stinner793b5312011-04-27 00:24:21 +0200390 if (initfsencoding(interp) < 0)
391 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (install_sigs)
394 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000395
Nick Coghlan85e729e2012-07-15 18:09:52 +1000396 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 if (initstdio() < 0)
398 Py_FatalError(
399 "Py_Initialize: can't initialize sys standard streams");
400
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000401 /* Initialize warnings. */
402 if (PySys_HasWarnOptions()) {
403 PyObject *warnings_module = PyImport_ImportModule("warnings");
404 if (warnings_module == NULL) {
405 fprintf(stderr, "'import warnings' failed; traceback:\n");
406 PyErr_Print();
407 }
408 Py_XDECREF(warnings_module);
409 }
410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (!Py_NoSiteFlag)
412 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000413}
414
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000415void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200416Py_InitializeEx(int install_sigs)
417{
418 _Py_InitializeEx_Private(install_sigs, 1);
419}
420
421void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000422Py_Initialize(void)
423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000425}
426
427
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000428#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000429extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000430#endif
431
Guido van Rossume8432ac2007-07-09 15:04:50 +0000432/* Flush stdout and stderr */
433
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100434static int
435file_is_closed(PyObject *fobj)
436{
437 int r;
438 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
439 if (tmp == NULL) {
440 PyErr_Clear();
441 return 0;
442 }
443 r = PyObject_IsTrue(tmp);
444 Py_DECREF(tmp);
445 if (r < 0)
446 PyErr_Clear();
447 return r > 0;
448}
449
Neal Norwitz2bad9702007-08-27 06:19:22 +0000450static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000451flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 PyObject *fout = PySys_GetObject("stdout");
454 PyObject *ferr = PySys_GetObject("stderr");
455 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200456 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000457
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100458 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200459 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000461 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 else
463 Py_DECREF(tmp);
464 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000465
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100466 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200467 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 if (tmp == NULL)
469 PyErr_Clear();
470 else
471 Py_DECREF(tmp);
472 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000473}
474
Guido van Rossum25ce5661997-08-02 03:10:38 +0000475/* Undo the effect of Py_Initialize().
476
477 Beware: if multiple interpreter and/or thread states exist, these
478 are not wiped out; only the current thread and interpreter state
479 are deleted. But since everything else is deleted, those other
480 interpreter and thread states should no longer be used.
481
482 (XXX We should do better, e.g. wipe out all interpreters and
483 threads.)
484
485 Locking: as above.
486
487*/
488
489void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000490Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 PyInterpreterState *interp;
493 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (!initialized)
496 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* The interpreter is still entirely intact at this point, and the
501 * exit funcs may be relying on that. In particular, if some thread
502 * or exit func is still waiting to do an import, the import machinery
503 * expects Py_IsInitialized() to return true. So don't say the
504 * interpreter is uninitialized until after the exit funcs have run.
505 * Note that Threading.py uses an exit func to do a join on all the
506 * threads created thru it, so this also protects pending imports in
507 * the threads created via Threading.
508 */
509 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 /* Get current thread state and interpreter pointer */
512 tstate = PyThreadState_GET();
513 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000514
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200515 /* Remaining threads (e.g. daemon threads) will automatically exit
516 after taking the GIL (in PyEval_RestoreThread()). */
517 _Py_Finalizing = tstate;
518 initialized = 0;
519
520 /* Flush stdout+stderr */
521 flush_std_files();
522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 /* Disable signal handling */
524 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* Clear type lookup cache */
527 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 /* Collect garbage. This may call finalizers; it's nice to call these
530 * before all modules are destroyed.
531 * XXX If a __del__ or weakref callback is triggered here, and tries to
532 * XXX import a module, bad things can happen, because Python no
533 * XXX longer believes it's initialized.
534 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
535 * XXX is easy to provoke that way. I've also seen, e.g.,
536 * XXX Exception exceptions.ImportError: 'No module named sha'
537 * XXX in <function callback at 0x008F5718> ignored
538 * XXX but I'm unclear on exactly how that one happens. In any case,
539 * XXX I haven't seen a real-life report of either of these.
540 */
541 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000542#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 /* With COUNT_ALLOCS, it helps to run GC multiple times:
544 each collection might release some types from the type
545 list, so they become garbage. */
546 while (PyGC_Collect() > 0)
547 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000548#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000549 /* We run this while most interpreter state is still alive, so that
550 debug information can be printed out */
551 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 /* Destroy all modules */
554 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 /* Flush stdout+stderr (again, in case more was printed) */
557 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100560 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 * XXX This is disabled because it caused too many problems. If
562 * XXX a __del__ or weakref callback triggers here, Python code has
563 * XXX a hard time running, because even the sys module has been
564 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
565 * XXX One symptom is a sequence of information-free messages
566 * XXX coming from threads (if a __del__ or callback is invoked,
567 * XXX other threads can execute too, and any exception they encounter
568 * XXX triggers a comedy of errors as subsystem after subsystem
569 * XXX fails to find what it *expects* to find in sys to help report
570 * XXX the exception and consequent unexpected failures). I've also
571 * XXX seen segfaults then, after adding print statements to the
572 * XXX Python code getting called.
573 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000574#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000576#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
579 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000580
Victor Stinner024e37a2011-03-31 01:31:06 +0200581 /* unload faulthandler module */
582 _PyFaulthandler_Fini();
583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000585#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000587#endif
588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000590
Tim Peters9cf25ce2003-04-17 15:21:01 +0000591#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 /* Display all objects still alive -- this can invoke arbitrary
593 * __repr__ overrides, so requires a mostly-intact interpreter.
594 * Alas, a lot of stuff may still be alive now that will be cleaned
595 * up later.
596 */
597 if (Py_GETENV("PYTHONDUMPREFS"))
598 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000599#endif /* Py_TRACE_REFS */
600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 /* Clear interpreter state */
602 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 /* Now we decref the exception classes. After this point nothing
605 can raise an exception. That's okay, because each Fini() method
606 below has been checked to make sure no exceptions are ever
607 raised.
608 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000613#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000615#endif /* WITH_THREAD */
616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 /* Delete current thread */
618 PyThreadState_Swap(NULL);
619 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* Sundry finalizers */
622 PyMethod_Fini();
623 PyFrame_Fini();
624 PyCFunction_Fini();
625 PyTuple_Fini();
626 PyList_Fini();
627 PySet_Fini();
628 PyBytes_Fini();
629 PyByteArray_Fini();
630 PyLong_Fini();
631 PyFloat_Fini();
632 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100633 PySlice_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 /* Cleanup Unicode implementation */
636 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000639 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 free((char*)Py_FileSystemDefaultEncoding);
641 Py_FileSystemDefaultEncoding = NULL;
642 }
Christian Heimesc8967002007-11-30 10:18:26 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 /* XXX Still allocated:
645 - various static ad-hoc pointers to interned strings
646 - int and float free list blocks
647 - whatever various modules and libraries allocate
648 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000651
Tim Peters269b2a62003-04-17 19:52:29 +0000652#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* Display addresses (& refcnts) of all objects still alive.
654 * An address can be used to find the repr of the object, printed
655 * above by _Py_PrintReferences.
656 */
657 if (Py_GETENV("PYTHONDUMPREFS"))
658 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000659#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000660#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400662 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000663#endif
664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000666}
667
668/* Create and initialize a new interpreter and thread, and return the
669 new thread. This requires that Py_Initialize() has been called
670 first.
671
672 Unsuccessful initialization yields a NULL pointer. Note that *no*
673 exception information is available even in this case -- the
674 exception information is held in the thread, and there is no
675 thread.
676
677 Locking: as above.
678
679*/
680
681PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000682Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyInterpreterState *interp;
685 PyThreadState *tstate, *save_tstate;
686 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (!initialized)
689 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 interp = PyInterpreterState_New();
692 if (interp == NULL)
693 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 tstate = PyThreadState_New(interp);
696 if (tstate == NULL) {
697 PyInterpreterState_Delete(interp);
698 return NULL;
699 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000706
Victor Stinner49d3f252010-10-17 01:24:53 +0000707 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (bimod != NULL) {
709 interp->builtins = PyModule_GetDict(bimod);
710 if (interp->builtins == NULL)
711 goto handle_error;
712 Py_INCREF(interp->builtins);
713 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400716 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000717
Victor Stinner49d3f252010-10-17 01:24:53 +0000718 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (bimod != NULL && sysmod != NULL) {
720 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 interp->sysdict = PyModule_GetDict(sysmod);
723 if (interp->sysdict == NULL)
724 goto handle_error;
725 Py_INCREF(interp->sysdict);
726 PySys_SetPath(Py_GetPath());
727 PyDict_SetItemString(interp->sysdict, "modules",
728 interp->modules);
729 /* Set up a preliminary stderr printer until we have enough
730 infrastructure for the io module in place. */
731 pstderr = PyFile_NewStdPrinter(fileno(stderr));
732 if (pstderr == NULL)
733 Py_FatalError("Py_Initialize: can't set preliminary stderr");
734 PySys_SetObject("stderr", pstderr);
735 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000736 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200739
Brett Cannonfd074152012-04-14 14:10:13 -0400740 import_init(interp, sysmod);
741
Victor Stinner793b5312011-04-27 00:24:21 +0200742 if (initfsencoding(interp) < 0)
743 goto handle_error;
744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (initstdio() < 0)
746 Py_FatalError(
747 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000748 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (!Py_NoSiteFlag)
750 initsite();
751 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (!PyErr_Occurred())
754 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000755
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000758
Victor Stinnerc40a3502011-04-27 00:20:27 +0200759 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyThreadState_Clear(tstate);
761 PyThreadState_Swap(save_tstate);
762 PyThreadState_Delete(tstate);
763 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000766}
767
768/* Delete an interpreter and its last thread. This requires that the
769 given thread state is current, that the thread has no remaining
770 frames, and that it is its interpreter's only remaining thread.
771 It is a fatal error to violate these constraints.
772
773 (Py_Finalize() doesn't have these constraints -- it zaps
774 everything, regardless.)
775
776 Locking: as above.
777
778*/
779
780void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000781Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (tstate != PyThreadState_GET())
786 Py_FatalError("Py_EndInterpreter: thread is not current");
787 if (tstate->frame != NULL)
788 Py_FatalError("Py_EndInterpreter: thread still has a frame");
789 if (tstate != interp->tstate_head || tstate->next != NULL)
790 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 PyImport_Cleanup();
793 PyInterpreterState_Clear(interp);
794 PyThreadState_Swap(NULL);
795 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000796}
797
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200798#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000799static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200800#else
801static wchar_t *progname = L"python3";
802#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000803
804void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000805Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (pn && *pn)
808 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000809}
810
Martin v. Löwis790465f2008-04-05 20:41:37 +0000811wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000812Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000815}
816
Martin v. Löwis790465f2008-04-05 20:41:37 +0000817static wchar_t *default_home = NULL;
818static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000819
820void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000821Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000824}
825
Martin v. Löwis790465f2008-04-05 20:41:37 +0000826wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000827Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 wchar_t *home = default_home;
830 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
831 char* chome = Py_GETENV("PYTHONHOME");
832 if (chome) {
833 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
834 if (r != (size_t)-1 && r <= PATH_MAX)
835 home = env_home;
836 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 }
839 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000840}
841
Guido van Rossum6135a871995-01-09 17:53:26 +0000842/* Create __main__ module */
843
844static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000845initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 PyObject *m, *d;
848 m = PyImport_AddModule("__main__");
849 if (m == NULL)
850 Py_FatalError("can't create __main__ module");
851 d = PyModule_GetDict(m);
852 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
853 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000854 if (bimod == NULL) {
855 Py_FatalError("Failed to retrieve builtins module");
856 }
857 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
858 Py_FatalError("Failed to initialize __main__.__builtins__");
859 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 Py_DECREF(bimod);
861 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000862 /* Main is a little special - imp.is_builtin("__main__") will return
863 * False, but BuiltinImporter is still the most appropriate initial
864 * setting for its __loader__ attribute. A more suitable value will
865 * be set if __main__ gets further initialized later in the startup
866 * process.
867 */
868 if (PyDict_GetItemString(d, "__loader__") == NULL) {
869 PyObject *loader = PyObject_GetAttrString(interp->importlib,
870 "BuiltinImporter");
871 if (loader == NULL) {
872 Py_FatalError("Failed to retrieve BuiltinImporter");
873 }
874 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
875 Py_FatalError("Failed to initialize __main__.__loader__");
876 }
877 Py_DECREF(loader);
878 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000879}
880
Victor Stinner793b5312011-04-27 00:24:21 +0200881static int
882initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000883{
884 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000885
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200886 if (Py_FileSystemDefaultEncoding == NULL)
887 {
888 Py_FileSystemDefaultEncoding = get_locale_encoding();
889 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000890 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000891
Victor Stinnere4743092010-10-19 00:05:51 +0000892 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200893 interp->fscodec_initialized = 1;
894 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000895 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000896
897 /* the encoding is mbcs, utf-8 or ascii */
898 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
899 if (!codec) {
900 /* Such error can only occurs in critical situations: no more
901 * memory, import a module of the standard library failed,
902 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200903 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000904 }
Victor Stinner793b5312011-04-27 00:24:21 +0200905 Py_DECREF(codec);
906 interp->fscodec_initialized = 1;
907 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000908}
909
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000910/* Import the site module (not into __main__ though) */
911
912static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000913initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 PyObject *m;
916 m = PyImport_ImportModule("site");
917 if (m == NULL) {
918 PyErr_Print();
919 Py_Finalize();
920 exit(1);
921 }
922 else {
923 Py_DECREF(m);
924 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000925}
926
Antoine Pitrou05608432009-01-09 18:53:14 +0000927static PyObject*
928create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 int fd, int write_mode, char* name,
930 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
933 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000934 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 PyObject *line_buffering;
936 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200937 _Py_IDENTIFIER(open);
938 _Py_IDENTIFIER(isatty);
939 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200940 _Py_IDENTIFIER(name);
941 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 /* stdin is always opened in buffered mode, first because it shouldn't
944 make a difference in common use cases, second because TextIOWrapper
945 depends on the presence of a read1() method which only exists on
946 buffered streams.
947 */
948 if (Py_UnbufferedStdioFlag && write_mode)
949 buffering = 0;
950 else
951 buffering = -1;
952 if (write_mode)
953 mode = "wb";
954 else
955 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200956 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
957 fd, mode, buffering,
958 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (buf == NULL)
960 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200963 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200964 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 if (raw == NULL)
966 goto error;
967 }
968 else {
969 raw = buf;
970 Py_INCREF(raw);
971 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200974 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200976 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (res == NULL)
978 goto error;
979 isatty = PyObject_IsTrue(res);
980 Py_DECREF(res);
981 if (isatty == -1)
982 goto error;
983 if (isatty || Py_UnbufferedStdioFlag)
984 line_buffering = Py_True;
985 else
986 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 Py_CLEAR(raw);
989 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000990
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000991#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +0200992 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
993 newlines to "\n".
994 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
995 newline = NULL;
996#else
997 /* sys.stdin: split lines at "\n".
998 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
999 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001000#endif
1001
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001002 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1003 buf, encoding, errors,
1004 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 Py_CLEAR(buf);
1006 if (stream == NULL)
1007 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (write_mode)
1010 mode = "w";
1011 else
1012 mode = "r";
1013 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001014 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 goto error;
1016 Py_CLEAR(text);
1017 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001018
1019error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 Py_XDECREF(buf);
1021 Py_XDECREF(stream);
1022 Py_XDECREF(text);
1023 Py_XDECREF(raw);
1024 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001025}
1026
Antoine Pitrou11942a52011-11-28 19:08:36 +01001027static int
1028is_valid_fd(int fd)
1029{
1030 int dummy_fd;
1031 if (fd < 0 || !_PyVerify_fd(fd))
1032 return 0;
1033 dummy_fd = dup(fd);
1034 if (dummy_fd < 0)
1035 return 0;
1036 close(dummy_fd);
1037 return 1;
1038}
1039
Georg Brandl1a3284e2007-12-02 09:40:06 +00001040/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001041static int
1042initstdio(void)
1043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyObject *iomod = NULL, *wrapper;
1045 PyObject *bimod = NULL;
1046 PyObject *m;
1047 PyObject *std = NULL;
1048 int status = 0, fd;
1049 PyObject * encoding_attr;
1050 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* Hack to avoid a nasty recursion issue when Python is invoked
1053 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1054 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1055 goto error;
1056 }
1057 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1060 goto error;
1061 }
1062 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (!(bimod = PyImport_ImportModule("builtins"))) {
1065 goto error;
1066 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 if (!(iomod = PyImport_ImportModule("io"))) {
1069 goto error;
1070 }
1071 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1072 goto error;
1073 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 /* Set builtins.open */
1076 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001077 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 goto error;
1079 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001080 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 encoding = Py_GETENV("PYTHONIOENCODING");
1083 errors = NULL;
1084 if (encoding) {
1085 encoding = strdup(encoding);
1086 errors = strchr(encoding, ':');
1087 if (errors) {
1088 *errors = '\0';
1089 errors++;
1090 }
1091 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 /* Set sys.stdin */
1094 fd = fileno(stdin);
1095 /* Under some conditions stdin, stdout and stderr may not be connected
1096 * and fileno() may point to an invalid file descriptor. For example
1097 * GUI apps don't have valid standard streams by default.
1098 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001099 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 std = Py_None;
1101 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 }
1103 else {
1104 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1105 if (std == NULL)
1106 goto error;
1107 } /* if (fd < 0) */
1108 PySys_SetObject("__stdin__", std);
1109 PySys_SetObject("stdin", std);
1110 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* Set sys.stdout */
1113 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001114 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 std = Py_None;
1116 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 }
1118 else {
1119 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1120 if (std == NULL)
1121 goto error;
1122 } /* if (fd < 0) */
1123 PySys_SetObject("__stdout__", std);
1124 PySys_SetObject("stdout", std);
1125 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001126
Guido van Rossum98297ee2007-11-06 21:34:58 +00001127#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 /* Set sys.stderr, replaces the preliminary stderr */
1129 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001130 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 std = Py_None;
1132 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 }
1134 else {
1135 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1136 if (std == NULL)
1137 goto error;
1138 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 /* Same as hack above, pre-import stderr's codec to avoid recursion
1141 when import.c tries to write to stderr in verbose mode. */
1142 encoding_attr = PyObject_GetAttrString(std, "encoding");
1143 if (encoding_attr != NULL) {
1144 const char * encoding;
1145 encoding = _PyUnicode_AsString(encoding_attr);
1146 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001147 PyObject *codec_info = _PyCodec_Lookup(encoding);
1148 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001150 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 }
1152 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PySys_SetObject("__stderr__", std);
1155 PySys_SetObject("stderr", std);
1156 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001157#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001160 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 status = -1;
1162 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (encoding)
1165 free(encoding);
1166 Py_XDECREF(bimod);
1167 Py_XDECREF(iomod);
1168 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001169}
1170
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001171/* Parse input from a file and execute it */
1172
1173int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001174PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (filename == NULL)
1178 filename = "???";
1179 if (Py_FdIsInteractive(fp, filename)) {
1180 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1181 if (closeit)
1182 fclose(fp);
1183 return err;
1184 }
1185 else
1186 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001187}
1188
1189int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001190PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyObject *v;
1193 int ret;
1194 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (flags == NULL) {
1197 flags = &local_flags;
1198 local_flags.cf_flags = 0;
1199 }
1200 v = PySys_GetObject("ps1");
1201 if (v == NULL) {
1202 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1203 Py_XDECREF(v);
1204 }
1205 v = PySys_GetObject("ps2");
1206 if (v == NULL) {
1207 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1208 Py_XDECREF(v);
1209 }
1210 for (;;) {
1211 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1212 PRINT_TOTAL_REFS();
1213 if (ret == E_EOF)
1214 return 0;
1215 /*
1216 if (ret == E_NOMEM)
1217 return -1;
1218 */
1219 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001220}
1221
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001222/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001223static int PARSER_FLAGS(PyCompilerFlags *flags)
1224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 int parser_flags = 0;
1226 if (!flags)
1227 return 0;
1228 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1229 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1230 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1231 parser_flags |= PyPARSE_IGNORE_COOKIE;
1232 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1233 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1234 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001235}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001236
Thomas Wouters89f507f2006-12-13 04:49:30 +00001237#if 0
1238/* Keep an example of flags with future keyword support. */
1239#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1241 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1242 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1243 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001244#endif
1245
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001246int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001247PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 PyObject *m, *d, *v, *w, *oenc = NULL;
1250 mod_ty mod;
1251 PyArena *arena;
1252 char *ps1 = "", *ps2 = "", *enc = NULL;
1253 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001254 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (fp == stdin) {
1257 /* Fetch encoding from sys.stdin */
1258 v = PySys_GetObject("stdin");
1259 if (v == NULL || v == Py_None)
1260 return -1;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001261 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (!oenc)
1263 return -1;
1264 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001265 if (enc == NULL)
1266 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 }
1268 v = PySys_GetObject("ps1");
1269 if (v != NULL) {
1270 v = PyObject_Str(v);
1271 if (v == NULL)
1272 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001273 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001275 if (ps1 == NULL) {
1276 PyErr_Clear();
1277 ps1 = "";
1278 }
1279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 }
1281 w = PySys_GetObject("ps2");
1282 if (w != NULL) {
1283 w = PyObject_Str(w);
1284 if (w == NULL)
1285 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001286 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001288 if (ps2 == NULL) {
1289 PyErr_Clear();
1290 ps2 = "";
1291 }
1292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 }
1294 arena = PyArena_New();
1295 if (arena == NULL) {
1296 Py_XDECREF(v);
1297 Py_XDECREF(w);
1298 Py_XDECREF(oenc);
1299 return -1;
1300 }
1301 mod = PyParser_ASTFromFile(fp, filename, enc,
1302 Py_single_input, ps1, ps2,
1303 flags, &errcode, arena);
1304 Py_XDECREF(v);
1305 Py_XDECREF(w);
1306 Py_XDECREF(oenc);
1307 if (mod == NULL) {
1308 PyArena_Free(arena);
1309 if (errcode == E_EOF) {
1310 PyErr_Clear();
1311 return E_EOF;
1312 }
1313 PyErr_Print();
1314 return -1;
1315 }
1316 m = PyImport_AddModule("__main__");
1317 if (m == NULL) {
1318 PyArena_Free(arena);
1319 return -1;
1320 }
1321 d = PyModule_GetDict(m);
1322 v = run_mod(mod, filename, d, d, flags, arena);
1323 PyArena_Free(arena);
1324 flush_io();
1325 if (v == NULL) {
1326 PyErr_Print();
1327 return -1;
1328 }
1329 Py_DECREF(v);
1330 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001331}
1332
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001333/* Check whether a file maybe a pyc file: Look at the extension,
1334 the file type, and, if we may close it, at the first few bytes. */
1335
1336static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001337maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1340 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 /* Only look into the file if we are allowed to close it, since
1343 it then should also be seekable. */
1344 if (closeit) {
1345 /* Read only two bytes of the magic. If the file was opened in
1346 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1347 be read as they are on disk. */
1348 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1349 unsigned char buf[2];
1350 /* Mess: In case of -x, the stream is NOT at its start now,
1351 and ungetc() was used to push back the first newline,
1352 which makes the current stream position formally undefined,
1353 and a x-platform nightmare.
1354 Unfortunately, we have no direct way to know whether -x
1355 was specified. So we use a terrible hack: if the current
1356 stream position is not 0, we assume -x was specified, and
1357 give up. Bug 132850 on SourceForge spells out the
1358 hopelessness of trying anything else (fseek and ftell
1359 don't work predictably x-platform for text-mode files).
1360 */
1361 int ispyc = 0;
1362 if (ftell(fp) == 0) {
1363 if (fread(buf, 1, 2, fp) == 2 &&
1364 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1365 ispyc = 1;
1366 rewind(fp);
1367 }
1368 return ispyc;
1369 }
1370 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001371}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001372
Guido van Rossum0df002c2000-08-27 19:21:52 +00001373int
Nick Coghlanceda83c2012-07-15 23:18:08 +10001374static set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001375{
1376 PyInterpreterState *interp;
1377 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001378 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001379 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001380
1381 filename_obj = PyUnicode_DecodeFSDefault(filename);
1382 if (filename_obj == NULL)
1383 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001384 /* Get current thread state and interpreter pointer */
1385 tstate = PyThreadState_GET();
1386 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001387 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1388 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001389 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001390 return -1;
1391 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001392 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001393 Py_DECREF(loader_type);
1394 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001395 return -1;
1396 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001397 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1398 result = -1;
1399 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001400 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001401 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001402}
1403
1404int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001405PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 PyObject *m, *d, *v;
1409 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001410 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001411 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 m = PyImport_AddModule("__main__");
1414 if (m == NULL)
1415 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001416 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 d = PyModule_GetDict(m);
1418 if (PyDict_GetItemString(d, "__file__") == NULL) {
1419 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001420 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001422 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1424 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001425 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001427 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1428 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001429 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001430 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 set_file_name = 1;
1432 Py_DECREF(f);
1433 }
1434 len = strlen(filename);
1435 ext = filename + len - (len > 4 ? 4 : 0);
1436 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001437 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 /* Try to run a pyc file. First, re-open in binary */
1439 if (closeit)
1440 fclose(fp);
Christian Heimes04ac4c12012-09-11 15:47:28 +02001441 if ((pyc_fp = fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 goto done;
1444 }
1445 /* Turn on optimization if a .pyo file is given */
1446 if (strcmp(ext, ".pyo") == 0)
1447 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001448
1449 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1450 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1451 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001452 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001453 goto done;
1454 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001455 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1456 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001458 /* When running from stdin, leave __main__.__loader__ alone */
1459 if (strcmp(filename, "<stdin>") != 0 &&
1460 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1461 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1462 ret = -1;
1463 goto done;
1464 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1466 closeit, flags);
1467 }
1468 flush_io();
1469 if (v == NULL) {
1470 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 goto done;
1472 }
1473 Py_DECREF(v);
1474 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001475 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1477 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001478 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001480}
1481
1482int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001483PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 PyObject *m, *d, *v;
1486 m = PyImport_AddModule("__main__");
1487 if (m == NULL)
1488 return -1;
1489 d = PyModule_GetDict(m);
1490 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1491 if (v == NULL) {
1492 PyErr_Print();
1493 return -1;
1494 }
1495 Py_DECREF(v);
1496 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001497}
1498
Barry Warsaw035574d1997-08-29 22:07:17 +00001499static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001500parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 long hold;
1504 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001505 _Py_IDENTIFIER(msg);
1506 _Py_IDENTIFIER(filename);
1507 _Py_IDENTIFIER(lineno);
1508 _Py_IDENTIFIER(offset);
1509 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001510
Benjamin Peterson80d50422012-04-03 00:30:38 -04001511 *message = NULL;
1512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001514 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001515 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001517
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001518 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001519 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001521 if (v == Py_None) {
1522 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001524 }
1525 else {
1526 *filename = _PyUnicode_AsString(v);
1527 Py_DECREF(v);
1528 if (!*filename)
1529 goto finally;
1530 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001531
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001532 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001533 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 goto finally;
1535 hold = PyLong_AsLong(v);
1536 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (hold < 0 && PyErr_Occurred())
1538 goto finally;
1539 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001540
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001541 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001542 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 goto finally;
1544 if (v == Py_None) {
1545 *offset = -1;
1546 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 } else {
1548 hold = PyLong_AsLong(v);
1549 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (hold < 0 && PyErr_Occurred())
1551 goto finally;
1552 *offset = (int)hold;
1553 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001554
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001555 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001556 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001558 if (v == Py_None) {
1559 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001561 }
1562 else {
1563 *text = _PyUnicode_AsString(v);
1564 Py_DECREF(v);
1565 if (!*text)
1566 goto finally;
1567 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001569
1570finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001571 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001573}
1574
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001575void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001576PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001579}
1580
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001581static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001582print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 char *nl;
1585 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001586 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1587 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 for (;;) {
1589 nl = strchr(text, '\n');
1590 if (nl == NULL || nl-text >= offset)
1591 break;
1592 offset -= (int)(nl+1-text);
1593 text = nl+1;
1594 }
1595 while (*text == ' ' || *text == '\t') {
1596 text++;
1597 offset--;
1598 }
1599 }
1600 PyFile_WriteString(" ", f);
1601 PyFile_WriteString(text, f);
1602 if (*text == '\0' || text[strlen(text)-1] != '\n')
1603 PyFile_WriteString("\n", f);
1604 if (offset == -1)
1605 return;
1606 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001607 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001610}
1611
Guido van Rossum66e8e862001-03-23 17:54:43 +00001612static void
1613handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 PyObject *exception, *value, *tb;
1616 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (Py_InspectFlag)
1619 /* Don't exit if -i flag was given. This flag is set to 0
1620 * when entering interactive mode for inspecting. */
1621 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 PyErr_Fetch(&exception, &value, &tb);
1624 fflush(stdout);
1625 if (value == NULL || value == Py_None)
1626 goto done;
1627 if (PyExceptionInstance_Check(value)) {
1628 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001629 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001630 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (code) {
1632 Py_DECREF(value);
1633 value = code;
1634 if (value == Py_None)
1635 goto done;
1636 }
1637 /* If we failed to dig out the 'code' attribute,
1638 just let the else clause below print the error. */
1639 }
1640 if (PyLong_Check(value))
1641 exitcode = (int)PyLong_AsLong(value);
1642 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001643 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001644 if (sys_stderr != NULL && sys_stderr != Py_None) {
1645 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1646 } else {
1647 PyObject_Print(value, stderr, Py_PRINT_RAW);
1648 fflush(stderr);
1649 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 PySys_WriteStderr("\n");
1651 exitcode = 1;
1652 }
Tim Peterscf615b52003-04-19 18:47:02 +00001653 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* Restore and clear the exception info, in order to properly decref
1655 * the exception, value, and traceback. If we just exit instead,
1656 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1657 * some finalizers from running.
1658 */
1659 PyErr_Restore(exception, value, tb);
1660 PyErr_Clear();
1661 Py_Exit(exitcode);
1662 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001663}
1664
1665void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001666PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1671 handle_system_exit();
1672 }
1673 PyErr_Fetch(&exception, &v, &tb);
1674 if (exception == NULL)
1675 return;
1676 PyErr_NormalizeException(&exception, &v, &tb);
1677 if (tb == NULL) {
1678 tb = Py_None;
1679 Py_INCREF(tb);
1680 }
1681 PyException_SetTraceback(v, tb);
1682 if (exception == NULL)
1683 return;
1684 /* Now we know v != NULL too */
1685 if (set_sys_last_vars) {
1686 PySys_SetObject("last_type", exception);
1687 PySys_SetObject("last_value", v);
1688 PySys_SetObject("last_traceback", tb);
1689 }
1690 hook = PySys_GetObject("excepthook");
1691 if (hook) {
1692 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1693 PyObject *result = PyEval_CallObject(hook, args);
1694 if (result == NULL) {
1695 PyObject *exception2, *v2, *tb2;
1696 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1697 handle_system_exit();
1698 }
1699 PyErr_Fetch(&exception2, &v2, &tb2);
1700 PyErr_NormalizeException(&exception2, &v2, &tb2);
1701 /* It should not be possible for exception2 or v2
1702 to be NULL. However PyErr_Display() can't
1703 tolerate NULLs, so just be safe. */
1704 if (exception2 == NULL) {
1705 exception2 = Py_None;
1706 Py_INCREF(exception2);
1707 }
1708 if (v2 == NULL) {
1709 v2 = Py_None;
1710 Py_INCREF(v2);
1711 }
1712 fflush(stdout);
1713 PySys_WriteStderr("Error in sys.excepthook:\n");
1714 PyErr_Display(exception2, v2, tb2);
1715 PySys_WriteStderr("\nOriginal exception was:\n");
1716 PyErr_Display(exception, v, tb);
1717 Py_DECREF(exception2);
1718 Py_DECREF(v2);
1719 Py_XDECREF(tb2);
1720 }
1721 Py_XDECREF(result);
1722 Py_XDECREF(args);
1723 } else {
1724 PySys_WriteStderr("sys.excepthook is missing\n");
1725 PyErr_Display(exception, v, tb);
1726 }
1727 Py_XDECREF(exception);
1728 Py_XDECREF(v);
1729 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001730}
1731
Benjamin Petersone6528212008-07-15 15:32:09 +00001732static void
1733print_exception(PyObject *f, PyObject *value)
1734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 int err = 0;
1736 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001737 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 if (!PyExceptionInstance_Check(value)) {
1740 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1741 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1742 PyFile_WriteString(" found\n", f);
1743 return;
1744 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 Py_INCREF(value);
1747 fflush(stdout);
1748 type = (PyObject *) Py_TYPE(value);
1749 tb = PyException_GetTraceback(value);
1750 if (tb && tb != Py_None)
1751 err = PyTraceBack_Print(tb, f);
1752 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001753 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 {
1755 PyObject *message;
1756 const char *filename, *text;
1757 int lineno, offset;
1758 if (!parse_syntax_error(value, &message, &filename,
1759 &lineno, &offset, &text))
1760 PyErr_Clear();
1761 else {
1762 char buf[10];
1763 PyFile_WriteString(" File \"", f);
1764 if (filename == NULL)
1765 PyFile_WriteString("<string>", f);
1766 else
1767 PyFile_WriteString(filename, f);
1768 PyFile_WriteString("\", line ", f);
1769 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1770 PyFile_WriteString(buf, f);
1771 PyFile_WriteString("\n", f);
1772 if (text != NULL)
1773 print_error_text(f, offset, text);
1774 Py_DECREF(value);
1775 value = message;
1776 /* Can't be bothered to check all those
1777 PyFile_WriteString() calls */
1778 if (PyErr_Occurred())
1779 err = -1;
1780 }
1781 }
1782 if (err) {
1783 /* Don't do anything else */
1784 }
1785 else {
1786 PyObject* moduleName;
1787 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001788 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 assert(PyExceptionClass_Check(type));
1790 className = PyExceptionClass_Name(type);
1791 if (className != NULL) {
1792 char *dot = strrchr(className, '.');
1793 if (dot != NULL)
1794 className = dot+1;
1795 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001796
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001797 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1799 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001800 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 err = PyFile_WriteString("<unknown>", f);
1802 }
1803 else {
1804 char* modstr = _PyUnicode_AsString(moduleName);
1805 if (modstr && strcmp(modstr, "builtins"))
1806 {
1807 err = PyFile_WriteString(modstr, f);
1808 err += PyFile_WriteString(".", f);
1809 }
1810 Py_DECREF(moduleName);
1811 }
1812 if (err == 0) {
1813 if (className == NULL)
1814 err = PyFile_WriteString("<unknown>", f);
1815 else
1816 err = PyFile_WriteString(className, f);
1817 }
1818 }
1819 if (err == 0 && (value != Py_None)) {
1820 PyObject *s = PyObject_Str(value);
1821 /* only print colon if the str() of the
1822 object is not the empty string
1823 */
1824 if (s == NULL)
1825 err = -1;
1826 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001827 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 err = PyFile_WriteString(": ", f);
1829 if (err == 0)
1830 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1831 Py_XDECREF(s);
1832 }
1833 /* try to write a newline in any case */
1834 err += PyFile_WriteString("\n", f);
1835 Py_XDECREF(tb);
1836 Py_DECREF(value);
1837 /* If an error happened here, don't show it.
1838 XXX This is wrong, but too many callers rely on this behavior. */
1839 if (err != 0)
1840 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001841}
1842
1843static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 "\nThe above exception was the direct cause "
1845 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001846
1847static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 "\nDuring handling of the above exception, "
1849 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001850
1851static void
1852print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 int err = 0, res;
1855 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 if (seen != NULL) {
1858 /* Exception chaining */
1859 if (PySet_Add(seen, value) == -1)
1860 PyErr_Clear();
1861 else if (PyExceptionInstance_Check(value)) {
1862 cause = PyException_GetCause(value);
1863 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001864 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 res = PySet_Contains(seen, cause);
1866 if (res == -1)
1867 PyErr_Clear();
1868 if (res == 0) {
1869 print_exception_recursive(
1870 f, cause, seen);
1871 err |= PyFile_WriteString(
1872 cause_message, f);
1873 }
1874 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001875 else if (context &&
1876 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 res = PySet_Contains(seen, context);
1878 if (res == -1)
1879 PyErr_Clear();
1880 if (res == 0) {
1881 print_exception_recursive(
1882 f, context, seen);
1883 err |= PyFile_WriteString(
1884 context_message, f);
1885 }
1886 }
1887 Py_XDECREF(context);
1888 Py_XDECREF(cause);
1889 }
1890 }
1891 print_exception(f, value);
1892 if (err != 0)
1893 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001894}
1895
Thomas Wouters477c8d52006-05-27 19:21:47 +00001896void
1897PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 PyObject *seen;
1900 PyObject *f = PySys_GetObject("stderr");
1901 if (f == Py_None) {
1902 /* pass */
1903 }
1904 else if (f == NULL) {
1905 _PyObject_Dump(value);
1906 fprintf(stderr, "lost sys.stderr\n");
1907 }
1908 else {
1909 /* We choose to ignore seen being possibly NULL, and report
1910 at least the main exception (it could be a MemoryError).
1911 */
1912 seen = PySet_New(NULL);
1913 if (seen == NULL)
1914 PyErr_Clear();
1915 print_exception_recursive(f, value, seen);
1916 Py_XDECREF(seen);
1917 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001918}
1919
Guido van Rossum82598051997-03-05 00:20:32 +00001920PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001921PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 PyObject *ret = NULL;
1925 mod_ty mod;
1926 PyArena *arena = PyArena_New();
1927 if (arena == NULL)
1928 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1931 if (mod != NULL)
1932 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1933 PyArena_Free(arena);
1934 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001935}
1936
1937PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001938PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 PyObject *ret;
1942 mod_ty mod;
1943 PyArena *arena = PyArena_New();
1944 if (arena == NULL)
1945 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1948 flags, NULL, arena);
1949 if (closeit)
1950 fclose(fp);
1951 if (mod == NULL) {
1952 PyArena_Free(arena);
1953 return NULL;
1954 }
1955 ret = run_mod(mod, filename, globals, locals, flags, arena);
1956 PyArena_Free(arena);
1957 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001958}
1959
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001960static void
1961flush_io(void)
1962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 PyObject *f, *r;
1964 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001965 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 /* Save the current exception */
1968 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 f = PySys_GetObject("stderr");
1971 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001972 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (r)
1974 Py_DECREF(r);
1975 else
1976 PyErr_Clear();
1977 }
1978 f = PySys_GetObject("stdout");
1979 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001980 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 if (r)
1982 Py_DECREF(r);
1983 else
1984 PyErr_Clear();
1985 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001988}
1989
Guido van Rossum82598051997-03-05 00:20:32 +00001990static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 PyCodeObject *co;
1995 PyObject *v;
1996 co = PyAST_Compile(mod, filename, flags, arena);
1997 if (co == NULL)
1998 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001999 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 Py_DECREF(co);
2001 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002002}
2003
Guido van Rossum82598051997-03-05 00:20:32 +00002004static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002005run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 PyCodeObject *co;
2009 PyObject *v;
2010 long magic;
2011 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 magic = PyMarshal_ReadLongFromFile(fp);
2014 if (magic != PyImport_GetMagicNumber()) {
2015 PyErr_SetString(PyExc_RuntimeError,
2016 "Bad magic number in .pyc file");
2017 return NULL;
2018 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002019 /* Skip mtime and size */
2020 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 (void) PyMarshal_ReadLongFromFile(fp);
2022 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 if (v == NULL || !PyCode_Check(v)) {
2024 Py_XDECREF(v);
2025 PyErr_SetString(PyExc_RuntimeError,
2026 "Bad code object in .pyc file");
2027 return NULL;
2028 }
2029 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002030 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (v && flags)
2032 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2033 Py_DECREF(co);
2034 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002035}
2036
Guido van Rossum82598051997-03-05 00:20:32 +00002037PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00002038Py_CompileStringExFlags(const char *str, const char *filename, int start,
2039 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 PyCodeObject *co;
2042 mod_ty mod;
2043 PyArena *arena = PyArena_New();
2044 if (arena == NULL)
2045 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
2048 if (mod == NULL) {
2049 PyArena_Free(arena);
2050 return NULL;
2051 }
2052 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2053 PyObject *result = PyAST_mod2obj(mod);
2054 PyArena_Free(arena);
2055 return result;
2056 }
Georg Brandl8334fd92010-12-04 10:26:46 +00002057 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 PyArena_Free(arena);
2059 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002060}
2061
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002062/* For use in Py_LIMITED_API */
2063#undef Py_CompileString
2064PyObject *
2065PyCompileString(const char *str, const char *filename, int start)
2066{
2067 return Py_CompileStringFlags(str, filename, start, NULL);
2068}
2069
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002070struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002071Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 struct symtable *st;
2074 mod_ty mod;
2075 PyCompilerFlags flags;
2076 PyArena *arena = PyArena_New();
2077 if (arena == NULL)
2078 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 flags.cf_flags = 0;
2081 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
2082 if (mod == NULL) {
2083 PyArena_Free(arena);
2084 return NULL;
2085 }
2086 st = PySymtable_Build(mod, filename, 0);
2087 PyArena_Free(arena);
2088 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002089}
2090
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091/* Preferred access to parser is through AST. */
2092mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002093PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 mod_ty mod;
2097 PyCompilerFlags localflags;
2098 perrdetail err;
2099 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2102 &_PyParser_Grammar, start, &err,
2103 &iflags);
2104 if (flags == NULL) {
2105 localflags.cf_flags = 0;
2106 flags = &localflags;
2107 }
2108 if (n) {
2109 flags->cf_flags |= iflags & PyCF_MASK;
2110 mod = PyAST_FromNode(n, flags, filename, arena);
2111 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 }
2113 else {
2114 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002115 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002117 err_free(&err);
2118 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119}
2120
2121mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002122PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 int start, char *ps1,
2124 char *ps2, PyCompilerFlags *flags, int *errcode,
2125 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 mod_ty mod;
2128 PyCompilerFlags localflags;
2129 perrdetail err;
2130 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2133 &_PyParser_Grammar,
2134 start, ps1, ps2, &err, &iflags);
2135 if (flags == NULL) {
2136 localflags.cf_flags = 0;
2137 flags = &localflags;
2138 }
2139 if (n) {
2140 flags->cf_flags |= iflags & PyCF_MASK;
2141 mod = PyAST_FromNode(n, flags, filename, arena);
2142 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 }
2144 else {
2145 err_input(&err);
2146 if (errcode)
2147 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002148 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002150 err_free(&err);
2151 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152}
2153
Guido van Rossuma110aa61994-08-29 12:50:44 +00002154/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002155
Guido van Rossuma110aa61994-08-29 12:50:44 +00002156node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002157PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 perrdetail err;
2160 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2161 &_PyParser_Grammar,
2162 start, NULL, NULL, &err, flags);
2163 if (n == NULL)
2164 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002165 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002168}
2169
Guido van Rossuma110aa61994-08-29 12:50:44 +00002170/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002171
Guido van Rossuma110aa61994-08-29 12:50:44 +00002172node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002173PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 perrdetail err;
2176 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2177 start, &err, flags);
2178 if (n == NULL)
2179 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002180 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002182}
2183
2184node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002185PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 perrdetail err;
2189 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2190 &_PyParser_Grammar, start, &err, flags);
2191 if (n == NULL)
2192 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002193 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002195}
2196
2197node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002198PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002201}
2202
Guido van Rossum66ebd912003-04-17 16:02:26 +00002203/* May want to move a more generalized form of this to parsetok.c or
2204 even parser modules. */
2205
2206void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002207PyParser_ClearError(perrdetail *err)
2208{
2209 err_free(err);
2210}
2211
2212void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002213PyParser_SetError(perrdetail *err)
2214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002216}
2217
Victor Stinner7f2fee32011-04-05 00:39:01 +02002218static void
2219err_free(perrdetail *err)
2220{
2221 Py_CLEAR(err->filename);
2222}
2223
Guido van Rossuma110aa61994-08-29 12:50:44 +00002224/* Set the error appropriate to the given input error code (see errcode.h) */
2225
2226static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002227err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyObject *v, *w, *errtype, *errtext;
2230 PyObject *msg_obj = NULL;
2231 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 errtype = PyExc_SyntaxError;
2234 switch (err->error) {
2235 case E_ERROR:
2236 return;
2237 case E_SYNTAX:
2238 errtype = PyExc_IndentationError;
2239 if (err->expected == INDENT)
2240 msg = "expected an indented block";
2241 else if (err->token == INDENT)
2242 msg = "unexpected indent";
2243 else if (err->token == DEDENT)
2244 msg = "unexpected unindent";
2245 else {
2246 errtype = PyExc_SyntaxError;
2247 msg = "invalid syntax";
2248 }
2249 break;
2250 case E_TOKEN:
2251 msg = "invalid token";
2252 break;
2253 case E_EOFS:
2254 msg = "EOF while scanning triple-quoted string literal";
2255 break;
2256 case E_EOLS:
2257 msg = "EOL while scanning string literal";
2258 break;
2259 case E_INTR:
2260 if (!PyErr_Occurred())
2261 PyErr_SetNone(PyExc_KeyboardInterrupt);
2262 goto cleanup;
2263 case E_NOMEM:
2264 PyErr_NoMemory();
2265 goto cleanup;
2266 case E_EOF:
2267 msg = "unexpected EOF while parsing";
2268 break;
2269 case E_TABSPACE:
2270 errtype = PyExc_TabError;
2271 msg = "inconsistent use of tabs and spaces in indentation";
2272 break;
2273 case E_OVERFLOW:
2274 msg = "expression too long";
2275 break;
2276 case E_DEDENT:
2277 errtype = PyExc_IndentationError;
2278 msg = "unindent does not match any outer indentation level";
2279 break;
2280 case E_TOODEEP:
2281 errtype = PyExc_IndentationError;
2282 msg = "too many levels of indentation";
2283 break;
2284 case E_DECODE: {
2285 PyObject *type, *value, *tb;
2286 PyErr_Fetch(&type, &value, &tb);
2287 msg = "unknown decode error";
2288 if (value != NULL)
2289 msg_obj = PyObject_Str(value);
2290 Py_XDECREF(type);
2291 Py_XDECREF(value);
2292 Py_XDECREF(tb);
2293 break;
2294 }
2295 case E_LINECONT:
2296 msg = "unexpected character after line continuation character";
2297 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 case E_IDENTIFIER:
2300 msg = "invalid character in identifier";
2301 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002302 case E_BADSINGLE:
2303 msg = "multiple statements found while compiling a single statement";
2304 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 default:
2306 fprintf(stderr, "error=%d\n", err->error);
2307 msg = "unknown parsing error";
2308 break;
2309 }
2310 /* err->text may not be UTF-8 in case of decoding errors.
2311 Explicitly convert to an object. */
2312 if (!err->text) {
2313 errtext = Py_None;
2314 Py_INCREF(Py_None);
2315 } else {
2316 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2317 "replace");
2318 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002319 v = Py_BuildValue("(OiiN)", err->filename,
2320 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 if (v != NULL) {
2322 if (msg_obj)
2323 w = Py_BuildValue("(OO)", msg_obj, v);
2324 else
2325 w = Py_BuildValue("(sO)", msg, v);
2326 } else
2327 w = NULL;
2328 Py_XDECREF(v);
2329 PyErr_SetObject(errtype, w);
2330 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002331cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 Py_XDECREF(msg_obj);
2333 if (err->text != NULL) {
2334 PyObject_FREE(err->text);
2335 err->text = NULL;
2336 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002337}
2338
2339/* Print fatal error message and abort */
2340
2341void
Tim Peters7c321a82002-07-09 02:57:01 +00002342Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002343{
Victor Stinner024e37a2011-03-31 01:31:06 +02002344 const int fd = fileno(stderr);
2345 PyThreadState *tstate;
2346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 fprintf(stderr, "Fatal Python error: %s\n", msg);
2348 fflush(stderr); /* it helps in Windows debug build */
2349 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002350 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002352 else {
2353 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2354 if (tstate != NULL) {
2355 fputc('\n', stderr);
2356 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002357 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002358 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002359 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002360 }
2361
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002362#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 {
2364 size_t len = strlen(msg);
2365 WCHAR* buffer;
2366 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 /* Convert the message to wchar_t. This uses a simple one-to-one
2369 conversion, assuming that the this error message actually uses ASCII
2370 only. If this ceases to be true, we will have to convert. */
2371 buffer = alloca( (len+1) * (sizeof *buffer));
2372 for( i=0; i<=len; ++i)
2373 buffer[i] = msg[i];
2374 OutputDebugStringW(L"Fatal Python error: ");
2375 OutputDebugStringW(buffer);
2376 OutputDebugStringW(L"\n");
2377 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002378#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002380#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002381#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002383}
2384
2385/* Clean up and exit */
2386
Guido van Rossuma110aa61994-08-29 12:50:44 +00002387#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002388#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002389#endif
2390
Collin Winter670e6922007-03-21 02:57:17 +00002391static void (*pyexitfunc)(void) = NULL;
2392/* For the atexit module. */
2393void _Py_PyAtExit(void (*func)(void))
2394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002396}
2397
2398static void
2399call_py_exitfuncs(void)
2400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 if (pyexitfunc == NULL)
2402 return;
Collin Winter670e6922007-03-21 02:57:17 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 (*pyexitfunc)();
2405 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002406}
2407
Antoine Pitrou011bd622009-10-20 21:52:47 +00002408/* Wait until threading._shutdown completes, provided
2409 the threading module was imported in the first place.
2410 The shutdown routine will wait until all non-daemon
2411 "threading" threads have completed. */
2412static void
2413wait_for_thread_shutdown(void)
2414{
2415#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002416 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 PyObject *result;
2418 PyThreadState *tstate = PyThreadState_GET();
2419 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2420 "threading");
2421 if (threading == NULL) {
2422 /* threading not imported */
2423 PyErr_Clear();
2424 return;
2425 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002426 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 if (result == NULL) {
2428 PyErr_WriteUnraisable(threading);
2429 }
2430 else {
2431 Py_DECREF(result);
2432 }
2433 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002434#endif
2435}
2436
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002437#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002438static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002439static int nexitfuncs = 0;
2440
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002441int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 if (nexitfuncs >= NEXITFUNCS)
2444 return -1;
2445 exitfuncs[nexitfuncs++] = func;
2446 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002447}
2448
Guido van Rossumcc283f51997-08-05 02:22:03 +00002449static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002450call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 while (nexitfuncs > 0)
2453 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 fflush(stdout);
2456 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002457}
2458
2459void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002460Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002465}
2466
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002467static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002468initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002469{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002470#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002472#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002473#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002475#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002476#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002478#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002480}
2481
Guido van Rossum7433b121997-02-14 19:45:36 +00002482
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002483/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2484 *
2485 * All of the code in this function must only use async-signal-safe functions,
2486 * listed at `man 7 signal` or
2487 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2488 */
2489void
2490_Py_RestoreSignals(void)
2491{
2492#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002494#endif
2495#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002497#endif
2498#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002500#endif
2501}
2502
2503
Guido van Rossum7433b121997-02-14 19:45:36 +00002504/*
2505 * The file descriptor fd is considered ``interactive'' if either
2506 * a) isatty(fd) is TRUE, or
2507 * b) the -i flag was given, and the filename associated with
2508 * the descriptor is NULL or "<stdin>" or "???".
2509 */
2510int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002511Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 if (isatty((int)fileno(fp)))
2514 return 1;
2515 if (!Py_InteractiveFlag)
2516 return 0;
2517 return (filename == NULL) ||
2518 (strcmp(filename, "<stdin>") == 0) ||
2519 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002520}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002521
2522
Tim Petersd08e3822003-04-17 15:24:21 +00002523#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002524#if defined(WIN32) && defined(_MSC_VER)
2525
2526/* Stack checking for Microsoft C */
2527
2528#include <malloc.h>
2529#include <excpt.h>
2530
Fred Drakee8de31c2000-08-31 05:38:39 +00002531/*
2532 * Return non-zero when we run out of memory on the stack; zero otherwise.
2533 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002534int
Fred Drake399739f2000-08-31 05:52:44 +00002535PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 __try {
2538 /* alloca throws a stack overflow exception if there's
2539 not enough space left on the stack */
2540 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2541 return 0;
2542 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2543 EXCEPTION_EXECUTE_HANDLER :
2544 EXCEPTION_CONTINUE_SEARCH) {
2545 int errcode = _resetstkoflw();
2546 if (errcode == 0)
2547 {
2548 Py_FatalError("Could not reset the stack!");
2549 }
2550 }
2551 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002552}
2553
2554#endif /* WIN32 && _MSC_VER */
2555
2556/* Alternate implementations can be added here... */
2557
2558#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002559
2560
2561/* Wrappers around sigaction() or signal(). */
2562
2563PyOS_sighandler_t
2564PyOS_getsig(int sig)
2565{
2566#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 struct sigaction context;
2568 if (sigaction(sig, NULL, &context) == -1)
2569 return SIG_ERR;
2570 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002571#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002573/* Special signal handling for the secure CRT in Visual Studio 2005 */
2574#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 switch (sig) {
2576 /* Only these signals are valid */
2577 case SIGINT:
2578 case SIGILL:
2579 case SIGFPE:
2580 case SIGSEGV:
2581 case SIGTERM:
2582 case SIGBREAK:
2583 case SIGABRT:
2584 break;
2585 /* Don't call signal() with other values or it will assert */
2586 default:
2587 return SIG_ERR;
2588 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002589#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 handler = signal(sig, SIG_IGN);
2591 if (handler != SIG_ERR)
2592 signal(sig, handler);
2593 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002594#endif
2595}
2596
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002597/*
2598 * All of the code in this function must only use async-signal-safe functions,
2599 * listed at `man 7 signal` or
2600 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2601 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002602PyOS_sighandler_t
2603PyOS_setsig(int sig, PyOS_sighandler_t handler)
2604{
2605#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 /* Some code in Modules/signalmodule.c depends on sigaction() being
2607 * used here if HAVE_SIGACTION is defined. Fix that if this code
2608 * changes to invalidate that assumption.
2609 */
2610 struct sigaction context, ocontext;
2611 context.sa_handler = handler;
2612 sigemptyset(&context.sa_mask);
2613 context.sa_flags = 0;
2614 if (sigaction(sig, &context, &ocontext) == -1)
2615 return SIG_ERR;
2616 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002617#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 PyOS_sighandler_t oldhandler;
2619 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002620#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002622#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002624#endif
2625}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626
2627/* Deprecated C API functions still provided for binary compatiblity */
2628
2629#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002630PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634}
2635
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002636#undef PyParser_SimpleParseString
2637PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638PyParser_SimpleParseString(const char *str, int start)
2639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002642
2643#undef PyRun_AnyFile
2644PyAPI_FUNC(int)
2645PyRun_AnyFile(FILE *fp, const char *name)
2646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002648}
2649
2650#undef PyRun_AnyFileEx
2651PyAPI_FUNC(int)
2652PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002655}
2656
2657#undef PyRun_AnyFileFlags
2658PyAPI_FUNC(int)
2659PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002662}
2663
2664#undef PyRun_File
2665PyAPI_FUNC(PyObject *)
2666PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002669}
2670
2671#undef PyRun_FileEx
2672PyAPI_FUNC(PyObject *)
2673PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002676}
2677
2678#undef PyRun_FileFlags
2679PyAPI_FUNC(PyObject *)
2680PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002684}
2685
2686#undef PyRun_SimpleFile
2687PyAPI_FUNC(int)
2688PyRun_SimpleFile(FILE *f, const char *p)
2689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002691}
2692
2693#undef PyRun_SimpleFileEx
2694PyAPI_FUNC(int)
2695PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002698}
2699
2700
2701#undef PyRun_String
2702PyAPI_FUNC(PyObject *)
2703PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002706}
2707
2708#undef PyRun_SimpleString
2709PyAPI_FUNC(int)
2710PyRun_SimpleString(const char *s)
2711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002713}
2714
2715#undef Py_CompileString
2716PyAPI_FUNC(PyObject *)
2717Py_CompileString(const char *str, const char *p, int s)
2718{
Georg Brandl8334fd92010-12-04 10:26:46 +00002719 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2720}
2721
2722#undef Py_CompileStringFlags
2723PyAPI_FUNC(PyObject *)
2724Py_CompileStringFlags(const char *str, const char *p, int s,
2725 PyCompilerFlags *flags)
2726{
2727 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002728}
2729
2730#undef PyRun_InteractiveOne
2731PyAPI_FUNC(int)
2732PyRun_InteractiveOne(FILE *f, const char *p)
2733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002735}
2736
2737#undef PyRun_InteractiveLoop
2738PyAPI_FUNC(int)
2739PyRun_InteractiveLoop(FILE *f, const char *p)
2740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002742}
2743
2744#ifdef __cplusplus
2745}
2746#endif