blob: 677f6e48111be44900da4afd99059cbafc511b1a [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
Anthony Baxterac6bd462006-04-13 02:06:09 +000040#ifdef __cplusplus
41extern "C" {
42#endif
43
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000044extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000045
Guido van Rossum82598051997-03-05 00:20:32 +000046extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000047
Guido van Rossumb73cc041993-11-01 16:28:59 +000048/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000049static void initmain(void);
50static void initsite(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000051static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000052 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000053static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000054 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void err_input(perrdetail *);
56static void initsigs(void);
Antoine Pitrouefb60c02009-10-20 21:29:37 +000057static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000058static void call_sys_exitfunc(void);
59static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000060extern void _PyUnicode_Init(void);
61extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000062
Mark Hammond8d98d2c2003-04-19 15:41:53 +000063#ifdef WITH_THREAD
64extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
65extern void _PyGILState_Fini(void);
66#endif /* WITH_THREAD */
67
Guido van Rossum82598051997-03-05 00:20:32 +000068int Py_DebugFlag; /* Needed by parser.c */
69int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000070int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl11041f02011-05-15 08:50:32 +020071int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000072int Py_NoSiteFlag; /* Suppress 'import site' */
Christian Heimes1a6387e2008-03-26 12:49:49 +000073int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Georg Brandl2da0fce2008-01-07 17:09:35 +000074int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000075int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000076int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000077int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000078int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000079/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
80 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
81 true divisions (which they will be in 2.3). */
82int _Py_QnewFlag = 0;
Christian Heimesaf748c32008-05-06 22:41:46 +000083int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Barry Warsaw1e13eb02012-02-20 20:42:21 -050084int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000085
Christian Heimes51c4d722013-10-22 10:22:29 +020086
87/* Hack to force loading of object files */
88int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
89 PyOS_mystrnicmp; /* Python/pystrcmp.o */
90
Brett Cannone9746892008-04-12 23:44:07 +000091/* PyModule_GetWarningsModule is no longer necessary as of 2.6
92since _warnings is builtin. This API should not be used. */
93PyObject *
94PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000095{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000096 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000097}
Mark Hammonda43fd0c2003-02-19 00:33:33 +000098
Victor Stinner3c082a72017-10-17 01:35:19 -070099static void
100_PyDebug_PrintTotalRefs(void)
101{
102#ifdef Py_REF_DEBUG
103 Py_ssize_t total;
104
105 if (!Py_GETENV("PYTHONSHOWREFCOUNT")) {
106 return;
107 }
108
109 total = _Py_GetRefTotal();
110 fprintf(stderr, "[%" PY_FORMAT_SIZE_T "d refs]\n", total);
111#endif
112}
113
Guido van Rossum25ce5661997-08-02 03:10:38 +0000114static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000115
Thomas Wouters7e474022000-07-16 12:04:32 +0000116/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000117
118int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000119Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000120{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000121 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000122}
123
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124/* Global initializations. Can be undone by Py_Finalize(). Don't
125 call this twice without an intervening Py_Finalize() call. When
126 initializations fail, a fatal error is issued and the function does
127 not return. On return, the first thread and interpreter state have
128 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000129
Guido van Rossum25ce5661997-08-02 03:10:38 +0000130 Locking: you must hold the interpreter lock while calling this.
131 (If the lock has not yet been initialized, that's equivalent to
132 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000133
Guido van Rossum25ce5661997-08-02 03:10:38 +0000134*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000135
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000136static int
137add_flag(int flag, const char *envs)
138{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000139 int env = atoi(envs);
140 if (flag < env)
141 flag = env;
142 if (flag < 1)
143 flag = 1;
144 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000145}
146
Serhiy Storchaka5127ed72015-05-30 17:45:12 +0300147static int
148isatty_no_error(PyObject *sys_stream)
149{
150 PyObject *sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
151 if (sys_isatty) {
152 int isatty = PyObject_IsTrue(sys_isatty);
153 Py_DECREF(sys_isatty);
154 if (isatty >= 0)
155 return isatty;
156 }
157 PyErr_Clear();
158 return 0;
159}
160
Guido van Rossuma027efa1997-05-05 20:56:21 +0000161void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000162Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000163{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000164 PyInterpreterState *interp;
165 PyThreadState *tstate;
166 PyObject *bimod, *sysmod;
167 char *p;
168 char *icodeset = NULL; /* On Windows, input codeset may theoretically
169 differ from output codeset. */
170 char *codeset = NULL;
171 char *errors = NULL;
172 int free_codeset = 0;
173 int overridden = 0;
Serhiy Storchaka5127ed72015-05-30 17:45:12 +0300174 PyObject *sys_stream;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000175#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000176 char *saved_locale, *loc_codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000177#endif
Martin v. Löwis99815892008-06-01 07:20:46 +0000178#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000179 char ibuf[128];
180 char buf[128];
Martin v. Löwis99815892008-06-01 07:20:46 +0000181#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000182 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000183
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000184 if (initialized)
185 return;
186 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000187
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000188 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
189 Py_DebugFlag = add_flag(Py_DebugFlag, p);
190 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
191 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
192 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
193 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
194 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
195 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500196 /* The variable is only tested for existence here; _PyRandom_Init will
197 check its value further. */
198 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
199 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
200
201 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000202
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000203 interp = PyInterpreterState_New();
204 if (interp == NULL)
205 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000206
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000207 tstate = PyThreadState_New(interp);
208 if (tstate == NULL)
209 Py_FatalError("Py_Initialize: can't make first thread");
210 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000211
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000212 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000213
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000214 if (!_PyFrame_Init())
215 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000216
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000217 if (!_PyInt_Init())
218 Py_FatalError("Py_Initialize: can't init ints");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000219
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000220 if (!_PyLong_Init())
221 Py_FatalError("Py_Initialize: can't init longs");
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000222
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000223 if (!PyByteArray_Init())
224 Py_FatalError("Py_Initialize: can't init bytearray");
Christian Heimes1a6387e2008-03-26 12:49:49 +0000225
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000226 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000227
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000228 interp->modules = PyDict_New();
229 if (interp->modules == NULL)
230 Py_FatalError("Py_Initialize: can't make modules dictionary");
231 interp->modules_reloading = PyDict_New();
232 if (interp->modules_reloading == NULL)
233 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000234
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000235#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000236 /* Init Unicode implementation; relies on the codec registry */
237 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000238#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000239
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000240 bimod = _PyBuiltin_Init();
241 if (bimod == NULL)
242 Py_FatalError("Py_Initialize: can't initialize __builtin__");
243 interp->builtins = PyModule_GetDict(bimod);
244 if (interp->builtins == NULL)
245 Py_FatalError("Py_Initialize: can't initialize builtins dict");
246 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000247
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 sysmod = _PySys_Init();
249 if (sysmod == NULL)
250 Py_FatalError("Py_Initialize: can't initialize sys");
251 interp->sysdict = PyModule_GetDict(sysmod);
252 if (interp->sysdict == NULL)
253 Py_FatalError("Py_Initialize: can't initialize sys dict");
254 Py_INCREF(interp->sysdict);
255 _PyImport_FixupExtension("sys", "sys");
256 PySys_SetPath(Py_GetPath());
257 PyDict_SetItemString(interp->sysdict, "modules",
258 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000259
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000260 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000261
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000262 /* initialize builtin exceptions */
263 _PyExc_Init();
264 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000265
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000266 /* phase 2 of builtins */
267 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000268
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000269 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000270
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000271 if (install_sigs)
272 initsigs(); /* Signal handling stuff, including initintr() */
Brett Cannonc33e82d2010-05-05 20:38:52 +0000273
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000274 /* Initialize warnings. */
275 _PyWarnings_Init();
276 if (PySys_HasWarnOptions()) {
277 PyObject *warnings_module = PyImport_ImportModule("warnings");
278 if (!warnings_module)
279 PyErr_Clear();
280 Py_XDECREF(warnings_module);
281 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000282
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 initmain(); /* Module __main__ */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000284
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000285 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000286#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000287 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000288#endif /* WITH_THREAD */
289
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000290 if (!Py_NoSiteFlag)
291 initsite(); /* Module site */
Victor Stinner66644262010-03-10 22:30:19 +0000292
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000293 if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
294 p = icodeset = codeset = strdup(p);
295 free_codeset = 1;
296 errors = strchr(p, ':');
297 if (errors) {
298 *errors = '\0';
299 errors++;
300 }
301 overridden = 1;
302 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000303
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000304#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000305 /* On Unix, set the file system encoding according to the
306 user's preference, if the CODESET names a well-known
307 Python codec, and Py_FileSystemDefaultEncoding isn't
308 initialized by other means. Also set the encoding of
309 stdin and stdout if these are terminals, unless overridden. */
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000310
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000311 if (!overridden || !Py_FileSystemDefaultEncoding) {
312 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
313 setlocale(LC_CTYPE, "");
314 loc_codeset = nl_langinfo(CODESET);
315 if (loc_codeset && *loc_codeset) {
316 PyObject *enc = PyCodec_Encoder(loc_codeset);
317 if (enc) {
318 loc_codeset = strdup(loc_codeset);
319 Py_DECREF(enc);
320 } else {
321 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
322 PyErr_Clear();
323 loc_codeset = NULL;
324 } else {
325 PyErr_Print();
326 exit(1);
327 }
328 }
329 } else
330 loc_codeset = NULL;
331 setlocale(LC_CTYPE, saved_locale);
332 free(saved_locale);
Martin v. Löwis99815892008-06-01 07:20:46 +0000333
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000334 if (!overridden) {
335 codeset = icodeset = loc_codeset;
336 free_codeset = 1;
337 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000338
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000339 /* Initialize Py_FileSystemDefaultEncoding from
340 locale even if PYTHONIOENCODING is set. */
341 if (!Py_FileSystemDefaultEncoding) {
342 Py_FileSystemDefaultEncoding = loc_codeset;
343 if (!overridden)
344 free_codeset = 0;
345 }
346 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000347#endif
348
349#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000350 if (!overridden) {
351 icodeset = ibuf;
352 codeset = buf;
353 sprintf(ibuf, "cp%d", GetConsoleCP());
354 sprintf(buf, "cp%d", GetConsoleOutputCP());
355 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000356#endif
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000357
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000358 if (codeset) {
359 sys_stream = PySys_GetObject("stdin");
Serhiy Storchaka5127ed72015-05-30 17:45:12 +0300360 if ((overridden || isatty_no_error(sys_stream)) &&
361 PyFile_Check(sys_stream)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000362 if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
363 Py_FatalError("Cannot set codeset of stdin");
364 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000365
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000366 sys_stream = PySys_GetObject("stdout");
Serhiy Storchaka5127ed72015-05-30 17:45:12 +0300367 if ((overridden || isatty_no_error(sys_stream)) &&
368 PyFile_Check(sys_stream)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000369 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
370 Py_FatalError("Cannot set codeset of stdout");
371 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000372
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000373 sys_stream = PySys_GetObject("stderr");
Serhiy Storchaka5127ed72015-05-30 17:45:12 +0300374 if ((overridden || isatty_no_error(sys_stream)) &&
375 PyFile_Check(sys_stream)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000376 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
377 Py_FatalError("Cannot set codeset of stderr");
378 }
Martin v. Löwisea62d252006-04-03 10:56:49 +0000379
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000380 if (free_codeset)
381 free(codeset);
382 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383}
384
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000385void
386Py_Initialize(void)
387{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000388 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000389}
390
391
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000392#ifdef COUNT_ALLOCS
Martin v. Löwis45294a92006-04-18 06:24:08 +0000393extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000394#endif
395
Guido van Rossum25ce5661997-08-02 03:10:38 +0000396/* Undo the effect of Py_Initialize().
397
398 Beware: if multiple interpreter and/or thread states exist, these
399 are not wiped out; only the current thread and interpreter state
400 are deleted. But since everything else is deleted, those other
401 interpreter and thread states should no longer be used.
402
403 (XXX We should do better, e.g. wipe out all interpreters and
404 threads.)
405
406 Locking: as above.
407
408*/
409
410void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000411Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000412{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000413 PyInterpreterState *interp;
414 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000415
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000416 if (!initialized)
417 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000418
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000419 wait_for_thread_shutdown();
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000420
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000421 /* The interpreter is still entirely intact at this point, and the
422 * exit funcs may be relying on that. In particular, if some thread
423 * or exit func is still waiting to do an import, the import machinery
424 * expects Py_IsInitialized() to return true. So don't say the
425 * interpreter is uninitialized until after the exit funcs have run.
426 * Note that Threading.py uses an exit func to do a join on all the
427 * threads created thru it, so this also protects pending imports in
428 * the threads created via Threading.
429 */
430 call_sys_exitfunc();
Antoine Pitroub9a45012014-11-21 02:04:21 +0100431 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000432
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000433 /* Get current thread state and interpreter pointer */
434 tstate = PyThreadState_GET();
435 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000436
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000437 /* Disable signal handling */
438 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000439
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000440 /* Clear type lookup cache */
441 PyType_ClearCache();
Christian Heimes908caac2008-01-27 23:34:59 +0000442
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000443 /* Collect garbage. This may call finalizers; it's nice to call these
444 * before all modules are destroyed.
445 * XXX If a __del__ or weakref callback is triggered here, and tries to
446 * XXX import a module, bad things can happen, because Python no
447 * XXX longer believes it's initialized.
448 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
449 * XXX is easy to provoke that way. I've also seen, e.g.,
450 * XXX Exception exceptions.ImportError: 'No module named sha'
451 * XXX in <function callback at 0x008F5718> ignored
452 * XXX but I'm unclear on exactly how that one happens. In any case,
453 * XXX I haven't seen a real-life report of either of these.
454 */
455 PyGC_Collect();
Martin v. Löwis45294a92006-04-18 06:24:08 +0000456#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000457 /* With COUNT_ALLOCS, it helps to run GC multiple times:
458 each collection might release some types from the type
459 list, so they become garbage. */
460 while (PyGC_Collect() > 0)
461 /* nothing */;
Martin v. Löwis45294a92006-04-18 06:24:08 +0000462#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000463
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 /* Destroy all modules */
465 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000466
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000467 /* Collect final garbage. This disposes of cycles created by
468 * new-style class definitions, for example.
469 * XXX This is disabled because it caused too many problems. If
470 * XXX a __del__ or weakref callback triggers here, Python code has
471 * XXX a hard time running, because even the sys module has been
472 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
473 * XXX One symptom is a sequence of information-free messages
474 * XXX coming from threads (if a __del__ or callback is invoked,
475 * XXX other threads can execute too, and any exception they encounter
476 * XXX triggers a comedy of errors as subsystem after subsystem
477 * XXX fails to find what it *expects* to find in sys to help report
478 * XXX the exception and consequent unexpected failures). I've also
479 * XXX seen segfaults then, after adding print statements to the
480 * XXX Python code getting called.
481 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000482#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000484#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000485
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
487 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000488
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000489 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000490#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000491 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000492#endif
493
Victor Stinner3c082a72017-10-17 01:35:19 -0700494 _PyDebug_PrintTotalRefs();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000495
Tim Peters9cf25ce2003-04-17 15:21:01 +0000496#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000497 /* Display all objects still alive -- this can invoke arbitrary
498 * __repr__ overrides, so requires a mostly-intact interpreter.
499 * Alas, a lot of stuff may still be alive now that will be cleaned
500 * up later.
501 */
502 if (Py_GETENV("PYTHONDUMPREFS"))
503 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000504#endif /* Py_TRACE_REFS */
505
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000506 /* Clear interpreter state */
507 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000508
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000509 /* Now we decref the exception classes. After this point nothing
510 can raise an exception. That's okay, because each Fini() method
511 below has been checked to make sure no exceptions are ever
512 raised.
513 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000514
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000515 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000516
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000517 /* Cleanup auto-thread-state */
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000518#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 _PyGILState_Fini();
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000520#endif /* WITH_THREAD */
521
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000522 /* Delete current thread */
523 PyThreadState_Swap(NULL);
524 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000525
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000526 /* Sundry finalizers */
527 PyMethod_Fini();
528 PyFrame_Fini();
529 PyCFunction_Fini();
530 PyTuple_Fini();
531 PyList_Fini();
532 PySet_Fini();
533 PyString_Fini();
534 PyByteArray_Fini();
535 PyInt_Fini();
536 PyFloat_Fini();
537 PyDict_Fini();
Benjamin Peterson57057a62014-08-28 12:30:00 -0400538 _PyRandom_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);
Victor Stinner3c082a72017-10-17 01:35:19 -0700785 _PyDebug_PrintTotalRefs();
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000786 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 }
Mark Dickinsonea829722017-02-02 19:31:53 +00001137 if (PyInt_Check(value) || PyLong_Check(value))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001138 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 */
Martin Panteref85a1a2016-02-28 00:18:43 +00001309 if (s == NULL) {
1310 PyErr_Clear();
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001311 err = -1;
Martin Panteref85a1a2016-02-28 00:18:43 +00001312 PyFile_WriteString(": <exception str() failed>", f);
1313 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001314 else if (!PyString_Check(s) ||
1315 PyString_GET_SIZE(s) != 0)
1316 err = PyFile_WriteString(": ", f);
1317 if (err == 0)
1318 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1319 Py_XDECREF(s);
1320 }
1321 /* try to write a newline in any case */
Martin Panteref85a1a2016-02-28 00:18:43 +00001322 if (err < 0) {
1323 PyErr_Clear();
1324 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001325 err += PyFile_WriteString("\n", f);
1326 }
1327 Py_DECREF(value);
1328 /* If an error happened here, don't show it.
1329 XXX This is wrong, but too many callers rely on this behavior. */
1330 if (err != 0)
1331 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001332}
1333
Guido van Rossum82598051997-03-05 00:20:32 +00001334PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001335PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001336 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001337{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001338 PyObject *ret = NULL;
1339 mod_ty mod;
1340 PyArena *arena = PyArena_New();
1341 if (arena == NULL)
1342 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001343
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001344 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1345 if (mod != NULL)
1346 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1347 PyArena_Free(arena);
1348 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001349}
1350
1351PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001352PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001353 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001354{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001355 PyObject *ret;
1356 mod_ty mod;
1357 PyArena *arena = PyArena_New();
1358 if (arena == NULL)
1359 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001360
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001361 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1362 flags, NULL, arena);
1363 if (closeit)
1364 fclose(fp);
1365 if (mod == NULL) {
1366 PyArena_Free(arena);
1367 return NULL;
1368 }
1369 ret = run_mod(mod, filename, globals, locals, flags, arena);
1370 PyArena_Free(arena);
1371 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001372}
1373
Guido van Rossum82598051997-03-05 00:20:32 +00001374static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001376 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001377{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001378 PyCodeObject *co;
1379 PyObject *v;
1380 co = PyAST_Compile(mod, filename, flags, arena);
1381 if (co == NULL)
1382 return NULL;
1383 v = PyEval_EvalCode(co, globals, locals);
1384 Py_DECREF(co);
1385 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001386}
1387
Guido van Rossum82598051997-03-05 00:20:32 +00001388static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001389run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001390 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001391{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001392 PyCodeObject *co;
1393 PyObject *v;
1394 long magic;
1395 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001396
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001397 magic = PyMarshal_ReadLongFromFile(fp);
1398 if (magic != PyImport_GetMagicNumber()) {
1399 PyErr_SetString(PyExc_RuntimeError,
1400 "Bad magic number in .pyc file");
1401 return NULL;
1402 }
1403 (void) PyMarshal_ReadLongFromFile(fp);
1404 v = PyMarshal_ReadLastObjectFromFile(fp);
1405 fclose(fp);
1406 if (v == NULL || !PyCode_Check(v)) {
1407 Py_XDECREF(v);
1408 PyErr_SetString(PyExc_RuntimeError,
1409 "Bad code object in .pyc file");
1410 return NULL;
1411 }
1412 co = (PyCodeObject *)v;
1413 v = PyEval_EvalCode(co, globals, locals);
1414 if (v && flags)
1415 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1416 Py_DECREF(co);
1417 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001418}
1419
Guido van Rossum82598051997-03-05 00:20:32 +00001420PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001421Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001422 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001423{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001424 PyCodeObject *co;
1425 mod_ty mod;
1426 PyArena *arena = PyArena_New();
1427 if (arena == NULL)
1428 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001429
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001430 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1431 if (mod == NULL) {
1432 PyArena_Free(arena);
1433 return NULL;
1434 }
1435 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1436 PyObject *result = PyAST_mod2obj(mod);
1437 PyArena_Free(arena);
1438 return result;
1439 }
1440 co = PyAST_Compile(mod, filename, flags, arena);
1441 PyArena_Free(arena);
1442 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001443}
1444
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001445struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001446Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001447{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001448 struct symtable *st;
1449 mod_ty mod;
1450 PyCompilerFlags flags;
1451 PyArena *arena = PyArena_New();
1452 if (arena == NULL)
1453 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001454
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001455 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001457 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1458 if (mod == NULL) {
1459 PyArena_Free(arena);
1460 return NULL;
1461 }
1462 st = PySymtable_Build(mod, filename, 0);
1463 PyArena_Free(arena);
1464 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001465}
1466
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467/* Preferred access to parser is through AST. */
1468mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001469PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001470 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001472 mod_ty mod;
1473 PyCompilerFlags localflags;
1474 perrdetail err;
1475 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001476
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001477 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1478 &_PyParser_Grammar, start, &err,
1479 &iflags);
1480 if (flags == NULL) {
1481 localflags.cf_flags = 0;
1482 flags = &localflags;
1483 }
1484 if (n) {
1485 flags->cf_flags |= iflags & PyCF_MASK;
1486 mod = PyAST_FromNode(n, flags, filename, arena);
1487 PyNode_Free(n);
1488 return mod;
1489 }
1490 else {
1491 err_input(&err);
1492 return NULL;
1493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494}
1495
1496mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001497PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001498 char *ps2, PyCompilerFlags *flags, int *errcode,
1499 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001501 mod_ty mod;
1502 PyCompilerFlags localflags;
1503 perrdetail err;
1504 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001505
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1507 start, ps1, ps2, &err, &iflags);
1508 if (flags == NULL) {
1509 localflags.cf_flags = 0;
1510 flags = &localflags;
1511 }
1512 if (n) {
1513 flags->cf_flags |= iflags & PyCF_MASK;
1514 mod = PyAST_FromNode(n, flags, filename, arena);
1515 PyNode_Free(n);
1516 return mod;
1517 }
1518 else {
1519 err_input(&err);
1520 if (errcode)
1521 *errcode = err.error;
1522 return NULL;
1523 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524}
1525
Guido van Rossuma110aa61994-08-29 12:50:44 +00001526/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001527
Guido van Rossuma110aa61994-08-29 12:50:44 +00001528node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001529PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001530{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001531 perrdetail err;
1532 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1533 start, NULL, NULL, &err, flags);
1534 if (n == NULL)
1535 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001536
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001537 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001538}
1539
Guido van Rossuma110aa61994-08-29 12:50:44 +00001540/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001541
Guido van Rossuma110aa61994-08-29 12:50:44 +00001542node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001543PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001544{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001545 perrdetail err;
1546 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1547 start, &err, flags);
1548 if (n == NULL)
1549 err_input(&err);
1550 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001551}
1552
1553node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001554PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001555 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001556{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001557 perrdetail err;
1558 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1559 &_PyParser_Grammar, start, &err, flags);
1560 if (n == NULL)
1561 err_input(&err);
1562 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001563}
1564
1565node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001566PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001567{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001568 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001569}
1570
Guido van Rossum66ebd912003-04-17 16:02:26 +00001571/* May want to move a more generalized form of this to parsetok.c or
1572 even parser modules. */
1573
1574void
1575PyParser_SetError(perrdetail *err)
1576{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001577 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001578}
1579
Guido van Rossuma110aa61994-08-29 12:50:44 +00001580/* Set the error appropriate to the given input error code (see errcode.h) */
1581
1582static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001583err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001584{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001585 PyObject *v, *w, *errtype;
1586 PyObject* u = NULL;
1587 char *msg = NULL;
1588 errtype = PyExc_SyntaxError;
1589 switch (err->error) {
1590 case E_ERROR:
1591 return;
1592 case E_SYNTAX:
1593 errtype = PyExc_IndentationError;
1594 if (err->expected == INDENT)
1595 msg = "expected an indented block";
1596 else if (err->token == INDENT)
1597 msg = "unexpected indent";
1598 else if (err->token == DEDENT)
1599 msg = "unexpected unindent";
1600 else {
1601 errtype = PyExc_SyntaxError;
1602 msg = "invalid syntax";
1603 }
1604 break;
1605 case E_TOKEN:
1606 msg = "invalid token";
1607 break;
1608 case E_EOFS:
1609 msg = "EOF while scanning triple-quoted string literal";
1610 break;
1611 case E_EOLS:
1612 msg = "EOL while scanning string literal";
1613 break;
1614 case E_INTR:
1615 if (!PyErr_Occurred())
1616 PyErr_SetNone(PyExc_KeyboardInterrupt);
1617 goto cleanup;
1618 case E_NOMEM:
1619 PyErr_NoMemory();
1620 goto cleanup;
1621 case E_EOF:
1622 msg = "unexpected EOF while parsing";
1623 break;
1624 case E_TABSPACE:
1625 errtype = PyExc_TabError;
1626 msg = "inconsistent use of tabs and spaces in indentation";
1627 break;
1628 case E_OVERFLOW:
1629 msg = "expression too long";
1630 break;
1631 case E_DEDENT:
1632 errtype = PyExc_IndentationError;
1633 msg = "unindent does not match any outer indentation level";
1634 break;
1635 case E_TOODEEP:
1636 errtype = PyExc_IndentationError;
1637 msg = "too many levels of indentation";
1638 break;
1639 case E_DECODE: {
1640 PyObject *type, *value, *tb;
1641 PyErr_Fetch(&type, &value, &tb);
1642 if (value != NULL) {
1643 u = PyObject_Str(value);
1644 if (u != NULL) {
1645 msg = PyString_AsString(u);
1646 }
1647 }
1648 if (msg == NULL)
1649 msg = "unknown decode error";
1650 Py_XDECREF(type);
1651 Py_XDECREF(value);
1652 Py_XDECREF(tb);
1653 break;
1654 }
1655 case E_LINECONT:
1656 msg = "unexpected character after line continuation character";
1657 break;
1658 default:
1659 fprintf(stderr, "error=%d\n", err->error);
1660 msg = "unknown parsing error";
1661 break;
1662 }
1663 v = Py_BuildValue("(ziiz)", err->filename,
1664 err->lineno, err->offset, err->text);
1665 w = NULL;
1666 if (v != NULL)
1667 w = Py_BuildValue("(sO)", msg, v);
1668 Py_XDECREF(u);
1669 Py_XDECREF(v);
1670 PyErr_SetObject(errtype, w);
1671 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001672cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001673 if (err->text != NULL) {
1674 PyObject_FREE(err->text);
1675 err->text = NULL;
1676 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001677}
1678
1679/* Print fatal error message and abort */
1680
1681void
Tim Peters7c321a82002-07-09 02:57:01 +00001682Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001683{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001684 fprintf(stderr, "Fatal Python error: %s\n", msg);
1685 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller42f9b4e2009-03-31 22:20:35 +00001686
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001687#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001688 {
1689 size_t len = strlen(msg);
1690 WCHAR* buffer;
1691 size_t i;
Martin v. Löwis5344c992009-01-02 20:32:55 +00001692
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001693 /* Convert the message to wchar_t. This uses a simple one-to-one
1694 conversion, assuming that the this error message actually uses ASCII
1695 only. If this ceases to be true, we will have to convert. */
1696 buffer = alloca( (len+1) * (sizeof *buffer));
1697 for( i=0; i<=len; ++i)
1698 buffer[i] = msg[i];
1699 OutputDebugStringW(L"Fatal Python error: ");
1700 OutputDebugStringW(buffer);
1701 OutputDebugStringW(L"\n");
1702 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001703#ifdef _DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001704 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001705#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001706#endif /* MS_WINDOWS */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001707 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001708}
1709
1710/* Clean up and exit */
1711
Guido van Rossuma110aa61994-08-29 12:50:44 +00001712#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001713#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001714#endif
1715
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001716/* Wait until threading._shutdown completes, provided
1717 the threading module was imported in the first place.
1718 The shutdown routine will wait until all non-daemon
1719 "threading" threads have completed. */
1720static void
1721wait_for_thread_shutdown(void)
1722{
1723#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001724 PyObject *result;
1725 PyThreadState *tstate = PyThreadState_GET();
1726 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1727 "threading");
1728 if (threading == NULL) {
1729 /* threading not imported */
1730 PyErr_Clear();
1731 return;
1732 }
1733 result = PyObject_CallMethod(threading, "_shutdown", "");
1734 if (result == NULL)
1735 PyErr_WriteUnraisable(threading);
1736 else
1737 Py_DECREF(result);
1738 Py_DECREF(threading);
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001739#endif
1740}
1741
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001742#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001743static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001744static int nexitfuncs = 0;
1745
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001746int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001747{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001748 if (nexitfuncs >= NEXITFUNCS)
1749 return -1;
1750 exitfuncs[nexitfuncs++] = func;
1751 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001752}
1753
Guido van Rossumcc283f51997-08-05 02:22:03 +00001754static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001755call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001756{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001757 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001758
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001759 if (exitfunc) {
1760 PyObject *res;
1761 Py_INCREF(exitfunc);
1762 PySys_SetObject("exitfunc", (PyObject *)NULL);
1763 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1764 if (res == NULL) {
1765 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1766 PySys_WriteStderr("Error in sys.exitfunc:\n");
1767 }
1768 PyErr_Print();
1769 }
1770 Py_DECREF(exitfunc);
1771 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001772
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001773 if (Py_FlushLine())
1774 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001775}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001776
Guido van Rossumcc283f51997-08-05 02:22:03 +00001777static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001778call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001779{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001780 while (nexitfuncs > 0)
1781 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001782
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001783 fflush(stdout);
1784 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001785}
1786
1787void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001788Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001789{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001790 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001791
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001792 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001793}
1794
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001795static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001796initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001797{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001798#ifdef SIGPIPE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001799 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001800#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001801#ifdef SIGXFZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001802 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001803#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001804#ifdef SIGXFSZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001805 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001806#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001807 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001808}
1809
Guido van Rossum7433b121997-02-14 19:45:36 +00001810
1811/*
1812 * The file descriptor fd is considered ``interactive'' if either
1813 * a) isatty(fd) is TRUE, or
1814 * b) the -i flag was given, and the filename associated with
1815 * the descriptor is NULL or "<stdin>" or "???".
1816 */
1817int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001818Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001819{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001820 if (isatty((int)fileno(fp)))
1821 return 1;
1822 if (!Py_InteractiveFlag)
1823 return 0;
1824 return (filename == NULL) ||
1825 (strcmp(filename, "<stdin>") == 0) ||
1826 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001827}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001828
1829
Tim Petersd08e3822003-04-17 15:24:21 +00001830#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001831#if defined(WIN32) && defined(_MSC_VER)
1832
1833/* Stack checking for Microsoft C */
1834
1835#include <malloc.h>
1836#include <excpt.h>
1837
Fred Drakee8de31c2000-08-31 05:38:39 +00001838/*
1839 * Return non-zero when we run out of memory on the stack; zero otherwise.
1840 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001841int
Fred Drake399739f2000-08-31 05:52:44 +00001842PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001843{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001844 __try {
1845 /* alloca throws a stack overflow exception if there's
1846 not enough space left on the stack */
1847 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1848 return 0;
1849 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1850 EXCEPTION_EXECUTE_HANDLER :
1851 EXCEPTION_CONTINUE_SEARCH) {
1852 int errcode = _resetstkoflw();
1853 if (errcode == 0)
1854 {
1855 Py_FatalError("Could not reset the stack!");
1856 }
1857 }
1858 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001859}
1860
1861#endif /* WIN32 && _MSC_VER */
1862
1863/* Alternate implementations can be added here... */
1864
1865#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001866
1867
1868/* Wrappers around sigaction() or signal(). */
1869
1870PyOS_sighandler_t
1871PyOS_getsig(int sig)
1872{
1873#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001874 struct sigaction context;
1875 if (sigaction(sig, NULL, &context) == -1)
1876 return SIG_ERR;
1877 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001878#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001879 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001880/* Special signal handling for the secure CRT in Visual Studio 2005 */
1881#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001882 switch (sig) {
1883 /* Only these signals are valid */
1884 case SIGINT:
1885 case SIGILL:
1886 case SIGFPE:
1887 case SIGSEGV:
1888 case SIGTERM:
1889 case SIGBREAK:
1890 case SIGABRT:
1891 break;
1892 /* Don't call signal() with other values or it will assert */
1893 default:
1894 return SIG_ERR;
1895 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001896#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001897 handler = signal(sig, SIG_IGN);
1898 if (handler != SIG_ERR)
1899 signal(sig, handler);
1900 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001901#endif
1902}
1903
1904PyOS_sighandler_t
1905PyOS_setsig(int sig, PyOS_sighandler_t handler)
1906{
1907#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001908 /* Some code in Modules/signalmodule.c depends on sigaction() being
1909 * used here if HAVE_SIGACTION is defined. Fix that if this code
1910 * changes to invalidate that assumption.
1911 */
1912 struct sigaction context, ocontext;
1913 context.sa_handler = handler;
1914 sigemptyset(&context.sa_mask);
1915 context.sa_flags = 0;
1916 if (sigaction(sig, &context, &ocontext) == -1)
1917 return SIG_ERR;
1918 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001919#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001920 PyOS_sighandler_t oldhandler;
1921 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001922#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001923 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001924#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001925 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001926#endif
1927}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928
Martin Panterb1d867f2016-05-26 05:28:50 +00001929/* Deprecated C API functions still provided for binary compatibility */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930
1931#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001932PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1934{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001935 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001936}
1937
Thomas Heller1b046642006-04-18 18:51:06 +00001938#undef PyParser_SimpleParseString
1939PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001940PyParser_SimpleParseString(const char *str, int start)
1941{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001942 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001944
Thomas Heller1b046642006-04-18 18:51:06 +00001945#undef PyRun_AnyFile
1946PyAPI_FUNC(int)
1947PyRun_AnyFile(FILE *fp, const char *name)
1948{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001949 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001950}
1951
1952#undef PyRun_AnyFileEx
1953PyAPI_FUNC(int)
1954PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1955{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001956 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001957}
1958
1959#undef PyRun_AnyFileFlags
1960PyAPI_FUNC(int)
1961PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1962{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001963 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001964}
1965
1966#undef PyRun_File
1967PyAPI_FUNC(PyObject *)
1968PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1969{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001970 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001971}
1972
1973#undef PyRun_FileEx
1974PyAPI_FUNC(PyObject *)
1975PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1976{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001977 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001978}
1979
1980#undef PyRun_FileFlags
1981PyAPI_FUNC(PyObject *)
1982PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001983 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001984{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001985 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001986}
1987
1988#undef PyRun_SimpleFile
1989PyAPI_FUNC(int)
1990PyRun_SimpleFile(FILE *f, const char *p)
1991{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001992 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001993}
1994
1995#undef PyRun_SimpleFileEx
1996PyAPI_FUNC(int)
1997PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1998{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001999 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002000}
2001
2002
2003#undef PyRun_String
2004PyAPI_FUNC(PyObject *)
2005PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2006{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002007 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002008}
2009
2010#undef PyRun_SimpleString
2011PyAPI_FUNC(int)
2012PyRun_SimpleString(const char *s)
2013{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002014 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002015}
2016
2017#undef Py_CompileString
2018PyAPI_FUNC(PyObject *)
2019Py_CompileString(const char *str, const char *p, int s)
2020{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002021 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002022}
2023
2024#undef PyRun_InteractiveOne
2025PyAPI_FUNC(int)
2026PyRun_InteractiveOne(FILE *f, const char *p)
2027{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002028 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002029}
2030
2031#undef PyRun_InteractiveLoop
2032PyAPI_FUNC(int)
2033PyRun_InteractiveLoop(FILE *f, const char *p)
2034{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002035 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002036}
2037
Anthony Baxterac6bd462006-04-13 02:06:09 +00002038#ifdef __cplusplus
2039}
2040#endif
2041