blob: 2c9f55fbd1dff32059f2443ed33d259d41956f14 [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
Victor Stinner7b4ba622017-10-17 02:25:23 -0700491 if (Py_GETENV("PYTHONSHOWALLOCCOUNT")) {
492 dump_counts(stderr);
493 }
Guido van Rossum1707aad1997-12-08 23:43:45 +0000494#endif
495
Victor Stinner3c082a72017-10-17 01:35:19 -0700496 _PyDebug_PrintTotalRefs();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000497
Tim Peters9cf25ce2003-04-17 15:21:01 +0000498#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000499 /* Display all objects still alive -- this can invoke arbitrary
500 * __repr__ overrides, so requires a mostly-intact interpreter.
501 * Alas, a lot of stuff may still be alive now that will be cleaned
502 * up later.
503 */
504 if (Py_GETENV("PYTHONDUMPREFS"))
505 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000506#endif /* Py_TRACE_REFS */
507
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 /* Clear interpreter state */
509 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000510
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000511 /* Now we decref the exception classes. After this point nothing
512 can raise an exception. That's okay, because each Fini() method
513 below has been checked to make sure no exceptions are ever
514 raised.
515 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000516
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000517 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000518
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 /* Cleanup auto-thread-state */
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000520#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000521 _PyGILState_Fini();
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000522#endif /* WITH_THREAD */
523
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000524 /* Delete current thread */
525 PyThreadState_Swap(NULL);
526 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000527
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528 /* Sundry finalizers */
529 PyMethod_Fini();
530 PyFrame_Fini();
531 PyCFunction_Fini();
532 PyTuple_Fini();
533 PyList_Fini();
534 PySet_Fini();
535 PyString_Fini();
536 PyByteArray_Fini();
537 PyInt_Fini();
538 PyFloat_Fini();
539 PyDict_Fini();
Benjamin Peterson57057a62014-08-28 12:30:00 -0400540 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000541
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000542#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000543 /* Cleanup Unicode implementation */
544 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000545#endif
546
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000547 /* XXX Still allocated:
548 - various static ad-hoc pointers to interned strings
549 - int and float free list blocks
550 - whatever various modules and libraries allocate
551 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000552
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000553 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000554
Tim Peters269b2a62003-04-17 19:52:29 +0000555#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000556 /* Display addresses (& refcnts) of all objects still alive.
557 * An address can be used to find the repr of the object, printed
558 * above by _Py_PrintReferences.
559 */
560 if (Py_GETENV("PYTHONDUMPREFS"))
561 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000562#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000563#ifdef PYMALLOC_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000564 if (Py_GETENV("PYTHONMALLOCSTATS"))
565 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000566#endif
567
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569}
570
571/* Create and initialize a new interpreter and thread, and return the
572 new thread. This requires that Py_Initialize() has been called
573 first.
574
575 Unsuccessful initialization yields a NULL pointer. Note that *no*
576 exception information is available even in this case -- the
577 exception information is held in the thread, and there is no
578 thread.
579
580 Locking: as above.
581
582*/
583
584PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000585Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000587 PyInterpreterState *interp;
588 PyThreadState *tstate, *save_tstate;
589 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000591 if (!initialized)
592 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000593
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000594 interp = PyInterpreterState_New();
595 if (interp == NULL)
596 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000597
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000598 tstate = PyThreadState_New(interp);
599 if (tstate == NULL) {
600 PyInterpreterState_Delete(interp);
601 return NULL;
602 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000603
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000604 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000606 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000608 interp->modules = PyDict_New();
609 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000611 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
612 if (bimod != NULL) {
613 interp->builtins = PyModule_GetDict(bimod);
614 if (interp->builtins == NULL)
615 goto handle_error;
616 Py_INCREF(interp->builtins);
617 }
618 sysmod = _PyImport_FindExtension("sys", "sys");
619 if (bimod != NULL && sysmod != NULL) {
620 interp->sysdict = PyModule_GetDict(sysmod);
621 if (interp->sysdict == NULL)
622 goto handle_error;
623 Py_INCREF(interp->sysdict);
624 PySys_SetPath(Py_GetPath());
625 PyDict_SetItemString(interp->sysdict, "modules",
626 interp->modules);
627 _PyImportHooks_Init();
628 initmain();
629 if (!Py_NoSiteFlag)
630 initsite();
631 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000632
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000633 if (!PyErr_Occurred())
634 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000636handle_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000637 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000638
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000639 PyErr_Print();
640 PyThreadState_Clear(tstate);
641 PyThreadState_Swap(save_tstate);
642 PyThreadState_Delete(tstate);
643 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000645 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000646}
647
648/* Delete an interpreter and its last thread. This requires that the
649 given thread state is current, that the thread has no remaining
650 frames, and that it is its interpreter's only remaining thread.
651 It is a fatal error to violate these constraints.
652
653 (Py_Finalize() doesn't have these constraints -- it zaps
654 everything, regardless.)
655
656 Locking: as above.
657
658*/
659
660void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000661Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000662{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000663 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000664
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000665 if (tstate != PyThreadState_GET())
666 Py_FatalError("Py_EndInterpreter: thread is not current");
667 if (tstate->frame != NULL)
668 Py_FatalError("Py_EndInterpreter: thread still has a frame");
669 if (tstate != interp->tstate_head || tstate->next != NULL)
670 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000671
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000672 PyImport_Cleanup();
673 PyInterpreterState_Clear(interp);
674 PyThreadState_Swap(NULL);
675 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000676}
677
678static char *progname = "python";
679
680void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000681Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000682{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000683 if (pn && *pn)
684 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000685}
686
687char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000689{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000691}
692
Guido van Rossuma61691e1998-02-06 22:27:24 +0000693static char *default_home = NULL;
694
695void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000696Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000697{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000698 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000699}
700
701char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000702Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000703{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000704 char *home = default_home;
705 if (home == NULL && !Py_IgnoreEnvironmentFlag)
706 home = Py_GETENV("PYTHONHOME");
707 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000708}
709
Guido van Rossum6135a871995-01-09 17:53:26 +0000710/* Create __main__ module */
711
712static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000713initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000714{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000715 PyObject *m, *d;
716 m = PyImport_AddModule("__main__");
717 if (m == NULL)
718 Py_FatalError("can't create __main__ module");
719 d = PyModule_GetDict(m);
720 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
721 PyObject *bimod = PyImport_ImportModule("__builtin__");
722 if (bimod == NULL ||
723 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
724 Py_FatalError("can't add __builtins__ to __main__");
725 Py_XDECREF(bimod);
726 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000727}
728
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000729/* Import the site module (not into __main__ though) */
730
731static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000732initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000733{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000734 PyObject *m;
735 m = PyImport_ImportModule("site");
736 if (m == NULL) {
737 PyErr_Print();
738 Py_Finalize();
739 exit(1);
740 }
741 else {
742 Py_DECREF(m);
743 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000744}
745
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000746/* Parse input from a file and execute it */
747
748int
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000749PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000750 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000751{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000752 if (filename == NULL)
753 filename = "???";
754 if (Py_FdIsInteractive(fp, filename)) {
755 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
756 if (closeit)
757 fclose(fp);
758 return err;
759 }
760 else
761 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000762}
763
764int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000765PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000766{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000767 PyObject *v;
768 int ret;
769 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000770
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000771 if (flags == NULL) {
772 flags = &local_flags;
773 local_flags.cf_flags = 0;
774 }
775 v = PySys_GetObject("ps1");
776 if (v == NULL) {
777 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
778 Py_XDECREF(v);
779 }
780 v = PySys_GetObject("ps2");
781 if (v == NULL) {
782 PySys_SetObject("ps2", v = PyString_FromString("... "));
783 Py_XDECREF(v);
784 }
785 for (;;) {
786 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Victor Stinner3c082a72017-10-17 01:35:19 -0700787 _PyDebug_PrintTotalRefs();
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000788 if (ret == E_EOF)
789 return 0;
790 /*
791 if (ret == E_NOMEM)
792 return -1;
793 */
794 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000795}
796
Eric Smith7c478942008-03-18 23:45:49 +0000797#if 0
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000798/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000799#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000800 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
801 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Eric Smith7c478942008-03-18 23:45:49 +0000802#endif
803#if 1
Neal Norwitzca460d92006-09-06 06:28:06 +0000804/* Keep an example of flags with future keyword support. */
805#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000806 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
807 PyPARSE_DONT_IMPLY_DEDENT : 0) \
808 | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
809 PyPARSE_PRINT_IS_FUNCTION : 0) \
810 | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
811 PyPARSE_UNICODE_LITERALS : 0) \
812 ) : 0)
Neal Norwitzca460d92006-09-06 06:28:06 +0000813#endif
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000814
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000815int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000816PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000817{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000818 PyObject *m, *d, *v, *w;
819 mod_ty mod;
820 PyArena *arena;
821 char *ps1 = "", *ps2 = "";
822 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000823
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000824 v = PySys_GetObject("ps1");
825 if (v != NULL) {
826 v = PyObject_Str(v);
827 if (v == NULL)
828 PyErr_Clear();
829 else if (PyString_Check(v))
830 ps1 = PyString_AsString(v);
831 }
832 w = PySys_GetObject("ps2");
833 if (w != NULL) {
834 w = PyObject_Str(w);
835 if (w == NULL)
836 PyErr_Clear();
837 else if (PyString_Check(w))
838 ps2 = PyString_AsString(w);
839 }
840 arena = PyArena_New();
841 if (arena == NULL) {
842 Py_XDECREF(v);
843 Py_XDECREF(w);
844 return -1;
845 }
846 mod = PyParser_ASTFromFile(fp, filename,
847 Py_single_input, ps1, ps2,
848 flags, &errcode, arena);
849 Py_XDECREF(v);
850 Py_XDECREF(w);
851 if (mod == NULL) {
852 PyArena_Free(arena);
853 if (errcode == E_EOF) {
854 PyErr_Clear();
855 return E_EOF;
856 }
857 PyErr_Print();
858 return -1;
859 }
860 m = PyImport_AddModule("__main__");
861 if (m == NULL) {
862 PyArena_Free(arena);
863 return -1;
864 }
865 d = PyModule_GetDict(m);
866 v = run_mod(mod, filename, d, d, flags, arena);
867 PyArena_Free(arena);
868 if (v == NULL) {
869 PyErr_Print();
870 return -1;
871 }
872 Py_DECREF(v);
873 if (Py_FlushLine())
874 PyErr_Clear();
875 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000876}
877
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000878/* Check whether a file maybe a pyc file: Look at the extension,
879 the file type, and, if we may close it, at the first few bytes. */
880
881static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000882maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000883{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000884 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
885 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000886
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000887 /* Only look into the file if we are allowed to close it, since
888 it then should also be seekable. */
889 if (closeit) {
890 /* Read only two bytes of the magic. If the file was opened in
891 text mode, the bytes 3 and 4 of the magic (\r\n) might not
892 be read as they are on disk. */
893 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
894 unsigned char buf[2];
895 /* Mess: In case of -x, the stream is NOT at its start now,
896 and ungetc() was used to push back the first newline,
897 which makes the current stream position formally undefined,
898 and a x-platform nightmare.
899 Unfortunately, we have no direct way to know whether -x
900 was specified. So we use a terrible hack: if the current
901 stream position is not 0, we assume -x was specified, and
902 give up. Bug 132850 on SourceForge spells out the
903 hopelessness of trying anything else (fseek and ftell
904 don't work predictably x-platform for text-mode files).
905 */
906 int ispyc = 0;
907 if (ftell(fp) == 0) {
908 if (fread(buf, 1, 2, fp) == 2 &&
909 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
910 ispyc = 1;
911 rewind(fp);
912 }
913 return ispyc;
914 }
915 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000916}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000917
Guido van Rossum0df002c2000-08-27 19:21:52 +0000918int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000919PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000920 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000921{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000922 PyObject *m, *d, *v;
923 const char *ext;
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100924 int set_file_name = 0, len, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000925
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000926 m = PyImport_AddModule("__main__");
927 if (m == NULL)
928 return -1;
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100929 Py_INCREF(m);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000930 d = PyModule_GetDict(m);
931 if (PyDict_GetItemString(d, "__file__") == NULL) {
932 PyObject *f = PyString_FromString(filename);
933 if (f == NULL)
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100934 goto done;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000935 if (PyDict_SetItemString(d, "__file__", f) < 0) {
936 Py_DECREF(f);
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100937 goto done;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000938 }
939 set_file_name = 1;
940 Py_DECREF(f);
941 }
942 len = strlen(filename);
943 ext = filename + len - (len > 4 ? 4 : 0);
944 if (maybe_pyc_file(fp, filename, ext, closeit)) {
945 /* Try to run a pyc file. First, re-open in binary */
946 if (closeit)
947 fclose(fp);
948 if ((fp = fopen(filename, "rb")) == NULL) {
949 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000950 goto done;
951 }
952 /* Turn on optimization if a .pyo file is given */
953 if (strcmp(ext, ".pyo") == 0)
954 Py_OptimizeFlag = 1;
955 v = run_pyc_file(fp, filename, d, d, flags);
956 } else {
957 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
958 closeit, flags);
959 }
960 if (v == NULL) {
961 PyErr_Print();
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000962 goto done;
963 }
964 Py_DECREF(v);
965 if (Py_FlushLine())
966 PyErr_Clear();
967 ret = 0;
Georg Brandlaa2321b2007-03-07 00:40:28 +0000968 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000969 if (set_file_name && PyDict_DelItemString(d, "__file__"))
970 PyErr_Clear();
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100971 Py_DECREF(m);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000972 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000973}
974
975int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000976PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000977{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000978 PyObject *m, *d, *v;
979 m = PyImport_AddModule("__main__");
980 if (m == NULL)
981 return -1;
982 d = PyModule_GetDict(m);
983 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
984 if (v == NULL) {
985 PyErr_Print();
986 return -1;
987 }
988 Py_DECREF(v);
989 if (Py_FlushLine())
990 PyErr_Clear();
991 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000992}
993
Barry Warsaw035574d1997-08-29 22:07:17 +0000994static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000995parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000996 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000997{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000998 long hold;
999 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001001 /* old style errors */
1002 if (PyTuple_Check(err))
1003 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1004 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001005
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001006 *message = NULL;
1007
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001008 /* new style errors. `err' is an instance */
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001009 *message = PyObject_GetAttrString(err, "msg");
1010 if (!*message)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001011 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001012
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001013 v = PyObject_GetAttrString(err, "filename");
1014 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001016 if (v == Py_None) {
1017 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001018 *filename = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001019 }
1020 else {
1021 *filename = PyString_AsString(v);
1022 Py_DECREF(v);
1023 if (!*filename)
1024 goto finally;
1025 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001026
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001027 v = PyObject_GetAttrString(err, "lineno");
1028 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001029 goto finally;
1030 hold = PyInt_AsLong(v);
1031 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001032 if (hold < 0 && PyErr_Occurred())
1033 goto finally;
1034 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001035
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001036 v = PyObject_GetAttrString(err, "offset");
1037 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 goto finally;
1039 if (v == Py_None) {
1040 *offset = -1;
1041 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001042 } else {
1043 hold = PyInt_AsLong(v);
1044 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001045 if (hold < 0 && PyErr_Occurred())
1046 goto finally;
1047 *offset = (int)hold;
1048 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001049
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001050 v = PyObject_GetAttrString(err, "text");
1051 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001052 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001053 if (v == Py_None) {
1054 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001055 *text = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001056 }
1057 else {
1058 *text = PyString_AsString(v);
1059 Py_DECREF(v);
1060 if (!*text)
1061 goto finally;
1062 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001063 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001064
1065finally:
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001066 Py_XDECREF(*message);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001067 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001068}
1069
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001070void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001071PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001072{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001073 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001074}
1075
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001076static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001077print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001078{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001079 char *nl;
1080 if (offset >= 0) {
Benjamin Petersonec9f9f52010-10-29 03:45:34 +00001081 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1082 offset--;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001083 for (;;) {
1084 nl = strchr(text, '\n');
1085 if (nl == NULL || nl-text >= offset)
1086 break;
1087 offset -= (int)(nl+1-text);
1088 text = nl+1;
1089 }
1090 while (*text == ' ' || *text == '\t') {
1091 text++;
1092 offset--;
1093 }
1094 }
1095 PyFile_WriteString(" ", f);
1096 PyFile_WriteString(text, f);
1097 if (*text == '\0' || text[strlen(text)-1] != '\n')
1098 PyFile_WriteString("\n", f);
1099 if (offset == -1)
1100 return;
1101 PyFile_WriteString(" ", f);
1102 offset--;
1103 while (offset > 0) {
1104 PyFile_WriteString(" ", f);
1105 offset--;
1106 }
1107 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001108}
1109
Guido van Rossum66e8e862001-03-23 17:54:43 +00001110static void
1111handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001112{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001113 PyObject *exception, *value, *tb;
1114 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001115
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001116 if (Py_InspectFlag)
1117 /* Don't exit if -i flag was given. This flag is set to 0
1118 * when entering interactive mode for inspecting. */
1119 return;
Georg Brandl49aafc92007-03-07 00:34:46 +00001120
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001121 PyErr_Fetch(&exception, &value, &tb);
1122 if (Py_FlushLine())
1123 PyErr_Clear();
1124 fflush(stdout);
1125 if (value == NULL || value == Py_None)
1126 goto done;
1127 if (PyExceptionInstance_Check(value)) {
1128 /* The error code should be in the `code' attribute. */
1129 PyObject *code = PyObject_GetAttrString(value, "code");
1130 if (code) {
1131 Py_DECREF(value);
1132 value = code;
1133 if (value == Py_None)
1134 goto done;
1135 }
1136 /* If we failed to dig out the 'code' attribute,
1137 just let the else clause below print the error. */
1138 }
Serhiy Storchaka48c8bf22018-07-31 09:09:36 +03001139 if (_PyAnyInt_Check(value))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001140 exitcode = (int)PyInt_AsLong(value);
1141 else {
Victor Stinnerc49dfcc2010-05-25 22:30:32 +00001142 PyObject *sys_stderr = PySys_GetObject("stderr");
1143 if (sys_stderr != NULL && sys_stderr != Py_None) {
1144 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1145 } else {
1146 PyObject_Print(value, stderr, Py_PRINT_RAW);
1147 fflush(stderr);
1148 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001149 PySys_WriteStderr("\n");
1150 exitcode = 1;
1151 }
Tim Peterscf615b52003-04-19 18:47:02 +00001152 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 /* Restore and clear the exception info, in order to properly decref
1154 * the exception, value, and traceback. If we just exit instead,
1155 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1156 * some finalizers from running.
1157 */
1158 PyErr_Restore(exception, value, tb);
1159 PyErr_Clear();
1160 Py_Exit(exitcode);
1161 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001162}
1163
1164void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001165PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001166{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001167 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001168
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001169 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1170 handle_system_exit();
1171 }
1172 PyErr_Fetch(&exception, &v, &tb);
1173 if (exception == NULL)
1174 return;
1175 PyErr_NormalizeException(&exception, &v, &tb);
1176 if (exception == NULL)
1177 return;
1178 /* Now we know v != NULL too */
1179 if (set_sys_last_vars) {
1180 PySys_SetObject("last_type", exception);
1181 PySys_SetObject("last_value", v);
1182 PySys_SetObject("last_traceback", tb);
1183 }
1184 hook = PySys_GetObject("excepthook");
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001185 if (hook && hook != Py_None) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001186 PyObject *args = PyTuple_Pack(3,
1187 exception, v, tb ? tb : Py_None);
1188 PyObject *result = PyEval_CallObject(hook, args);
1189 if (result == NULL) {
1190 PyObject *exception2, *v2, *tb2;
1191 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1192 handle_system_exit();
1193 }
1194 PyErr_Fetch(&exception2, &v2, &tb2);
1195 PyErr_NormalizeException(&exception2, &v2, &tb2);
1196 /* It should not be possible for exception2 or v2
1197 to be NULL. However PyErr_Display() can't
1198 tolerate NULLs, so just be safe. */
1199 if (exception2 == NULL) {
1200 exception2 = Py_None;
1201 Py_INCREF(exception2);
1202 }
1203 if (v2 == NULL) {
1204 v2 = Py_None;
1205 Py_INCREF(v2);
1206 }
1207 if (Py_FlushLine())
1208 PyErr_Clear();
1209 fflush(stdout);
1210 PySys_WriteStderr("Error in sys.excepthook:\n");
1211 PyErr_Display(exception2, v2, tb2);
1212 PySys_WriteStderr("\nOriginal exception was:\n");
1213 PyErr_Display(exception, v, tb);
1214 Py_DECREF(exception2);
1215 Py_DECREF(v2);
1216 Py_XDECREF(tb2);
1217 }
1218 Py_XDECREF(result);
1219 Py_XDECREF(args);
1220 } else {
1221 PySys_WriteStderr("sys.excepthook is missing\n");
1222 PyErr_Display(exception, v, tb);
1223 }
1224 Py_XDECREF(exception);
1225 Py_XDECREF(v);
1226 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001227}
1228
Richard Jones7b9558d2006-05-27 12:29:24 +00001229void
1230PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001231{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001232 int err = 0;
1233 PyObject *f = PySys_GetObject("stderr");
1234 Py_INCREF(value);
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001235 if (f == NULL || f == Py_None)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001236 fprintf(stderr, "lost sys.stderr\n");
1237 else {
1238 if (Py_FlushLine())
1239 PyErr_Clear();
1240 fflush(stdout);
1241 if (tb && tb != Py_None)
1242 err = PyTraceBack_Print(tb, f);
1243 if (err == 0 &&
1244 PyObject_HasAttrString(value, "print_file_and_line"))
1245 {
1246 PyObject *message;
1247 const char *filename, *text;
1248 int lineno, offset;
1249 if (!parse_syntax_error(value, &message, &filename,
1250 &lineno, &offset, &text))
1251 PyErr_Clear();
1252 else {
1253 char buf[10];
1254 PyFile_WriteString(" File \"", f);
1255 if (filename == NULL)
1256 PyFile_WriteString("<string>", f);
1257 else
1258 PyFile_WriteString(filename, f);
1259 PyFile_WriteString("\", line ", f);
1260 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1261 PyFile_WriteString(buf, f);
1262 PyFile_WriteString("\n", f);
1263 if (text != NULL)
1264 print_error_text(f, offset, text);
1265 Py_DECREF(value);
1266 value = message;
1267 /* Can't be bothered to check all those
1268 PyFile_WriteString() calls */
1269 if (PyErr_Occurred())
1270 err = -1;
1271 }
1272 }
1273 if (err) {
1274 /* Don't do anything else */
1275 }
1276 else if (PyExceptionClass_Check(exception)) {
1277 PyObject* moduleName;
1278 char* className = PyExceptionClass_Name(exception);
1279 if (className != NULL) {
1280 char *dot = strrchr(className, '.');
1281 if (dot != NULL)
1282 className = dot+1;
1283 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001284
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001285 moduleName = PyObject_GetAttrString(exception, "__module__");
1286 if (moduleName == NULL)
1287 err = PyFile_WriteString("<unknown>", f);
1288 else {
1289 char* modstr = PyString_AsString(moduleName);
1290 if (modstr && strcmp(modstr, "exceptions"))
1291 {
1292 err = PyFile_WriteString(modstr, f);
1293 err += PyFile_WriteString(".", f);
1294 }
1295 Py_DECREF(moduleName);
1296 }
1297 if (err == 0) {
1298 if (className == NULL)
1299 err = PyFile_WriteString("<unknown>", f);
1300 else
1301 err = PyFile_WriteString(className, f);
1302 }
1303 }
1304 else
1305 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1306 if (err == 0 && (value != Py_None)) {
1307 PyObject *s = PyObject_Str(value);
1308 /* only print colon if the str() of the
1309 object is not the empty string
1310 */
Martin Panteref85a1a2016-02-28 00:18:43 +00001311 if (s == NULL) {
1312 PyErr_Clear();
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001313 err = -1;
Martin Panteref85a1a2016-02-28 00:18:43 +00001314 PyFile_WriteString(": <exception str() failed>", f);
1315 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001316 else if (!PyString_Check(s) ||
1317 PyString_GET_SIZE(s) != 0)
1318 err = PyFile_WriteString(": ", f);
1319 if (err == 0)
1320 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1321 Py_XDECREF(s);
1322 }
1323 /* try to write a newline in any case */
Martin Panteref85a1a2016-02-28 00:18:43 +00001324 if (err < 0) {
1325 PyErr_Clear();
1326 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001327 err += PyFile_WriteString("\n", f);
1328 }
1329 Py_DECREF(value);
1330 /* If an error happened here, don't show it.
1331 XXX This is wrong, but too many callers rely on this behavior. */
1332 if (err != 0)
1333 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001334}
1335
Guido van Rossum82598051997-03-05 00:20:32 +00001336PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001337PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001338 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001339{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001340 PyObject *ret = NULL;
1341 mod_ty mod;
1342 PyArena *arena = PyArena_New();
1343 if (arena == NULL)
1344 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001345
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001346 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1347 if (mod != NULL)
1348 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1349 PyArena_Free(arena);
1350 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001351}
1352
1353PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001354PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001355 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001356{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001357 PyObject *ret;
1358 mod_ty mod;
1359 PyArena *arena = PyArena_New();
1360 if (arena == NULL)
1361 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001362
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001363 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1364 flags, NULL, arena);
1365 if (closeit)
1366 fclose(fp);
1367 if (mod == NULL) {
1368 PyArena_Free(arena);
1369 return NULL;
1370 }
1371 ret = run_mod(mod, filename, globals, locals, flags, arena);
1372 PyArena_Free(arena);
1373 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001374}
1375
Guido van Rossum82598051997-03-05 00:20:32 +00001376static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001378 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001379{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001380 PyCodeObject *co;
1381 PyObject *v;
1382 co = PyAST_Compile(mod, filename, flags, arena);
1383 if (co == NULL)
1384 return NULL;
1385 v = PyEval_EvalCode(co, globals, locals);
1386 Py_DECREF(co);
1387 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001388}
1389
Guido van Rossum82598051997-03-05 00:20:32 +00001390static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001391run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001392 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001393{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001394 PyCodeObject *co;
1395 PyObject *v;
1396 long magic;
1397 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001398
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001399 magic = PyMarshal_ReadLongFromFile(fp);
1400 if (magic != PyImport_GetMagicNumber()) {
1401 PyErr_SetString(PyExc_RuntimeError,
1402 "Bad magic number in .pyc file");
1403 return NULL;
1404 }
1405 (void) PyMarshal_ReadLongFromFile(fp);
1406 v = PyMarshal_ReadLastObjectFromFile(fp);
1407 fclose(fp);
1408 if (v == NULL || !PyCode_Check(v)) {
1409 Py_XDECREF(v);
1410 PyErr_SetString(PyExc_RuntimeError,
1411 "Bad code object in .pyc file");
1412 return NULL;
1413 }
1414 co = (PyCodeObject *)v;
1415 v = PyEval_EvalCode(co, globals, locals);
1416 if (v && flags)
1417 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1418 Py_DECREF(co);
1419 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001420}
1421
Guido van Rossum82598051997-03-05 00:20:32 +00001422PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001423Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001424 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001425{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001426 PyCodeObject *co;
1427 mod_ty mod;
1428 PyArena *arena = PyArena_New();
1429 if (arena == NULL)
1430 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001431
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001432 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1433 if (mod == NULL) {
1434 PyArena_Free(arena);
1435 return NULL;
1436 }
1437 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1438 PyObject *result = PyAST_mod2obj(mod);
1439 PyArena_Free(arena);
1440 return result;
1441 }
1442 co = PyAST_Compile(mod, filename, flags, arena);
1443 PyArena_Free(arena);
1444 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001445}
1446
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001447struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001448Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001449{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001450 struct symtable *st;
1451 mod_ty mod;
1452 PyCompilerFlags flags;
1453 PyArena *arena = PyArena_New();
1454 if (arena == NULL)
1455 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001457 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001458
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001459 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1460 if (mod == NULL) {
1461 PyArena_Free(arena);
1462 return NULL;
1463 }
1464 st = PySymtable_Build(mod, filename, 0);
1465 PyArena_Free(arena);
1466 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001467}
1468
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469/* Preferred access to parser is through AST. */
1470mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001471PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001472 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001474 mod_ty mod;
1475 PyCompilerFlags localflags;
1476 perrdetail err;
1477 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001479 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1480 &_PyParser_Grammar, start, &err,
1481 &iflags);
1482 if (flags == NULL) {
1483 localflags.cf_flags = 0;
1484 flags = &localflags;
1485 }
1486 if (n) {
1487 flags->cf_flags |= iflags & PyCF_MASK;
1488 mod = PyAST_FromNode(n, flags, filename, arena);
1489 PyNode_Free(n);
1490 return mod;
1491 }
1492 else {
1493 err_input(&err);
1494 return NULL;
1495 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496}
1497
1498mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001499PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001500 char *ps2, PyCompilerFlags *flags, int *errcode,
1501 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 mod_ty mod;
1504 PyCompilerFlags localflags;
1505 perrdetail err;
1506 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001507
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001508 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1509 start, ps1, ps2, &err, &iflags);
1510 if (flags == NULL) {
1511 localflags.cf_flags = 0;
1512 flags = &localflags;
1513 }
1514 if (n) {
1515 flags->cf_flags |= iflags & PyCF_MASK;
1516 mod = PyAST_FromNode(n, flags, filename, arena);
1517 PyNode_Free(n);
1518 return mod;
1519 }
1520 else {
1521 err_input(&err);
1522 if (errcode)
1523 *errcode = err.error;
1524 return NULL;
1525 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526}
1527
Guido van Rossuma110aa61994-08-29 12:50:44 +00001528/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001529
Guido van Rossuma110aa61994-08-29 12:50:44 +00001530node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001531PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001532{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001533 perrdetail err;
1534 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1535 start, NULL, NULL, &err, flags);
1536 if (n == NULL)
1537 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001538
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001539 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001540}
1541
Guido van Rossuma110aa61994-08-29 12:50:44 +00001542/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001543
Guido van Rossuma110aa61994-08-29 12:50:44 +00001544node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001545PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001546{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001547 perrdetail err;
1548 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1549 start, &err, flags);
1550 if (n == NULL)
1551 err_input(&err);
1552 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001553}
1554
1555node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001556PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001557 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001558{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001559 perrdetail err;
1560 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1561 &_PyParser_Grammar, start, &err, flags);
1562 if (n == NULL)
1563 err_input(&err);
1564 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001565}
1566
1567node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001568PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001569{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001570 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001571}
1572
Guido van Rossum66ebd912003-04-17 16:02:26 +00001573/* May want to move a more generalized form of this to parsetok.c or
1574 even parser modules. */
1575
1576void
1577PyParser_SetError(perrdetail *err)
1578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001579 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001580}
1581
Guido van Rossuma110aa61994-08-29 12:50:44 +00001582/* Set the error appropriate to the given input error code (see errcode.h) */
1583
1584static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001585err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001586{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001587 PyObject *v, *w, *errtype;
1588 PyObject* u = NULL;
1589 char *msg = NULL;
1590 errtype = PyExc_SyntaxError;
1591 switch (err->error) {
1592 case E_ERROR:
Miss Islington (bot)a45fa392018-07-11 14:53:17 -07001593 goto cleanup;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001594 case E_SYNTAX:
1595 errtype = PyExc_IndentationError;
1596 if (err->expected == INDENT)
1597 msg = "expected an indented block";
1598 else if (err->token == INDENT)
1599 msg = "unexpected indent";
1600 else if (err->token == DEDENT)
1601 msg = "unexpected unindent";
1602 else {
1603 errtype = PyExc_SyntaxError;
1604 msg = "invalid syntax";
1605 }
1606 break;
1607 case E_TOKEN:
1608 msg = "invalid token";
1609 break;
1610 case E_EOFS:
1611 msg = "EOF while scanning triple-quoted string literal";
1612 break;
1613 case E_EOLS:
1614 msg = "EOL while scanning string literal";
1615 break;
1616 case E_INTR:
1617 if (!PyErr_Occurred())
1618 PyErr_SetNone(PyExc_KeyboardInterrupt);
1619 goto cleanup;
1620 case E_NOMEM:
1621 PyErr_NoMemory();
1622 goto cleanup;
1623 case E_EOF:
1624 msg = "unexpected EOF while parsing";
1625 break;
1626 case E_TABSPACE:
1627 errtype = PyExc_TabError;
1628 msg = "inconsistent use of tabs and spaces in indentation";
1629 break;
1630 case E_OVERFLOW:
1631 msg = "expression too long";
1632 break;
1633 case E_DEDENT:
1634 errtype = PyExc_IndentationError;
1635 msg = "unindent does not match any outer indentation level";
1636 break;
1637 case E_TOODEEP:
1638 errtype = PyExc_IndentationError;
1639 msg = "too many levels of indentation";
1640 break;
1641 case E_DECODE: {
1642 PyObject *type, *value, *tb;
1643 PyErr_Fetch(&type, &value, &tb);
1644 if (value != NULL) {
1645 u = PyObject_Str(value);
1646 if (u != NULL) {
1647 msg = PyString_AsString(u);
1648 }
1649 }
1650 if (msg == NULL)
1651 msg = "unknown decode error";
1652 Py_XDECREF(type);
1653 Py_XDECREF(value);
1654 Py_XDECREF(tb);
1655 break;
1656 }
tzickelf64c8132018-09-10 21:46:14 +03001657 case E_IO:
1658 msg = "I/O error while reading";
1659 break;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001660 case E_LINECONT:
1661 msg = "unexpected character after line continuation character";
1662 break;
1663 default:
1664 fprintf(stderr, "error=%d\n", err->error);
1665 msg = "unknown parsing error";
1666 break;
1667 }
1668 v = Py_BuildValue("(ziiz)", err->filename,
1669 err->lineno, err->offset, err->text);
1670 w = NULL;
1671 if (v != NULL)
1672 w = Py_BuildValue("(sO)", msg, v);
1673 Py_XDECREF(u);
1674 Py_XDECREF(v);
1675 PyErr_SetObject(errtype, w);
1676 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001677cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001678 if (err->text != NULL) {
1679 PyObject_FREE(err->text);
1680 err->text = NULL;
1681 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001682}
1683
1684/* Print fatal error message and abort */
1685
1686void
Tim Peters7c321a82002-07-09 02:57:01 +00001687Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001688{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001689 fprintf(stderr, "Fatal Python error: %s\n", msg);
1690 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller42f9b4e2009-03-31 22:20:35 +00001691
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001692#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001693 {
1694 size_t len = strlen(msg);
1695 WCHAR* buffer;
1696 size_t i;
Martin v. Löwis5344c992009-01-02 20:32:55 +00001697
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001698 /* Convert the message to wchar_t. This uses a simple one-to-one
1699 conversion, assuming that the this error message actually uses ASCII
1700 only. If this ceases to be true, we will have to convert. */
1701 buffer = alloca( (len+1) * (sizeof *buffer));
1702 for( i=0; i<=len; ++i)
1703 buffer[i] = msg[i];
1704 OutputDebugStringW(L"Fatal Python error: ");
1705 OutputDebugStringW(buffer);
1706 OutputDebugStringW(L"\n");
1707 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001708#ifdef _DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001709 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001710#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001711#endif /* MS_WINDOWS */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001712 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001713}
1714
1715/* Clean up and exit */
1716
Guido van Rossuma110aa61994-08-29 12:50:44 +00001717#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001718#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001719#endif
1720
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001721/* Wait until threading._shutdown completes, provided
1722 the threading module was imported in the first place.
1723 The shutdown routine will wait until all non-daemon
1724 "threading" threads have completed. */
1725static void
1726wait_for_thread_shutdown(void)
1727{
1728#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001729 PyObject *result;
1730 PyThreadState *tstate = PyThreadState_GET();
1731 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1732 "threading");
1733 if (threading == NULL) {
1734 /* threading not imported */
1735 PyErr_Clear();
1736 return;
1737 }
1738 result = PyObject_CallMethod(threading, "_shutdown", "");
1739 if (result == NULL)
1740 PyErr_WriteUnraisable(threading);
1741 else
1742 Py_DECREF(result);
1743 Py_DECREF(threading);
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001744#endif
1745}
1746
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001747#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001748static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001749static int nexitfuncs = 0;
1750
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001751int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001752{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001753 if (nexitfuncs >= NEXITFUNCS)
1754 return -1;
1755 exitfuncs[nexitfuncs++] = func;
1756 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001757}
1758
Guido van Rossumcc283f51997-08-05 02:22:03 +00001759static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001760call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001761{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001762 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001763
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001764 if (exitfunc) {
1765 PyObject *res;
1766 Py_INCREF(exitfunc);
1767 PySys_SetObject("exitfunc", (PyObject *)NULL);
1768 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1769 if (res == NULL) {
1770 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1771 PySys_WriteStderr("Error in sys.exitfunc:\n");
1772 }
1773 PyErr_Print();
1774 }
1775 Py_DECREF(exitfunc);
1776 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001777
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001778 if (Py_FlushLine())
1779 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001780}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001781
Guido van Rossumcc283f51997-08-05 02:22:03 +00001782static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001783call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001784{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001785 while (nexitfuncs > 0)
1786 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001787
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001788 fflush(stdout);
1789 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001790}
1791
1792void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001793Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001794{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001795 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001796
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001797 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001798}
1799
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001800static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001801initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001802{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001803#ifdef SIGPIPE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001804 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001805#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001806#ifdef SIGXFZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001807 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001808#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001809#ifdef SIGXFSZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001810 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001811#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001812 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001813}
1814
Guido van Rossum7433b121997-02-14 19:45:36 +00001815
1816/*
1817 * The file descriptor fd is considered ``interactive'' if either
1818 * a) isatty(fd) is TRUE, or
1819 * b) the -i flag was given, and the filename associated with
1820 * the descriptor is NULL or "<stdin>" or "???".
1821 */
1822int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001823Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001824{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001825 if (isatty((int)fileno(fp)))
1826 return 1;
1827 if (!Py_InteractiveFlag)
1828 return 0;
1829 return (filename == NULL) ||
1830 (strcmp(filename, "<stdin>") == 0) ||
1831 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001832}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001833
1834
Tim Petersd08e3822003-04-17 15:24:21 +00001835#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001836#if defined(WIN32) && defined(_MSC_VER)
1837
1838/* Stack checking for Microsoft C */
1839
1840#include <malloc.h>
1841#include <excpt.h>
1842
Fred Drakee8de31c2000-08-31 05:38:39 +00001843/*
1844 * Return non-zero when we run out of memory on the stack; zero otherwise.
1845 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001846int
Fred Drake399739f2000-08-31 05:52:44 +00001847PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001848{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 __try {
1850 /* alloca throws a stack overflow exception if there's
1851 not enough space left on the stack */
1852 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1853 return 0;
1854 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1855 EXCEPTION_EXECUTE_HANDLER :
1856 EXCEPTION_CONTINUE_SEARCH) {
1857 int errcode = _resetstkoflw();
1858 if (errcode == 0)
1859 {
1860 Py_FatalError("Could not reset the stack!");
1861 }
1862 }
1863 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001864}
1865
1866#endif /* WIN32 && _MSC_VER */
1867
1868/* Alternate implementations can be added here... */
1869
1870#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001871
1872
1873/* Wrappers around sigaction() or signal(). */
1874
1875PyOS_sighandler_t
1876PyOS_getsig(int sig)
1877{
1878#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001879 struct sigaction context;
1880 if (sigaction(sig, NULL, &context) == -1)
1881 return SIG_ERR;
1882 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001883#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001884 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001885/* Special signal handling for the secure CRT in Visual Studio 2005 */
1886#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001887 switch (sig) {
1888 /* Only these signals are valid */
1889 case SIGINT:
1890 case SIGILL:
1891 case SIGFPE:
1892 case SIGSEGV:
1893 case SIGTERM:
1894 case SIGBREAK:
1895 case SIGABRT:
1896 break;
1897 /* Don't call signal() with other values or it will assert */
1898 default:
1899 return SIG_ERR;
1900 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001901#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 handler = signal(sig, SIG_IGN);
1903 if (handler != SIG_ERR)
1904 signal(sig, handler);
1905 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001906#endif
1907}
1908
1909PyOS_sighandler_t
1910PyOS_setsig(int sig, PyOS_sighandler_t handler)
1911{
1912#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001913 /* Some code in Modules/signalmodule.c depends on sigaction() being
1914 * used here if HAVE_SIGACTION is defined. Fix that if this code
1915 * changes to invalidate that assumption.
1916 */
1917 struct sigaction context, ocontext;
1918 context.sa_handler = handler;
1919 sigemptyset(&context.sa_mask);
1920 context.sa_flags = 0;
1921 if (sigaction(sig, &context, &ocontext) == -1)
1922 return SIG_ERR;
1923 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001924#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001925 PyOS_sighandler_t oldhandler;
1926 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001927#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001928 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001929#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001930 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001931#endif
1932}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933
Martin Panterb1d867f2016-05-26 05:28:50 +00001934/* Deprecated C API functions still provided for binary compatibility */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935
1936#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001937PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1939{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001940 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941}
1942
Thomas Heller1b046642006-04-18 18:51:06 +00001943#undef PyParser_SimpleParseString
1944PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945PyParser_SimpleParseString(const char *str, int start)
1946{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001947 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001949
Thomas Heller1b046642006-04-18 18:51:06 +00001950#undef PyRun_AnyFile
1951PyAPI_FUNC(int)
1952PyRun_AnyFile(FILE *fp, const char *name)
1953{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001954 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001955}
1956
1957#undef PyRun_AnyFileEx
1958PyAPI_FUNC(int)
1959PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1960{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001961 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001962}
1963
1964#undef PyRun_AnyFileFlags
1965PyAPI_FUNC(int)
1966PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1967{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001968 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001969}
1970
1971#undef PyRun_File
1972PyAPI_FUNC(PyObject *)
1973PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1974{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001975 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001976}
1977
1978#undef PyRun_FileEx
1979PyAPI_FUNC(PyObject *)
1980PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1981{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001982 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001983}
1984
1985#undef PyRun_FileFlags
1986PyAPI_FUNC(PyObject *)
1987PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001988 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001989{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001990 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001991}
1992
1993#undef PyRun_SimpleFile
1994PyAPI_FUNC(int)
1995PyRun_SimpleFile(FILE *f, const char *p)
1996{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001997 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001998}
1999
2000#undef PyRun_SimpleFileEx
2001PyAPI_FUNC(int)
2002PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2003{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002004 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002005}
2006
2007
2008#undef PyRun_String
2009PyAPI_FUNC(PyObject *)
2010PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2011{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002012 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002013}
2014
2015#undef PyRun_SimpleString
2016PyAPI_FUNC(int)
2017PyRun_SimpleString(const char *s)
2018{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002019 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002020}
2021
2022#undef Py_CompileString
2023PyAPI_FUNC(PyObject *)
2024Py_CompileString(const char *str, const char *p, int s)
2025{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002026 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002027}
2028
2029#undef PyRun_InteractiveOne
2030PyAPI_FUNC(int)
2031PyRun_InteractiveOne(FILE *f, const char *p)
2032{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002033 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002034}
2035
2036#undef PyRun_InteractiveLoop
2037PyAPI_FUNC(int)
2038PyRun_InteractiveLoop(FILE *f, const char *p)
2039{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002040 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002041}
2042
Anthony Baxterac6bd462006-04-13 02:06:09 +00002043#ifdef __cplusplus
2044}
2045#endif
2046