blob: 05bb62b64a2fa135baa2f650a9c9747ebc651e26 [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"
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +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"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Antoine Pitrouefb60c02009-10-20 21:29:37 +000020#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000022#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023#include <signal.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000024#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000025
Benjamin Peterson796798b2009-01-02 20:47:27 +000026#ifdef MS_WINDOWS
Martin v. Löwis5344c992009-01-02 20:32:55 +000027#include "malloc.h" /* for alloca */
Benjamin Peterson796798b2009-01-02 20:47:27 +000028#endif
Martin v. Löwis5344c992009-01-02 20:32:55 +000029
Martin v. Löwis73d538b2003-03-05 15:13:47 +000030#ifdef HAVE_LANGINFO_H
31#include <locale.h>
32#include <langinfo.h>
33#endif
34
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000035#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#undef BYTE
37#include "windows.h"
38#endif
39
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#ifndef Py_REF_DEBUG
Tim Peters62e97f02006-03-28 21:44:32 +000041#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#else /* Py_REF_DEBUG */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000043#define PRINT_TOTAL_REFS() fprintf(stderr, \
44 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
45 _Py_GetRefTotal())
Neal Norwitz4281cef2006-03-04 19:58:13 +000046#endif
47
Anthony Baxterac6bd462006-04-13 02:06:09 +000048#ifdef __cplusplus
49extern "C" {
50#endif
51
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000052extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossum82598051997-03-05 00:20:32 +000054extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossumb73cc041993-11-01 16:28:59 +000056/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initmain(void);
58static void initsite(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000059static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000060 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000061static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000062 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000063static void err_input(perrdetail *);
64static void initsigs(void);
Antoine Pitrouefb60c02009-10-20 21:29:37 +000065static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void call_sys_exitfunc(void);
67static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000068extern void _PyUnicode_Init(void);
69extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000070
Mark Hammond8d98d2c2003-04-19 15:41:53 +000071#ifdef WITH_THREAD
72extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
73extern void _PyGILState_Fini(void);
74#endif /* WITH_THREAD */
75
Guido van Rossum82598051997-03-05 00:20:32 +000076int Py_DebugFlag; /* Needed by parser.c */
77int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000078int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl11041f02011-05-15 08:50:32 +020079int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000080int Py_NoSiteFlag; /* Suppress 'import site' */
Christian Heimes1a6387e2008-03-26 12:49:49 +000081int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Georg Brandl2da0fce2008-01-07 17:09:35 +000082int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000083int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000084int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000085int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000086int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000087/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
88 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
89 true divisions (which they will be in 2.3). */
90int _Py_QnewFlag = 0;
Christian Heimesaf748c32008-05-06 22:41:46 +000091int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Barry Warsaw1e13eb02012-02-20 20:42:21 -050092int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000093
Benjamin Petersonc0bc4ef2014-06-16 19:39:18 -070094PyThreadState *_Py_Finalizing = NULL;
95
Christian Heimes51c4d722013-10-22 10:22:29 +020096
97/* Hack to force loading of object files */
98int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
99 PyOS_mystrnicmp; /* Python/pystrcmp.o */
100
Brett Cannone9746892008-04-12 23:44:07 +0000101/* PyModule_GetWarningsModule is no longer necessary as of 2.6
102since _warnings is builtin. This API should not be used. */
103PyObject *
104PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000105{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000106 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000107}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000108
Guido van Rossum25ce5661997-08-02 03:10:38 +0000109static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000110
Thomas Wouters7e474022000-07-16 12:04:32 +0000111/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000112
113int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000114Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000115{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000116 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000117}
118
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119/* Global initializations. Can be undone by Py_Finalize(). Don't
120 call this twice without an intervening Py_Finalize() call. When
121 initializations fail, a fatal error is issued and the function does
122 not return. On return, the first thread and interpreter state have
123 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000124
Guido van Rossum25ce5661997-08-02 03:10:38 +0000125 Locking: you must hold the interpreter lock while calling this.
126 (If the lock has not yet been initialized, that's equivalent to
127 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000128
Guido van Rossum25ce5661997-08-02 03:10:38 +0000129*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000130
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000131static int
132add_flag(int flag, const char *envs)
133{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000134 int env = atoi(envs);
135 if (flag < env)
136 flag = env;
137 if (flag < 1)
138 flag = 1;
139 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000140}
141
Guido van Rossuma027efa1997-05-05 20:56:21 +0000142void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000143Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000144{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000145 PyInterpreterState *interp;
146 PyThreadState *tstate;
147 PyObject *bimod, *sysmod;
148 char *p;
149 char *icodeset = NULL; /* On Windows, input codeset may theoretically
150 differ from output codeset. */
151 char *codeset = NULL;
152 char *errors = NULL;
153 int free_codeset = 0;
154 int overridden = 0;
155 PyObject *sys_stream, *sys_isatty;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000156#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000157 char *saved_locale, *loc_codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000158#endif
Martin v. Löwis99815892008-06-01 07:20:46 +0000159#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000160 char ibuf[128];
161 char buf[128];
Martin v. Löwis99815892008-06-01 07:20:46 +0000162#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000163 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000164
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000165 if (initialized)
166 return;
167 initialized = 1;
Benjamin Petersonc0bc4ef2014-06-16 19:39:18 -0700168 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000169
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000170 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
171 Py_DebugFlag = add_flag(Py_DebugFlag, p);
172 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
173 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
174 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
175 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
176 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
177 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500178 /* The variable is only tested for existence here; _PyRandom_Init will
179 check its value further. */
180 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
181 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
182
183 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000184
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000185 interp = PyInterpreterState_New();
186 if (interp == NULL)
187 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000188
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000189 tstate = PyThreadState_New(interp);
190 if (tstate == NULL)
191 Py_FatalError("Py_Initialize: can't make first thread");
192 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000193
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000194 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000195
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000196 if (!_PyFrame_Init())
197 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000198
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000199 if (!_PyInt_Init())
200 Py_FatalError("Py_Initialize: can't init ints");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000201
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000202 if (!_PyLong_Init())
203 Py_FatalError("Py_Initialize: can't init longs");
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000204
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000205 if (!PyByteArray_Init())
206 Py_FatalError("Py_Initialize: can't init bytearray");
Christian Heimes1a6387e2008-03-26 12:49:49 +0000207
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000208 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000209
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000210 interp->modules = PyDict_New();
211 if (interp->modules == NULL)
212 Py_FatalError("Py_Initialize: can't make modules dictionary");
213 interp->modules_reloading = PyDict_New();
214 if (interp->modules_reloading == NULL)
215 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000216
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000217#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000218 /* Init Unicode implementation; relies on the codec registry */
219 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000220#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000221
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000222 bimod = _PyBuiltin_Init();
223 if (bimod == NULL)
224 Py_FatalError("Py_Initialize: can't initialize __builtin__");
225 interp->builtins = PyModule_GetDict(bimod);
226 if (interp->builtins == NULL)
227 Py_FatalError("Py_Initialize: can't initialize builtins dict");
228 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000230 sysmod = _PySys_Init();
231 if (sysmod == NULL)
232 Py_FatalError("Py_Initialize: can't initialize sys");
233 interp->sysdict = PyModule_GetDict(sysmod);
234 if (interp->sysdict == NULL)
235 Py_FatalError("Py_Initialize: can't initialize sys dict");
236 Py_INCREF(interp->sysdict);
237 _PyImport_FixupExtension("sys", "sys");
238 PySys_SetPath(Py_GetPath());
239 PyDict_SetItemString(interp->sysdict, "modules",
240 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000241
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000242 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000243
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000244 /* initialize builtin exceptions */
245 _PyExc_Init();
246 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000247
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 /* phase 2 of builtins */
249 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000250
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000251 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000252
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000253 if (install_sigs)
254 initsigs(); /* Signal handling stuff, including initintr() */
Brett Cannonc33e82d2010-05-05 20:38:52 +0000255
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000256 /* Initialize warnings. */
257 _PyWarnings_Init();
258 if (PySys_HasWarnOptions()) {
259 PyObject *warnings_module = PyImport_ImportModule("warnings");
260 if (!warnings_module)
261 PyErr_Clear();
262 Py_XDECREF(warnings_module);
263 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000264
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000265 initmain(); /* Module __main__ */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000266
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000267 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000268#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000269 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000270#endif /* WITH_THREAD */
271
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000272 if (!Py_NoSiteFlag)
273 initsite(); /* Module site */
Victor Stinner66644262010-03-10 22:30:19 +0000274
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000275 if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
276 p = icodeset = codeset = strdup(p);
277 free_codeset = 1;
278 errors = strchr(p, ':');
279 if (errors) {
280 *errors = '\0';
281 errors++;
282 }
283 overridden = 1;
284 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000285
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000286#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000287 /* On Unix, set the file system encoding according to the
288 user's preference, if the CODESET names a well-known
289 Python codec, and Py_FileSystemDefaultEncoding isn't
290 initialized by other means. Also set the encoding of
291 stdin and stdout if these are terminals, unless overridden. */
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000292
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000293 if (!overridden || !Py_FileSystemDefaultEncoding) {
294 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
295 setlocale(LC_CTYPE, "");
296 loc_codeset = nl_langinfo(CODESET);
297 if (loc_codeset && *loc_codeset) {
298 PyObject *enc = PyCodec_Encoder(loc_codeset);
299 if (enc) {
300 loc_codeset = strdup(loc_codeset);
301 Py_DECREF(enc);
302 } else {
303 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
304 PyErr_Clear();
305 loc_codeset = NULL;
306 } else {
307 PyErr_Print();
308 exit(1);
309 }
310 }
311 } else
312 loc_codeset = NULL;
313 setlocale(LC_CTYPE, saved_locale);
314 free(saved_locale);
Martin v. Löwis99815892008-06-01 07:20:46 +0000315
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000316 if (!overridden) {
317 codeset = icodeset = loc_codeset;
318 free_codeset = 1;
319 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000320
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000321 /* Initialize Py_FileSystemDefaultEncoding from
322 locale even if PYTHONIOENCODING is set. */
323 if (!Py_FileSystemDefaultEncoding) {
324 Py_FileSystemDefaultEncoding = loc_codeset;
325 if (!overridden)
326 free_codeset = 0;
327 }
328 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000329#endif
330
331#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000332 if (!overridden) {
333 icodeset = ibuf;
334 codeset = buf;
335 sprintf(ibuf, "cp%d", GetConsoleCP());
336 sprintf(buf, "cp%d", GetConsoleOutputCP());
337 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000338#endif
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000339
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000340 if (codeset) {
341 sys_stream = PySys_GetObject("stdin");
342 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
343 if (!sys_isatty)
344 PyErr_Clear();
345 if ((overridden ||
346 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
347 PyFile_Check(sys_stream)) {
348 if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
349 Py_FatalError("Cannot set codeset of stdin");
350 }
351 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000352
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000353 sys_stream = PySys_GetObject("stdout");
354 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
355 if (!sys_isatty)
356 PyErr_Clear();
357 if ((overridden ||
358 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
359 PyFile_Check(sys_stream)) {
360 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
361 Py_FatalError("Cannot set codeset of stdout");
362 }
363 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000364
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000365 sys_stream = PySys_GetObject("stderr");
366 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
367 if (!sys_isatty)
368 PyErr_Clear();
369 if((overridden ||
370 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
371 PyFile_Check(sys_stream)) {
372 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
373 Py_FatalError("Cannot set codeset of stderr");
374 }
375 Py_XDECREF(sys_isatty);
Martin v. Löwisea62d252006-04-03 10:56:49 +0000376
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000377 if (free_codeset)
378 free(codeset);
379 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380}
381
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000382void
383Py_Initialize(void)
384{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000385 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000386}
387
388
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000389#ifdef COUNT_ALLOCS
Martin v. Löwis45294a92006-04-18 06:24:08 +0000390extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000391#endif
392
Guido van Rossum25ce5661997-08-02 03:10:38 +0000393/* Undo the effect of Py_Initialize().
394
395 Beware: if multiple interpreter and/or thread states exist, these
396 are not wiped out; only the current thread and interpreter state
397 are deleted. But since everything else is deleted, those other
398 interpreter and thread states should no longer be used.
399
400 (XXX We should do better, e.g. wipe out all interpreters and
401 threads.)
402
403 Locking: as above.
404
405*/
406
407void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000408Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000409{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000410 PyInterpreterState *interp;
411 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000412
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000413 if (!initialized)
414 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000415
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000416 wait_for_thread_shutdown();
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000417
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000418 /* The interpreter is still entirely intact at this point, and the
419 * exit funcs may be relying on that. In particular, if some thread
420 * or exit func is still waiting to do an import, the import machinery
421 * expects Py_IsInitialized() to return true. So don't say the
422 * interpreter is uninitialized until after the exit funcs have run.
423 * Note that Threading.py uses an exit func to do a join on all the
424 * threads created thru it, so this also protects pending imports in
425 * the threads created via Threading.
426 */
427 call_sys_exitfunc();
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000428
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000429 /* Get current thread state and interpreter pointer */
430 tstate = PyThreadState_GET();
431 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000432
Benjamin Petersonc0bc4ef2014-06-16 19:39:18 -0700433 /* Remaining threads (e.g. daemon threads) will automatically exit
434 after taking the GIL (in PyEval_RestoreThread()). */
435 _Py_Finalizing = tstate;
436 initialized = 0;
437
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000438 /* Disable signal handling */
439 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000440
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000441 /* Clear type lookup cache */
442 PyType_ClearCache();
Christian Heimes908caac2008-01-27 23:34:59 +0000443
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000444 /* Collect garbage. This may call finalizers; it's nice to call these
445 * before all modules are destroyed.
446 * XXX If a __del__ or weakref callback is triggered here, and tries to
447 * XXX import a module, bad things can happen, because Python no
448 * XXX longer believes it's initialized.
449 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
450 * XXX is easy to provoke that way. I've also seen, e.g.,
451 * XXX Exception exceptions.ImportError: 'No module named sha'
452 * XXX in <function callback at 0x008F5718> ignored
453 * XXX but I'm unclear on exactly how that one happens. In any case,
454 * XXX I haven't seen a real-life report of either of these.
455 */
456 PyGC_Collect();
Martin v. Löwis45294a92006-04-18 06:24:08 +0000457#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000458 /* With COUNT_ALLOCS, it helps to run GC multiple times:
459 each collection might release some types from the type
460 list, so they become garbage. */
461 while (PyGC_Collect() > 0)
462 /* nothing */;
Martin v. Löwis45294a92006-04-18 06:24:08 +0000463#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000464
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000465 /* Destroy all modules */
466 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000467
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000468 /* Collect final garbage. This disposes of cycles created by
469 * new-style class definitions, for example.
470 * XXX This is disabled because it caused too many problems. If
471 * XXX a __del__ or weakref callback triggers here, Python code has
472 * XXX a hard time running, because even the sys module has been
473 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
474 * XXX One symptom is a sequence of information-free messages
475 * XXX coming from threads (if a __del__ or callback is invoked,
476 * XXX other threads can execute too, and any exception they encounter
477 * XXX triggers a comedy of errors as subsystem after subsystem
478 * XXX fails to find what it *expects* to find in sys to help report
479 * XXX the exception and consequent unexpected failures). I've also
480 * XXX seen segfaults then, after adding print statements to the
481 * XXX Python code getting called.
482 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000483#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000484 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000485#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000486
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000487 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
488 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000489
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000490 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000491#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000492 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000493#endif
494
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000495 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000496
Tim Peters9cf25ce2003-04-17 15:21:01 +0000497#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000498 /* Display all objects still alive -- this can invoke arbitrary
499 * __repr__ overrides, so requires a mostly-intact interpreter.
500 * Alas, a lot of stuff may still be alive now that will be cleaned
501 * up later.
502 */
503 if (Py_GETENV("PYTHONDUMPREFS"))
504 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000505#endif /* Py_TRACE_REFS */
506
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000507 /* Clear interpreter state */
508 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000509
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000510 /* Now we decref the exception classes. After this point nothing
511 can raise an exception. That's okay, because each Fini() method
512 below has been checked to make sure no exceptions are ever
513 raised.
514 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000515
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000516 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000517
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000518 /* Cleanup auto-thread-state */
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000519#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000520 _PyGILState_Fini();
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000521#endif /* WITH_THREAD */
522
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000523 /* Delete current thread */
524 PyThreadState_Swap(NULL);
525 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000526
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000527 /* Sundry finalizers */
528 PyMethod_Fini();
529 PyFrame_Fini();
530 PyCFunction_Fini();
531 PyTuple_Fini();
532 PyList_Fini();
533 PySet_Fini();
534 PyString_Fini();
535 PyByteArray_Fini();
536 PyInt_Fini();
537 PyFloat_Fini();
538 PyDict_Fini();
Benjamin Peterson57057a62014-08-28 12:30:00 -0400539 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000540
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000541#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000542 /* Cleanup Unicode implementation */
543 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000544#endif
545
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000546 /* XXX Still allocated:
547 - various static ad-hoc pointers to interned strings
548 - int and float free list blocks
549 - whatever various modules and libraries allocate
550 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000551
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000552 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000553
Tim Peters269b2a62003-04-17 19:52:29 +0000554#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000555 /* Display addresses (& refcnts) of all objects still alive.
556 * An address can be used to find the repr of the object, printed
557 * above by _Py_PrintReferences.
558 */
559 if (Py_GETENV("PYTHONDUMPREFS"))
560 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000561#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000562#ifdef PYMALLOC_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000563 if (Py_GETENV("PYTHONMALLOCSTATS"))
564 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000565#endif
566
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000567 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000568}
569
570/* Create and initialize a new interpreter and thread, and return the
571 new thread. This requires that Py_Initialize() has been called
572 first.
573
574 Unsuccessful initialization yields a NULL pointer. Note that *no*
575 exception information is available even in this case -- the
576 exception information is held in the thread, and there is no
577 thread.
578
579 Locking: as above.
580
581*/
582
583PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000584Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000586 PyInterpreterState *interp;
587 PyThreadState *tstate, *save_tstate;
588 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000590 if (!initialized)
591 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000592
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000593 interp = PyInterpreterState_New();
594 if (interp == NULL)
595 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000597 tstate = PyThreadState_New(interp);
598 if (tstate == NULL) {
599 PyInterpreterState_Delete(interp);
600 return NULL;
601 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000602
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000603 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000605 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000606
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000607 interp->modules = PyDict_New();
608 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000609
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000610 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
611 if (bimod != NULL) {
612 interp->builtins = PyModule_GetDict(bimod);
613 if (interp->builtins == NULL)
614 goto handle_error;
615 Py_INCREF(interp->builtins);
616 }
617 sysmod = _PyImport_FindExtension("sys", "sys");
618 if (bimod != NULL && sysmod != NULL) {
619 interp->sysdict = PyModule_GetDict(sysmod);
620 if (interp->sysdict == NULL)
621 goto handle_error;
622 Py_INCREF(interp->sysdict);
623 PySys_SetPath(Py_GetPath());
624 PyDict_SetItemString(interp->sysdict, "modules",
625 interp->modules);
626 _PyImportHooks_Init();
627 initmain();
628 if (!Py_NoSiteFlag)
629 initsite();
630 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000632 if (!PyErr_Occurred())
633 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000634
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000635handle_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000638 PyErr_Print();
639 PyThreadState_Clear(tstate);
640 PyThreadState_Swap(save_tstate);
641 PyThreadState_Delete(tstate);
642 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000643
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000644 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000645}
646
647/* Delete an interpreter and its last thread. This requires that the
648 given thread state is current, that the thread has no remaining
649 frames, and that it is its interpreter's only remaining thread.
650 It is a fatal error to violate these constraints.
651
652 (Py_Finalize() doesn't have these constraints -- it zaps
653 everything, regardless.)
654
655 Locking: as above.
656
657*/
658
659void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000660Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000662 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000663
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000664 if (tstate != PyThreadState_GET())
665 Py_FatalError("Py_EndInterpreter: thread is not current");
666 if (tstate->frame != NULL)
667 Py_FatalError("Py_EndInterpreter: thread still has a frame");
668 if (tstate != interp->tstate_head || tstate->next != NULL)
669 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000670
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000671 PyImport_Cleanup();
672 PyInterpreterState_Clear(interp);
673 PyThreadState_Swap(NULL);
674 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000675}
676
677static char *progname = "python";
678
679void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000680Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000681{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000682 if (pn && *pn)
683 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000684}
685
686char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000687Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000688{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000689 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000690}
691
Guido van Rossuma61691e1998-02-06 22:27:24 +0000692static char *default_home = NULL;
693
694void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000695Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000696{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000697 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000698}
699
700char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000701Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000702{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000703 char *home = default_home;
704 if (home == NULL && !Py_IgnoreEnvironmentFlag)
705 home = Py_GETENV("PYTHONHOME");
706 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000707}
708
Guido van Rossum6135a871995-01-09 17:53:26 +0000709/* Create __main__ module */
710
711static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000712initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000713{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000714 PyObject *m, *d;
715 m = PyImport_AddModule("__main__");
716 if (m == NULL)
717 Py_FatalError("can't create __main__ module");
718 d = PyModule_GetDict(m);
719 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
720 PyObject *bimod = PyImport_ImportModule("__builtin__");
721 if (bimod == NULL ||
722 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
723 Py_FatalError("can't add __builtins__ to __main__");
724 Py_XDECREF(bimod);
725 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000726}
727
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000728/* Import the site module (not into __main__ though) */
729
730static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000731initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000732{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000733 PyObject *m;
734 m = PyImport_ImportModule("site");
735 if (m == NULL) {
736 PyErr_Print();
737 Py_Finalize();
738 exit(1);
739 }
740 else {
741 Py_DECREF(m);
742 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000743}
744
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000745/* Parse input from a file and execute it */
746
747int
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000748PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000749 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000750{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751 if (filename == NULL)
752 filename = "???";
753 if (Py_FdIsInteractive(fp, filename)) {
754 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
755 if (closeit)
756 fclose(fp);
757 return err;
758 }
759 else
760 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000761}
762
763int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000764PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000765{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000766 PyObject *v;
767 int ret;
768 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000769
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000770 if (flags == NULL) {
771 flags = &local_flags;
772 local_flags.cf_flags = 0;
773 }
774 v = PySys_GetObject("ps1");
775 if (v == NULL) {
776 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
777 Py_XDECREF(v);
778 }
779 v = PySys_GetObject("ps2");
780 if (v == NULL) {
781 PySys_SetObject("ps2", v = PyString_FromString("... "));
782 Py_XDECREF(v);
783 }
784 for (;;) {
785 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
786 PRINT_TOTAL_REFS();
787 if (ret == E_EOF)
788 return 0;
789 /*
790 if (ret == E_NOMEM)
791 return -1;
792 */
793 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000794}
795
Eric Smith7c478942008-03-18 23:45:49 +0000796#if 0
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000797/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000798#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000799 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
800 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Eric Smith7c478942008-03-18 23:45:49 +0000801#endif
802#if 1
Neal Norwitzca460d92006-09-06 06:28:06 +0000803/* Keep an example of flags with future keyword support. */
804#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000805 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
806 PyPARSE_DONT_IMPLY_DEDENT : 0) \
807 | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
808 PyPARSE_PRINT_IS_FUNCTION : 0) \
809 | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
810 PyPARSE_UNICODE_LITERALS : 0) \
811 ) : 0)
Neal Norwitzca460d92006-09-06 06:28:06 +0000812#endif
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000813
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000814int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000815PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000816{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000817 PyObject *m, *d, *v, *w;
818 mod_ty mod;
819 PyArena *arena;
820 char *ps1 = "", *ps2 = "";
821 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000822
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000823 v = PySys_GetObject("ps1");
824 if (v != NULL) {
825 v = PyObject_Str(v);
826 if (v == NULL)
827 PyErr_Clear();
828 else if (PyString_Check(v))
829 ps1 = PyString_AsString(v);
830 }
831 w = PySys_GetObject("ps2");
832 if (w != NULL) {
833 w = PyObject_Str(w);
834 if (w == NULL)
835 PyErr_Clear();
836 else if (PyString_Check(w))
837 ps2 = PyString_AsString(w);
838 }
839 arena = PyArena_New();
840 if (arena == NULL) {
841 Py_XDECREF(v);
842 Py_XDECREF(w);
843 return -1;
844 }
845 mod = PyParser_ASTFromFile(fp, filename,
846 Py_single_input, ps1, ps2,
847 flags, &errcode, arena);
848 Py_XDECREF(v);
849 Py_XDECREF(w);
850 if (mod == NULL) {
851 PyArena_Free(arena);
852 if (errcode == E_EOF) {
853 PyErr_Clear();
854 return E_EOF;
855 }
856 PyErr_Print();
857 return -1;
858 }
859 m = PyImport_AddModule("__main__");
860 if (m == NULL) {
861 PyArena_Free(arena);
862 return -1;
863 }
864 d = PyModule_GetDict(m);
865 v = run_mod(mod, filename, d, d, flags, arena);
866 PyArena_Free(arena);
867 if (v == NULL) {
868 PyErr_Print();
869 return -1;
870 }
871 Py_DECREF(v);
872 if (Py_FlushLine())
873 PyErr_Clear();
874 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000875}
876
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000877/* Check whether a file maybe a pyc file: Look at the extension,
878 the file type, and, if we may close it, at the first few bytes. */
879
880static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000881maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000882{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000883 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
884 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000885
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000886 /* Only look into the file if we are allowed to close it, since
887 it then should also be seekable. */
888 if (closeit) {
889 /* Read only two bytes of the magic. If the file was opened in
890 text mode, the bytes 3 and 4 of the magic (\r\n) might not
891 be read as they are on disk. */
892 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
893 unsigned char buf[2];
894 /* Mess: In case of -x, the stream is NOT at its start now,
895 and ungetc() was used to push back the first newline,
896 which makes the current stream position formally undefined,
897 and a x-platform nightmare.
898 Unfortunately, we have no direct way to know whether -x
899 was specified. So we use a terrible hack: if the current
900 stream position is not 0, we assume -x was specified, and
901 give up. Bug 132850 on SourceForge spells out the
902 hopelessness of trying anything else (fseek and ftell
903 don't work predictably x-platform for text-mode files).
904 */
905 int ispyc = 0;
906 if (ftell(fp) == 0) {
907 if (fread(buf, 1, 2, fp) == 2 &&
908 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
909 ispyc = 1;
910 rewind(fp);
911 }
912 return ispyc;
913 }
914 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000915}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000916
Guido van Rossum0df002c2000-08-27 19:21:52 +0000917int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000918PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000919 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000920{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000921 PyObject *m, *d, *v;
922 const char *ext;
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100923 int set_file_name = 0, len, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000924
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000925 m = PyImport_AddModule("__main__");
926 if (m == NULL)
927 return -1;
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100928 Py_INCREF(m);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000929 d = PyModule_GetDict(m);
930 if (PyDict_GetItemString(d, "__file__") == NULL) {
931 PyObject *f = PyString_FromString(filename);
932 if (f == NULL)
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100933 goto done;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000934 if (PyDict_SetItemString(d, "__file__", f) < 0) {
935 Py_DECREF(f);
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100936 goto done;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000937 }
938 set_file_name = 1;
939 Py_DECREF(f);
940 }
941 len = strlen(filename);
942 ext = filename + len - (len > 4 ? 4 : 0);
943 if (maybe_pyc_file(fp, filename, ext, closeit)) {
944 /* Try to run a pyc file. First, re-open in binary */
945 if (closeit)
946 fclose(fp);
947 if ((fp = fopen(filename, "rb")) == NULL) {
948 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000949 goto done;
950 }
951 /* Turn on optimization if a .pyo file is given */
952 if (strcmp(ext, ".pyo") == 0)
953 Py_OptimizeFlag = 1;
954 v = run_pyc_file(fp, filename, d, d, flags);
955 } else {
956 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
957 closeit, flags);
958 }
959 if (v == NULL) {
960 PyErr_Print();
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 goto done;
962 }
963 Py_DECREF(v);
964 if (Py_FlushLine())
965 PyErr_Clear();
966 ret = 0;
Georg Brandlaa2321b2007-03-07 00:40:28 +0000967 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000968 if (set_file_name && PyDict_DelItemString(d, "__file__"))
969 PyErr_Clear();
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100970 Py_DECREF(m);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000971 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000972}
973
974int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000975PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000976{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000977 PyObject *m, *d, *v;
978 m = PyImport_AddModule("__main__");
979 if (m == NULL)
980 return -1;
981 d = PyModule_GetDict(m);
982 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
983 if (v == NULL) {
984 PyErr_Print();
985 return -1;
986 }
987 Py_DECREF(v);
988 if (Py_FlushLine())
989 PyErr_Clear();
990 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000991}
992
Barry Warsaw035574d1997-08-29 22:07:17 +0000993static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000994parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000995 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000996{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000997 long hold;
998 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +0000999
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001000 /* old style errors */
1001 if (PyTuple_Check(err))
1002 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1003 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001004
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001005 *message = NULL;
1006
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001007 /* new style errors. `err' is an instance */
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001008 *message = PyObject_GetAttrString(err, "msg");
1009 if (!*message)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001010 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001011
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001012 v = PyObject_GetAttrString(err, "filename");
1013 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001014 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001015 if (v == Py_None) {
1016 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001017 *filename = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001018 }
1019 else {
1020 *filename = PyString_AsString(v);
1021 Py_DECREF(v);
1022 if (!*filename)
1023 goto finally;
1024 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001025
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001026 v = PyObject_GetAttrString(err, "lineno");
1027 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001028 goto finally;
1029 hold = PyInt_AsLong(v);
1030 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001031 if (hold < 0 && PyErr_Occurred())
1032 goto finally;
1033 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001034
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001035 v = PyObject_GetAttrString(err, "offset");
1036 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001037 goto finally;
1038 if (v == Py_None) {
1039 *offset = -1;
1040 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001041 } else {
1042 hold = PyInt_AsLong(v);
1043 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001044 if (hold < 0 && PyErr_Occurred())
1045 goto finally;
1046 *offset = (int)hold;
1047 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001048
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001049 v = PyObject_GetAttrString(err, "text");
1050 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001051 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001052 if (v == Py_None) {
1053 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001054 *text = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001055 }
1056 else {
1057 *text = PyString_AsString(v);
1058 Py_DECREF(v);
1059 if (!*text)
1060 goto finally;
1061 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001062 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001063
1064finally:
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001065 Py_XDECREF(*message);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001066 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001067}
1068
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001069void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001070PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001071{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001072 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001073}
1074
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001075static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001076print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001077{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001078 char *nl;
1079 if (offset >= 0) {
Benjamin Petersonec9f9f52010-10-29 03:45:34 +00001080 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1081 offset--;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001082 for (;;) {
1083 nl = strchr(text, '\n');
1084 if (nl == NULL || nl-text >= offset)
1085 break;
1086 offset -= (int)(nl+1-text);
1087 text = nl+1;
1088 }
1089 while (*text == ' ' || *text == '\t') {
1090 text++;
1091 offset--;
1092 }
1093 }
1094 PyFile_WriteString(" ", f);
1095 PyFile_WriteString(text, f);
1096 if (*text == '\0' || text[strlen(text)-1] != '\n')
1097 PyFile_WriteString("\n", f);
1098 if (offset == -1)
1099 return;
1100 PyFile_WriteString(" ", f);
1101 offset--;
1102 while (offset > 0) {
1103 PyFile_WriteString(" ", f);
1104 offset--;
1105 }
1106 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001107}
1108
Guido van Rossum66e8e862001-03-23 17:54:43 +00001109static void
1110handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001111{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001112 PyObject *exception, *value, *tb;
1113 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001114
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001115 if (Py_InspectFlag)
1116 /* Don't exit if -i flag was given. This flag is set to 0
1117 * when entering interactive mode for inspecting. */
1118 return;
Georg Brandl49aafc92007-03-07 00:34:46 +00001119
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001120 PyErr_Fetch(&exception, &value, &tb);
1121 if (Py_FlushLine())
1122 PyErr_Clear();
1123 fflush(stdout);
1124 if (value == NULL || value == Py_None)
1125 goto done;
1126 if (PyExceptionInstance_Check(value)) {
1127 /* The error code should be in the `code' attribute. */
1128 PyObject *code = PyObject_GetAttrString(value, "code");
1129 if (code) {
1130 Py_DECREF(value);
1131 value = code;
1132 if (value == Py_None)
1133 goto done;
1134 }
1135 /* If we failed to dig out the 'code' attribute,
1136 just let the else clause below print the error. */
1137 }
1138 if (PyInt_Check(value))
1139 exitcode = (int)PyInt_AsLong(value);
1140 else {
Victor Stinnerc49dfcc2010-05-25 22:30:32 +00001141 PyObject *sys_stderr = PySys_GetObject("stderr");
1142 if (sys_stderr != NULL && sys_stderr != Py_None) {
1143 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1144 } else {
1145 PyObject_Print(value, stderr, Py_PRINT_RAW);
1146 fflush(stderr);
1147 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001148 PySys_WriteStderr("\n");
1149 exitcode = 1;
1150 }
Tim Peterscf615b52003-04-19 18:47:02 +00001151 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001152 /* Restore and clear the exception info, in order to properly decref
1153 * the exception, value, and traceback. If we just exit instead,
1154 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1155 * some finalizers from running.
1156 */
1157 PyErr_Restore(exception, value, tb);
1158 PyErr_Clear();
1159 Py_Exit(exitcode);
1160 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001161}
1162
1163void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001164PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001165{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001166 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001167
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001168 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1169 handle_system_exit();
1170 }
1171 PyErr_Fetch(&exception, &v, &tb);
1172 if (exception == NULL)
1173 return;
1174 PyErr_NormalizeException(&exception, &v, &tb);
1175 if (exception == NULL)
1176 return;
1177 /* Now we know v != NULL too */
1178 if (set_sys_last_vars) {
1179 PySys_SetObject("last_type", exception);
1180 PySys_SetObject("last_value", v);
1181 PySys_SetObject("last_traceback", tb);
1182 }
1183 hook = PySys_GetObject("excepthook");
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001184 if (hook && hook != Py_None) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001185 PyObject *args = PyTuple_Pack(3,
1186 exception, v, tb ? tb : Py_None);
1187 PyObject *result = PyEval_CallObject(hook, args);
1188 if (result == NULL) {
1189 PyObject *exception2, *v2, *tb2;
1190 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1191 handle_system_exit();
1192 }
1193 PyErr_Fetch(&exception2, &v2, &tb2);
1194 PyErr_NormalizeException(&exception2, &v2, &tb2);
1195 /* It should not be possible for exception2 or v2
1196 to be NULL. However PyErr_Display() can't
1197 tolerate NULLs, so just be safe. */
1198 if (exception2 == NULL) {
1199 exception2 = Py_None;
1200 Py_INCREF(exception2);
1201 }
1202 if (v2 == NULL) {
1203 v2 = Py_None;
1204 Py_INCREF(v2);
1205 }
1206 if (Py_FlushLine())
1207 PyErr_Clear();
1208 fflush(stdout);
1209 PySys_WriteStderr("Error in sys.excepthook:\n");
1210 PyErr_Display(exception2, v2, tb2);
1211 PySys_WriteStderr("\nOriginal exception was:\n");
1212 PyErr_Display(exception, v, tb);
1213 Py_DECREF(exception2);
1214 Py_DECREF(v2);
1215 Py_XDECREF(tb2);
1216 }
1217 Py_XDECREF(result);
1218 Py_XDECREF(args);
1219 } else {
1220 PySys_WriteStderr("sys.excepthook is missing\n");
1221 PyErr_Display(exception, v, tb);
1222 }
1223 Py_XDECREF(exception);
1224 Py_XDECREF(v);
1225 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001226}
1227
Richard Jones7b9558d2006-05-27 12:29:24 +00001228void
1229PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001230{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001231 int err = 0;
1232 PyObject *f = PySys_GetObject("stderr");
1233 Py_INCREF(value);
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001234 if (f == NULL || f == Py_None)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001235 fprintf(stderr, "lost sys.stderr\n");
1236 else {
1237 if (Py_FlushLine())
1238 PyErr_Clear();
1239 fflush(stdout);
1240 if (tb && tb != Py_None)
1241 err = PyTraceBack_Print(tb, f);
1242 if (err == 0 &&
1243 PyObject_HasAttrString(value, "print_file_and_line"))
1244 {
1245 PyObject *message;
1246 const char *filename, *text;
1247 int lineno, offset;
1248 if (!parse_syntax_error(value, &message, &filename,
1249 &lineno, &offset, &text))
1250 PyErr_Clear();
1251 else {
1252 char buf[10];
1253 PyFile_WriteString(" File \"", f);
1254 if (filename == NULL)
1255 PyFile_WriteString("<string>", f);
1256 else
1257 PyFile_WriteString(filename, f);
1258 PyFile_WriteString("\", line ", f);
1259 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1260 PyFile_WriteString(buf, f);
1261 PyFile_WriteString("\n", f);
1262 if (text != NULL)
1263 print_error_text(f, offset, text);
1264 Py_DECREF(value);
1265 value = message;
1266 /* Can't be bothered to check all those
1267 PyFile_WriteString() calls */
1268 if (PyErr_Occurred())
1269 err = -1;
1270 }
1271 }
1272 if (err) {
1273 /* Don't do anything else */
1274 }
1275 else if (PyExceptionClass_Check(exception)) {
1276 PyObject* moduleName;
1277 char* className = PyExceptionClass_Name(exception);
1278 if (className != NULL) {
1279 char *dot = strrchr(className, '.');
1280 if (dot != NULL)
1281 className = dot+1;
1282 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001283
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001284 moduleName = PyObject_GetAttrString(exception, "__module__");
1285 if (moduleName == NULL)
1286 err = PyFile_WriteString("<unknown>", f);
1287 else {
1288 char* modstr = PyString_AsString(moduleName);
1289 if (modstr && strcmp(modstr, "exceptions"))
1290 {
1291 err = PyFile_WriteString(modstr, f);
1292 err += PyFile_WriteString(".", f);
1293 }
1294 Py_DECREF(moduleName);
1295 }
1296 if (err == 0) {
1297 if (className == NULL)
1298 err = PyFile_WriteString("<unknown>", f);
1299 else
1300 err = PyFile_WriteString(className, f);
1301 }
1302 }
1303 else
1304 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1305 if (err == 0 && (value != Py_None)) {
1306 PyObject *s = PyObject_Str(value);
1307 /* only print colon if the str() of the
1308 object is not the empty string
1309 */
1310 if (s == NULL)
1311 err = -1;
1312 else if (!PyString_Check(s) ||
1313 PyString_GET_SIZE(s) != 0)
1314 err = PyFile_WriteString(": ", f);
1315 if (err == 0)
1316 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1317 Py_XDECREF(s);
1318 }
1319 /* try to write a newline in any case */
1320 err += PyFile_WriteString("\n", f);
1321 }
1322 Py_DECREF(value);
1323 /* If an error happened here, don't show it.
1324 XXX This is wrong, but too many callers rely on this behavior. */
1325 if (err != 0)
1326 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001327}
1328
Guido van Rossum82598051997-03-05 00:20:32 +00001329PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001330PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001331 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001332{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001333 PyObject *ret = NULL;
1334 mod_ty mod;
1335 PyArena *arena = PyArena_New();
1336 if (arena == NULL)
1337 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001338
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001339 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1340 if (mod != NULL)
1341 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1342 PyArena_Free(arena);
1343 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001344}
1345
1346PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001347PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001348 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001349{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001350 PyObject *ret;
1351 mod_ty mod;
1352 PyArena *arena = PyArena_New();
1353 if (arena == NULL)
1354 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001355
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001356 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1357 flags, NULL, arena);
1358 if (closeit)
1359 fclose(fp);
1360 if (mod == NULL) {
1361 PyArena_Free(arena);
1362 return NULL;
1363 }
1364 ret = run_mod(mod, filename, globals, locals, flags, arena);
1365 PyArena_Free(arena);
1366 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001367}
1368
Guido van Rossum82598051997-03-05 00:20:32 +00001369static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001371 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001372{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001373 PyCodeObject *co;
1374 PyObject *v;
1375 co = PyAST_Compile(mod, filename, flags, arena);
1376 if (co == NULL)
1377 return NULL;
1378 v = PyEval_EvalCode(co, globals, locals);
1379 Py_DECREF(co);
1380 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001381}
1382
Guido van Rossum82598051997-03-05 00:20:32 +00001383static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001384run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001385 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001386{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001387 PyCodeObject *co;
1388 PyObject *v;
1389 long magic;
1390 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001392 magic = PyMarshal_ReadLongFromFile(fp);
1393 if (magic != PyImport_GetMagicNumber()) {
1394 PyErr_SetString(PyExc_RuntimeError,
1395 "Bad magic number in .pyc file");
1396 return NULL;
1397 }
1398 (void) PyMarshal_ReadLongFromFile(fp);
1399 v = PyMarshal_ReadLastObjectFromFile(fp);
1400 fclose(fp);
1401 if (v == NULL || !PyCode_Check(v)) {
1402 Py_XDECREF(v);
1403 PyErr_SetString(PyExc_RuntimeError,
1404 "Bad code object in .pyc file");
1405 return NULL;
1406 }
1407 co = (PyCodeObject *)v;
1408 v = PyEval_EvalCode(co, globals, locals);
1409 if (v && flags)
1410 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1411 Py_DECREF(co);
1412 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001413}
1414
Guido van Rossum82598051997-03-05 00:20:32 +00001415PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001416Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001417 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001418{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001419 PyCodeObject *co;
1420 mod_ty mod;
1421 PyArena *arena = PyArena_New();
1422 if (arena == NULL)
1423 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001424
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001425 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1426 if (mod == NULL) {
1427 PyArena_Free(arena);
1428 return NULL;
1429 }
1430 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1431 PyObject *result = PyAST_mod2obj(mod);
1432 PyArena_Free(arena);
1433 return result;
1434 }
1435 co = PyAST_Compile(mod, filename, flags, arena);
1436 PyArena_Free(arena);
1437 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001438}
1439
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001440struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001441Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001442{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 struct symtable *st;
1444 mod_ty mod;
1445 PyCompilerFlags flags;
1446 PyArena *arena = PyArena_New();
1447 if (arena == NULL)
1448 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001449
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001450 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001451
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001452 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1453 if (mod == NULL) {
1454 PyArena_Free(arena);
1455 return NULL;
1456 }
1457 st = PySymtable_Build(mod, filename, 0);
1458 PyArena_Free(arena);
1459 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001460}
1461
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462/* Preferred access to parser is through AST. */
1463mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001464PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001465 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001467 mod_ty mod;
1468 PyCompilerFlags localflags;
1469 perrdetail err;
1470 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001471
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001472 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1473 &_PyParser_Grammar, start, &err,
1474 &iflags);
1475 if (flags == NULL) {
1476 localflags.cf_flags = 0;
1477 flags = &localflags;
1478 }
1479 if (n) {
1480 flags->cf_flags |= iflags & PyCF_MASK;
1481 mod = PyAST_FromNode(n, flags, filename, arena);
1482 PyNode_Free(n);
1483 return mod;
1484 }
1485 else {
1486 err_input(&err);
1487 return NULL;
1488 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489}
1490
1491mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001492PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001493 char *ps2, PyCompilerFlags *flags, int *errcode,
1494 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001496 mod_ty mod;
1497 PyCompilerFlags localflags;
1498 perrdetail err;
1499 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001500
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001501 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1502 start, ps1, ps2, &err, &iflags);
1503 if (flags == NULL) {
1504 localflags.cf_flags = 0;
1505 flags = &localflags;
1506 }
1507 if (n) {
1508 flags->cf_flags |= iflags & PyCF_MASK;
1509 mod = PyAST_FromNode(n, flags, filename, arena);
1510 PyNode_Free(n);
1511 return mod;
1512 }
1513 else {
1514 err_input(&err);
1515 if (errcode)
1516 *errcode = err.error;
1517 return NULL;
1518 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519}
1520
Guido van Rossuma110aa61994-08-29 12:50:44 +00001521/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001522
Guido van Rossuma110aa61994-08-29 12:50:44 +00001523node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001524PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001525{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001526 perrdetail err;
1527 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1528 start, NULL, NULL, &err, flags);
1529 if (n == NULL)
1530 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001532 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001533}
1534
Guido van Rossuma110aa61994-08-29 12:50:44 +00001535/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001536
Guido van Rossuma110aa61994-08-29 12:50:44 +00001537node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001538PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001539{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001540 perrdetail err;
1541 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1542 start, &err, flags);
1543 if (n == NULL)
1544 err_input(&err);
1545 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001546}
1547
1548node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001549PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001550 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001551{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001552 perrdetail err;
1553 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1554 &_PyParser_Grammar, start, &err, flags);
1555 if (n == NULL)
1556 err_input(&err);
1557 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001558}
1559
1560node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001561PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001562{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001563 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001564}
1565
Guido van Rossum66ebd912003-04-17 16:02:26 +00001566/* May want to move a more generalized form of this to parsetok.c or
1567 even parser modules. */
1568
1569void
1570PyParser_SetError(perrdetail *err)
1571{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001572 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001573}
1574
Guido van Rossuma110aa61994-08-29 12:50:44 +00001575/* Set the error appropriate to the given input error code (see errcode.h) */
1576
1577static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001578err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001579{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001580 PyObject *v, *w, *errtype;
1581 PyObject* u = NULL;
1582 char *msg = NULL;
1583 errtype = PyExc_SyntaxError;
1584 switch (err->error) {
1585 case E_ERROR:
1586 return;
1587 case E_SYNTAX:
1588 errtype = PyExc_IndentationError;
1589 if (err->expected == INDENT)
1590 msg = "expected an indented block";
1591 else if (err->token == INDENT)
1592 msg = "unexpected indent";
1593 else if (err->token == DEDENT)
1594 msg = "unexpected unindent";
1595 else {
1596 errtype = PyExc_SyntaxError;
1597 msg = "invalid syntax";
1598 }
1599 break;
1600 case E_TOKEN:
1601 msg = "invalid token";
1602 break;
1603 case E_EOFS:
1604 msg = "EOF while scanning triple-quoted string literal";
1605 break;
1606 case E_EOLS:
1607 msg = "EOL while scanning string literal";
1608 break;
1609 case E_INTR:
1610 if (!PyErr_Occurred())
1611 PyErr_SetNone(PyExc_KeyboardInterrupt);
1612 goto cleanup;
1613 case E_NOMEM:
1614 PyErr_NoMemory();
1615 goto cleanup;
1616 case E_EOF:
1617 msg = "unexpected EOF while parsing";
1618 break;
1619 case E_TABSPACE:
1620 errtype = PyExc_TabError;
1621 msg = "inconsistent use of tabs and spaces in indentation";
1622 break;
1623 case E_OVERFLOW:
1624 msg = "expression too long";
1625 break;
1626 case E_DEDENT:
1627 errtype = PyExc_IndentationError;
1628 msg = "unindent does not match any outer indentation level";
1629 break;
1630 case E_TOODEEP:
1631 errtype = PyExc_IndentationError;
1632 msg = "too many levels of indentation";
1633 break;
1634 case E_DECODE: {
1635 PyObject *type, *value, *tb;
1636 PyErr_Fetch(&type, &value, &tb);
1637 if (value != NULL) {
1638 u = PyObject_Str(value);
1639 if (u != NULL) {
1640 msg = PyString_AsString(u);
1641 }
1642 }
1643 if (msg == NULL)
1644 msg = "unknown decode error";
1645 Py_XDECREF(type);
1646 Py_XDECREF(value);
1647 Py_XDECREF(tb);
1648 break;
1649 }
1650 case E_LINECONT:
1651 msg = "unexpected character after line continuation character";
1652 break;
1653 default:
1654 fprintf(stderr, "error=%d\n", err->error);
1655 msg = "unknown parsing error";
1656 break;
1657 }
1658 v = Py_BuildValue("(ziiz)", err->filename,
1659 err->lineno, err->offset, err->text);
1660 w = NULL;
1661 if (v != NULL)
1662 w = Py_BuildValue("(sO)", msg, v);
1663 Py_XDECREF(u);
1664 Py_XDECREF(v);
1665 PyErr_SetObject(errtype, w);
1666 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001667cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001668 if (err->text != NULL) {
1669 PyObject_FREE(err->text);
1670 err->text = NULL;
1671 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001672}
1673
1674/* Print fatal error message and abort */
1675
1676void
Tim Peters7c321a82002-07-09 02:57:01 +00001677Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001678{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001679 fprintf(stderr, "Fatal Python error: %s\n", msg);
1680 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller42f9b4e2009-03-31 22:20:35 +00001681
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001682#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001683 {
1684 size_t len = strlen(msg);
1685 WCHAR* buffer;
1686 size_t i;
Martin v. Löwis5344c992009-01-02 20:32:55 +00001687
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001688 /* Convert the message to wchar_t. This uses a simple one-to-one
1689 conversion, assuming that the this error message actually uses ASCII
1690 only. If this ceases to be true, we will have to convert. */
1691 buffer = alloca( (len+1) * (sizeof *buffer));
1692 for( i=0; i<=len; ++i)
1693 buffer[i] = msg[i];
1694 OutputDebugStringW(L"Fatal Python error: ");
1695 OutputDebugStringW(buffer);
1696 OutputDebugStringW(L"\n");
1697 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001698#ifdef _DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001699 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001700#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001701#endif /* MS_WINDOWS */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001702 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001703}
1704
1705/* Clean up and exit */
1706
Guido van Rossuma110aa61994-08-29 12:50:44 +00001707#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001708#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001709#endif
1710
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001711/* Wait until threading._shutdown completes, provided
1712 the threading module was imported in the first place.
1713 The shutdown routine will wait until all non-daemon
1714 "threading" threads have completed. */
1715static void
1716wait_for_thread_shutdown(void)
1717{
1718#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001719 PyObject *result;
1720 PyThreadState *tstate = PyThreadState_GET();
1721 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1722 "threading");
1723 if (threading == NULL) {
1724 /* threading not imported */
1725 PyErr_Clear();
1726 return;
1727 }
1728 result = PyObject_CallMethod(threading, "_shutdown", "");
1729 if (result == NULL)
1730 PyErr_WriteUnraisable(threading);
1731 else
1732 Py_DECREF(result);
1733 Py_DECREF(threading);
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001734#endif
1735}
1736
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001737#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001738static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001739static int nexitfuncs = 0;
1740
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001741int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001742{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001743 if (nexitfuncs >= NEXITFUNCS)
1744 return -1;
1745 exitfuncs[nexitfuncs++] = func;
1746 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001747}
1748
Guido van Rossumcc283f51997-08-05 02:22:03 +00001749static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001750call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001751{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001752 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001753
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001754 if (exitfunc) {
1755 PyObject *res;
1756 Py_INCREF(exitfunc);
1757 PySys_SetObject("exitfunc", (PyObject *)NULL);
1758 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1759 if (res == NULL) {
1760 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1761 PySys_WriteStderr("Error in sys.exitfunc:\n");
1762 }
1763 PyErr_Print();
1764 }
1765 Py_DECREF(exitfunc);
1766 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001767
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001768 if (Py_FlushLine())
1769 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001770}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001771
Guido van Rossumcc283f51997-08-05 02:22:03 +00001772static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001773call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001774{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001775 while (nexitfuncs > 0)
1776 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001777
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001778 fflush(stdout);
1779 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001780}
1781
1782void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001783Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001784{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001785 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001786
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001787 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001788}
1789
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001790static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001791initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001792{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001793#ifdef SIGPIPE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001794 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001795#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001796#ifdef SIGXFZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001797 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001798#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001799#ifdef SIGXFSZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001800 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001801#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001802 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001803}
1804
Guido van Rossum7433b121997-02-14 19:45:36 +00001805
1806/*
1807 * The file descriptor fd is considered ``interactive'' if either
1808 * a) isatty(fd) is TRUE, or
1809 * b) the -i flag was given, and the filename associated with
1810 * the descriptor is NULL or "<stdin>" or "???".
1811 */
1812int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001813Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001814{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001815 if (isatty((int)fileno(fp)))
1816 return 1;
1817 if (!Py_InteractiveFlag)
1818 return 0;
1819 return (filename == NULL) ||
1820 (strcmp(filename, "<stdin>") == 0) ||
1821 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001822}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001823
1824
Tim Petersd08e3822003-04-17 15:24:21 +00001825#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001826#if defined(WIN32) && defined(_MSC_VER)
1827
1828/* Stack checking for Microsoft C */
1829
1830#include <malloc.h>
1831#include <excpt.h>
1832
Fred Drakee8de31c2000-08-31 05:38:39 +00001833/*
1834 * Return non-zero when we run out of memory on the stack; zero otherwise.
1835 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001836int
Fred Drake399739f2000-08-31 05:52:44 +00001837PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001838{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001839 __try {
1840 /* alloca throws a stack overflow exception if there's
1841 not enough space left on the stack */
1842 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1843 return 0;
1844 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1845 EXCEPTION_EXECUTE_HANDLER :
1846 EXCEPTION_CONTINUE_SEARCH) {
1847 int errcode = _resetstkoflw();
1848 if (errcode == 0)
1849 {
1850 Py_FatalError("Could not reset the stack!");
1851 }
1852 }
1853 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001854}
1855
1856#endif /* WIN32 && _MSC_VER */
1857
1858/* Alternate implementations can be added here... */
1859
1860#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001861
1862
1863/* Wrappers around sigaction() or signal(). */
1864
1865PyOS_sighandler_t
1866PyOS_getsig(int sig)
1867{
1868#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001869 struct sigaction context;
1870 if (sigaction(sig, NULL, &context) == -1)
1871 return SIG_ERR;
1872 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001873#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001874 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001875/* Special signal handling for the secure CRT in Visual Studio 2005 */
1876#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001877 switch (sig) {
1878 /* Only these signals are valid */
1879 case SIGINT:
1880 case SIGILL:
1881 case SIGFPE:
1882 case SIGSEGV:
1883 case SIGTERM:
1884 case SIGBREAK:
1885 case SIGABRT:
1886 break;
1887 /* Don't call signal() with other values or it will assert */
1888 default:
1889 return SIG_ERR;
1890 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001891#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001892 handler = signal(sig, SIG_IGN);
1893 if (handler != SIG_ERR)
1894 signal(sig, handler);
1895 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001896#endif
1897}
1898
1899PyOS_sighandler_t
1900PyOS_setsig(int sig, PyOS_sighandler_t handler)
1901{
1902#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001903 /* Some code in Modules/signalmodule.c depends on sigaction() being
1904 * used here if HAVE_SIGACTION is defined. Fix that if this code
1905 * changes to invalidate that assumption.
1906 */
1907 struct sigaction context, ocontext;
1908 context.sa_handler = handler;
1909 sigemptyset(&context.sa_mask);
1910 context.sa_flags = 0;
1911 if (sigaction(sig, &context, &ocontext) == -1)
1912 return SIG_ERR;
1913 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001914#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001915 PyOS_sighandler_t oldhandler;
1916 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001917#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001918 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001919#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001920 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001921#endif
1922}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923
1924/* Deprecated C API functions still provided for binary compatiblity */
1925
1926#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001927PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1929{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001930 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931}
1932
Thomas Heller1b046642006-04-18 18:51:06 +00001933#undef PyParser_SimpleParseString
1934PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935PyParser_SimpleParseString(const char *str, int start)
1936{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001937 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001939
Thomas Heller1b046642006-04-18 18:51:06 +00001940#undef PyRun_AnyFile
1941PyAPI_FUNC(int)
1942PyRun_AnyFile(FILE *fp, const char *name)
1943{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001944 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001945}
1946
1947#undef PyRun_AnyFileEx
1948PyAPI_FUNC(int)
1949PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1950{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001951 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001952}
1953
1954#undef PyRun_AnyFileFlags
1955PyAPI_FUNC(int)
1956PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1957{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001958 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001959}
1960
1961#undef PyRun_File
1962PyAPI_FUNC(PyObject *)
1963PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1964{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001965 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001966}
1967
1968#undef PyRun_FileEx
1969PyAPI_FUNC(PyObject *)
1970PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1971{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001972 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001973}
1974
1975#undef PyRun_FileFlags
1976PyAPI_FUNC(PyObject *)
1977PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001978 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001979{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001980 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001981}
1982
1983#undef PyRun_SimpleFile
1984PyAPI_FUNC(int)
1985PyRun_SimpleFile(FILE *f, const char *p)
1986{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001987 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001988}
1989
1990#undef PyRun_SimpleFileEx
1991PyAPI_FUNC(int)
1992PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1993{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001994 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001995}
1996
1997
1998#undef PyRun_String
1999PyAPI_FUNC(PyObject *)
2000PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2001{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002002 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002003}
2004
2005#undef PyRun_SimpleString
2006PyAPI_FUNC(int)
2007PyRun_SimpleString(const char *s)
2008{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002009 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002010}
2011
2012#undef Py_CompileString
2013PyAPI_FUNC(PyObject *)
2014Py_CompileString(const char *str, const char *p, int s)
2015{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002016 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002017}
2018
2019#undef PyRun_InteractiveOne
2020PyAPI_FUNC(int)
2021PyRun_InteractiveOne(FILE *f, const char *p)
2022{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002023 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002024}
2025
2026#undef PyRun_InteractiveLoop
2027PyAPI_FUNC(int)
2028PyRun_InteractiveLoop(FILE *f, const char *p)
2029{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002030 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002031}
2032
Anthony Baxterac6bd462006-04-13 02:06:09 +00002033#ifdef __cplusplus
2034}
2035#endif
2036