blob: 2ffecc722dc317f91147d6f4f39bed5ff6e74225 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Antoine Pitrouefb60c02009-10-20 21:29:37 +000020#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000022#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023#include <signal.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000024#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000025
Benjamin Peterson796798b2009-01-02 20:47:27 +000026#ifdef MS_WINDOWS
Martin v. Löwis5344c992009-01-02 20:32:55 +000027#include "malloc.h" /* for alloca */
Benjamin Peterson796798b2009-01-02 20:47:27 +000028#endif
Martin v. Löwis5344c992009-01-02 20:32:55 +000029
Martin v. Löwis73d538b2003-03-05 15:13:47 +000030#ifdef HAVE_LANGINFO_H
31#include <locale.h>
32#include <langinfo.h>
33#endif
34
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000035#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#undef BYTE
37#include "windows.h"
38#endif
39
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#ifndef Py_REF_DEBUG
Tim Peters62e97f02006-03-28 21:44:32 +000041#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#else /* Py_REF_DEBUG */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000043#define PRINT_TOTAL_REFS() fprintf(stderr, \
44 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
45 _Py_GetRefTotal())
Neal Norwitz4281cef2006-03-04 19:58:13 +000046#endif
47
Anthony Baxterac6bd462006-04-13 02:06:09 +000048#ifdef __cplusplus
49extern "C" {
50#endif
51
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000052extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossum82598051997-03-05 00:20:32 +000054extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossumb73cc041993-11-01 16:28:59 +000056/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initmain(void);
58static void initsite(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000059static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000060 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000061static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000062 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000063static void err_input(perrdetail *);
64static void initsigs(void);
Antoine Pitrouefb60c02009-10-20 21:29:37 +000065static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void call_sys_exitfunc(void);
67static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000068extern void _PyUnicode_Init(void);
69extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000070
Mark Hammond8d98d2c2003-04-19 15:41:53 +000071#ifdef WITH_THREAD
72extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
73extern void _PyGILState_Fini(void);
74#endif /* WITH_THREAD */
75
Guido van Rossum82598051997-03-05 00:20:32 +000076int Py_DebugFlag; /* Needed by parser.c */
77int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000078int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl11041f02011-05-15 08:50:32 +020079int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000080int Py_NoSiteFlag; /* Suppress 'import site' */
Christian Heimes1a6387e2008-03-26 12:49:49 +000081int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Georg Brandl2da0fce2008-01-07 17:09:35 +000082int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000083int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000084int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000085int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000086int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000087/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
88 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
89 true divisions (which they will be in 2.3). */
90int _Py_QnewFlag = 0;
Christian Heimesaf748c32008-05-06 22:41:46 +000091int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Barry Warsaw1e13eb02012-02-20 20:42:21 -050092int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000093
Christian Heimes51c4d722013-10-22 10:22:29 +020094
95/* Hack to force loading of object files */
96int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
97 PyOS_mystrnicmp; /* Python/pystrcmp.o */
98
Brett Cannone9746892008-04-12 23:44:07 +000099/* PyModule_GetWarningsModule is no longer necessary as of 2.6
100since _warnings is builtin. This API should not be used. */
101PyObject *
102PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000103{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000104 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000105}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000106
Guido van Rossum25ce5661997-08-02 03:10:38 +0000107static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000108
Thomas Wouters7e474022000-07-16 12:04:32 +0000109/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000110
111int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000112Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000113{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000114 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000115}
116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117/* Global initializations. Can be undone by Py_Finalize(). Don't
118 call this twice without an intervening Py_Finalize() call. When
119 initializations fail, a fatal error is issued and the function does
120 not return. On return, the first thread and interpreter state have
121 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123 Locking: you must hold the interpreter lock while calling this.
124 (If the lock has not yet been initialized, that's equivalent to
125 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000128
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000129static int
130add_flag(int flag, const char *envs)
131{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000132 int env = atoi(envs);
133 if (flag < env)
134 flag = env;
135 if (flag < 1)
136 flag = 1;
137 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000138}
139
Serhiy Storchaka5127ed72015-05-30 17:45:12 +0300140static int
141isatty_no_error(PyObject *sys_stream)
142{
143 PyObject *sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
144 if (sys_isatty) {
145 int isatty = PyObject_IsTrue(sys_isatty);
146 Py_DECREF(sys_isatty);
147 if (isatty >= 0)
148 return isatty;
149 }
150 PyErr_Clear();
151 return 0;
152}
153
Guido van Rossuma027efa1997-05-05 20:56:21 +0000154void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000155Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000156{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000157 PyInterpreterState *interp;
158 PyThreadState *tstate;
159 PyObject *bimod, *sysmod;
160 char *p;
161 char *icodeset = NULL; /* On Windows, input codeset may theoretically
162 differ from output codeset. */
163 char *codeset = NULL;
164 char *errors = NULL;
165 int free_codeset = 0;
166 int overridden = 0;
Serhiy Storchaka5127ed72015-05-30 17:45:12 +0300167 PyObject *sys_stream;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000168#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000169 char *saved_locale, *loc_codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000170#endif
Martin v. Löwis99815892008-06-01 07:20:46 +0000171#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 char ibuf[128];
173 char buf[128];
Martin v. Löwis99815892008-06-01 07:20:46 +0000174#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000175 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000176
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000177 if (initialized)
178 return;
179 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000180
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000181 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
182 Py_DebugFlag = add_flag(Py_DebugFlag, p);
183 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
184 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
185 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
186 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
187 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
188 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500189 /* The variable is only tested for existence here; _PyRandom_Init will
190 check its value further. */
191 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
192 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
193
194 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000195
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000196 interp = PyInterpreterState_New();
197 if (interp == NULL)
198 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000199
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000200 tstate = PyThreadState_New(interp);
201 if (tstate == NULL)
202 Py_FatalError("Py_Initialize: can't make first thread");
203 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000205 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000206
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000207 if (!_PyFrame_Init())
208 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000209
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000210 if (!_PyInt_Init())
211 Py_FatalError("Py_Initialize: can't init ints");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000212
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000213 if (!_PyLong_Init())
214 Py_FatalError("Py_Initialize: can't init longs");
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000215
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000216 if (!PyByteArray_Init())
217 Py_FatalError("Py_Initialize: can't init bytearray");
Christian Heimes1a6387e2008-03-26 12:49:49 +0000218
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000219 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000220
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000221 interp->modules = PyDict_New();
222 if (interp->modules == NULL)
223 Py_FatalError("Py_Initialize: can't make modules dictionary");
224 interp->modules_reloading = PyDict_New();
225 if (interp->modules_reloading == NULL)
226 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000227
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000228#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000229 /* Init Unicode implementation; relies on the codec registry */
230 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000231#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000232
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000233 bimod = _PyBuiltin_Init();
234 if (bimod == NULL)
235 Py_FatalError("Py_Initialize: can't initialize __builtin__");
236 interp->builtins = PyModule_GetDict(bimod);
237 if (interp->builtins == NULL)
238 Py_FatalError("Py_Initialize: can't initialize builtins dict");
239 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000241 sysmod = _PySys_Init();
242 if (sysmod == NULL)
243 Py_FatalError("Py_Initialize: can't initialize sys");
244 interp->sysdict = PyModule_GetDict(sysmod);
245 if (interp->sysdict == NULL)
246 Py_FatalError("Py_Initialize: can't initialize sys dict");
247 Py_INCREF(interp->sysdict);
248 _PyImport_FixupExtension("sys", "sys");
249 PySys_SetPath(Py_GetPath());
250 PyDict_SetItemString(interp->sysdict, "modules",
251 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000252
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000253 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000254
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000255 /* initialize builtin exceptions */
256 _PyExc_Init();
257 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000258
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000259 /* phase 2 of builtins */
260 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000261
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000262 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000263
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000264 if (install_sigs)
265 initsigs(); /* Signal handling stuff, including initintr() */
Brett Cannonc33e82d2010-05-05 20:38:52 +0000266
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000267 /* Initialize warnings. */
268 _PyWarnings_Init();
269 if (PySys_HasWarnOptions()) {
270 PyObject *warnings_module = PyImport_ImportModule("warnings");
271 if (!warnings_module)
272 PyErr_Clear();
273 Py_XDECREF(warnings_module);
274 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000276 initmain(); /* Module __main__ */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000277
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000278 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000279#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000280 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000281#endif /* WITH_THREAD */
282
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000283 if (!Py_NoSiteFlag)
284 initsite(); /* Module site */
Victor Stinner66644262010-03-10 22:30:19 +0000285
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000286 if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
287 p = icodeset = codeset = strdup(p);
288 free_codeset = 1;
289 errors = strchr(p, ':');
290 if (errors) {
291 *errors = '\0';
292 errors++;
293 }
294 overridden = 1;
295 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000296
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000297#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000298 /* On Unix, set the file system encoding according to the
299 user's preference, if the CODESET names a well-known
300 Python codec, and Py_FileSystemDefaultEncoding isn't
301 initialized by other means. Also set the encoding of
302 stdin and stdout if these are terminals, unless overridden. */
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000303
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000304 if (!overridden || !Py_FileSystemDefaultEncoding) {
305 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
306 setlocale(LC_CTYPE, "");
307 loc_codeset = nl_langinfo(CODESET);
308 if (loc_codeset && *loc_codeset) {
309 PyObject *enc = PyCodec_Encoder(loc_codeset);
310 if (enc) {
311 loc_codeset = strdup(loc_codeset);
312 Py_DECREF(enc);
313 } else {
314 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
315 PyErr_Clear();
316 loc_codeset = NULL;
317 } else {
318 PyErr_Print();
319 exit(1);
320 }
321 }
322 } else
323 loc_codeset = NULL;
324 setlocale(LC_CTYPE, saved_locale);
325 free(saved_locale);
Martin v. Löwis99815892008-06-01 07:20:46 +0000326
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000327 if (!overridden) {
328 codeset = icodeset = loc_codeset;
329 free_codeset = 1;
330 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000331
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000332 /* Initialize Py_FileSystemDefaultEncoding from
333 locale even if PYTHONIOENCODING is set. */
334 if (!Py_FileSystemDefaultEncoding) {
335 Py_FileSystemDefaultEncoding = loc_codeset;
336 if (!overridden)
337 free_codeset = 0;
338 }
339 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000340#endif
341
342#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000343 if (!overridden) {
344 icodeset = ibuf;
345 codeset = buf;
346 sprintf(ibuf, "cp%d", GetConsoleCP());
347 sprintf(buf, "cp%d", GetConsoleOutputCP());
348 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000349#endif
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000350
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000351 if (codeset) {
352 sys_stream = PySys_GetObject("stdin");
Serhiy Storchaka5127ed72015-05-30 17:45:12 +0300353 if ((overridden || isatty_no_error(sys_stream)) &&
354 PyFile_Check(sys_stream)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000355 if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
356 Py_FatalError("Cannot set codeset of stdin");
357 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000358
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000359 sys_stream = PySys_GetObject("stdout");
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, codeset, errors))
363 Py_FatalError("Cannot set codeset of stdout");
364 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000365
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000366 sys_stream = PySys_GetObject("stderr");
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 stderr");
371 }
Martin v. Löwisea62d252006-04-03 10:56:49 +0000372
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000373 if (free_codeset)
374 free(codeset);
375 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000376}
377
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000378void
379Py_Initialize(void)
380{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000381 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000382}
383
384
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000385#ifdef COUNT_ALLOCS
Martin v. Löwis45294a92006-04-18 06:24:08 +0000386extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000387#endif
388
Guido van Rossum25ce5661997-08-02 03:10:38 +0000389/* Undo the effect of Py_Initialize().
390
391 Beware: if multiple interpreter and/or thread states exist, these
392 are not wiped out; only the current thread and interpreter state
393 are deleted. But since everything else is deleted, those other
394 interpreter and thread states should no longer be used.
395
396 (XXX We should do better, e.g. wipe out all interpreters and
397 threads.)
398
399 Locking: as above.
400
401*/
402
403void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000404Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000405{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000406 PyInterpreterState *interp;
407 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000408
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000409 if (!initialized)
410 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000411
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000412 wait_for_thread_shutdown();
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000413
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000414 /* The interpreter is still entirely intact at this point, and the
415 * exit funcs may be relying on that. In particular, if some thread
416 * or exit func is still waiting to do an import, the import machinery
417 * expects Py_IsInitialized() to return true. So don't say the
418 * interpreter is uninitialized until after the exit funcs have run.
419 * Note that Threading.py uses an exit func to do a join on all the
420 * threads created thru it, so this also protects pending imports in
421 * the threads created via Threading.
422 */
423 call_sys_exitfunc();
Antoine Pitroub9a45012014-11-21 02:04:21 +0100424 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000425
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000426 /* Get current thread state and interpreter pointer */
427 tstate = PyThreadState_GET();
428 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000429
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000430 /* Disable signal handling */
431 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000432
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000433 /* Clear type lookup cache */
434 PyType_ClearCache();
Christian Heimes908caac2008-01-27 23:34:59 +0000435
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000436 /* Collect garbage. This may call finalizers; it's nice to call these
437 * before all modules are destroyed.
438 * XXX If a __del__ or weakref callback is triggered here, and tries to
439 * XXX import a module, bad things can happen, because Python no
440 * XXX longer believes it's initialized.
441 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
442 * XXX is easy to provoke that way. I've also seen, e.g.,
443 * XXX Exception exceptions.ImportError: 'No module named sha'
444 * XXX in <function callback at 0x008F5718> ignored
445 * XXX but I'm unclear on exactly how that one happens. In any case,
446 * XXX I haven't seen a real-life report of either of these.
447 */
448 PyGC_Collect();
Martin v. Löwis45294a92006-04-18 06:24:08 +0000449#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000450 /* With COUNT_ALLOCS, it helps to run GC multiple times:
451 each collection might release some types from the type
452 list, so they become garbage. */
453 while (PyGC_Collect() > 0)
454 /* nothing */;
Martin v. Löwis45294a92006-04-18 06:24:08 +0000455#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000456
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000457 /* Destroy all modules */
458 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000459
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000460 /* Collect final garbage. This disposes of cycles created by
461 * new-style class definitions, for example.
462 * XXX This is disabled because it caused too many problems. If
463 * XXX a __del__ or weakref callback triggers here, Python code has
464 * XXX a hard time running, because even the sys module has been
465 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
466 * XXX One symptom is a sequence of information-free messages
467 * XXX coming from threads (if a __del__ or callback is invoked,
468 * XXX other threads can execute too, and any exception they encounter
469 * XXX triggers a comedy of errors as subsystem after subsystem
470 * XXX fails to find what it *expects* to find in sys to help report
471 * XXX the exception and consequent unexpected failures). I've also
472 * XXX seen segfaults then, after adding print statements to the
473 * XXX Python code getting called.
474 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000475#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000476 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000477#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000478
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000479 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
480 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000481
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000482 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000483#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000484 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000485#endif
486
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000487 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000488
Tim Peters9cf25ce2003-04-17 15:21:01 +0000489#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000490 /* Display all objects still alive -- this can invoke arbitrary
491 * __repr__ overrides, so requires a mostly-intact interpreter.
492 * Alas, a lot of stuff may still be alive now that will be cleaned
493 * up later.
494 */
495 if (Py_GETENV("PYTHONDUMPREFS"))
496 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000497#endif /* Py_TRACE_REFS */
498
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000499 /* Clear interpreter state */
500 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000501
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000502 /* Now we decref the exception classes. After this point nothing
503 can raise an exception. That's okay, because each Fini() method
504 below has been checked to make sure no exceptions are ever
505 raised.
506 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000507
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000509
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000510 /* Cleanup auto-thread-state */
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000511#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000512 _PyGILState_Fini();
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000513#endif /* WITH_THREAD */
514
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000515 /* Delete current thread */
516 PyThreadState_Swap(NULL);
517 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000518
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 /* Sundry finalizers */
520 PyMethod_Fini();
521 PyFrame_Fini();
522 PyCFunction_Fini();
523 PyTuple_Fini();
524 PyList_Fini();
525 PySet_Fini();
526 PyString_Fini();
527 PyByteArray_Fini();
528 PyInt_Fini();
529 PyFloat_Fini();
530 PyDict_Fini();
Benjamin Peterson57057a62014-08-28 12:30:00 -0400531 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000532
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000533#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000534 /* Cleanup Unicode implementation */
535 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000536#endif
537
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000538 /* XXX Still allocated:
539 - various static ad-hoc pointers to interned strings
540 - int and float free list blocks
541 - whatever various modules and libraries allocate
542 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000543
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000544 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000545
Tim Peters269b2a62003-04-17 19:52:29 +0000546#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000547 /* Display addresses (& refcnts) of all objects still alive.
548 * An address can be used to find the repr of the object, printed
549 * above by _Py_PrintReferences.
550 */
551 if (Py_GETENV("PYTHONDUMPREFS"))
552 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000553#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000554#ifdef PYMALLOC_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000555 if (Py_GETENV("PYTHONMALLOCSTATS"))
556 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000557#endif
558
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000559 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560}
561
562/* Create and initialize a new interpreter and thread, and return the
563 new thread. This requires that Py_Initialize() has been called
564 first.
565
566 Unsuccessful initialization yields a NULL pointer. Note that *no*
567 exception information is available even in this case -- the
568 exception information is held in the thread, and there is no
569 thread.
570
571 Locking: as above.
572
573*/
574
575PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000576Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000578 PyInterpreterState *interp;
579 PyThreadState *tstate, *save_tstate;
580 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000581
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000582 if (!initialized)
583 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000585 interp = PyInterpreterState_New();
586 if (interp == NULL)
587 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000589 tstate = PyThreadState_New(interp);
590 if (tstate == NULL) {
591 PyInterpreterState_Delete(interp);
592 return NULL;
593 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000595 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000597 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000598
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000599 interp->modules = PyDict_New();
600 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000602 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
603 if (bimod != NULL) {
604 interp->builtins = PyModule_GetDict(bimod);
605 if (interp->builtins == NULL)
606 goto handle_error;
607 Py_INCREF(interp->builtins);
608 }
609 sysmod = _PyImport_FindExtension("sys", "sys");
610 if (bimod != NULL && sysmod != NULL) {
611 interp->sysdict = PyModule_GetDict(sysmod);
612 if (interp->sysdict == NULL)
613 goto handle_error;
614 Py_INCREF(interp->sysdict);
615 PySys_SetPath(Py_GetPath());
616 PyDict_SetItemString(interp->sysdict, "modules",
617 interp->modules);
618 _PyImportHooks_Init();
619 initmain();
620 if (!Py_NoSiteFlag)
621 initsite();
622 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000624 if (!PyErr_Occurred())
625 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000626
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000627handle_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000628 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000630 PyErr_Print();
631 PyThreadState_Clear(tstate);
632 PyThreadState_Swap(save_tstate);
633 PyThreadState_Delete(tstate);
634 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637}
638
639/* Delete an interpreter and its last thread. This requires that the
640 given thread state is current, that the thread has no remaining
641 frames, and that it is its interpreter's only remaining thread.
642 It is a fatal error to violate these constraints.
643
644 (Py_Finalize() doesn't have these constraints -- it zaps
645 everything, regardless.)
646
647 Locking: as above.
648
649*/
650
651void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000652Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000654 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000655
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000656 if (tstate != PyThreadState_GET())
657 Py_FatalError("Py_EndInterpreter: thread is not current");
658 if (tstate->frame != NULL)
659 Py_FatalError("Py_EndInterpreter: thread still has a frame");
660 if (tstate != interp->tstate_head || tstate->next != NULL)
661 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000662
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000663 PyImport_Cleanup();
664 PyInterpreterState_Clear(interp);
665 PyThreadState_Swap(NULL);
666 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000667}
668
669static char *progname = "python";
670
671void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000672Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000673{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 if (pn && *pn)
675 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000676}
677
678char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000679Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000680{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000681 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000682}
683
Guido van Rossuma61691e1998-02-06 22:27:24 +0000684static char *default_home = NULL;
685
686void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000687Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000688{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000689 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000690}
691
692char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000693Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000694{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000695 char *home = default_home;
696 if (home == NULL && !Py_IgnoreEnvironmentFlag)
697 home = Py_GETENV("PYTHONHOME");
698 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000699}
700
Guido van Rossum6135a871995-01-09 17:53:26 +0000701/* Create __main__ module */
702
703static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000704initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000705{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 PyObject *m, *d;
707 m = PyImport_AddModule("__main__");
708 if (m == NULL)
709 Py_FatalError("can't create __main__ module");
710 d = PyModule_GetDict(m);
711 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
712 PyObject *bimod = PyImport_ImportModule("__builtin__");
713 if (bimod == NULL ||
714 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
715 Py_FatalError("can't add __builtins__ to __main__");
716 Py_XDECREF(bimod);
717 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000718}
719
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000720/* Import the site module (not into __main__ though) */
721
722static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000723initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000724{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000725 PyObject *m;
726 m = PyImport_ImportModule("site");
727 if (m == NULL) {
728 PyErr_Print();
729 Py_Finalize();
730 exit(1);
731 }
732 else {
733 Py_DECREF(m);
734 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000735}
736
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000737/* Parse input from a file and execute it */
738
739int
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000740PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000741 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000742{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000743 if (filename == NULL)
744 filename = "???";
745 if (Py_FdIsInteractive(fp, filename)) {
746 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
747 if (closeit)
748 fclose(fp);
749 return err;
750 }
751 else
752 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000753}
754
755int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000756PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000757{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000758 PyObject *v;
759 int ret;
760 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000761
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000762 if (flags == NULL) {
763 flags = &local_flags;
764 local_flags.cf_flags = 0;
765 }
766 v = PySys_GetObject("ps1");
767 if (v == NULL) {
768 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
769 Py_XDECREF(v);
770 }
771 v = PySys_GetObject("ps2");
772 if (v == NULL) {
773 PySys_SetObject("ps2", v = PyString_FromString("... "));
774 Py_XDECREF(v);
775 }
776 for (;;) {
777 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
778 PRINT_TOTAL_REFS();
779 if (ret == E_EOF)
780 return 0;
781 /*
782 if (ret == E_NOMEM)
783 return -1;
784 */
785 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000786}
787
Eric Smith7c478942008-03-18 23:45:49 +0000788#if 0
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000789/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000790#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000791 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
792 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Eric Smith7c478942008-03-18 23:45:49 +0000793#endif
794#if 1
Neal Norwitzca460d92006-09-06 06:28:06 +0000795/* Keep an example of flags with future keyword support. */
796#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000797 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
798 PyPARSE_DONT_IMPLY_DEDENT : 0) \
799 | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
800 PyPARSE_PRINT_IS_FUNCTION : 0) \
801 | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
802 PyPARSE_UNICODE_LITERALS : 0) \
803 ) : 0)
Neal Norwitzca460d92006-09-06 06:28:06 +0000804#endif
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000805
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000806int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000807PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000808{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000809 PyObject *m, *d, *v, *w;
810 mod_ty mod;
811 PyArena *arena;
812 char *ps1 = "", *ps2 = "";
813 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000814
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000815 v = PySys_GetObject("ps1");
816 if (v != NULL) {
817 v = PyObject_Str(v);
818 if (v == NULL)
819 PyErr_Clear();
820 else if (PyString_Check(v))
821 ps1 = PyString_AsString(v);
822 }
823 w = PySys_GetObject("ps2");
824 if (w != NULL) {
825 w = PyObject_Str(w);
826 if (w == NULL)
827 PyErr_Clear();
828 else if (PyString_Check(w))
829 ps2 = PyString_AsString(w);
830 }
831 arena = PyArena_New();
832 if (arena == NULL) {
833 Py_XDECREF(v);
834 Py_XDECREF(w);
835 return -1;
836 }
837 mod = PyParser_ASTFromFile(fp, filename,
838 Py_single_input, ps1, ps2,
839 flags, &errcode, arena);
840 Py_XDECREF(v);
841 Py_XDECREF(w);
842 if (mod == NULL) {
843 PyArena_Free(arena);
844 if (errcode == E_EOF) {
845 PyErr_Clear();
846 return E_EOF;
847 }
848 PyErr_Print();
849 return -1;
850 }
851 m = PyImport_AddModule("__main__");
852 if (m == NULL) {
853 PyArena_Free(arena);
854 return -1;
855 }
856 d = PyModule_GetDict(m);
857 v = run_mod(mod, filename, d, d, flags, arena);
858 PyArena_Free(arena);
859 if (v == NULL) {
860 PyErr_Print();
861 return -1;
862 }
863 Py_DECREF(v);
864 if (Py_FlushLine())
865 PyErr_Clear();
866 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000867}
868
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000869/* Check whether a file maybe a pyc file: Look at the extension,
870 the file type, and, if we may close it, at the first few bytes. */
871
872static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000873maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000874{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000875 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
876 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000877
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000878 /* Only look into the file if we are allowed to close it, since
879 it then should also be seekable. */
880 if (closeit) {
881 /* Read only two bytes of the magic. If the file was opened in
882 text mode, the bytes 3 and 4 of the magic (\r\n) might not
883 be read as they are on disk. */
884 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
885 unsigned char buf[2];
886 /* Mess: In case of -x, the stream is NOT at its start now,
887 and ungetc() was used to push back the first newline,
888 which makes the current stream position formally undefined,
889 and a x-platform nightmare.
890 Unfortunately, we have no direct way to know whether -x
891 was specified. So we use a terrible hack: if the current
892 stream position is not 0, we assume -x was specified, and
893 give up. Bug 132850 on SourceForge spells out the
894 hopelessness of trying anything else (fseek and ftell
895 don't work predictably x-platform for text-mode files).
896 */
897 int ispyc = 0;
898 if (ftell(fp) == 0) {
899 if (fread(buf, 1, 2, fp) == 2 &&
900 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
901 ispyc = 1;
902 rewind(fp);
903 }
904 return ispyc;
905 }
906 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000907}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000908
Guido van Rossum0df002c2000-08-27 19:21:52 +0000909int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000910PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000911 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000912{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000913 PyObject *m, *d, *v;
914 const char *ext;
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100915 int set_file_name = 0, len, ret = -1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000916
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000917 m = PyImport_AddModule("__main__");
918 if (m == NULL)
919 return -1;
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100920 Py_INCREF(m);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000921 d = PyModule_GetDict(m);
922 if (PyDict_GetItemString(d, "__file__") == NULL) {
923 PyObject *f = PyString_FromString(filename);
924 if (f == NULL)
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100925 goto done;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000926 if (PyDict_SetItemString(d, "__file__", f) < 0) {
927 Py_DECREF(f);
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100928 goto done;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000929 }
930 set_file_name = 1;
931 Py_DECREF(f);
932 }
933 len = strlen(filename);
934 ext = filename + len - (len > 4 ? 4 : 0);
935 if (maybe_pyc_file(fp, filename, ext, closeit)) {
936 /* Try to run a pyc file. First, re-open in binary */
937 if (closeit)
938 fclose(fp);
939 if ((fp = fopen(filename, "rb")) == NULL) {
940 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000941 goto done;
942 }
943 /* Turn on optimization if a .pyo file is given */
944 if (strcmp(ext, ".pyo") == 0)
945 Py_OptimizeFlag = 1;
946 v = run_pyc_file(fp, filename, d, d, flags);
947 } else {
948 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
949 closeit, flags);
950 }
951 if (v == NULL) {
952 PyErr_Print();
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000953 goto done;
954 }
955 Py_DECREF(v);
956 if (Py_FlushLine())
957 PyErr_Clear();
958 ret = 0;
Georg Brandlaa2321b2007-03-07 00:40:28 +0000959 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000960 if (set_file_name && PyDict_DelItemString(d, "__file__"))
961 PyErr_Clear();
Hynek Schlawackb271b3e2012-11-07 09:41:28 +0100962 Py_DECREF(m);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000963 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000964}
965
966int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000967PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000968{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000969 PyObject *m, *d, *v;
970 m = PyImport_AddModule("__main__");
971 if (m == NULL)
972 return -1;
973 d = PyModule_GetDict(m);
974 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
975 if (v == NULL) {
976 PyErr_Print();
977 return -1;
978 }
979 Py_DECREF(v);
980 if (Py_FlushLine())
981 PyErr_Clear();
982 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000983}
984
Barry Warsaw035574d1997-08-29 22:07:17 +0000985static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000986parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000987 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000988{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000989 long hold;
990 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +0000991
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000992 /* old style errors */
993 if (PyTuple_Check(err))
994 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
995 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000996
Benjamin Petersonb9348e72012-04-03 00:30:38 -0400997 *message = NULL;
998
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000999 /* new style errors. `err' is an instance */
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001000 *message = PyObject_GetAttrString(err, "msg");
1001 if (!*message)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001002 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001003
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001004 v = PyObject_GetAttrString(err, "filename");
1005 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001006 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001007 if (v == Py_None) {
1008 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001009 *filename = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001010 }
1011 else {
1012 *filename = PyString_AsString(v);
1013 Py_DECREF(v);
1014 if (!*filename)
1015 goto finally;
1016 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001017
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001018 v = PyObject_GetAttrString(err, "lineno");
1019 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001020 goto finally;
1021 hold = PyInt_AsLong(v);
1022 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001023 if (hold < 0 && PyErr_Occurred())
1024 goto finally;
1025 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001026
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001027 v = PyObject_GetAttrString(err, "offset");
1028 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001029 goto finally;
1030 if (v == Py_None) {
1031 *offset = -1;
1032 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001033 } else {
1034 hold = PyInt_AsLong(v);
1035 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001036 if (hold < 0 && PyErr_Occurred())
1037 goto finally;
1038 *offset = (int)hold;
1039 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001040
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001041 v = PyObject_GetAttrString(err, "text");
1042 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001043 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001044 if (v == Py_None) {
1045 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001046 *text = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001047 }
1048 else {
1049 *text = PyString_AsString(v);
1050 Py_DECREF(v);
1051 if (!*text)
1052 goto finally;
1053 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001054 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001055
1056finally:
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001057 Py_XDECREF(*message);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001058 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001059}
1060
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001061void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001062PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001063{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001064 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001065}
1066
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001067static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001068print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001069{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001070 char *nl;
1071 if (offset >= 0) {
Benjamin Petersonec9f9f52010-10-29 03:45:34 +00001072 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1073 offset--;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001074 for (;;) {
1075 nl = strchr(text, '\n');
1076 if (nl == NULL || nl-text >= offset)
1077 break;
1078 offset -= (int)(nl+1-text);
1079 text = nl+1;
1080 }
1081 while (*text == ' ' || *text == '\t') {
1082 text++;
1083 offset--;
1084 }
1085 }
1086 PyFile_WriteString(" ", f);
1087 PyFile_WriteString(text, f);
1088 if (*text == '\0' || text[strlen(text)-1] != '\n')
1089 PyFile_WriteString("\n", f);
1090 if (offset == -1)
1091 return;
1092 PyFile_WriteString(" ", f);
1093 offset--;
1094 while (offset > 0) {
1095 PyFile_WriteString(" ", f);
1096 offset--;
1097 }
1098 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001099}
1100
Guido van Rossum66e8e862001-03-23 17:54:43 +00001101static void
1102handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001103{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001104 PyObject *exception, *value, *tb;
1105 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001106
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001107 if (Py_InspectFlag)
1108 /* Don't exit if -i flag was given. This flag is set to 0
1109 * when entering interactive mode for inspecting. */
1110 return;
Georg Brandl49aafc92007-03-07 00:34:46 +00001111
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001112 PyErr_Fetch(&exception, &value, &tb);
1113 if (Py_FlushLine())
1114 PyErr_Clear();
1115 fflush(stdout);
1116 if (value == NULL || value == Py_None)
1117 goto done;
1118 if (PyExceptionInstance_Check(value)) {
1119 /* The error code should be in the `code' attribute. */
1120 PyObject *code = PyObject_GetAttrString(value, "code");
1121 if (code) {
1122 Py_DECREF(value);
1123 value = code;
1124 if (value == Py_None)
1125 goto done;
1126 }
1127 /* If we failed to dig out the 'code' attribute,
1128 just let the else clause below print the error. */
1129 }
Mark Dickinsonea829722017-02-02 19:31:53 +00001130 if (PyInt_Check(value) || PyLong_Check(value))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001131 exitcode = (int)PyInt_AsLong(value);
1132 else {
Victor Stinnerc49dfcc2010-05-25 22:30:32 +00001133 PyObject *sys_stderr = PySys_GetObject("stderr");
1134 if (sys_stderr != NULL && sys_stderr != Py_None) {
1135 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1136 } else {
1137 PyObject_Print(value, stderr, Py_PRINT_RAW);
1138 fflush(stderr);
1139 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001140 PySys_WriteStderr("\n");
1141 exitcode = 1;
1142 }
Tim Peterscf615b52003-04-19 18:47:02 +00001143 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001144 /* Restore and clear the exception info, in order to properly decref
1145 * the exception, value, and traceback. If we just exit instead,
1146 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1147 * some finalizers from running.
1148 */
1149 PyErr_Restore(exception, value, tb);
1150 PyErr_Clear();
1151 Py_Exit(exitcode);
1152 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001153}
1154
1155void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001156PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001157{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001158 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001159
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001160 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1161 handle_system_exit();
1162 }
1163 PyErr_Fetch(&exception, &v, &tb);
1164 if (exception == NULL)
1165 return;
1166 PyErr_NormalizeException(&exception, &v, &tb);
1167 if (exception == NULL)
1168 return;
1169 /* Now we know v != NULL too */
1170 if (set_sys_last_vars) {
1171 PySys_SetObject("last_type", exception);
1172 PySys_SetObject("last_value", v);
1173 PySys_SetObject("last_traceback", tb);
1174 }
1175 hook = PySys_GetObject("excepthook");
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001176 if (hook && hook != Py_None) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001177 PyObject *args = PyTuple_Pack(3,
1178 exception, v, tb ? tb : Py_None);
1179 PyObject *result = PyEval_CallObject(hook, args);
1180 if (result == NULL) {
1181 PyObject *exception2, *v2, *tb2;
1182 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1183 handle_system_exit();
1184 }
1185 PyErr_Fetch(&exception2, &v2, &tb2);
1186 PyErr_NormalizeException(&exception2, &v2, &tb2);
1187 /* It should not be possible for exception2 or v2
1188 to be NULL. However PyErr_Display() can't
1189 tolerate NULLs, so just be safe. */
1190 if (exception2 == NULL) {
1191 exception2 = Py_None;
1192 Py_INCREF(exception2);
1193 }
1194 if (v2 == NULL) {
1195 v2 = Py_None;
1196 Py_INCREF(v2);
1197 }
1198 if (Py_FlushLine())
1199 PyErr_Clear();
1200 fflush(stdout);
1201 PySys_WriteStderr("Error in sys.excepthook:\n");
1202 PyErr_Display(exception2, v2, tb2);
1203 PySys_WriteStderr("\nOriginal exception was:\n");
1204 PyErr_Display(exception, v, tb);
1205 Py_DECREF(exception2);
1206 Py_DECREF(v2);
1207 Py_XDECREF(tb2);
1208 }
1209 Py_XDECREF(result);
1210 Py_XDECREF(args);
1211 } else {
1212 PySys_WriteStderr("sys.excepthook is missing\n");
1213 PyErr_Display(exception, v, tb);
1214 }
1215 Py_XDECREF(exception);
1216 Py_XDECREF(v);
1217 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001218}
1219
Richard Jones7b9558d2006-05-27 12:29:24 +00001220void
1221PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001222{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001223 int err = 0;
1224 PyObject *f = PySys_GetObject("stderr");
1225 Py_INCREF(value);
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001226 if (f == NULL || f == Py_None)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001227 fprintf(stderr, "lost sys.stderr\n");
1228 else {
1229 if (Py_FlushLine())
1230 PyErr_Clear();
1231 fflush(stdout);
1232 if (tb && tb != Py_None)
1233 err = PyTraceBack_Print(tb, f);
1234 if (err == 0 &&
1235 PyObject_HasAttrString(value, "print_file_and_line"))
1236 {
1237 PyObject *message;
1238 const char *filename, *text;
1239 int lineno, offset;
1240 if (!parse_syntax_error(value, &message, &filename,
1241 &lineno, &offset, &text))
1242 PyErr_Clear();
1243 else {
1244 char buf[10];
1245 PyFile_WriteString(" File \"", f);
1246 if (filename == NULL)
1247 PyFile_WriteString("<string>", f);
1248 else
1249 PyFile_WriteString(filename, f);
1250 PyFile_WriteString("\", line ", f);
1251 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1252 PyFile_WriteString(buf, f);
1253 PyFile_WriteString("\n", f);
1254 if (text != NULL)
1255 print_error_text(f, offset, text);
1256 Py_DECREF(value);
1257 value = message;
1258 /* Can't be bothered to check all those
1259 PyFile_WriteString() calls */
1260 if (PyErr_Occurred())
1261 err = -1;
1262 }
1263 }
1264 if (err) {
1265 /* Don't do anything else */
1266 }
1267 else if (PyExceptionClass_Check(exception)) {
1268 PyObject* moduleName;
1269 char* className = PyExceptionClass_Name(exception);
1270 if (className != NULL) {
1271 char *dot = strrchr(className, '.');
1272 if (dot != NULL)
1273 className = dot+1;
1274 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001275
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001276 moduleName = PyObject_GetAttrString(exception, "__module__");
1277 if (moduleName == NULL)
1278 err = PyFile_WriteString("<unknown>", f);
1279 else {
1280 char* modstr = PyString_AsString(moduleName);
1281 if (modstr && strcmp(modstr, "exceptions"))
1282 {
1283 err = PyFile_WriteString(modstr, f);
1284 err += PyFile_WriteString(".", f);
1285 }
1286 Py_DECREF(moduleName);
1287 }
1288 if (err == 0) {
1289 if (className == NULL)
1290 err = PyFile_WriteString("<unknown>", f);
1291 else
1292 err = PyFile_WriteString(className, f);
1293 }
1294 }
1295 else
1296 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1297 if (err == 0 && (value != Py_None)) {
1298 PyObject *s = PyObject_Str(value);
1299 /* only print colon if the str() of the
1300 object is not the empty string
1301 */
Martin Panteref85a1a2016-02-28 00:18:43 +00001302 if (s == NULL) {
1303 PyErr_Clear();
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001304 err = -1;
Martin Panteref85a1a2016-02-28 00:18:43 +00001305 PyFile_WriteString(": <exception str() failed>", f);
1306 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001307 else if (!PyString_Check(s) ||
1308 PyString_GET_SIZE(s) != 0)
1309 err = PyFile_WriteString(": ", f);
1310 if (err == 0)
1311 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1312 Py_XDECREF(s);
1313 }
1314 /* try to write a newline in any case */
Martin Panteref85a1a2016-02-28 00:18:43 +00001315 if (err < 0) {
1316 PyErr_Clear();
1317 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001318 err += PyFile_WriteString("\n", f);
1319 }
1320 Py_DECREF(value);
1321 /* If an error happened here, don't show it.
1322 XXX This is wrong, but too many callers rely on this behavior. */
1323 if (err != 0)
1324 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001325}
1326
Guido van Rossum82598051997-03-05 00:20:32 +00001327PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001328PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001329 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001330{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001331 PyObject *ret = NULL;
1332 mod_ty mod;
1333 PyArena *arena = PyArena_New();
1334 if (arena == NULL)
1335 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001336
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001337 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1338 if (mod != NULL)
1339 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1340 PyArena_Free(arena);
1341 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001342}
1343
1344PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001345PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001346 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001347{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001348 PyObject *ret;
1349 mod_ty mod;
1350 PyArena *arena = PyArena_New();
1351 if (arena == NULL)
1352 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001353
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001354 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1355 flags, NULL, arena);
1356 if (closeit)
1357 fclose(fp);
1358 if (mod == NULL) {
1359 PyArena_Free(arena);
1360 return NULL;
1361 }
1362 ret = run_mod(mod, filename, globals, locals, flags, arena);
1363 PyArena_Free(arena);
1364 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001365}
1366
Guido van Rossum82598051997-03-05 00:20:32 +00001367static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001369 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001370{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001371 PyCodeObject *co;
1372 PyObject *v;
1373 co = PyAST_Compile(mod, filename, flags, arena);
1374 if (co == NULL)
1375 return NULL;
1376 v = PyEval_EvalCode(co, globals, locals);
1377 Py_DECREF(co);
1378 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001379}
1380
Guido van Rossum82598051997-03-05 00:20:32 +00001381static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001382run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001383 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001384{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001385 PyCodeObject *co;
1386 PyObject *v;
1387 long magic;
1388 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001389
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001390 magic = PyMarshal_ReadLongFromFile(fp);
1391 if (magic != PyImport_GetMagicNumber()) {
1392 PyErr_SetString(PyExc_RuntimeError,
1393 "Bad magic number in .pyc file");
1394 return NULL;
1395 }
1396 (void) PyMarshal_ReadLongFromFile(fp);
1397 v = PyMarshal_ReadLastObjectFromFile(fp);
1398 fclose(fp);
1399 if (v == NULL || !PyCode_Check(v)) {
1400 Py_XDECREF(v);
1401 PyErr_SetString(PyExc_RuntimeError,
1402 "Bad code object in .pyc file");
1403 return NULL;
1404 }
1405 co = (PyCodeObject *)v;
1406 v = PyEval_EvalCode(co, globals, locals);
1407 if (v && flags)
1408 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1409 Py_DECREF(co);
1410 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001411}
1412
Guido van Rossum82598051997-03-05 00:20:32 +00001413PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001414Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001415 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001416{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001417 PyCodeObject *co;
1418 mod_ty mod;
1419 PyArena *arena = PyArena_New();
1420 if (arena == NULL)
1421 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001422
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001423 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1424 if (mod == NULL) {
1425 PyArena_Free(arena);
1426 return NULL;
1427 }
1428 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1429 PyObject *result = PyAST_mod2obj(mod);
1430 PyArena_Free(arena);
1431 return result;
1432 }
1433 co = PyAST_Compile(mod, filename, flags, arena);
1434 PyArena_Free(arena);
1435 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001436}
1437
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001438struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001439Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001440{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001441 struct symtable *st;
1442 mod_ty mod;
1443 PyCompilerFlags flags;
1444 PyArena *arena = PyArena_New();
1445 if (arena == NULL)
1446 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001447
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001448 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001449
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001450 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1451 if (mod == NULL) {
1452 PyArena_Free(arena);
1453 return NULL;
1454 }
1455 st = PySymtable_Build(mod, filename, 0);
1456 PyArena_Free(arena);
1457 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001458}
1459
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460/* Preferred access to parser is through AST. */
1461mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001462PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001463 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001465 mod_ty mod;
1466 PyCompilerFlags localflags;
1467 perrdetail err;
1468 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001469
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001470 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1471 &_PyParser_Grammar, start, &err,
1472 &iflags);
1473 if (flags == NULL) {
1474 localflags.cf_flags = 0;
1475 flags = &localflags;
1476 }
1477 if (n) {
1478 flags->cf_flags |= iflags & PyCF_MASK;
1479 mod = PyAST_FromNode(n, flags, filename, arena);
1480 PyNode_Free(n);
1481 return mod;
1482 }
1483 else {
1484 err_input(&err);
1485 return NULL;
1486 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487}
1488
1489mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001490PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001491 char *ps2, PyCompilerFlags *flags, int *errcode,
1492 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001494 mod_ty mod;
1495 PyCompilerFlags localflags;
1496 perrdetail err;
1497 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001498
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001499 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1500 start, ps1, ps2, &err, &iflags);
1501 if (flags == NULL) {
1502 localflags.cf_flags = 0;
1503 flags = &localflags;
1504 }
1505 if (n) {
1506 flags->cf_flags |= iflags & PyCF_MASK;
1507 mod = PyAST_FromNode(n, flags, filename, arena);
1508 PyNode_Free(n);
1509 return mod;
1510 }
1511 else {
1512 err_input(&err);
1513 if (errcode)
1514 *errcode = err.error;
1515 return NULL;
1516 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517}
1518
Guido van Rossuma110aa61994-08-29 12:50:44 +00001519/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001520
Guido van Rossuma110aa61994-08-29 12:50:44 +00001521node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001522PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001523{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001524 perrdetail err;
1525 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1526 start, NULL, NULL, &err, flags);
1527 if (n == NULL)
1528 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001529
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001530 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001531}
1532
Guido van Rossuma110aa61994-08-29 12:50:44 +00001533/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001534
Guido van Rossuma110aa61994-08-29 12:50:44 +00001535node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001536PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001537{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001538 perrdetail err;
1539 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1540 start, &err, flags);
1541 if (n == NULL)
1542 err_input(&err);
1543 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001544}
1545
1546node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001547PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001548 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001549{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001550 perrdetail err;
1551 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1552 &_PyParser_Grammar, start, &err, flags);
1553 if (n == NULL)
1554 err_input(&err);
1555 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001556}
1557
1558node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001559PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001560{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001561 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001562}
1563
Guido van Rossum66ebd912003-04-17 16:02:26 +00001564/* May want to move a more generalized form of this to parsetok.c or
1565 even parser modules. */
1566
1567void
1568PyParser_SetError(perrdetail *err)
1569{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001570 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001571}
1572
Guido van Rossuma110aa61994-08-29 12:50:44 +00001573/* Set the error appropriate to the given input error code (see errcode.h) */
1574
1575static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001576err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001577{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001578 PyObject *v, *w, *errtype;
1579 PyObject* u = NULL;
1580 char *msg = NULL;
1581 errtype = PyExc_SyntaxError;
1582 switch (err->error) {
1583 case E_ERROR:
1584 return;
1585 case E_SYNTAX:
1586 errtype = PyExc_IndentationError;
1587 if (err->expected == INDENT)
1588 msg = "expected an indented block";
1589 else if (err->token == INDENT)
1590 msg = "unexpected indent";
1591 else if (err->token == DEDENT)
1592 msg = "unexpected unindent";
1593 else {
1594 errtype = PyExc_SyntaxError;
1595 msg = "invalid syntax";
1596 }
1597 break;
1598 case E_TOKEN:
1599 msg = "invalid token";
1600 break;
1601 case E_EOFS:
1602 msg = "EOF while scanning triple-quoted string literal";
1603 break;
1604 case E_EOLS:
1605 msg = "EOL while scanning string literal";
1606 break;
1607 case E_INTR:
1608 if (!PyErr_Occurred())
1609 PyErr_SetNone(PyExc_KeyboardInterrupt);
1610 goto cleanup;
1611 case E_NOMEM:
1612 PyErr_NoMemory();
1613 goto cleanup;
1614 case E_EOF:
1615 msg = "unexpected EOF while parsing";
1616 break;
1617 case E_TABSPACE:
1618 errtype = PyExc_TabError;
1619 msg = "inconsistent use of tabs and spaces in indentation";
1620 break;
1621 case E_OVERFLOW:
1622 msg = "expression too long";
1623 break;
1624 case E_DEDENT:
1625 errtype = PyExc_IndentationError;
1626 msg = "unindent does not match any outer indentation level";
1627 break;
1628 case E_TOODEEP:
1629 errtype = PyExc_IndentationError;
1630 msg = "too many levels of indentation";
1631 break;
1632 case E_DECODE: {
1633 PyObject *type, *value, *tb;
1634 PyErr_Fetch(&type, &value, &tb);
1635 if (value != NULL) {
1636 u = PyObject_Str(value);
1637 if (u != NULL) {
1638 msg = PyString_AsString(u);
1639 }
1640 }
1641 if (msg == NULL)
1642 msg = "unknown decode error";
1643 Py_XDECREF(type);
1644 Py_XDECREF(value);
1645 Py_XDECREF(tb);
1646 break;
1647 }
1648 case E_LINECONT:
1649 msg = "unexpected character after line continuation character";
1650 break;
1651 default:
1652 fprintf(stderr, "error=%d\n", err->error);
1653 msg = "unknown parsing error";
1654 break;
1655 }
1656 v = Py_BuildValue("(ziiz)", err->filename,
1657 err->lineno, err->offset, err->text);
1658 w = NULL;
1659 if (v != NULL)
1660 w = Py_BuildValue("(sO)", msg, v);
1661 Py_XDECREF(u);
1662 Py_XDECREF(v);
1663 PyErr_SetObject(errtype, w);
1664 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001665cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001666 if (err->text != NULL) {
1667 PyObject_FREE(err->text);
1668 err->text = NULL;
1669 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001670}
1671
1672/* Print fatal error message and abort */
1673
1674void
Tim Peters7c321a82002-07-09 02:57:01 +00001675Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001676{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001677 fprintf(stderr, "Fatal Python error: %s\n", msg);
1678 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller42f9b4e2009-03-31 22:20:35 +00001679
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001680#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001681 {
1682 size_t len = strlen(msg);
1683 WCHAR* buffer;
1684 size_t i;
Martin v. Löwis5344c992009-01-02 20:32:55 +00001685
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001686 /* Convert the message to wchar_t. This uses a simple one-to-one
1687 conversion, assuming that the this error message actually uses ASCII
1688 only. If this ceases to be true, we will have to convert. */
1689 buffer = alloca( (len+1) * (sizeof *buffer));
1690 for( i=0; i<=len; ++i)
1691 buffer[i] = msg[i];
1692 OutputDebugStringW(L"Fatal Python error: ");
1693 OutputDebugStringW(buffer);
1694 OutputDebugStringW(L"\n");
1695 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001696#ifdef _DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001697 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001698#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001699#endif /* MS_WINDOWS */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001700 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001701}
1702
1703/* Clean up and exit */
1704
Guido van Rossuma110aa61994-08-29 12:50:44 +00001705#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001706#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001707#endif
1708
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001709/* Wait until threading._shutdown completes, provided
1710 the threading module was imported in the first place.
1711 The shutdown routine will wait until all non-daemon
1712 "threading" threads have completed. */
1713static void
1714wait_for_thread_shutdown(void)
1715{
1716#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001717 PyObject *result;
1718 PyThreadState *tstate = PyThreadState_GET();
1719 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1720 "threading");
1721 if (threading == NULL) {
1722 /* threading not imported */
1723 PyErr_Clear();
1724 return;
1725 }
1726 result = PyObject_CallMethod(threading, "_shutdown", "");
1727 if (result == NULL)
1728 PyErr_WriteUnraisable(threading);
1729 else
1730 Py_DECREF(result);
1731 Py_DECREF(threading);
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001732#endif
1733}
1734
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001735#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001736static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001737static int nexitfuncs = 0;
1738
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001739int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001740{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001741 if (nexitfuncs >= NEXITFUNCS)
1742 return -1;
1743 exitfuncs[nexitfuncs++] = func;
1744 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001745}
1746
Guido van Rossumcc283f51997-08-05 02:22:03 +00001747static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001748call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001749{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001750 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001751
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001752 if (exitfunc) {
1753 PyObject *res;
1754 Py_INCREF(exitfunc);
1755 PySys_SetObject("exitfunc", (PyObject *)NULL);
1756 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1757 if (res == NULL) {
1758 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1759 PySys_WriteStderr("Error in sys.exitfunc:\n");
1760 }
1761 PyErr_Print();
1762 }
1763 Py_DECREF(exitfunc);
1764 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001765
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001766 if (Py_FlushLine())
1767 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001768}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001769
Guido van Rossumcc283f51997-08-05 02:22:03 +00001770static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001771call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001772{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001773 while (nexitfuncs > 0)
1774 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001775
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001776 fflush(stdout);
1777 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001778}
1779
1780void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001781Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001782{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001783 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001784
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001785 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001786}
1787
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001788static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001789initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001790{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001791#ifdef SIGPIPE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001792 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001793#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001794#ifdef SIGXFZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001795 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001796#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001797#ifdef SIGXFSZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001798 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001799#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001800 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001801}
1802
Guido van Rossum7433b121997-02-14 19:45:36 +00001803
1804/*
1805 * The file descriptor fd is considered ``interactive'' if either
1806 * a) isatty(fd) is TRUE, or
1807 * b) the -i flag was given, and the filename associated with
1808 * the descriptor is NULL or "<stdin>" or "???".
1809 */
1810int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001811Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001812{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001813 if (isatty((int)fileno(fp)))
1814 return 1;
1815 if (!Py_InteractiveFlag)
1816 return 0;
1817 return (filename == NULL) ||
1818 (strcmp(filename, "<stdin>") == 0) ||
1819 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001820}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001821
1822
Tim Petersd08e3822003-04-17 15:24:21 +00001823#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001824#if defined(WIN32) && defined(_MSC_VER)
1825
1826/* Stack checking for Microsoft C */
1827
1828#include <malloc.h>
1829#include <excpt.h>
1830
Fred Drakee8de31c2000-08-31 05:38:39 +00001831/*
1832 * Return non-zero when we run out of memory on the stack; zero otherwise.
1833 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001834int
Fred Drake399739f2000-08-31 05:52:44 +00001835PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001836{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001837 __try {
1838 /* alloca throws a stack overflow exception if there's
1839 not enough space left on the stack */
1840 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1841 return 0;
1842 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1843 EXCEPTION_EXECUTE_HANDLER :
1844 EXCEPTION_CONTINUE_SEARCH) {
1845 int errcode = _resetstkoflw();
1846 if (errcode == 0)
1847 {
1848 Py_FatalError("Could not reset the stack!");
1849 }
1850 }
1851 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001852}
1853
1854#endif /* WIN32 && _MSC_VER */
1855
1856/* Alternate implementations can be added here... */
1857
1858#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001859
1860
1861/* Wrappers around sigaction() or signal(). */
1862
1863PyOS_sighandler_t
1864PyOS_getsig(int sig)
1865{
1866#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001867 struct sigaction context;
1868 if (sigaction(sig, NULL, &context) == -1)
1869 return SIG_ERR;
1870 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001871#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001872 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001873/* Special signal handling for the secure CRT in Visual Studio 2005 */
1874#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001875 switch (sig) {
1876 /* Only these signals are valid */
1877 case SIGINT:
1878 case SIGILL:
1879 case SIGFPE:
1880 case SIGSEGV:
1881 case SIGTERM:
1882 case SIGBREAK:
1883 case SIGABRT:
1884 break;
1885 /* Don't call signal() with other values or it will assert */
1886 default:
1887 return SIG_ERR;
1888 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001889#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001890 handler = signal(sig, SIG_IGN);
1891 if (handler != SIG_ERR)
1892 signal(sig, handler);
1893 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001894#endif
1895}
1896
1897PyOS_sighandler_t
1898PyOS_setsig(int sig, PyOS_sighandler_t handler)
1899{
1900#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001901 /* Some code in Modules/signalmodule.c depends on sigaction() being
1902 * used here if HAVE_SIGACTION is defined. Fix that if this code
1903 * changes to invalidate that assumption.
1904 */
1905 struct sigaction context, ocontext;
1906 context.sa_handler = handler;
1907 sigemptyset(&context.sa_mask);
1908 context.sa_flags = 0;
1909 if (sigaction(sig, &context, &ocontext) == -1)
1910 return SIG_ERR;
1911 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001912#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001913 PyOS_sighandler_t oldhandler;
1914 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001915#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001916 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001917#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001918 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001919#endif
1920}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921
Martin Panterb1d867f2016-05-26 05:28:50 +00001922/* Deprecated C API functions still provided for binary compatibility */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923
1924#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001925PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1927{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001928 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929}
1930
Thomas Heller1b046642006-04-18 18:51:06 +00001931#undef PyParser_SimpleParseString
1932PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933PyParser_SimpleParseString(const char *str, int start)
1934{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001935 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001936}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001937
Thomas Heller1b046642006-04-18 18:51:06 +00001938#undef PyRun_AnyFile
1939PyAPI_FUNC(int)
1940PyRun_AnyFile(FILE *fp, const char *name)
1941{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001942 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001943}
1944
1945#undef PyRun_AnyFileEx
1946PyAPI_FUNC(int)
1947PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1948{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001949 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001950}
1951
1952#undef PyRun_AnyFileFlags
1953PyAPI_FUNC(int)
1954PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1955{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001956 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001957}
1958
1959#undef PyRun_File
1960PyAPI_FUNC(PyObject *)
1961PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1962{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001963 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001964}
1965
1966#undef PyRun_FileEx
1967PyAPI_FUNC(PyObject *)
1968PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1969{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001970 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001971}
1972
1973#undef PyRun_FileFlags
1974PyAPI_FUNC(PyObject *)
1975PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001976 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001977{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001978 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001979}
1980
1981#undef PyRun_SimpleFile
1982PyAPI_FUNC(int)
1983PyRun_SimpleFile(FILE *f, const char *p)
1984{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001985 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001986}
1987
1988#undef PyRun_SimpleFileEx
1989PyAPI_FUNC(int)
1990PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1991{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001992 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001993}
1994
1995
1996#undef PyRun_String
1997PyAPI_FUNC(PyObject *)
1998PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1999{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002000 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002001}
2002
2003#undef PyRun_SimpleString
2004PyAPI_FUNC(int)
2005PyRun_SimpleString(const char *s)
2006{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002007 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002008}
2009
2010#undef Py_CompileString
2011PyAPI_FUNC(PyObject *)
2012Py_CompileString(const char *str, const char *p, int s)
2013{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002014 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002015}
2016
2017#undef PyRun_InteractiveOne
2018PyAPI_FUNC(int)
2019PyRun_InteractiveOne(FILE *f, const char *p)
2020{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002021 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002022}
2023
2024#undef PyRun_InteractiveLoop
2025PyAPI_FUNC(int)
2026PyRun_InteractiveLoop(FILE *f, const char *p)
2027{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002028 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002029}
2030
Anthony Baxterac6bd462006-04-13 02:06:09 +00002031#ifdef __cplusplus
2032}
2033#endif
2034