blob: bfb7fca9de8557d49d22fca8e93bb2a3c71dfd00 [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 */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000092
Brett Cannone9746892008-04-12 23:44:07 +000093/* PyModule_GetWarningsModule is no longer necessary as of 2.6
94since _warnings is builtin. This API should not be used. */
95PyObject *
96PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000097{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000098 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000099}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000100
Guido van Rossum25ce5661997-08-02 03:10:38 +0000101static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000102
Thomas Wouters7e474022000-07-16 12:04:32 +0000103/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000104
105int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000106Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000107{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000108 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109}
110
Guido van Rossum25ce5661997-08-02 03:10:38 +0000111/* Global initializations. Can be undone by Py_Finalize(). Don't
112 call this twice without an intervening Py_Finalize() call. When
113 initializations fail, a fatal error is issued and the function does
114 not return. On return, the first thread and interpreter state have
115 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117 Locking: you must hold the interpreter lock while calling this.
118 (If the lock has not yet been initialized, that's equivalent to
119 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000122
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000123static int
124add_flag(int flag, const char *envs)
125{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000126 int env = atoi(envs);
127 if (flag < env)
128 flag = env;
129 if (flag < 1)
130 flag = 1;
131 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000132}
133
Guido van Rossuma027efa1997-05-05 20:56:21 +0000134void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000135Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000137 PyInterpreterState *interp;
138 PyThreadState *tstate;
139 PyObject *bimod, *sysmod;
140 char *p;
141 char *icodeset = NULL; /* On Windows, input codeset may theoretically
142 differ from output codeset. */
143 char *codeset = NULL;
144 char *errors = NULL;
145 int free_codeset = 0;
146 int overridden = 0;
147 PyObject *sys_stream, *sys_isatty;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000148#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000149 char *saved_locale, *loc_codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000150#endif
Martin v. Löwis99815892008-06-01 07:20:46 +0000151#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000152 char ibuf[128];
153 char buf[128];
Martin v. Löwis99815892008-06-01 07:20:46 +0000154#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000155 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000156
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000157 if (initialized)
158 return;
159 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000160
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000161 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
162 Py_DebugFlag = add_flag(Py_DebugFlag, p);
163 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
164 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
165 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
166 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
167 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
168 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000169
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000170 interp = PyInterpreterState_New();
171 if (interp == NULL)
172 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000173
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000174 tstate = PyThreadState_New(interp);
175 if (tstate == NULL)
176 Py_FatalError("Py_Initialize: can't make first thread");
177 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000178
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000179 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000180
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000181 if (!_PyFrame_Init())
182 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000183
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000184 if (!_PyInt_Init())
185 Py_FatalError("Py_Initialize: can't init ints");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000186
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000187 if (!_PyLong_Init())
188 Py_FatalError("Py_Initialize: can't init longs");
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000189
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000190 if (!PyByteArray_Init())
191 Py_FatalError("Py_Initialize: can't init bytearray");
Christian Heimes1a6387e2008-03-26 12:49:49 +0000192
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000193 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000194
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000195 interp->modules = PyDict_New();
196 if (interp->modules == NULL)
197 Py_FatalError("Py_Initialize: can't make modules dictionary");
198 interp->modules_reloading = PyDict_New();
199 if (interp->modules_reloading == NULL)
200 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000201
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000202#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000203 /* Init Unicode implementation; relies on the codec registry */
204 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000205#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000206
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000207 bimod = _PyBuiltin_Init();
208 if (bimod == NULL)
209 Py_FatalError("Py_Initialize: can't initialize __builtin__");
210 interp->builtins = PyModule_GetDict(bimod);
211 if (interp->builtins == NULL)
212 Py_FatalError("Py_Initialize: can't initialize builtins dict");
213 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000214
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000215 sysmod = _PySys_Init();
216 if (sysmod == NULL)
217 Py_FatalError("Py_Initialize: can't initialize sys");
218 interp->sysdict = PyModule_GetDict(sysmod);
219 if (interp->sysdict == NULL)
220 Py_FatalError("Py_Initialize: can't initialize sys dict");
221 Py_INCREF(interp->sysdict);
222 _PyImport_FixupExtension("sys", "sys");
223 PySys_SetPath(Py_GetPath());
224 PyDict_SetItemString(interp->sysdict, "modules",
225 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000226
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000228
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000229 /* initialize builtin exceptions */
230 _PyExc_Init();
231 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000232
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000233 /* phase 2 of builtins */
234 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000235
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000236 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000237
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000238 if (install_sigs)
239 initsigs(); /* Signal handling stuff, including initintr() */
Brett Cannonc33e82d2010-05-05 20:38:52 +0000240
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000241 /* Initialize warnings. */
242 _PyWarnings_Init();
243 if (PySys_HasWarnOptions()) {
244 PyObject *warnings_module = PyImport_ImportModule("warnings");
245 if (!warnings_module)
246 PyErr_Clear();
247 Py_XDECREF(warnings_module);
248 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000249
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000250 initmain(); /* Module __main__ */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000251
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000252 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000253#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000254 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000255#endif /* WITH_THREAD */
256
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 if (!Py_NoSiteFlag)
258 initsite(); /* Module site */
Victor Stinner66644262010-03-10 22:30:19 +0000259
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000260 if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
261 p = icodeset = codeset = strdup(p);
262 free_codeset = 1;
263 errors = strchr(p, ':');
264 if (errors) {
265 *errors = '\0';
266 errors++;
267 }
268 overridden = 1;
269 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000270
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000271#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000272 /* On Unix, set the file system encoding according to the
273 user's preference, if the CODESET names a well-known
274 Python codec, and Py_FileSystemDefaultEncoding isn't
275 initialized by other means. Also set the encoding of
276 stdin and stdout if these are terminals, unless overridden. */
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000277
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000278 if (!overridden || !Py_FileSystemDefaultEncoding) {
279 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
280 setlocale(LC_CTYPE, "");
281 loc_codeset = nl_langinfo(CODESET);
282 if (loc_codeset && *loc_codeset) {
283 PyObject *enc = PyCodec_Encoder(loc_codeset);
284 if (enc) {
285 loc_codeset = strdup(loc_codeset);
286 Py_DECREF(enc);
287 } else {
288 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
289 PyErr_Clear();
290 loc_codeset = NULL;
291 } else {
292 PyErr_Print();
293 exit(1);
294 }
295 }
296 } else
297 loc_codeset = NULL;
298 setlocale(LC_CTYPE, saved_locale);
299 free(saved_locale);
Martin v. Löwis99815892008-06-01 07:20:46 +0000300
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000301 if (!overridden) {
302 codeset = icodeset = loc_codeset;
303 free_codeset = 1;
304 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000305
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000306 /* Initialize Py_FileSystemDefaultEncoding from
307 locale even if PYTHONIOENCODING is set. */
308 if (!Py_FileSystemDefaultEncoding) {
309 Py_FileSystemDefaultEncoding = loc_codeset;
310 if (!overridden)
311 free_codeset = 0;
312 }
313 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000314#endif
315
316#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000317 if (!overridden) {
318 icodeset = ibuf;
319 codeset = buf;
320 sprintf(ibuf, "cp%d", GetConsoleCP());
321 sprintf(buf, "cp%d", GetConsoleOutputCP());
322 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000323#endif
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000324
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000325 if (codeset) {
326 sys_stream = PySys_GetObject("stdin");
327 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
328 if (!sys_isatty)
329 PyErr_Clear();
330 if ((overridden ||
331 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
332 PyFile_Check(sys_stream)) {
333 if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
334 Py_FatalError("Cannot set codeset of stdin");
335 }
336 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000337
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000338 sys_stream = PySys_GetObject("stdout");
339 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
340 if (!sys_isatty)
341 PyErr_Clear();
342 if ((overridden ||
343 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
344 PyFile_Check(sys_stream)) {
345 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
346 Py_FatalError("Cannot set codeset of stdout");
347 }
348 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000349
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000350 sys_stream = PySys_GetObject("stderr");
351 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
352 if (!sys_isatty)
353 PyErr_Clear();
354 if((overridden ||
355 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
356 PyFile_Check(sys_stream)) {
357 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
358 Py_FatalError("Cannot set codeset of stderr");
359 }
360 Py_XDECREF(sys_isatty);
Martin v. Löwisea62d252006-04-03 10:56:49 +0000361
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000362 if (free_codeset)
363 free(codeset);
364 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365}
366
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000367void
368Py_Initialize(void)
369{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000370 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000371}
372
373
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000374#ifdef COUNT_ALLOCS
Martin v. Löwis45294a92006-04-18 06:24:08 +0000375extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000376#endif
377
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378/* Undo the effect of Py_Initialize().
379
380 Beware: if multiple interpreter and/or thread states exist, these
381 are not wiped out; only the current thread and interpreter state
382 are deleted. But since everything else is deleted, those other
383 interpreter and thread states should no longer be used.
384
385 (XXX We should do better, e.g. wipe out all interpreters and
386 threads.)
387
388 Locking: as above.
389
390*/
391
392void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000393Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000394{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000395 PyInterpreterState *interp;
396 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000397
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000398 if (!initialized)
399 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000400
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000401 wait_for_thread_shutdown();
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000402
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000403 /* The interpreter is still entirely intact at this point, and the
404 * exit funcs may be relying on that. In particular, if some thread
405 * or exit func is still waiting to do an import, the import machinery
406 * expects Py_IsInitialized() to return true. So don't say the
407 * interpreter is uninitialized until after the exit funcs have run.
408 * Note that Threading.py uses an exit func to do a join on all the
409 * threads created thru it, so this also protects pending imports in
410 * the threads created via Threading.
411 */
412 call_sys_exitfunc();
413 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000414
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000415 /* Get current thread state and interpreter pointer */
416 tstate = PyThreadState_GET();
417 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000418
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000419 /* Disable signal handling */
420 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000421
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000422 /* Clear type lookup cache */
423 PyType_ClearCache();
Christian Heimes908caac2008-01-27 23:34:59 +0000424
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000425 /* Collect garbage. This may call finalizers; it's nice to call these
426 * before all modules are destroyed.
427 * XXX If a __del__ or weakref callback is triggered here, and tries to
428 * XXX import a module, bad things can happen, because Python no
429 * XXX longer believes it's initialized.
430 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
431 * XXX is easy to provoke that way. I've also seen, e.g.,
432 * XXX Exception exceptions.ImportError: 'No module named sha'
433 * XXX in <function callback at 0x008F5718> ignored
434 * XXX but I'm unclear on exactly how that one happens. In any case,
435 * XXX I haven't seen a real-life report of either of these.
436 */
437 PyGC_Collect();
Martin v. Löwis45294a92006-04-18 06:24:08 +0000438#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000439 /* With COUNT_ALLOCS, it helps to run GC multiple times:
440 each collection might release some types from the type
441 list, so they become garbage. */
442 while (PyGC_Collect() > 0)
443 /* nothing */;
Martin v. Löwis45294a92006-04-18 06:24:08 +0000444#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000445
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000446 /* Destroy all modules */
447 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000448
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000449 /* Collect final garbage. This disposes of cycles created by
450 * new-style class definitions, for example.
451 * XXX This is disabled because it caused too many problems. If
452 * XXX a __del__ or weakref callback triggers here, Python code has
453 * XXX a hard time running, because even the sys module has been
454 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
455 * XXX One symptom is a sequence of information-free messages
456 * XXX coming from threads (if a __del__ or callback is invoked,
457 * XXX other threads can execute too, and any exception they encounter
458 * XXX triggers a comedy of errors as subsystem after subsystem
459 * XXX fails to find what it *expects* to find in sys to help report
460 * XXX the exception and consequent unexpected failures). I've also
461 * XXX seen segfaults then, after adding print statements to the
462 * XXX Python code getting called.
463 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000464#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000465 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000466#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000467
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000468 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
469 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000470
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000471 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000472#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000473 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000474#endif
475
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000476 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000477
Tim Peters9cf25ce2003-04-17 15:21:01 +0000478#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000479 /* Display all objects still alive -- this can invoke arbitrary
480 * __repr__ overrides, so requires a mostly-intact interpreter.
481 * Alas, a lot of stuff may still be alive now that will be cleaned
482 * up later.
483 */
484 if (Py_GETENV("PYTHONDUMPREFS"))
485 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000486#endif /* Py_TRACE_REFS */
487
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 /* Clear interpreter state */
489 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000490
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000491 /* Now we decref the exception classes. After this point nothing
492 can raise an exception. That's okay, because each Fini() method
493 below has been checked to make sure no exceptions are ever
494 raised.
495 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000496
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000497 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000498
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000499 /* Cleanup auto-thread-state */
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000500#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000501 _PyGILState_Fini();
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000502#endif /* WITH_THREAD */
503
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000504 /* Delete current thread */
505 PyThreadState_Swap(NULL);
506 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000507
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 /* Sundry finalizers */
509 PyMethod_Fini();
510 PyFrame_Fini();
511 PyCFunction_Fini();
512 PyTuple_Fini();
513 PyList_Fini();
514 PySet_Fini();
515 PyString_Fini();
516 PyByteArray_Fini();
517 PyInt_Fini();
518 PyFloat_Fini();
519 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000520
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000521#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000522 /* Cleanup Unicode implementation */
523 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000524#endif
525
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000526 /* XXX Still allocated:
527 - various static ad-hoc pointers to interned strings
528 - int and float free list blocks
529 - whatever various modules and libraries allocate
530 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000531
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000532 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000533
Tim Peters269b2a62003-04-17 19:52:29 +0000534#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000535 /* Display addresses (& refcnts) of all objects still alive.
536 * An address can be used to find the repr of the object, printed
537 * above by _Py_PrintReferences.
538 */
539 if (Py_GETENV("PYTHONDUMPREFS"))
540 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000541#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000542#ifdef PYMALLOC_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000543 if (Py_GETENV("PYTHONMALLOCSTATS"))
544 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000545#endif
546
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000547 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000548}
549
550/* Create and initialize a new interpreter and thread, and return the
551 new thread. This requires that Py_Initialize() has been called
552 first.
553
554 Unsuccessful initialization yields a NULL pointer. Note that *no*
555 exception information is available even in this case -- the
556 exception information is held in the thread, and there is no
557 thread.
558
559 Locking: as above.
560
561*/
562
563PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000564Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000566 PyInterpreterState *interp;
567 PyThreadState *tstate, *save_tstate;
568 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000570 if (!initialized)
571 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000573 interp = PyInterpreterState_New();
574 if (interp == NULL)
575 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000577 tstate = PyThreadState_New(interp);
578 if (tstate == NULL) {
579 PyInterpreterState_Delete(interp);
580 return NULL;
581 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000582
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000583 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000585 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000587 interp->modules = PyDict_New();
588 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000590 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
591 if (bimod != NULL) {
592 interp->builtins = PyModule_GetDict(bimod);
593 if (interp->builtins == NULL)
594 goto handle_error;
595 Py_INCREF(interp->builtins);
596 }
597 sysmod = _PyImport_FindExtension("sys", "sys");
598 if (bimod != NULL && sysmod != NULL) {
599 interp->sysdict = PyModule_GetDict(sysmod);
600 if (interp->sysdict == NULL)
601 goto handle_error;
602 Py_INCREF(interp->sysdict);
603 PySys_SetPath(Py_GetPath());
604 PyDict_SetItemString(interp->sysdict, "modules",
605 interp->modules);
606 _PyImportHooks_Init();
607 initmain();
608 if (!Py_NoSiteFlag)
609 initsite();
610 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000611
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000612 if (!PyErr_Occurred())
613 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000615handle_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000616 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000618 PyErr_Print();
619 PyThreadState_Clear(tstate);
620 PyThreadState_Swap(save_tstate);
621 PyThreadState_Delete(tstate);
622 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000624 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000625}
626
627/* Delete an interpreter and its last thread. This requires that the
628 given thread state is current, that the thread has no remaining
629 frames, and that it is its interpreter's only remaining thread.
630 It is a fatal error to violate these constraints.
631
632 (Py_Finalize() doesn't have these constraints -- it zaps
633 everything, regardless.)
634
635 Locking: as above.
636
637*/
638
639void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000640Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000641{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000642 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000643
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000644 if (tstate != PyThreadState_GET())
645 Py_FatalError("Py_EndInterpreter: thread is not current");
646 if (tstate->frame != NULL)
647 Py_FatalError("Py_EndInterpreter: thread still has a frame");
648 if (tstate != interp->tstate_head || tstate->next != NULL)
649 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000650
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000651 PyImport_Cleanup();
652 PyInterpreterState_Clear(interp);
653 PyThreadState_Swap(NULL);
654 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000655}
656
657static char *progname = "python";
658
659void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000660Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000661{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000662 if (pn && *pn)
663 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000664}
665
666char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000667Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000668{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000669 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000670}
671
Guido van Rossuma61691e1998-02-06 22:27:24 +0000672static char *default_home = NULL;
673
674void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000675Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000676{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000677 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000678}
679
680char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000681Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000682{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000683 char *home = default_home;
684 if (home == NULL && !Py_IgnoreEnvironmentFlag)
685 home = Py_GETENV("PYTHONHOME");
686 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000687}
688
Guido van Rossum6135a871995-01-09 17:53:26 +0000689/* Create __main__ module */
690
691static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000692initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000693{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000694 PyObject *m, *d;
695 m = PyImport_AddModule("__main__");
696 if (m == NULL)
697 Py_FatalError("can't create __main__ module");
698 d = PyModule_GetDict(m);
699 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
700 PyObject *bimod = PyImport_ImportModule("__builtin__");
701 if (bimod == NULL ||
702 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
703 Py_FatalError("can't add __builtins__ to __main__");
704 Py_XDECREF(bimod);
705 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000706}
707
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000708/* Import the site module (not into __main__ though) */
709
710static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000712{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000713 PyObject *m;
714 m = PyImport_ImportModule("site");
715 if (m == NULL) {
716 PyErr_Print();
717 Py_Finalize();
718 exit(1);
719 }
720 else {
721 Py_DECREF(m);
722 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000723}
724
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000725/* Parse input from a file and execute it */
726
727int
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000728PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000729 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000730{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000731 if (filename == NULL)
732 filename = "???";
733 if (Py_FdIsInteractive(fp, filename)) {
734 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
735 if (closeit)
736 fclose(fp);
737 return err;
738 }
739 else
740 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000741}
742
743int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000744PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000745{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000746 PyObject *v;
747 int ret;
748 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000749
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000750 if (flags == NULL) {
751 flags = &local_flags;
752 local_flags.cf_flags = 0;
753 }
754 v = PySys_GetObject("ps1");
755 if (v == NULL) {
756 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
757 Py_XDECREF(v);
758 }
759 v = PySys_GetObject("ps2");
760 if (v == NULL) {
761 PySys_SetObject("ps2", v = PyString_FromString("... "));
762 Py_XDECREF(v);
763 }
764 for (;;) {
765 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
766 PRINT_TOTAL_REFS();
767 if (ret == E_EOF)
768 return 0;
769 /*
770 if (ret == E_NOMEM)
771 return -1;
772 */
773 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000774}
775
Eric Smith7c478942008-03-18 23:45:49 +0000776#if 0
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000777/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000778#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000779 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
780 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Eric Smith7c478942008-03-18 23:45:49 +0000781#endif
782#if 1
Neal Norwitzca460d92006-09-06 06:28:06 +0000783/* Keep an example of flags with future keyword support. */
784#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000785 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
786 PyPARSE_DONT_IMPLY_DEDENT : 0) \
787 | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
788 PyPARSE_PRINT_IS_FUNCTION : 0) \
789 | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
790 PyPARSE_UNICODE_LITERALS : 0) \
791 ) : 0)
Neal Norwitzca460d92006-09-06 06:28:06 +0000792#endif
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000793
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000794int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000795PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000796{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000797 PyObject *m, *d, *v, *w;
798 mod_ty mod;
799 PyArena *arena;
800 char *ps1 = "", *ps2 = "";
801 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000802
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000803 v = PySys_GetObject("ps1");
804 if (v != NULL) {
805 v = PyObject_Str(v);
806 if (v == NULL)
807 PyErr_Clear();
808 else if (PyString_Check(v))
809 ps1 = PyString_AsString(v);
810 }
811 w = PySys_GetObject("ps2");
812 if (w != NULL) {
813 w = PyObject_Str(w);
814 if (w == NULL)
815 PyErr_Clear();
816 else if (PyString_Check(w))
817 ps2 = PyString_AsString(w);
818 }
819 arena = PyArena_New();
820 if (arena == NULL) {
821 Py_XDECREF(v);
822 Py_XDECREF(w);
823 return -1;
824 }
825 mod = PyParser_ASTFromFile(fp, filename,
826 Py_single_input, ps1, ps2,
827 flags, &errcode, arena);
828 Py_XDECREF(v);
829 Py_XDECREF(w);
830 if (mod == NULL) {
831 PyArena_Free(arena);
832 if (errcode == E_EOF) {
833 PyErr_Clear();
834 return E_EOF;
835 }
836 PyErr_Print();
837 return -1;
838 }
839 m = PyImport_AddModule("__main__");
840 if (m == NULL) {
841 PyArena_Free(arena);
842 return -1;
843 }
844 d = PyModule_GetDict(m);
845 v = run_mod(mod, filename, d, d, flags, arena);
846 PyArena_Free(arena);
847 if (v == NULL) {
848 PyErr_Print();
849 return -1;
850 }
851 Py_DECREF(v);
852 if (Py_FlushLine())
853 PyErr_Clear();
854 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000855}
856
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000857/* Check whether a file maybe a pyc file: Look at the extension,
858 the file type, and, if we may close it, at the first few bytes. */
859
860static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000861maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000862{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000863 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
864 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000865
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000866 /* Only look into the file if we are allowed to close it, since
867 it then should also be seekable. */
868 if (closeit) {
869 /* Read only two bytes of the magic. If the file was opened in
870 text mode, the bytes 3 and 4 of the magic (\r\n) might not
871 be read as they are on disk. */
872 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
873 unsigned char buf[2];
874 /* Mess: In case of -x, the stream is NOT at its start now,
875 and ungetc() was used to push back the first newline,
876 which makes the current stream position formally undefined,
877 and a x-platform nightmare.
878 Unfortunately, we have no direct way to know whether -x
879 was specified. So we use a terrible hack: if the current
880 stream position is not 0, we assume -x was specified, and
881 give up. Bug 132850 on SourceForge spells out the
882 hopelessness of trying anything else (fseek and ftell
883 don't work predictably x-platform for text-mode files).
884 */
885 int ispyc = 0;
886 if (ftell(fp) == 0) {
887 if (fread(buf, 1, 2, fp) == 2 &&
888 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
889 ispyc = 1;
890 rewind(fp);
891 }
892 return ispyc;
893 }
894 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000895}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000896
Guido van Rossum0df002c2000-08-27 19:21:52 +0000897int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000898PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000899 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000900{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000901 PyObject *m, *d, *v;
902 const char *ext;
903 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000904
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000905 m = PyImport_AddModule("__main__");
906 if (m == NULL)
907 return -1;
908 d = PyModule_GetDict(m);
909 if (PyDict_GetItemString(d, "__file__") == NULL) {
910 PyObject *f = PyString_FromString(filename);
911 if (f == NULL)
912 return -1;
913 if (PyDict_SetItemString(d, "__file__", f) < 0) {
914 Py_DECREF(f);
915 return -1;
916 }
917 set_file_name = 1;
918 Py_DECREF(f);
919 }
920 len = strlen(filename);
921 ext = filename + len - (len > 4 ? 4 : 0);
922 if (maybe_pyc_file(fp, filename, ext, closeit)) {
923 /* Try to run a pyc file. First, re-open in binary */
924 if (closeit)
925 fclose(fp);
926 if ((fp = fopen(filename, "rb")) == NULL) {
927 fprintf(stderr, "python: Can't reopen .pyc file\n");
928 ret = -1;
929 goto done;
930 }
931 /* Turn on optimization if a .pyo file is given */
932 if (strcmp(ext, ".pyo") == 0)
933 Py_OptimizeFlag = 1;
934 v = run_pyc_file(fp, filename, d, d, flags);
935 } else {
936 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
937 closeit, flags);
938 }
939 if (v == NULL) {
940 PyErr_Print();
941 ret = -1;
942 goto done;
943 }
944 Py_DECREF(v);
945 if (Py_FlushLine())
946 PyErr_Clear();
947 ret = 0;
Georg Brandlaa2321b2007-03-07 00:40:28 +0000948 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000949 if (set_file_name && PyDict_DelItemString(d, "__file__"))
950 PyErr_Clear();
951 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000952}
953
954int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000955PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000956{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000957 PyObject *m, *d, *v;
958 m = PyImport_AddModule("__main__");
959 if (m == NULL)
960 return -1;
961 d = PyModule_GetDict(m);
962 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
963 if (v == NULL) {
964 PyErr_Print();
965 return -1;
966 }
967 Py_DECREF(v);
968 if (Py_FlushLine())
969 PyErr_Clear();
970 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000971}
972
Barry Warsaw035574d1997-08-29 22:07:17 +0000973static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000974parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000975 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000976{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000977 long hold;
978 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +0000979
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000980 /* old style errors */
981 if (PyTuple_Check(err))
982 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
983 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000984
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000985 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +0000986
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000987 if (! (v = PyObject_GetAttrString(err, "msg")))
988 goto finally;
989 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +0000990
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000991 if (!(v = PyObject_GetAttrString(err, "filename")))
992 goto finally;
993 if (v == Py_None)
994 *filename = NULL;
995 else if (! (*filename = PyString_AsString(v)))
996 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000997
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000998 Py_DECREF(v);
999 if (!(v = PyObject_GetAttrString(err, "lineno")))
1000 goto finally;
1001 hold = PyInt_AsLong(v);
1002 Py_DECREF(v);
1003 v = NULL;
1004 if (hold < 0 && PyErr_Occurred())
1005 goto finally;
1006 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001007
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001008 if (!(v = PyObject_GetAttrString(err, "offset")))
1009 goto finally;
1010 if (v == Py_None) {
1011 *offset = -1;
1012 Py_DECREF(v);
1013 v = NULL;
1014 } else {
1015 hold = PyInt_AsLong(v);
1016 Py_DECREF(v);
1017 v = NULL;
1018 if (hold < 0 && PyErr_Occurred())
1019 goto finally;
1020 *offset = (int)hold;
1021 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001022
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001023 if (!(v = PyObject_GetAttrString(err, "text")))
1024 goto finally;
1025 if (v == Py_None)
1026 *text = NULL;
1027 else if (! (*text = PyString_AsString(v)))
1028 goto finally;
1029 Py_DECREF(v);
1030 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001031
1032finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001033 Py_XDECREF(v);
1034 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001035}
1036
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001037void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001038PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001039{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001040 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001041}
1042
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001043static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001044print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001045{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001046 char *nl;
1047 if (offset >= 0) {
Benjamin Petersonec9f9f52010-10-29 03:45:34 +00001048 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1049 offset--;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001050 for (;;) {
1051 nl = strchr(text, '\n');
1052 if (nl == NULL || nl-text >= offset)
1053 break;
1054 offset -= (int)(nl+1-text);
1055 text = nl+1;
1056 }
1057 while (*text == ' ' || *text == '\t') {
1058 text++;
1059 offset--;
1060 }
1061 }
1062 PyFile_WriteString(" ", f);
1063 PyFile_WriteString(text, f);
1064 if (*text == '\0' || text[strlen(text)-1] != '\n')
1065 PyFile_WriteString("\n", f);
1066 if (offset == -1)
1067 return;
1068 PyFile_WriteString(" ", f);
1069 offset--;
1070 while (offset > 0) {
1071 PyFile_WriteString(" ", f);
1072 offset--;
1073 }
1074 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001075}
1076
Guido van Rossum66e8e862001-03-23 17:54:43 +00001077static void
1078handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001079{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001080 PyObject *exception, *value, *tb;
1081 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001082
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001083 if (Py_InspectFlag)
1084 /* Don't exit if -i flag was given. This flag is set to 0
1085 * when entering interactive mode for inspecting. */
1086 return;
Georg Brandl49aafc92007-03-07 00:34:46 +00001087
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001088 PyErr_Fetch(&exception, &value, &tb);
1089 if (Py_FlushLine())
1090 PyErr_Clear();
1091 fflush(stdout);
1092 if (value == NULL || value == Py_None)
1093 goto done;
1094 if (PyExceptionInstance_Check(value)) {
1095 /* The error code should be in the `code' attribute. */
1096 PyObject *code = PyObject_GetAttrString(value, "code");
1097 if (code) {
1098 Py_DECREF(value);
1099 value = code;
1100 if (value == Py_None)
1101 goto done;
1102 }
1103 /* If we failed to dig out the 'code' attribute,
1104 just let the else clause below print the error. */
1105 }
1106 if (PyInt_Check(value))
1107 exitcode = (int)PyInt_AsLong(value);
1108 else {
Victor Stinnerc49dfcc2010-05-25 22:30:32 +00001109 PyObject *sys_stderr = PySys_GetObject("stderr");
1110 if (sys_stderr != NULL && sys_stderr != Py_None) {
1111 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1112 } else {
1113 PyObject_Print(value, stderr, Py_PRINT_RAW);
1114 fflush(stderr);
1115 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001116 PySys_WriteStderr("\n");
1117 exitcode = 1;
1118 }
Tim Peterscf615b52003-04-19 18:47:02 +00001119 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001120 /* Restore and clear the exception info, in order to properly decref
1121 * the exception, value, and traceback. If we just exit instead,
1122 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1123 * some finalizers from running.
1124 */
1125 PyErr_Restore(exception, value, tb);
1126 PyErr_Clear();
1127 Py_Exit(exitcode);
1128 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001129}
1130
1131void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001132PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001133{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001134 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001135
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001136 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1137 handle_system_exit();
1138 }
1139 PyErr_Fetch(&exception, &v, &tb);
1140 if (exception == NULL)
1141 return;
1142 PyErr_NormalizeException(&exception, &v, &tb);
1143 if (exception == NULL)
1144 return;
1145 /* Now we know v != NULL too */
1146 if (set_sys_last_vars) {
1147 PySys_SetObject("last_type", exception);
1148 PySys_SetObject("last_value", v);
1149 PySys_SetObject("last_traceback", tb);
1150 }
1151 hook = PySys_GetObject("excepthook");
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001152 if (hook && hook != Py_None) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 PyObject *args = PyTuple_Pack(3,
1154 exception, v, tb ? tb : Py_None);
1155 PyObject *result = PyEval_CallObject(hook, args);
1156 if (result == NULL) {
1157 PyObject *exception2, *v2, *tb2;
1158 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1159 handle_system_exit();
1160 }
1161 PyErr_Fetch(&exception2, &v2, &tb2);
1162 PyErr_NormalizeException(&exception2, &v2, &tb2);
1163 /* It should not be possible for exception2 or v2
1164 to be NULL. However PyErr_Display() can't
1165 tolerate NULLs, so just be safe. */
1166 if (exception2 == NULL) {
1167 exception2 = Py_None;
1168 Py_INCREF(exception2);
1169 }
1170 if (v2 == NULL) {
1171 v2 = Py_None;
1172 Py_INCREF(v2);
1173 }
1174 if (Py_FlushLine())
1175 PyErr_Clear();
1176 fflush(stdout);
1177 PySys_WriteStderr("Error in sys.excepthook:\n");
1178 PyErr_Display(exception2, v2, tb2);
1179 PySys_WriteStderr("\nOriginal exception was:\n");
1180 PyErr_Display(exception, v, tb);
1181 Py_DECREF(exception2);
1182 Py_DECREF(v2);
1183 Py_XDECREF(tb2);
1184 }
1185 Py_XDECREF(result);
1186 Py_XDECREF(args);
1187 } else {
1188 PySys_WriteStderr("sys.excepthook is missing\n");
1189 PyErr_Display(exception, v, tb);
1190 }
1191 Py_XDECREF(exception);
1192 Py_XDECREF(v);
1193 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001194}
1195
Richard Jones7b9558d2006-05-27 12:29:24 +00001196void
1197PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001198{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001199 int err = 0;
1200 PyObject *f = PySys_GetObject("stderr");
1201 Py_INCREF(value);
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001202 if (f == NULL || f == Py_None)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001203 fprintf(stderr, "lost sys.stderr\n");
1204 else {
1205 if (Py_FlushLine())
1206 PyErr_Clear();
1207 fflush(stdout);
1208 if (tb && tb != Py_None)
1209 err = PyTraceBack_Print(tb, f);
1210 if (err == 0 &&
1211 PyObject_HasAttrString(value, "print_file_and_line"))
1212 {
1213 PyObject *message;
1214 const char *filename, *text;
1215 int lineno, offset;
1216 if (!parse_syntax_error(value, &message, &filename,
1217 &lineno, &offset, &text))
1218 PyErr_Clear();
1219 else {
1220 char buf[10];
1221 PyFile_WriteString(" File \"", f);
1222 if (filename == NULL)
1223 PyFile_WriteString("<string>", f);
1224 else
1225 PyFile_WriteString(filename, f);
1226 PyFile_WriteString("\", line ", f);
1227 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1228 PyFile_WriteString(buf, f);
1229 PyFile_WriteString("\n", f);
1230 if (text != NULL)
1231 print_error_text(f, offset, text);
1232 Py_DECREF(value);
1233 value = message;
1234 /* Can't be bothered to check all those
1235 PyFile_WriteString() calls */
1236 if (PyErr_Occurred())
1237 err = -1;
1238 }
1239 }
1240 if (err) {
1241 /* Don't do anything else */
1242 }
1243 else if (PyExceptionClass_Check(exception)) {
1244 PyObject* moduleName;
1245 char* className = PyExceptionClass_Name(exception);
1246 if (className != NULL) {
1247 char *dot = strrchr(className, '.');
1248 if (dot != NULL)
1249 className = dot+1;
1250 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001251
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001252 moduleName = PyObject_GetAttrString(exception, "__module__");
1253 if (moduleName == NULL)
1254 err = PyFile_WriteString("<unknown>", f);
1255 else {
1256 char* modstr = PyString_AsString(moduleName);
1257 if (modstr && strcmp(modstr, "exceptions"))
1258 {
1259 err = PyFile_WriteString(modstr, f);
1260 err += PyFile_WriteString(".", f);
1261 }
1262 Py_DECREF(moduleName);
1263 }
1264 if (err == 0) {
1265 if (className == NULL)
1266 err = PyFile_WriteString("<unknown>", f);
1267 else
1268 err = PyFile_WriteString(className, f);
1269 }
1270 }
1271 else
1272 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1273 if (err == 0 && (value != Py_None)) {
1274 PyObject *s = PyObject_Str(value);
1275 /* only print colon if the str() of the
1276 object is not the empty string
1277 */
1278 if (s == NULL)
1279 err = -1;
1280 else if (!PyString_Check(s) ||
1281 PyString_GET_SIZE(s) != 0)
1282 err = PyFile_WriteString(": ", f);
1283 if (err == 0)
1284 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1285 Py_XDECREF(s);
1286 }
1287 /* try to write a newline in any case */
1288 err += PyFile_WriteString("\n", f);
1289 }
1290 Py_DECREF(value);
1291 /* If an error happened here, don't show it.
1292 XXX This is wrong, but too many callers rely on this behavior. */
1293 if (err != 0)
1294 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001295}
1296
Guido van Rossum82598051997-03-05 00:20:32 +00001297PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001298PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001299 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001300{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001301 PyObject *ret = NULL;
1302 mod_ty mod;
1303 PyArena *arena = PyArena_New();
1304 if (arena == NULL)
1305 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001306
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001307 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1308 if (mod != NULL)
1309 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1310 PyArena_Free(arena);
1311 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001312}
1313
1314PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001315PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001316 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001317{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001318 PyObject *ret;
1319 mod_ty mod;
1320 PyArena *arena = PyArena_New();
1321 if (arena == NULL)
1322 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001323
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001324 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1325 flags, NULL, arena);
1326 if (closeit)
1327 fclose(fp);
1328 if (mod == NULL) {
1329 PyArena_Free(arena);
1330 return NULL;
1331 }
1332 ret = run_mod(mod, filename, globals, locals, flags, arena);
1333 PyArena_Free(arena);
1334 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001335}
1336
Guido van Rossum82598051997-03-05 00:20:32 +00001337static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001339 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001340{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001341 PyCodeObject *co;
1342 PyObject *v;
1343 co = PyAST_Compile(mod, filename, flags, arena);
1344 if (co == NULL)
1345 return NULL;
1346 v = PyEval_EvalCode(co, globals, locals);
1347 Py_DECREF(co);
1348 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001349}
1350
Guido van Rossum82598051997-03-05 00:20:32 +00001351static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001352run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001353 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001354{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001355 PyCodeObject *co;
1356 PyObject *v;
1357 long magic;
1358 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001359
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001360 magic = PyMarshal_ReadLongFromFile(fp);
1361 if (magic != PyImport_GetMagicNumber()) {
1362 PyErr_SetString(PyExc_RuntimeError,
1363 "Bad magic number in .pyc file");
1364 return NULL;
1365 }
1366 (void) PyMarshal_ReadLongFromFile(fp);
1367 v = PyMarshal_ReadLastObjectFromFile(fp);
1368 fclose(fp);
1369 if (v == NULL || !PyCode_Check(v)) {
1370 Py_XDECREF(v);
1371 PyErr_SetString(PyExc_RuntimeError,
1372 "Bad code object in .pyc file");
1373 return NULL;
1374 }
1375 co = (PyCodeObject *)v;
1376 v = PyEval_EvalCode(co, globals, locals);
1377 if (v && flags)
1378 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1379 Py_DECREF(co);
1380 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001381}
1382
Guido van Rossum82598051997-03-05 00:20:32 +00001383PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001384Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001385 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001386{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001387 PyCodeObject *co;
1388 mod_ty mod;
1389 PyArena *arena = PyArena_New();
1390 if (arena == NULL)
1391 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001392
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001393 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1394 if (mod == NULL) {
1395 PyArena_Free(arena);
1396 return NULL;
1397 }
1398 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1399 PyObject *result = PyAST_mod2obj(mod);
1400 PyArena_Free(arena);
1401 return result;
1402 }
1403 co = PyAST_Compile(mod, filename, flags, arena);
1404 PyArena_Free(arena);
1405 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001406}
1407
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001408struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001409Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001410{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001411 struct symtable *st;
1412 mod_ty mod;
1413 PyCompilerFlags flags;
1414 PyArena *arena = PyArena_New();
1415 if (arena == NULL)
1416 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001417
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001418 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001419
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001420 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1421 if (mod == NULL) {
1422 PyArena_Free(arena);
1423 return NULL;
1424 }
1425 st = PySymtable_Build(mod, filename, 0);
1426 PyArena_Free(arena);
1427 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001428}
1429
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430/* Preferred access to parser is through AST. */
1431mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001432PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001433 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001435 mod_ty mod;
1436 PyCompilerFlags localflags;
1437 perrdetail err;
1438 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001439
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001440 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1441 &_PyParser_Grammar, start, &err,
1442 &iflags);
1443 if (flags == NULL) {
1444 localflags.cf_flags = 0;
1445 flags = &localflags;
1446 }
1447 if (n) {
1448 flags->cf_flags |= iflags & PyCF_MASK;
1449 mod = PyAST_FromNode(n, flags, filename, arena);
1450 PyNode_Free(n);
1451 return mod;
1452 }
1453 else {
1454 err_input(&err);
1455 return NULL;
1456 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457}
1458
1459mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001460PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001461 char *ps2, PyCompilerFlags *flags, int *errcode,
1462 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001464 mod_ty mod;
1465 PyCompilerFlags localflags;
1466 perrdetail err;
1467 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001468
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001469 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1470 start, ps1, ps2, &err, &iflags);
1471 if (flags == NULL) {
1472 localflags.cf_flags = 0;
1473 flags = &localflags;
1474 }
1475 if (n) {
1476 flags->cf_flags |= iflags & PyCF_MASK;
1477 mod = PyAST_FromNode(n, flags, filename, arena);
1478 PyNode_Free(n);
1479 return mod;
1480 }
1481 else {
1482 err_input(&err);
1483 if (errcode)
1484 *errcode = err.error;
1485 return NULL;
1486 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487}
1488
Guido van Rossuma110aa61994-08-29 12:50:44 +00001489/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001490
Guido van Rossuma110aa61994-08-29 12:50:44 +00001491node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001492PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001493{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001494 perrdetail err;
1495 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1496 start, NULL, NULL, &err, flags);
1497 if (n == NULL)
1498 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001499
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001500 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001501}
1502
Guido van Rossuma110aa61994-08-29 12:50:44 +00001503/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001504
Guido van Rossuma110aa61994-08-29 12:50:44 +00001505node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001506PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001507{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001508 perrdetail err;
1509 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1510 start, &err, flags);
1511 if (n == NULL)
1512 err_input(&err);
1513 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001514}
1515
1516node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001517PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001518 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001519{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001520 perrdetail err;
1521 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1522 &_PyParser_Grammar, start, &err, flags);
1523 if (n == NULL)
1524 err_input(&err);
1525 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001526}
1527
1528node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001529PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001530{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001531 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001532}
1533
Guido van Rossum66ebd912003-04-17 16:02:26 +00001534/* May want to move a more generalized form of this to parsetok.c or
1535 even parser modules. */
1536
1537void
1538PyParser_SetError(perrdetail *err)
1539{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001540 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001541}
1542
Guido van Rossuma110aa61994-08-29 12:50:44 +00001543/* Set the error appropriate to the given input error code (see errcode.h) */
1544
1545static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001546err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001547{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001548 PyObject *v, *w, *errtype;
1549 PyObject* u = NULL;
1550 char *msg = NULL;
1551 errtype = PyExc_SyntaxError;
1552 switch (err->error) {
1553 case E_ERROR:
1554 return;
1555 case E_SYNTAX:
1556 errtype = PyExc_IndentationError;
1557 if (err->expected == INDENT)
1558 msg = "expected an indented block";
1559 else if (err->token == INDENT)
1560 msg = "unexpected indent";
1561 else if (err->token == DEDENT)
1562 msg = "unexpected unindent";
1563 else {
1564 errtype = PyExc_SyntaxError;
1565 msg = "invalid syntax";
1566 }
1567 break;
1568 case E_TOKEN:
1569 msg = "invalid token";
1570 break;
1571 case E_EOFS:
1572 msg = "EOF while scanning triple-quoted string literal";
1573 break;
1574 case E_EOLS:
1575 msg = "EOL while scanning string literal";
1576 break;
1577 case E_INTR:
1578 if (!PyErr_Occurred())
1579 PyErr_SetNone(PyExc_KeyboardInterrupt);
1580 goto cleanup;
1581 case E_NOMEM:
1582 PyErr_NoMemory();
1583 goto cleanup;
1584 case E_EOF:
1585 msg = "unexpected EOF while parsing";
1586 break;
1587 case E_TABSPACE:
1588 errtype = PyExc_TabError;
1589 msg = "inconsistent use of tabs and spaces in indentation";
1590 break;
1591 case E_OVERFLOW:
1592 msg = "expression too long";
1593 break;
1594 case E_DEDENT:
1595 errtype = PyExc_IndentationError;
1596 msg = "unindent does not match any outer indentation level";
1597 break;
1598 case E_TOODEEP:
1599 errtype = PyExc_IndentationError;
1600 msg = "too many levels of indentation";
1601 break;
1602 case E_DECODE: {
1603 PyObject *type, *value, *tb;
1604 PyErr_Fetch(&type, &value, &tb);
1605 if (value != NULL) {
1606 u = PyObject_Str(value);
1607 if (u != NULL) {
1608 msg = PyString_AsString(u);
1609 }
1610 }
1611 if (msg == NULL)
1612 msg = "unknown decode error";
1613 Py_XDECREF(type);
1614 Py_XDECREF(value);
1615 Py_XDECREF(tb);
1616 break;
1617 }
1618 case E_LINECONT:
1619 msg = "unexpected character after line continuation character";
1620 break;
1621 default:
1622 fprintf(stderr, "error=%d\n", err->error);
1623 msg = "unknown parsing error";
1624 break;
1625 }
1626 v = Py_BuildValue("(ziiz)", err->filename,
1627 err->lineno, err->offset, err->text);
1628 w = NULL;
1629 if (v != NULL)
1630 w = Py_BuildValue("(sO)", msg, v);
1631 Py_XDECREF(u);
1632 Py_XDECREF(v);
1633 PyErr_SetObject(errtype, w);
1634 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001635cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001636 if (err->text != NULL) {
1637 PyObject_FREE(err->text);
1638 err->text = NULL;
1639 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001640}
1641
1642/* Print fatal error message and abort */
1643
1644void
Tim Peters7c321a82002-07-09 02:57:01 +00001645Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001646{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001647 fprintf(stderr, "Fatal Python error: %s\n", msg);
1648 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller42f9b4e2009-03-31 22:20:35 +00001649
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001650#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001651 {
1652 size_t len = strlen(msg);
1653 WCHAR* buffer;
1654 size_t i;
Martin v. Löwis5344c992009-01-02 20:32:55 +00001655
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001656 /* Convert the message to wchar_t. This uses a simple one-to-one
1657 conversion, assuming that the this error message actually uses ASCII
1658 only. If this ceases to be true, we will have to convert. */
1659 buffer = alloca( (len+1) * (sizeof *buffer));
1660 for( i=0; i<=len; ++i)
1661 buffer[i] = msg[i];
1662 OutputDebugStringW(L"Fatal Python error: ");
1663 OutputDebugStringW(buffer);
1664 OutputDebugStringW(L"\n");
1665 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001666#ifdef _DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001667 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001668#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001669#endif /* MS_WINDOWS */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001670 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001671}
1672
1673/* Clean up and exit */
1674
Guido van Rossuma110aa61994-08-29 12:50:44 +00001675#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001676#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001677#endif
1678
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001679/* Wait until threading._shutdown completes, provided
1680 the threading module was imported in the first place.
1681 The shutdown routine will wait until all non-daemon
1682 "threading" threads have completed. */
1683static void
1684wait_for_thread_shutdown(void)
1685{
1686#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001687 PyObject *result;
1688 PyThreadState *tstate = PyThreadState_GET();
1689 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1690 "threading");
1691 if (threading == NULL) {
1692 /* threading not imported */
1693 PyErr_Clear();
1694 return;
1695 }
1696 result = PyObject_CallMethod(threading, "_shutdown", "");
1697 if (result == NULL)
1698 PyErr_WriteUnraisable(threading);
1699 else
1700 Py_DECREF(result);
1701 Py_DECREF(threading);
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001702#endif
1703}
1704
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001705#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001706static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001707static int nexitfuncs = 0;
1708
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001709int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001710{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001711 if (nexitfuncs >= NEXITFUNCS)
1712 return -1;
1713 exitfuncs[nexitfuncs++] = func;
1714 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001715}
1716
Guido van Rossumcc283f51997-08-05 02:22:03 +00001717static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001718call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001719{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001720 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001721
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001722 if (exitfunc) {
1723 PyObject *res;
1724 Py_INCREF(exitfunc);
1725 PySys_SetObject("exitfunc", (PyObject *)NULL);
1726 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1727 if (res == NULL) {
1728 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1729 PySys_WriteStderr("Error in sys.exitfunc:\n");
1730 }
1731 PyErr_Print();
1732 }
1733 Py_DECREF(exitfunc);
1734 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001735
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001736 if (Py_FlushLine())
1737 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001738}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001739
Guido van Rossumcc283f51997-08-05 02:22:03 +00001740static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001741call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001742{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001743 while (nexitfuncs > 0)
1744 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001745
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001746 fflush(stdout);
1747 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001748}
1749
1750void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001751Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001752{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001753 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001754
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001755 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001756}
1757
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001758static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001759initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001760{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001761#ifdef SIGPIPE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001762 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001763#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001764#ifdef SIGXFZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001765 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001766#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001767#ifdef SIGXFSZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001768 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001769#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001770 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001771}
1772
Guido van Rossum7433b121997-02-14 19:45:36 +00001773
1774/*
1775 * The file descriptor fd is considered ``interactive'' if either
1776 * a) isatty(fd) is TRUE, or
1777 * b) the -i flag was given, and the filename associated with
1778 * the descriptor is NULL or "<stdin>" or "???".
1779 */
1780int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001781Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001782{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001783 if (isatty((int)fileno(fp)))
1784 return 1;
1785 if (!Py_InteractiveFlag)
1786 return 0;
1787 return (filename == NULL) ||
1788 (strcmp(filename, "<stdin>") == 0) ||
1789 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001790}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001791
1792
Tim Petersd08e3822003-04-17 15:24:21 +00001793#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001794#if defined(WIN32) && defined(_MSC_VER)
1795
1796/* Stack checking for Microsoft C */
1797
1798#include <malloc.h>
1799#include <excpt.h>
1800
Fred Drakee8de31c2000-08-31 05:38:39 +00001801/*
1802 * Return non-zero when we run out of memory on the stack; zero otherwise.
1803 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001804int
Fred Drake399739f2000-08-31 05:52:44 +00001805PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001806{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001807 __try {
1808 /* alloca throws a stack overflow exception if there's
1809 not enough space left on the stack */
1810 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1811 return 0;
1812 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1813 EXCEPTION_EXECUTE_HANDLER :
1814 EXCEPTION_CONTINUE_SEARCH) {
1815 int errcode = _resetstkoflw();
1816 if (errcode == 0)
1817 {
1818 Py_FatalError("Could not reset the stack!");
1819 }
1820 }
1821 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001822}
1823
1824#endif /* WIN32 && _MSC_VER */
1825
1826/* Alternate implementations can be added here... */
1827
1828#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001829
1830
1831/* Wrappers around sigaction() or signal(). */
1832
1833PyOS_sighandler_t
1834PyOS_getsig(int sig)
1835{
1836#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001837 struct sigaction context;
1838 if (sigaction(sig, NULL, &context) == -1)
1839 return SIG_ERR;
1840 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001841#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001842 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001843/* Special signal handling for the secure CRT in Visual Studio 2005 */
1844#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001845 switch (sig) {
1846 /* Only these signals are valid */
1847 case SIGINT:
1848 case SIGILL:
1849 case SIGFPE:
1850 case SIGSEGV:
1851 case SIGTERM:
1852 case SIGBREAK:
1853 case SIGABRT:
1854 break;
1855 /* Don't call signal() with other values or it will assert */
1856 default:
1857 return SIG_ERR;
1858 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001859#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001860 handler = signal(sig, SIG_IGN);
1861 if (handler != SIG_ERR)
1862 signal(sig, handler);
1863 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001864#endif
1865}
1866
1867PyOS_sighandler_t
1868PyOS_setsig(int sig, PyOS_sighandler_t handler)
1869{
1870#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001871 /* Some code in Modules/signalmodule.c depends on sigaction() being
1872 * used here if HAVE_SIGACTION is defined. Fix that if this code
1873 * changes to invalidate that assumption.
1874 */
1875 struct sigaction context, ocontext;
1876 context.sa_handler = handler;
1877 sigemptyset(&context.sa_mask);
1878 context.sa_flags = 0;
1879 if (sigaction(sig, &context, &ocontext) == -1)
1880 return SIG_ERR;
1881 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001882#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001883 PyOS_sighandler_t oldhandler;
1884 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001885#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001886 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001887#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001888 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001889#endif
1890}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891
1892/* Deprecated C API functions still provided for binary compatiblity */
1893
1894#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001895PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1897{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001898 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899}
1900
Thomas Heller1b046642006-04-18 18:51:06 +00001901#undef PyParser_SimpleParseString
1902PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903PyParser_SimpleParseString(const char *str, int start)
1904{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001905 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001907
Thomas Heller1b046642006-04-18 18:51:06 +00001908#undef PyRun_AnyFile
1909PyAPI_FUNC(int)
1910PyRun_AnyFile(FILE *fp, const char *name)
1911{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001912 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001913}
1914
1915#undef PyRun_AnyFileEx
1916PyAPI_FUNC(int)
1917PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1918{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001919 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001920}
1921
1922#undef PyRun_AnyFileFlags
1923PyAPI_FUNC(int)
1924PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1925{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001926 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001927}
1928
1929#undef PyRun_File
1930PyAPI_FUNC(PyObject *)
1931PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1932{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001933 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001934}
1935
1936#undef PyRun_FileEx
1937PyAPI_FUNC(PyObject *)
1938PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1939{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001940 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001941}
1942
1943#undef PyRun_FileFlags
1944PyAPI_FUNC(PyObject *)
1945PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001946 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001947{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001948 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001949}
1950
1951#undef PyRun_SimpleFile
1952PyAPI_FUNC(int)
1953PyRun_SimpleFile(FILE *f, const char *p)
1954{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001955 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001956}
1957
1958#undef PyRun_SimpleFileEx
1959PyAPI_FUNC(int)
1960PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1961{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001962 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001963}
1964
1965
1966#undef PyRun_String
1967PyAPI_FUNC(PyObject *)
1968PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1969{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001970 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001971}
1972
1973#undef PyRun_SimpleString
1974PyAPI_FUNC(int)
1975PyRun_SimpleString(const char *s)
1976{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001977 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001978}
1979
1980#undef Py_CompileString
1981PyAPI_FUNC(PyObject *)
1982Py_CompileString(const char *str, const char *p, int s)
1983{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001984 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001985}
1986
1987#undef PyRun_InteractiveOne
1988PyAPI_FUNC(int)
1989PyRun_InteractiveOne(FILE *f, const char *p)
1990{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001991 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001992}
1993
1994#undef PyRun_InteractiveLoop
1995PyAPI_FUNC(int)
1996PyRun_InteractiveLoop(FILE *f, const char *p)
1997{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001998 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001999}
2000
Anthony Baxterac6bd462006-04-13 02:06:09 +00002001#ifdef __cplusplus
2002}
2003#endif
2004