blob: 748a63b9559c5763cba9f84815722892ae3e10b6 [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();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000539
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000540#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000541 /* Cleanup Unicode implementation */
542 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000543#endif
544
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000545 /* XXX Still allocated:
546 - various static ad-hoc pointers to interned strings
547 - int and float free list blocks
548 - whatever various modules and libraries allocate
549 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000550
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000551 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000552
Tim Peters269b2a62003-04-17 19:52:29 +0000553#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000554 /* Display addresses (& refcnts) of all objects still alive.
555 * An address can be used to find the repr of the object, printed
556 * above by _Py_PrintReferences.
557 */
558 if (Py_GETENV("PYTHONDUMPREFS"))
559 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000560#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000561#ifdef PYMALLOC_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000562 if (Py_GETENV("PYTHONMALLOCSTATS"))
563 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000564#endif
565
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000566 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567}
568
569/* Create and initialize a new interpreter and thread, and return the
570 new thread. This requires that Py_Initialize() has been called
571 first.
572
573 Unsuccessful initialization yields a NULL pointer. Note that *no*
574 exception information is available even in this case -- the
575 exception information is held in the thread, and there is no
576 thread.
577
578 Locking: as above.
579
580*/
581
582PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000583Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000585 PyInterpreterState *interp;
586 PyThreadState *tstate, *save_tstate;
587 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000589 if (!initialized)
590 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000592 interp = PyInterpreterState_New();
593 if (interp == NULL)
594 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000595
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000596 tstate = PyThreadState_New(interp);
597 if (tstate == NULL) {
598 PyInterpreterState_Delete(interp);
599 return NULL;
600 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000602 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000603
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000604 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000606 interp->modules = PyDict_New();
607 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000609 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
610 if (bimod != NULL) {
611 interp->builtins = PyModule_GetDict(bimod);
612 if (interp->builtins == NULL)
613 goto handle_error;
614 Py_INCREF(interp->builtins);
615 }
616 sysmod = _PyImport_FindExtension("sys", "sys");
617 if (bimod != NULL && sysmod != NULL) {
618 interp->sysdict = PyModule_GetDict(sysmod);
619 if (interp->sysdict == NULL)
620 goto handle_error;
621 Py_INCREF(interp->sysdict);
622 PySys_SetPath(Py_GetPath());
623 PyDict_SetItemString(interp->sysdict, "modules",
624 interp->modules);
625 _PyImportHooks_Init();
626 initmain();
627 if (!Py_NoSiteFlag)
628 initsite();
629 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000631 if (!PyErr_Occurred())
632 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000634handle_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000635 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000636
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000637 PyErr_Print();
638 PyThreadState_Clear(tstate);
639 PyThreadState_Swap(save_tstate);
640 PyThreadState_Delete(tstate);
641 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000642
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000643 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644}
645
646/* Delete an interpreter and its last thread. This requires that the
647 given thread state is current, that the thread has no remaining
648 frames, and that it is its interpreter's only remaining thread.
649 It is a fatal error to violate these constraints.
650
651 (Py_Finalize() doesn't have these constraints -- it zaps
652 everything, regardless.)
653
654 Locking: as above.
655
656*/
657
658void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000659Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000661 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000662
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000663 if (tstate != PyThreadState_GET())
664 Py_FatalError("Py_EndInterpreter: thread is not current");
665 if (tstate->frame != NULL)
666 Py_FatalError("Py_EndInterpreter: thread still has a frame");
667 if (tstate != interp->tstate_head || tstate->next != NULL)
668 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000669
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000670 PyImport_Cleanup();
671 PyInterpreterState_Clear(interp);
672 PyThreadState_Swap(NULL);
673 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000674}
675
676static char *progname = "python";
677
678void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000679Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000680{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000681 if (pn && *pn)
682 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000683}
684
685char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000686Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000687{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000688 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000689}
690
Guido van Rossuma61691e1998-02-06 22:27:24 +0000691static char *default_home = NULL;
692
693void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000694Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000695{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000696 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000697}
698
699char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000700Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000701{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000702 char *home = default_home;
703 if (home == NULL && !Py_IgnoreEnvironmentFlag)
704 home = Py_GETENV("PYTHONHOME");
705 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000706}
707
Guido van Rossum6135a871995-01-09 17:53:26 +0000708/* Create __main__ module */
709
710static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000712{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000713 PyObject *m, *d;
714 m = PyImport_AddModule("__main__");
715 if (m == NULL)
716 Py_FatalError("can't create __main__ module");
717 d = PyModule_GetDict(m);
718 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
719 PyObject *bimod = PyImport_ImportModule("__builtin__");
720 if (bimod == NULL ||
721 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
722 Py_FatalError("can't add __builtins__ to __main__");
723 Py_XDECREF(bimod);
724 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000725}
726
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000727/* Import the site module (not into __main__ though) */
728
729static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000730initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000731{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000732 PyObject *m;
733 m = PyImport_ImportModule("site");
734 if (m == NULL) {
735 PyErr_Print();
736 Py_Finalize();
737 exit(1);
738 }
739 else {
740 Py_DECREF(m);
741 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000742}
743
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000744/* Parse input from a file and execute it */
745
746int
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000747PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000748 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000749{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000750 if (filename == NULL)
751 filename = "???";
752 if (Py_FdIsInteractive(fp, filename)) {
753 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
754 if (closeit)
755 fclose(fp);
756 return err;
757 }
758 else
759 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000760}
761
762int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000763PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000764{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000765 PyObject *v;
766 int ret;
767 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000768
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000769 if (flags == NULL) {
770 flags = &local_flags;
771 local_flags.cf_flags = 0;
772 }
773 v = PySys_GetObject("ps1");
774 if (v == NULL) {
775 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
776 Py_XDECREF(v);
777 }
778 v = PySys_GetObject("ps2");
779 if (v == NULL) {
780 PySys_SetObject("ps2", v = PyString_FromString("... "));
781 Py_XDECREF(v);
782 }
783 for (;;) {
784 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
785 PRINT_TOTAL_REFS();
786 if (ret == E_EOF)
787 return 0;
788 /*
789 if (ret == E_NOMEM)
790 return -1;
791 */
792 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000793}
794
Eric Smith7c478942008-03-18 23:45:49 +0000795#if 0
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000796/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000797#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000798 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
799 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Eric Smith7c478942008-03-18 23:45:49 +0000800#endif
801#if 1
Neal Norwitzca460d92006-09-06 06:28:06 +0000802/* Keep an example of flags with future keyword support. */
803#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000804 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
805 PyPARSE_DONT_IMPLY_DEDENT : 0) \
806 | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
807 PyPARSE_PRINT_IS_FUNCTION : 0) \
808 | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
809 PyPARSE_UNICODE_LITERALS : 0) \
810 ) : 0)
Neal Norwitzca460d92006-09-06 06:28:06 +0000811#endif
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000812
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000813int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000814PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000815{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000816 PyObject *m, *d, *v, *w;
817 mod_ty mod;
818 PyArena *arena;
819 char *ps1 = "", *ps2 = "";
820 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000821
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000822 v = PySys_GetObject("ps1");
823 if (v != NULL) {
824 v = PyObject_Str(v);
825 if (v == NULL)
826 PyErr_Clear();
827 else if (PyString_Check(v))
828 ps1 = PyString_AsString(v);
829 }
830 w = PySys_GetObject("ps2");
831 if (w != NULL) {
832 w = PyObject_Str(w);
833 if (w == NULL)
834 PyErr_Clear();
835 else if (PyString_Check(w))
836 ps2 = PyString_AsString(w);
837 }
838 arena = PyArena_New();
839 if (arena == NULL) {
840 Py_XDECREF(v);
841 Py_XDECREF(w);
842 return -1;
843 }
844 mod = PyParser_ASTFromFile(fp, filename,
845 Py_single_input, ps1, ps2,
846 flags, &errcode, arena);
847 Py_XDECREF(v);
848 Py_XDECREF(w);
849 if (mod == NULL) {
850 PyArena_Free(arena);
851 if (errcode == E_EOF) {
852 PyErr_Clear();
853 return E_EOF;
854 }
855 PyErr_Print();
856 return -1;
857 }
858 m = PyImport_AddModule("__main__");
859 if (m == NULL) {
860 PyArena_Free(arena);
861 return -1;
862 }
863 d = PyModule_GetDict(m);
864 v = run_mod(mod, filename, d, d, flags, arena);
865 PyArena_Free(arena);
866 if (v == NULL) {
867 PyErr_Print();
868 return -1;
869 }
870 Py_DECREF(v);
871 if (Py_FlushLine())
872 PyErr_Clear();
873 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000874}
875
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000876/* Check whether a file maybe a pyc file: Look at the extension,
877 the file type, and, if we may close it, at the first few bytes. */
878
879static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000880maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000881{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000882 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
883 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000884
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000885 /* Only look into the file if we are allowed to close it, since
886 it then should also be seekable. */
887 if (closeit) {
888 /* Read only two bytes of the magic. If the file was opened in
889 text mode, the bytes 3 and 4 of the magic (\r\n) might not
890 be read as they are on disk. */
891 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
892 unsigned char buf[2];
893 /* Mess: In case of -x, the stream is NOT at its start now,
894 and ungetc() was used to push back the first newline,
895 which makes the current stream position formally undefined,
896 and a x-platform nightmare.
897 Unfortunately, we have no direct way to know whether -x
898 was specified. So we use a terrible hack: if the current
899 stream position is not 0, we assume -x was specified, and
900 give up. Bug 132850 on SourceForge spells out the
901 hopelessness of trying anything else (fseek and ftell
902 don't work predictably x-platform for text-mode files).
903 */
904 int ispyc = 0;
905 if (ftell(fp) == 0) {
906 if (fread(buf, 1, 2, fp) == 2 &&
907 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
908 ispyc = 1;
909 rewind(fp);
910 }
911 return ispyc;
912 }
913 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000914}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000915
Guido van Rossum0df002c2000-08-27 19:21:52 +0000916int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000917PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000918 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000919{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000920 PyObject *m, *d, *v;
921 const char *ext;
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100922 int set_file_name = 0, len, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000923
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000924 m = PyImport_AddModule("__main__");
925 if (m == NULL)
926 return -1;
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100927 Py_INCREF(m);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 d = PyModule_GetDict(m);
929 if (PyDict_GetItemString(d, "__file__") == NULL) {
930 PyObject *f = PyString_FromString(filename);
931 if (f == NULL)
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100932 goto done;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000933 if (PyDict_SetItemString(d, "__file__", f) < 0) {
934 Py_DECREF(f);
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100935 goto done;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000936 }
937 set_file_name = 1;
938 Py_DECREF(f);
939 }
940 len = strlen(filename);
941 ext = filename + len - (len > 4 ? 4 : 0);
942 if (maybe_pyc_file(fp, filename, ext, closeit)) {
943 /* Try to run a pyc file. First, re-open in binary */
944 if (closeit)
945 fclose(fp);
946 if ((fp = fopen(filename, "rb")) == NULL) {
947 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000948 goto done;
949 }
950 /* Turn on optimization if a .pyo file is given */
951 if (strcmp(ext, ".pyo") == 0)
952 Py_OptimizeFlag = 1;
953 v = run_pyc_file(fp, filename, d, d, flags);
954 } else {
955 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
956 closeit, flags);
957 }
958 if (v == NULL) {
959 PyErr_Print();
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000960 goto done;
961 }
962 Py_DECREF(v);
963 if (Py_FlushLine())
964 PyErr_Clear();
965 ret = 0;
Georg Brandlaa2321b2007-03-07 00:40:28 +0000966 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000967 if (set_file_name && PyDict_DelItemString(d, "__file__"))
968 PyErr_Clear();
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100969 Py_DECREF(m);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000970 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000971}
972
973int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000974PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000975{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000976 PyObject *m, *d, *v;
977 m = PyImport_AddModule("__main__");
978 if (m == NULL)
979 return -1;
980 d = PyModule_GetDict(m);
981 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
982 if (v == NULL) {
983 PyErr_Print();
984 return -1;
985 }
986 Py_DECREF(v);
987 if (Py_FlushLine())
988 PyErr_Clear();
989 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000990}
991
Barry Warsaw035574d1997-08-29 22:07:17 +0000992static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000993parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000994 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000995{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000996 long hold;
997 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +0000998
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000999 /* old style errors */
1000 if (PyTuple_Check(err))
1001 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1002 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001003
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001004 *message = NULL;
1005
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001006 /* new style errors. `err' is an instance */
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001007 *message = PyObject_GetAttrString(err, "msg");
1008 if (!*message)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001009 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001010
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001011 v = PyObject_GetAttrString(err, "filename");
1012 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001013 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001014 if (v == Py_None) {
1015 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001016 *filename = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001017 }
1018 else {
1019 *filename = PyString_AsString(v);
1020 Py_DECREF(v);
1021 if (!*filename)
1022 goto finally;
1023 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001024
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001025 v = PyObject_GetAttrString(err, "lineno");
1026 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001027 goto finally;
1028 hold = PyInt_AsLong(v);
1029 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001030 if (hold < 0 && PyErr_Occurred())
1031 goto finally;
1032 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001033
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001034 v = PyObject_GetAttrString(err, "offset");
1035 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001036 goto finally;
1037 if (v == Py_None) {
1038 *offset = -1;
1039 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001040 } else {
1041 hold = PyInt_AsLong(v);
1042 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001043 if (hold < 0 && PyErr_Occurred())
1044 goto finally;
1045 *offset = (int)hold;
1046 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001047
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001048 v = PyObject_GetAttrString(err, "text");
1049 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001050 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001051 if (v == Py_None) {
1052 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001053 *text = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001054 }
1055 else {
1056 *text = PyString_AsString(v);
1057 Py_DECREF(v);
1058 if (!*text)
1059 goto finally;
1060 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001061 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001062
1063finally:
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001064 Py_XDECREF(*message);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001065 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001066}
1067
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001068void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001069PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001070{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001071 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001072}
1073
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001074static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001075print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001076{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001077 char *nl;
1078 if (offset >= 0) {
Benjamin Petersonec9f9f52010-10-29 03:45:34 +00001079 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1080 offset--;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001081 for (;;) {
1082 nl = strchr(text, '\n');
1083 if (nl == NULL || nl-text >= offset)
1084 break;
1085 offset -= (int)(nl+1-text);
1086 text = nl+1;
1087 }
1088 while (*text == ' ' || *text == '\t') {
1089 text++;
1090 offset--;
1091 }
1092 }
1093 PyFile_WriteString(" ", f);
1094 PyFile_WriteString(text, f);
1095 if (*text == '\0' || text[strlen(text)-1] != '\n')
1096 PyFile_WriteString("\n", f);
1097 if (offset == -1)
1098 return;
1099 PyFile_WriteString(" ", f);
1100 offset--;
1101 while (offset > 0) {
1102 PyFile_WriteString(" ", f);
1103 offset--;
1104 }
1105 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001106}
1107
Guido van Rossum66e8e862001-03-23 17:54:43 +00001108static void
1109handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001110{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001111 PyObject *exception, *value, *tb;
1112 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001113
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001114 if (Py_InspectFlag)
1115 /* Don't exit if -i flag was given. This flag is set to 0
1116 * when entering interactive mode for inspecting. */
1117 return;
Georg Brandl49aafc92007-03-07 00:34:46 +00001118
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001119 PyErr_Fetch(&exception, &value, &tb);
1120 if (Py_FlushLine())
1121 PyErr_Clear();
1122 fflush(stdout);
1123 if (value == NULL || value == Py_None)
1124 goto done;
1125 if (PyExceptionInstance_Check(value)) {
1126 /* The error code should be in the `code' attribute. */
1127 PyObject *code = PyObject_GetAttrString(value, "code");
1128 if (code) {
1129 Py_DECREF(value);
1130 value = code;
1131 if (value == Py_None)
1132 goto done;
1133 }
1134 /* If we failed to dig out the 'code' attribute,
1135 just let the else clause below print the error. */
1136 }
1137 if (PyInt_Check(value))
1138 exitcode = (int)PyInt_AsLong(value);
1139 else {
Victor Stinnerc49dfcc2010-05-25 22:30:32 +00001140 PyObject *sys_stderr = PySys_GetObject("stderr");
1141 if (sys_stderr != NULL && sys_stderr != Py_None) {
1142 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1143 } else {
1144 PyObject_Print(value, stderr, Py_PRINT_RAW);
1145 fflush(stderr);
1146 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001147 PySys_WriteStderr("\n");
1148 exitcode = 1;
1149 }
Tim Peterscf615b52003-04-19 18:47:02 +00001150 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001151 /* Restore and clear the exception info, in order to properly decref
1152 * the exception, value, and traceback. If we just exit instead,
1153 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1154 * some finalizers from running.
1155 */
1156 PyErr_Restore(exception, value, tb);
1157 PyErr_Clear();
1158 Py_Exit(exitcode);
1159 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001160}
1161
1162void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001163PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001164{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001165 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001166
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001167 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1168 handle_system_exit();
1169 }
1170 PyErr_Fetch(&exception, &v, &tb);
1171 if (exception == NULL)
1172 return;
1173 PyErr_NormalizeException(&exception, &v, &tb);
1174 if (exception == NULL)
1175 return;
1176 /* Now we know v != NULL too */
1177 if (set_sys_last_vars) {
1178 PySys_SetObject("last_type", exception);
1179 PySys_SetObject("last_value", v);
1180 PySys_SetObject("last_traceback", tb);
1181 }
1182 hook = PySys_GetObject("excepthook");
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001183 if (hook && hook != Py_None) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001184 PyObject *args = PyTuple_Pack(3,
1185 exception, v, tb ? tb : Py_None);
1186 PyObject *result = PyEval_CallObject(hook, args);
1187 if (result == NULL) {
1188 PyObject *exception2, *v2, *tb2;
1189 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1190 handle_system_exit();
1191 }
1192 PyErr_Fetch(&exception2, &v2, &tb2);
1193 PyErr_NormalizeException(&exception2, &v2, &tb2);
1194 /* It should not be possible for exception2 or v2
1195 to be NULL. However PyErr_Display() can't
1196 tolerate NULLs, so just be safe. */
1197 if (exception2 == NULL) {
1198 exception2 = Py_None;
1199 Py_INCREF(exception2);
1200 }
1201 if (v2 == NULL) {
1202 v2 = Py_None;
1203 Py_INCREF(v2);
1204 }
1205 if (Py_FlushLine())
1206 PyErr_Clear();
1207 fflush(stdout);
1208 PySys_WriteStderr("Error in sys.excepthook:\n");
1209 PyErr_Display(exception2, v2, tb2);
1210 PySys_WriteStderr("\nOriginal exception was:\n");
1211 PyErr_Display(exception, v, tb);
1212 Py_DECREF(exception2);
1213 Py_DECREF(v2);
1214 Py_XDECREF(tb2);
1215 }
1216 Py_XDECREF(result);
1217 Py_XDECREF(args);
1218 } else {
1219 PySys_WriteStderr("sys.excepthook is missing\n");
1220 PyErr_Display(exception, v, tb);
1221 }
1222 Py_XDECREF(exception);
1223 Py_XDECREF(v);
1224 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001225}
1226
Richard Jones7b9558d2006-05-27 12:29:24 +00001227void
1228PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001229{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001230 int err = 0;
1231 PyObject *f = PySys_GetObject("stderr");
1232 Py_INCREF(value);
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001233 if (f == NULL || f == Py_None)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001234 fprintf(stderr, "lost sys.stderr\n");
1235 else {
1236 if (Py_FlushLine())
1237 PyErr_Clear();
1238 fflush(stdout);
1239 if (tb && tb != Py_None)
1240 err = PyTraceBack_Print(tb, f);
1241 if (err == 0 &&
1242 PyObject_HasAttrString(value, "print_file_and_line"))
1243 {
1244 PyObject *message;
1245 const char *filename, *text;
1246 int lineno, offset;
1247 if (!parse_syntax_error(value, &message, &filename,
1248 &lineno, &offset, &text))
1249 PyErr_Clear();
1250 else {
1251 char buf[10];
1252 PyFile_WriteString(" File \"", f);
1253 if (filename == NULL)
1254 PyFile_WriteString("<string>", f);
1255 else
1256 PyFile_WriteString(filename, f);
1257 PyFile_WriteString("\", line ", f);
1258 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1259 PyFile_WriteString(buf, f);
1260 PyFile_WriteString("\n", f);
1261 if (text != NULL)
1262 print_error_text(f, offset, text);
1263 Py_DECREF(value);
1264 value = message;
1265 /* Can't be bothered to check all those
1266 PyFile_WriteString() calls */
1267 if (PyErr_Occurred())
1268 err = -1;
1269 }
1270 }
1271 if (err) {
1272 /* Don't do anything else */
1273 }
1274 else if (PyExceptionClass_Check(exception)) {
1275 PyObject* moduleName;
1276 char* className = PyExceptionClass_Name(exception);
1277 if (className != NULL) {
1278 char *dot = strrchr(className, '.');
1279 if (dot != NULL)
1280 className = dot+1;
1281 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001282
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001283 moduleName = PyObject_GetAttrString(exception, "__module__");
1284 if (moduleName == NULL)
1285 err = PyFile_WriteString("<unknown>", f);
1286 else {
1287 char* modstr = PyString_AsString(moduleName);
1288 if (modstr && strcmp(modstr, "exceptions"))
1289 {
1290 err = PyFile_WriteString(modstr, f);
1291 err += PyFile_WriteString(".", f);
1292 }
1293 Py_DECREF(moduleName);
1294 }
1295 if (err == 0) {
1296 if (className == NULL)
1297 err = PyFile_WriteString("<unknown>", f);
1298 else
1299 err = PyFile_WriteString(className, f);
1300 }
1301 }
1302 else
1303 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1304 if (err == 0 && (value != Py_None)) {
1305 PyObject *s = PyObject_Str(value);
1306 /* only print colon if the str() of the
1307 object is not the empty string
1308 */
1309 if (s == NULL)
1310 err = -1;
1311 else if (!PyString_Check(s) ||
1312 PyString_GET_SIZE(s) != 0)
1313 err = PyFile_WriteString(": ", f);
1314 if (err == 0)
1315 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1316 Py_XDECREF(s);
1317 }
1318 /* try to write a newline in any case */
1319 err += PyFile_WriteString("\n", f);
1320 }
1321 Py_DECREF(value);
1322 /* If an error happened here, don't show it.
1323 XXX This is wrong, but too many callers rely on this behavior. */
1324 if (err != 0)
1325 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001326}
1327
Guido van Rossum82598051997-03-05 00:20:32 +00001328PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001329PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001330 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001331{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001332 PyObject *ret = NULL;
1333 mod_ty mod;
1334 PyArena *arena = PyArena_New();
1335 if (arena == NULL)
1336 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001337
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001338 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1339 if (mod != NULL)
1340 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1341 PyArena_Free(arena);
1342 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001343}
1344
1345PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001346PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001347 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001348{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001349 PyObject *ret;
1350 mod_ty mod;
1351 PyArena *arena = PyArena_New();
1352 if (arena == NULL)
1353 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001354
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001355 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1356 flags, NULL, arena);
1357 if (closeit)
1358 fclose(fp);
1359 if (mod == NULL) {
1360 PyArena_Free(arena);
1361 return NULL;
1362 }
1363 ret = run_mod(mod, filename, globals, locals, flags, arena);
1364 PyArena_Free(arena);
1365 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001366}
1367
Guido van Rossum82598051997-03-05 00:20:32 +00001368static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001369run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001370 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001371{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001372 PyCodeObject *co;
1373 PyObject *v;
1374 co = PyAST_Compile(mod, filename, flags, arena);
1375 if (co == NULL)
1376 return NULL;
1377 v = PyEval_EvalCode(co, globals, locals);
1378 Py_DECREF(co);
1379 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001380}
1381
Guido van Rossum82598051997-03-05 00:20:32 +00001382static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001383run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001384 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001385{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001386 PyCodeObject *co;
1387 PyObject *v;
1388 long magic;
1389 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001390
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001391 magic = PyMarshal_ReadLongFromFile(fp);
1392 if (magic != PyImport_GetMagicNumber()) {
1393 PyErr_SetString(PyExc_RuntimeError,
1394 "Bad magic number in .pyc file");
1395 return NULL;
1396 }
1397 (void) PyMarshal_ReadLongFromFile(fp);
1398 v = PyMarshal_ReadLastObjectFromFile(fp);
1399 fclose(fp);
1400 if (v == NULL || !PyCode_Check(v)) {
1401 Py_XDECREF(v);
1402 PyErr_SetString(PyExc_RuntimeError,
1403 "Bad code object in .pyc file");
1404 return NULL;
1405 }
1406 co = (PyCodeObject *)v;
1407 v = PyEval_EvalCode(co, globals, locals);
1408 if (v && flags)
1409 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1410 Py_DECREF(co);
1411 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001412}
1413
Guido van Rossum82598051997-03-05 00:20:32 +00001414PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001415Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001416 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001417{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001418 PyCodeObject *co;
1419 mod_ty mod;
1420 PyArena *arena = PyArena_New();
1421 if (arena == NULL)
1422 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001423
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001424 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1425 if (mod == NULL) {
1426 PyArena_Free(arena);
1427 return NULL;
1428 }
1429 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1430 PyObject *result = PyAST_mod2obj(mod);
1431 PyArena_Free(arena);
1432 return result;
1433 }
1434 co = PyAST_Compile(mod, filename, flags, arena);
1435 PyArena_Free(arena);
1436 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001437}
1438
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001439struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001440Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001442 struct symtable *st;
1443 mod_ty mod;
1444 PyCompilerFlags flags;
1445 PyArena *arena = PyArena_New();
1446 if (arena == NULL)
1447 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001448
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001449 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001450
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001451 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1452 if (mod == NULL) {
1453 PyArena_Free(arena);
1454 return NULL;
1455 }
1456 st = PySymtable_Build(mod, filename, 0);
1457 PyArena_Free(arena);
1458 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001459}
1460
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461/* Preferred access to parser is through AST. */
1462mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001463PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001464 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001466 mod_ty mod;
1467 PyCompilerFlags localflags;
1468 perrdetail err;
1469 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001470
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001471 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1472 &_PyParser_Grammar, start, &err,
1473 &iflags);
1474 if (flags == NULL) {
1475 localflags.cf_flags = 0;
1476 flags = &localflags;
1477 }
1478 if (n) {
1479 flags->cf_flags |= iflags & PyCF_MASK;
1480 mod = PyAST_FromNode(n, flags, filename, arena);
1481 PyNode_Free(n);
1482 return mod;
1483 }
1484 else {
1485 err_input(&err);
1486 return NULL;
1487 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488}
1489
1490mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001491PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001492 char *ps2, PyCompilerFlags *flags, int *errcode,
1493 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001495 mod_ty mod;
1496 PyCompilerFlags localflags;
1497 perrdetail err;
1498 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001499
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001500 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1501 start, ps1, ps2, &err, &iflags);
1502 if (flags == NULL) {
1503 localflags.cf_flags = 0;
1504 flags = &localflags;
1505 }
1506 if (n) {
1507 flags->cf_flags |= iflags & PyCF_MASK;
1508 mod = PyAST_FromNode(n, flags, filename, arena);
1509 PyNode_Free(n);
1510 return mod;
1511 }
1512 else {
1513 err_input(&err);
1514 if (errcode)
1515 *errcode = err.error;
1516 return NULL;
1517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518}
1519
Guido van Rossuma110aa61994-08-29 12:50:44 +00001520/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001521
Guido van Rossuma110aa61994-08-29 12:50:44 +00001522node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001523PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001524{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001525 perrdetail err;
1526 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1527 start, NULL, NULL, &err, flags);
1528 if (n == NULL)
1529 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001530
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001531 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001532}
1533
Guido van Rossuma110aa61994-08-29 12:50:44 +00001534/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001535
Guido van Rossuma110aa61994-08-29 12:50:44 +00001536node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001537PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001538{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001539 perrdetail err;
1540 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1541 start, &err, flags);
1542 if (n == NULL)
1543 err_input(&err);
1544 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001545}
1546
1547node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001548PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001549 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001550{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001551 perrdetail err;
1552 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1553 &_PyParser_Grammar, start, &err, flags);
1554 if (n == NULL)
1555 err_input(&err);
1556 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001557}
1558
1559node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001560PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001561{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001562 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001563}
1564
Guido van Rossum66ebd912003-04-17 16:02:26 +00001565/* May want to move a more generalized form of this to parsetok.c or
1566 even parser modules. */
1567
1568void
1569PyParser_SetError(perrdetail *err)
1570{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001571 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001572}
1573
Guido van Rossuma110aa61994-08-29 12:50:44 +00001574/* Set the error appropriate to the given input error code (see errcode.h) */
1575
1576static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001577err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001579 PyObject *v, *w, *errtype;
1580 PyObject* u = NULL;
1581 char *msg = NULL;
1582 errtype = PyExc_SyntaxError;
1583 switch (err->error) {
1584 case E_ERROR:
1585 return;
1586 case E_SYNTAX:
1587 errtype = PyExc_IndentationError;
1588 if (err->expected == INDENT)
1589 msg = "expected an indented block";
1590 else if (err->token == INDENT)
1591 msg = "unexpected indent";
1592 else if (err->token == DEDENT)
1593 msg = "unexpected unindent";
1594 else {
1595 errtype = PyExc_SyntaxError;
1596 msg = "invalid syntax";
1597 }
1598 break;
1599 case E_TOKEN:
1600 msg = "invalid token";
1601 break;
1602 case E_EOFS:
1603 msg = "EOF while scanning triple-quoted string literal";
1604 break;
1605 case E_EOLS:
1606 msg = "EOL while scanning string literal";
1607 break;
1608 case E_INTR:
1609 if (!PyErr_Occurred())
1610 PyErr_SetNone(PyExc_KeyboardInterrupt);
1611 goto cleanup;
1612 case E_NOMEM:
1613 PyErr_NoMemory();
1614 goto cleanup;
1615 case E_EOF:
1616 msg = "unexpected EOF while parsing";
1617 break;
1618 case E_TABSPACE:
1619 errtype = PyExc_TabError;
1620 msg = "inconsistent use of tabs and spaces in indentation";
1621 break;
1622 case E_OVERFLOW:
1623 msg = "expression too long";
1624 break;
1625 case E_DEDENT:
1626 errtype = PyExc_IndentationError;
1627 msg = "unindent does not match any outer indentation level";
1628 break;
1629 case E_TOODEEP:
1630 errtype = PyExc_IndentationError;
1631 msg = "too many levels of indentation";
1632 break;
1633 case E_DECODE: {
1634 PyObject *type, *value, *tb;
1635 PyErr_Fetch(&type, &value, &tb);
1636 if (value != NULL) {
1637 u = PyObject_Str(value);
1638 if (u != NULL) {
1639 msg = PyString_AsString(u);
1640 }
1641 }
1642 if (msg == NULL)
1643 msg = "unknown decode error";
1644 Py_XDECREF(type);
1645 Py_XDECREF(value);
1646 Py_XDECREF(tb);
1647 break;
1648 }
1649 case E_LINECONT:
1650 msg = "unexpected character after line continuation character";
1651 break;
1652 default:
1653 fprintf(stderr, "error=%d\n", err->error);
1654 msg = "unknown parsing error";
1655 break;
1656 }
1657 v = Py_BuildValue("(ziiz)", err->filename,
1658 err->lineno, err->offset, err->text);
1659 w = NULL;
1660 if (v != NULL)
1661 w = Py_BuildValue("(sO)", msg, v);
1662 Py_XDECREF(u);
1663 Py_XDECREF(v);
1664 PyErr_SetObject(errtype, w);
1665 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001666cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001667 if (err->text != NULL) {
1668 PyObject_FREE(err->text);
1669 err->text = NULL;
1670 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001671}
1672
1673/* Print fatal error message and abort */
1674
1675void
Tim Peters7c321a82002-07-09 02:57:01 +00001676Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001677{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001678 fprintf(stderr, "Fatal Python error: %s\n", msg);
1679 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller42f9b4e2009-03-31 22:20:35 +00001680
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001681#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001682 {
1683 size_t len = strlen(msg);
1684 WCHAR* buffer;
1685 size_t i;
Martin v. Löwis5344c992009-01-02 20:32:55 +00001686
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001687 /* Convert the message to wchar_t. This uses a simple one-to-one
1688 conversion, assuming that the this error message actually uses ASCII
1689 only. If this ceases to be true, we will have to convert. */
1690 buffer = alloca( (len+1) * (sizeof *buffer));
1691 for( i=0; i<=len; ++i)
1692 buffer[i] = msg[i];
1693 OutputDebugStringW(L"Fatal Python error: ");
1694 OutputDebugStringW(buffer);
1695 OutputDebugStringW(L"\n");
1696 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001697#ifdef _DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001698 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001699#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001700#endif /* MS_WINDOWS */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001701 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001702}
1703
1704/* Clean up and exit */
1705
Guido van Rossuma110aa61994-08-29 12:50:44 +00001706#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001707#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001708#endif
1709
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001710/* Wait until threading._shutdown completes, provided
1711 the threading module was imported in the first place.
1712 The shutdown routine will wait until all non-daemon
1713 "threading" threads have completed. */
1714static void
1715wait_for_thread_shutdown(void)
1716{
1717#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001718 PyObject *result;
1719 PyThreadState *tstate = PyThreadState_GET();
1720 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1721 "threading");
1722 if (threading == NULL) {
1723 /* threading not imported */
1724 PyErr_Clear();
1725 return;
1726 }
1727 result = PyObject_CallMethod(threading, "_shutdown", "");
1728 if (result == NULL)
1729 PyErr_WriteUnraisable(threading);
1730 else
1731 Py_DECREF(result);
1732 Py_DECREF(threading);
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001733#endif
1734}
1735
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001736#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001737static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001738static int nexitfuncs = 0;
1739
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001740int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001741{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001742 if (nexitfuncs >= NEXITFUNCS)
1743 return -1;
1744 exitfuncs[nexitfuncs++] = func;
1745 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001746}
1747
Guido van Rossumcc283f51997-08-05 02:22:03 +00001748static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001749call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001750{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001751 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001752
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001753 if (exitfunc) {
1754 PyObject *res;
1755 Py_INCREF(exitfunc);
1756 PySys_SetObject("exitfunc", (PyObject *)NULL);
1757 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1758 if (res == NULL) {
1759 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1760 PySys_WriteStderr("Error in sys.exitfunc:\n");
1761 }
1762 PyErr_Print();
1763 }
1764 Py_DECREF(exitfunc);
1765 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001766
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001767 if (Py_FlushLine())
1768 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001769}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001770
Guido van Rossumcc283f51997-08-05 02:22:03 +00001771static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001772call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001773{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001774 while (nexitfuncs > 0)
1775 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001776
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001777 fflush(stdout);
1778 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001779}
1780
1781void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001782Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001783{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001784 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001785
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001786 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001787}
1788
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001789static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001790initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001791{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001792#ifdef SIGPIPE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001793 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001794#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001795#ifdef SIGXFZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001796 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001797#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001798#ifdef SIGXFSZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001799 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001800#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001801 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001802}
1803
Guido van Rossum7433b121997-02-14 19:45:36 +00001804
1805/*
1806 * The file descriptor fd is considered ``interactive'' if either
1807 * a) isatty(fd) is TRUE, or
1808 * b) the -i flag was given, and the filename associated with
1809 * the descriptor is NULL or "<stdin>" or "???".
1810 */
1811int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001812Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001813{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001814 if (isatty((int)fileno(fp)))
1815 return 1;
1816 if (!Py_InteractiveFlag)
1817 return 0;
1818 return (filename == NULL) ||
1819 (strcmp(filename, "<stdin>") == 0) ||
1820 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001821}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001822
1823
Tim Petersd08e3822003-04-17 15:24:21 +00001824#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001825#if defined(WIN32) && defined(_MSC_VER)
1826
1827/* Stack checking for Microsoft C */
1828
1829#include <malloc.h>
1830#include <excpt.h>
1831
Fred Drakee8de31c2000-08-31 05:38:39 +00001832/*
1833 * Return non-zero when we run out of memory on the stack; zero otherwise.
1834 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001835int
Fred Drake399739f2000-08-31 05:52:44 +00001836PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001837{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001838 __try {
1839 /* alloca throws a stack overflow exception if there's
1840 not enough space left on the stack */
1841 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1842 return 0;
1843 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1844 EXCEPTION_EXECUTE_HANDLER :
1845 EXCEPTION_CONTINUE_SEARCH) {
1846 int errcode = _resetstkoflw();
1847 if (errcode == 0)
1848 {
1849 Py_FatalError("Could not reset the stack!");
1850 }
1851 }
1852 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001853}
1854
1855#endif /* WIN32 && _MSC_VER */
1856
1857/* Alternate implementations can be added here... */
1858
1859#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001860
1861
1862/* Wrappers around sigaction() or signal(). */
1863
1864PyOS_sighandler_t
1865PyOS_getsig(int sig)
1866{
1867#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001868 struct sigaction context;
1869 if (sigaction(sig, NULL, &context) == -1)
1870 return SIG_ERR;
1871 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001872#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001873 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001874/* Special signal handling for the secure CRT in Visual Studio 2005 */
1875#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001876 switch (sig) {
1877 /* Only these signals are valid */
1878 case SIGINT:
1879 case SIGILL:
1880 case SIGFPE:
1881 case SIGSEGV:
1882 case SIGTERM:
1883 case SIGBREAK:
1884 case SIGABRT:
1885 break;
1886 /* Don't call signal() with other values or it will assert */
1887 default:
1888 return SIG_ERR;
1889 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001890#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001891 handler = signal(sig, SIG_IGN);
1892 if (handler != SIG_ERR)
1893 signal(sig, handler);
1894 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001895#endif
1896}
1897
1898PyOS_sighandler_t
1899PyOS_setsig(int sig, PyOS_sighandler_t handler)
1900{
1901#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 /* Some code in Modules/signalmodule.c depends on sigaction() being
1903 * used here if HAVE_SIGACTION is defined. Fix that if this code
1904 * changes to invalidate that assumption.
1905 */
1906 struct sigaction context, ocontext;
1907 context.sa_handler = handler;
1908 sigemptyset(&context.sa_mask);
1909 context.sa_flags = 0;
1910 if (sigaction(sig, &context, &ocontext) == -1)
1911 return SIG_ERR;
1912 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001913#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001914 PyOS_sighandler_t oldhandler;
1915 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001916#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001917 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001918#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001919 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001920#endif
1921}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922
1923/* Deprecated C API functions still provided for binary compatiblity */
1924
1925#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001926PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1928{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001929 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930}
1931
Thomas Heller1b046642006-04-18 18:51:06 +00001932#undef PyParser_SimpleParseString
1933PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001934PyParser_SimpleParseString(const char *str, int start)
1935{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001936 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001937}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001938
Thomas Heller1b046642006-04-18 18:51:06 +00001939#undef PyRun_AnyFile
1940PyAPI_FUNC(int)
1941PyRun_AnyFile(FILE *fp, const char *name)
1942{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001943 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001944}
1945
1946#undef PyRun_AnyFileEx
1947PyAPI_FUNC(int)
1948PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1949{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001950 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001951}
1952
1953#undef PyRun_AnyFileFlags
1954PyAPI_FUNC(int)
1955PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1956{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001957 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001958}
1959
1960#undef PyRun_File
1961PyAPI_FUNC(PyObject *)
1962PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1963{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001964 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001965}
1966
1967#undef PyRun_FileEx
1968PyAPI_FUNC(PyObject *)
1969PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1970{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001971 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001972}
1973
1974#undef PyRun_FileFlags
1975PyAPI_FUNC(PyObject *)
1976PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001977 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001978{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001979 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001980}
1981
1982#undef PyRun_SimpleFile
1983PyAPI_FUNC(int)
1984PyRun_SimpleFile(FILE *f, const char *p)
1985{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001986 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001987}
1988
1989#undef PyRun_SimpleFileEx
1990PyAPI_FUNC(int)
1991PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1992{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001993 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001994}
1995
1996
1997#undef PyRun_String
1998PyAPI_FUNC(PyObject *)
1999PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2000{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002001 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002002}
2003
2004#undef PyRun_SimpleString
2005PyAPI_FUNC(int)
2006PyRun_SimpleString(const char *s)
2007{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002008 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002009}
2010
2011#undef Py_CompileString
2012PyAPI_FUNC(PyObject *)
2013Py_CompileString(const char *str, const char *p, int s)
2014{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002015 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002016}
2017
2018#undef PyRun_InteractiveOne
2019PyAPI_FUNC(int)
2020PyRun_InteractiveOne(FILE *f, const char *p)
2021{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002022 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002023}
2024
2025#undef PyRun_InteractiveLoop
2026PyAPI_FUNC(int)
2027PyRun_InteractiveLoop(FILE *f, const char *p)
2028{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002029 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002030}
2031
Anthony Baxterac6bd462006-04-13 02:06:09 +00002032#ifdef __cplusplus
2033}
2034#endif
2035