blob: 1aa6930435a79ea9c5245e4bbdf624745a5a7c87 [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"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00007#include "grammar.h"
8#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +00009#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000013#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000015#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000017#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000018#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000019
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000021
Martin v. Löwis73d538b2003-03-05 15:13:47 +000022#ifdef HAVE_LANGINFO_H
23#include <locale.h>
24#include <langinfo.h>
25#endif
26
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000027#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000028#undef BYTE
29#include "windows.h"
30#endif
31
Neal Norwitz4281cef2006-03-04 19:58:13 +000032#ifndef Py_REF_DEBUG
Tim Peters62e97f02006-03-28 21:44:32 +000033#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000034#else /* Py_REF_DEBUG */
Tim Peters62e97f02006-03-28 21:44:32 +000035#define PRINT_TOTAL_REFS() fprintf(stderr, \
36 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
37 _Py_RefTotal)
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#endif
39
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000040extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000041
Guido van Rossum82598051997-03-05 00:20:32 +000042extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000043
Guido van Rossumb73cc041993-11-01 16:28:59 +000044/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000045static void initmain(void);
46static void initsite(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000048 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000049static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000050 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000051static void err_input(perrdetail *);
52static void initsigs(void);
53static void call_sys_exitfunc(void);
54static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000055extern void _PyUnicode_Init(void);
56extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000057
Mark Hammond8d98d2c2003-04-19 15:41:53 +000058#ifdef WITH_THREAD
59extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
60extern void _PyGILState_Fini(void);
61#endif /* WITH_THREAD */
62
Guido van Rossum82598051997-03-05 00:20:32 +000063int Py_DebugFlag; /* Needed by parser.c */
64int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000065int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000066int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000067int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000068int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000069int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000070int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000071/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
72 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
73 true divisions (which they will be in 2.3). */
74int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000075
Mark Hammonda43fd0c2003-02-19 00:33:33 +000076/* Reference to 'warnings' module, to avoid importing it
Mark Hammondedd07732003-07-15 23:03:55 +000077 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000078*/
Mark Hammondedd07732003-07-15 23:03:55 +000079static PyObject *warnings_module = NULL;
80
81/* Returns a borrowed reference to the 'warnings' module, or NULL.
82 If the module is returned, it is guaranteed to have been obtained
83 without acquiring the import lock
84*/
Martin v. Löwisa2c17c52003-08-09 09:47:11 +000085PyObject *PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000086{
87 PyObject *typ, *val, *tb;
88 PyObject *all_modules;
89 /* If we managed to get the module at init time, just use it */
90 if (warnings_module)
91 return warnings_module;
92 /* If it wasn't available at init time, it may be available
93 now in sys.modules (common scenario is frozen apps: import
94 at init time fails, but the frozen init code sets up sys.path
95 correctly, then does an implicit import of warnings for us
96 */
97 /* Save and restore any exceptions */
98 PyErr_Fetch(&typ, &val, &tb);
99
Mark Hammond5f4e8ca2003-07-16 01:54:38 +0000100 all_modules = PySys_GetObject("modules");
Mark Hammondedd07732003-07-15 23:03:55 +0000101 if (all_modules) {
102 warnings_module = PyDict_GetItemString(all_modules, "warnings");
103 /* We keep a ref in the global */
104 Py_XINCREF(warnings_module);
105 }
106 PyErr_Restore(typ, val, tb);
107 return warnings_module;
108}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000109
Guido van Rossum25ce5661997-08-02 03:10:38 +0000110static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000111
Thomas Wouters7e474022000-07-16 12:04:32 +0000112/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000113
114int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000115Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000116{
117 return initialized;
118}
119
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120/* Global initializations. Can be undone by Py_Finalize(). Don't
121 call this twice without an intervening Py_Finalize() call. When
122 initializations fail, a fatal error is issued and the function does
123 not return. On return, the first thread and interpreter state have
124 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000125
Guido van Rossum25ce5661997-08-02 03:10:38 +0000126 Locking: you must hold the interpreter lock while calling this.
127 (If the lock has not yet been initialized, that's equivalent to
128 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000129
Guido van Rossum25ce5661997-08-02 03:10:38 +0000130*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000131
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000132static int
133add_flag(int flag, const char *envs)
134{
135 int env = atoi(envs);
136 if (flag < env)
137 flag = env;
138 if (flag < 1)
139 flag = 1;
140 return flag;
141}
142
Guido van Rossuma027efa1997-05-05 20:56:21 +0000143void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000144Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000145{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000146 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000147 PyThreadState *tstate;
148 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000149 char *p;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000150#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
151 char *codeset;
152 char *saved_locale;
153 PyObject *sys_stream, *sys_isatty;
154#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000155 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000156
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000157 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000158 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000159 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000160
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000161 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000162 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000163 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000164 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000165 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000166 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000167
Guido van Rossuma027efa1997-05-05 20:56:21 +0000168 interp = PyInterpreterState_New();
169 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000170 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000171
Guido van Rossuma027efa1997-05-05 20:56:21 +0000172 tstate = PyThreadState_New(interp);
173 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000174 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000175 (void) PyThreadState_Swap(tstate);
176
Guido van Rossum70d893a2001-08-16 08:21:42 +0000177 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000178
Neal Norwitzb2501f42002-12-31 03:42:13 +0000179 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000180 Py_FatalError("Py_Initialize: can't init frames");
181
Neal Norwitzb2501f42002-12-31 03:42:13 +0000182 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000183 Py_FatalError("Py_Initialize: can't init ints");
184
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000185 _PyFloat_Init();
186
Guido van Rossum25ce5661997-08-02 03:10:38 +0000187 interp->modules = PyDict_New();
188 if (interp->modules == NULL)
189 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000190
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000191#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000192 /* Init Unicode implementation; relies on the codec registry */
193 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000194#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000195
Barry Warsawf242aa02000-05-25 23:09:49 +0000196 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000197 if (bimod == NULL)
198 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000199 interp->builtins = PyModule_GetDict(bimod);
200 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000201
202 sysmod = _PySys_Init();
203 if (sysmod == NULL)
204 Py_FatalError("Py_Initialize: can't initialize sys");
205 interp->sysdict = PyModule_GetDict(sysmod);
206 Py_INCREF(interp->sysdict);
207 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000208 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000209 PyDict_SetItemString(interp->sysdict, "modules",
210 interp->modules);
211
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000212 _PyImport_Init();
213
Barry Warsawf242aa02000-05-25 23:09:49 +0000214 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000216 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000217
Barry Warsaw035574d1997-08-29 22:07:17 +0000218 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000219 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000220
Just van Rossum52e14d62002-12-30 22:08:05 +0000221 _PyImportHooks_Init();
222
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000223 if (install_sigs)
224 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000225
226 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000227 if (!Py_NoSiteFlag)
228 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000229
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000230 /* auto-thread-state API, if available */
231#ifdef WITH_THREAD
232 _PyGILState_Init(interp, tstate);
233#endif /* WITH_THREAD */
234
Mark Hammondedd07732003-07-15 23:03:55 +0000235 warnings_module = PyImport_ImportModule("warnings");
236 if (!warnings_module)
237 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000238
239#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
240 /* On Unix, set the file system encoding according to the
241 user's preference, if the CODESET names a well-known
242 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000243 initialized by other means. Also set the encoding of
244 stdin and stdout if these are terminals. */
245
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000246 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000247 setlocale(LC_CTYPE, "");
248 codeset = nl_langinfo(CODESET);
249 if (codeset && *codeset) {
250 PyObject *enc = PyCodec_Encoder(codeset);
251 if (enc) {
252 codeset = strdup(codeset);
253 Py_DECREF(enc);
254 } else {
255 codeset = NULL;
256 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000257 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000258 } else
259 codeset = NULL;
260 setlocale(LC_CTYPE, saved_locale);
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000261 free(saved_locale);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000262
263 if (codeset) {
Michael W. Hudson68debc92003-08-11 12:20:24 +0000264 sys_stream = PySys_GetObject("stdin");
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000265 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
266 if (!sys_isatty)
267 PyErr_Clear();
268 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
269 if (!PyFile_SetEncoding(sys_stream, codeset))
270 Py_FatalError("Cannot set codeset of stdin");
271 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000272 Py_XDECREF(sys_isatty);
273
274 sys_stream = PySys_GetObject("stdout");
275 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
276 if (!sys_isatty)
277 PyErr_Clear();
278 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
279 if (!PyFile_SetEncoding(sys_stream, codeset))
280 Py_FatalError("Cannot set codeset of stdout");
281 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000282 Py_XDECREF(sys_isatty);
283
Martin v. Löwisea62d252006-04-03 10:56:49 +0000284 sys_stream = PySys_GetObject("stderr");
285 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
286 if (!sys_isatty)
287 PyErr_Clear();
288 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
289 if (!PyFile_SetEncoding(sys_stream, codeset))
290 Py_FatalError("Cannot set codeset of stderr");
291 }
292 Py_XDECREF(sys_isatty);
293
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000294 if (!Py_FileSystemDefaultEncoding)
295 Py_FileSystemDefaultEncoding = codeset;
296 else
297 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000298 }
299#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000300}
301
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000302void
303Py_Initialize(void)
304{
305 Py_InitializeEx(1);
306}
307
308
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000309#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000310extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000311#endif
312
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313/* Undo the effect of Py_Initialize().
314
315 Beware: if multiple interpreter and/or thread states exist, these
316 are not wiped out; only the current thread and interpreter state
317 are deleted. But since everything else is deleted, those other
318 interpreter and thread states should no longer be used.
319
320 (XXX We should do better, e.g. wipe out all interpreters and
321 threads.)
322
323 Locking: as above.
324
325*/
326
327void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000328Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000329{
330 PyInterpreterState *interp;
331 PyThreadState *tstate;
332
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000333 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000334 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000335
Tim Peters384fd102001-01-21 03:40:37 +0000336 /* The interpreter is still entirely intact at this point, and the
337 * exit funcs may be relying on that. In particular, if some thread
338 * or exit func is still waiting to do an import, the import machinery
339 * expects Py_IsInitialized() to return true. So don't say the
340 * interpreter is uninitialized until after the exit funcs have run.
341 * Note that Threading.py uses an exit func to do a join on all the
342 * threads created thru it, so this also protects pending imports in
343 * the threads created via Threading.
344 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000345 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000346 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000347
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000348 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000349 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000350 interp = tstate->interp;
351
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000352 /* Disable signal handling */
353 PyOS_FiniInterrupts();
354
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000355 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000356 Py_XDECREF(warnings_module);
357 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000358
Guido van Rossume13ddc92003-04-17 17:29:22 +0000359 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000360 * before all modules are destroyed.
361 * XXX If a __del__ or weakref callback is triggered here, and tries to
362 * XXX import a module, bad things can happen, because Python no
363 * XXX longer believes it's initialized.
364 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
365 * XXX is easy to provoke that way. I've also seen, e.g.,
366 * XXX Exception exceptions.ImportError: 'No module named sha'
367 * XXX in <function callback at 0x008F5718> ignored
368 * XXX but I'm unclear on exactly how that one happens. In any case,
369 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000370 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000371 PyGC_Collect();
372
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000373 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000375
Guido van Rossume13ddc92003-04-17 17:29:22 +0000376 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000377 * new-style class definitions, for example.
378 * XXX This is disabled because it caused too many problems. If
379 * XXX a __del__ or weakref callback triggers here, Python code has
380 * XXX a hard time running, because even the sys module has been
381 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
382 * XXX One symptom is a sequence of information-free messages
383 * XXX coming from threads (if a __del__ or callback is invoked,
384 * XXX other threads can execute too, and any exception they encounter
385 * XXX triggers a comedy of errors as subsystem after subsystem
386 * XXX fails to find what it *expects* to find in sys to help report
387 * XXX the exception and consequent unexpected failures). I've also
388 * XXX seen segfaults then, after adding print statements to the
389 * XXX Python code getting called.
390 */
391#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000392 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000393#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000394
Guido van Rossum1707aad1997-12-08 23:43:45 +0000395 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
396 _PyImport_Fini();
397
398 /* Debugging stuff */
399#ifdef COUNT_ALLOCS
400 dump_counts();
401#endif
402
Tim Peters62e97f02006-03-28 21:44:32 +0000403 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000404
Tim Peters9cf25ce2003-04-17 15:21:01 +0000405#ifdef Py_TRACE_REFS
406 /* Display all objects still alive -- this can invoke arbitrary
407 * __repr__ overrides, so requires a mostly-intact interpreter.
408 * Alas, a lot of stuff may still be alive now that will be cleaned
409 * up later.
410 */
Tim Peters269b2a62003-04-17 19:52:29 +0000411 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000412 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000413#endif /* Py_TRACE_REFS */
414
Mark Hammond6cb90292003-04-22 11:18:00 +0000415 /* Cleanup auto-thread-state */
416#ifdef WITH_THREAD
417 _PyGILState_Fini();
418#endif /* WITH_THREAD */
419
Guido van Rossumd922fa42003-04-15 14:10:09 +0000420 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000421 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000422
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000423 /* Now we decref the exception classes. After this point nothing
424 can raise an exception. That's okay, because each Fini() method
425 below has been checked to make sure no exceptions are ever
426 raised.
427 */
428
429 _PyExc_Fini();
430
Guido van Rossumd922fa42003-04-15 14:10:09 +0000431 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000432 PyThreadState_Swap(NULL);
433 PyInterpreterState_Delete(interp);
434
Guido van Rossumd922fa42003-04-15 14:10:09 +0000435 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000436 PyMethod_Fini();
437 PyFrame_Fini();
438 PyCFunction_Fini();
439 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000440 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000441 PySet_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000442 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000443 PyInt_Fini();
444 PyFloat_Fini();
445
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000446#ifdef Py_USING_UNICODE
447 /* Cleanup Unicode implementation */
448 _PyUnicode_Fini();
449#endif
450
Guido van Rossumcc283f51997-08-05 02:22:03 +0000451 /* XXX Still allocated:
452 - various static ad-hoc pointers to interned strings
453 - int and float free list blocks
454 - whatever various modules and libraries allocate
455 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000456
457 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000458
Tim Peters269b2a62003-04-17 19:52:29 +0000459#ifdef Py_TRACE_REFS
460 /* Display addresses (& refcnts) of all objects still alive.
461 * An address can be used to find the repr of the object, printed
462 * above by _Py_PrintReferences.
463 */
464 if (Py_GETENV("PYTHONDUMPREFS"))
465 _Py_PrintReferenceAddresses(stderr);
466#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000467#ifdef PYMALLOC_DEBUG
468 if (Py_GETENV("PYTHONMALLOCSTATS"))
469 _PyObject_DebugMallocStats();
470#endif
471
Guido van Rossumcc283f51997-08-05 02:22:03 +0000472 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000473}
474
475/* Create and initialize a new interpreter and thread, and return the
476 new thread. This requires that Py_Initialize() has been called
477 first.
478
479 Unsuccessful initialization yields a NULL pointer. Note that *no*
480 exception information is available even in this case -- the
481 exception information is held in the thread, and there is no
482 thread.
483
484 Locking: as above.
485
486*/
487
488PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000489Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000490{
491 PyInterpreterState *interp;
492 PyThreadState *tstate, *save_tstate;
493 PyObject *bimod, *sysmod;
494
495 if (!initialized)
496 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
497
498 interp = PyInterpreterState_New();
499 if (interp == NULL)
500 return NULL;
501
502 tstate = PyThreadState_New(interp);
503 if (tstate == NULL) {
504 PyInterpreterState_Delete(interp);
505 return NULL;
506 }
507
508 save_tstate = PyThreadState_Swap(tstate);
509
510 /* XXX The following is lax in error checking */
511
512 interp->modules = PyDict_New();
513
514 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
515 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000516 interp->builtins = PyModule_GetDict(bimod);
517 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000518 }
519 sysmod = _PyImport_FindExtension("sys", "sys");
520 if (bimod != NULL && sysmod != NULL) {
521 interp->sysdict = PyModule_GetDict(sysmod);
522 Py_INCREF(interp->sysdict);
523 PySys_SetPath(Py_GetPath());
524 PyDict_SetItemString(interp->sysdict, "modules",
525 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000526 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000527 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000528 if (!Py_NoSiteFlag)
529 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000530 }
531
532 if (!PyErr_Occurred())
533 return tstate;
534
535 /* Oops, it didn't work. Undo it all. */
536
537 PyErr_Print();
538 PyThreadState_Clear(tstate);
539 PyThreadState_Swap(save_tstate);
540 PyThreadState_Delete(tstate);
541 PyInterpreterState_Delete(interp);
542
543 return NULL;
544}
545
546/* Delete an interpreter and its last thread. This requires that the
547 given thread state is current, that the thread has no remaining
548 frames, and that it is its interpreter's only remaining thread.
549 It is a fatal error to violate these constraints.
550
551 (Py_Finalize() doesn't have these constraints -- it zaps
552 everything, regardless.)
553
554 Locking: as above.
555
556*/
557
558void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000559Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560{
561 PyInterpreterState *interp = tstate->interp;
562
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000563 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564 Py_FatalError("Py_EndInterpreter: thread is not current");
565 if (tstate->frame != NULL)
566 Py_FatalError("Py_EndInterpreter: thread still has a frame");
567 if (tstate != interp->tstate_head || tstate->next != NULL)
568 Py_FatalError("Py_EndInterpreter: not the last thread");
569
570 PyImport_Cleanup();
571 PyInterpreterState_Clear(interp);
572 PyThreadState_Swap(NULL);
573 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000574}
575
576static char *progname = "python";
577
578void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000579Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000580{
581 if (pn && *pn)
582 progname = pn;
583}
584
585char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000586Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000587{
588 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000589}
590
Guido van Rossuma61691e1998-02-06 22:27:24 +0000591static char *default_home = NULL;
592
593void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000594Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000595{
596 default_home = home;
597}
598
599char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000600Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000601{
602 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000603 if (home == NULL && !Py_IgnoreEnvironmentFlag)
604 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000605 return home;
606}
607
Guido van Rossum6135a871995-01-09 17:53:26 +0000608/* Create __main__ module */
609
610static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000611initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000612{
Guido van Rossum82598051997-03-05 00:20:32 +0000613 PyObject *m, *d;
614 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000615 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000616 Py_FatalError("can't create __main__ module");
617 d = PyModule_GetDict(m);
618 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000619 PyObject *bimod = PyImport_ImportModule("__builtin__");
620 if (bimod == NULL ||
621 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000622 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000623 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000624 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000625}
626
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000627/* Import the site module (not into __main__ though) */
628
629static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000630initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000631{
632 PyObject *m, *f;
633 m = PyImport_ImportModule("site");
634 if (m == NULL) {
635 f = PySys_GetObject("stderr");
636 if (Py_VerboseFlag) {
637 PyFile_WriteString(
638 "'import site' failed; traceback:\n", f);
639 PyErr_Print();
640 }
641 else {
642 PyFile_WriteString(
643 "'import site' failed; use -v for traceback\n", f);
644 PyErr_Clear();
645 }
646 }
647 else {
648 Py_DECREF(m);
649 }
650}
651
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000652/* Parse input from a file and execute it */
653
654int
Martin v. Löwis056a69c2006-03-01 16:55:42 +0000655PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000656 PyCompilerFlags *flags)
657{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000658 if (filename == NULL)
659 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000660 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000661 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000662 if (closeit)
663 fclose(fp);
664 return err;
665 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000666 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000667 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000668}
669
670int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000671PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000672{
Guido van Rossum82598051997-03-05 00:20:32 +0000673 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000674 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000675 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000676
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000677 if (flags == NULL) {
678 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000679 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000680 }
Guido van Rossum82598051997-03-05 00:20:32 +0000681 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000682 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000683 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
684 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000685 }
Guido van Rossum82598051997-03-05 00:20:32 +0000686 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000687 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000688 PySys_SetObject("ps2", v = PyString_FromString("... "));
689 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000690 }
691 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000692 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Tim Peters62e97f02006-03-28 21:44:32 +0000693 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000694 if (ret == E_EOF)
695 return 0;
696 /*
697 if (ret == E_NOMEM)
698 return -1;
699 */
700 }
701}
702
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000703/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000704#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000705 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
706 PyPARSE_DONT_IMPLY_DEDENT : 0) \
Neal Norwitz9589ee22006-03-04 19:01:22 +0000707 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
708 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000709
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000710int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000711PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000712{
Guido van Rossum82598051997-03-05 00:20:32 +0000713 PyObject *m, *d, *v, *w;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000714 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000715 PyArena *arena;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000716 char *ps1 = "", *ps2 = "";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000717 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000718
Guido van Rossum82598051997-03-05 00:20:32 +0000719 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000720 if (v != NULL) {
721 v = PyObject_Str(v);
722 if (v == NULL)
723 PyErr_Clear();
724 else if (PyString_Check(v))
725 ps1 = PyString_AsString(v);
726 }
Guido van Rossum82598051997-03-05 00:20:32 +0000727 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000728 if (w != NULL) {
729 w = PyObject_Str(w);
730 if (w == NULL)
731 PyErr_Clear();
732 else if (PyString_Check(w))
733 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000734 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000735 arena = PyArena_New();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000736 mod = PyParser_ASTFromFile(fp, filename,
737 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000738 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000739 Py_XDECREF(v);
740 Py_XDECREF(w);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000741 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000742 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743 if (errcode == E_EOF) {
744 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000745 return E_EOF;
746 }
Guido van Rossum82598051997-03-05 00:20:32 +0000747 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000748 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000749 }
Guido van Rossum82598051997-03-05 00:20:32 +0000750 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000751 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000752 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000753 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000754 }
Guido van Rossum82598051997-03-05 00:20:32 +0000755 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000756 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +0000757 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000758 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000759 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000760 return -1;
761 }
Guido van Rossum82598051997-03-05 00:20:32 +0000762 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000763 if (Py_FlushLine())
764 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000765 return 0;
766}
767
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000768/* Check whether a file maybe a pyc file: Look at the extension,
769 the file type, and, if we may close it, at the first few bytes. */
770
771static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000772maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000773{
774 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
775 return 1;
776
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000777 /* Only look into the file if we are allowed to close it, since
778 it then should also be seekable. */
779 if (closeit) {
780 /* Read only two bytes of the magic. If the file was opened in
781 text mode, the bytes 3 and 4 of the magic (\r\n) might not
782 be read as they are on disk. */
783 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
784 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000785 /* Mess: In case of -x, the stream is NOT at its start now,
786 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000787 which makes the current stream position formally undefined,
788 and a x-platform nightmare.
789 Unfortunately, we have no direct way to know whether -x
790 was specified. So we use a terrible hack: if the current
791 stream position is not 0, we assume -x was specified, and
792 give up. Bug 132850 on SourceForge spells out the
793 hopelessness of trying anything else (fseek and ftell
794 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000795 */
Tim Peters3e876562001-02-11 04:35:39 +0000796 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000797 if (ftell(fp) == 0) {
798 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000799 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000800 ispyc = 1;
801 rewind(fp);
802 }
Tim Peters3e876562001-02-11 04:35:39 +0000803 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000804 }
805 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000806}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000807
Guido van Rossum0df002c2000-08-27 19:21:52 +0000808int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000809PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000810 PyCompilerFlags *flags)
811{
Guido van Rossum82598051997-03-05 00:20:32 +0000812 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000813 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000814
Guido van Rossum82598051997-03-05 00:20:32 +0000815 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000816 if (m == NULL)
817 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000818 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000819 if (PyDict_GetItemString(d, "__file__") == NULL) {
820 PyObject *f = PyString_FromString(filename);
821 if (f == NULL)
822 return -1;
823 if (PyDict_SetItemString(d, "__file__", f) < 0) {
824 Py_DECREF(f);
825 return -1;
826 }
827 Py_DECREF(f);
828 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000829 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000830 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000831 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000832 if (closeit)
833 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000834 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000835 fprintf(stderr, "python: Can't reopen .pyc file\n");
836 return -1;
837 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000838 /* Turn on optimization if a .pyo file is given */
839 if (strcmp(ext, ".pyo") == 0)
840 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000841 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000842 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000843 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000844 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000845 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000846 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000847 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000848 return -1;
849 }
Guido van Rossum82598051997-03-05 00:20:32 +0000850 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000851 if (Py_FlushLine())
852 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000853 return 0;
854}
855
856int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000857PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000858{
Guido van Rossum82598051997-03-05 00:20:32 +0000859 PyObject *m, *d, *v;
860 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000861 if (m == NULL)
862 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000863 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000864 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000865 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000866 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000867 return -1;
868 }
Guido van Rossum82598051997-03-05 00:20:32 +0000869 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000870 if (Py_FlushLine())
871 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000872 return 0;
873}
874
Barry Warsaw035574d1997-08-29 22:07:17 +0000875static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000876parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
877 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000878{
879 long hold;
880 PyObject *v;
881
882 /* old style errors */
883 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000884 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +0000885 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000886
887 /* new style errors. `err' is an instance */
888
889 if (! (v = PyObject_GetAttrString(err, "msg")))
890 goto finally;
891 *message = v;
892
893 if (!(v = PyObject_GetAttrString(err, "filename")))
894 goto finally;
895 if (v == Py_None)
896 *filename = NULL;
897 else if (! (*filename = PyString_AsString(v)))
898 goto finally;
899
900 Py_DECREF(v);
901 if (!(v = PyObject_GetAttrString(err, "lineno")))
902 goto finally;
903 hold = PyInt_AsLong(v);
904 Py_DECREF(v);
905 v = NULL;
906 if (hold < 0 && PyErr_Occurred())
907 goto finally;
908 *lineno = (int)hold;
909
910 if (!(v = PyObject_GetAttrString(err, "offset")))
911 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000912 if (v == Py_None) {
913 *offset = -1;
914 Py_DECREF(v);
915 v = NULL;
916 } else {
917 hold = PyInt_AsLong(v);
918 Py_DECREF(v);
919 v = NULL;
920 if (hold < 0 && PyErr_Occurred())
921 goto finally;
922 *offset = (int)hold;
923 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000924
925 if (!(v = PyObject_GetAttrString(err, "text")))
926 goto finally;
927 if (v == Py_None)
928 *text = NULL;
929 else if (! (*text = PyString_AsString(v)))
930 goto finally;
931 Py_DECREF(v);
932 return 1;
933
934finally:
935 Py_XDECREF(v);
936 return 0;
937}
938
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000939void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000940PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000941{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000942 PyErr_PrintEx(1);
943}
944
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000945static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000946print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000947{
948 char *nl;
949 if (offset >= 0) {
950 if (offset > 0 && offset == (int)strlen(text))
951 offset--;
952 for (;;) {
953 nl = strchr(text, '\n');
954 if (nl == NULL || nl-text >= offset)
955 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000956 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000957 text = nl+1;
958 }
959 while (*text == ' ' || *text == '\t') {
960 text++;
961 offset--;
962 }
963 }
964 PyFile_WriteString(" ", f);
965 PyFile_WriteString(text, f);
966 if (*text == '\0' || text[strlen(text)-1] != '\n')
967 PyFile_WriteString("\n", f);
968 if (offset == -1)
969 return;
970 PyFile_WriteString(" ", f);
971 offset--;
972 while (offset > 0) {
973 PyFile_WriteString(" ", f);
974 offset--;
975 }
976 PyFile_WriteString("^\n", f);
977}
978
Guido van Rossum66e8e862001-03-23 17:54:43 +0000979static void
980handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000981{
Neal Norwitz9589ee22006-03-04 19:01:22 +0000982 PyObject *exception, *value, *tb;
983 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +0000984
Guido van Rossum66e8e862001-03-23 17:54:43 +0000985 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000986 if (Py_FlushLine())
987 PyErr_Clear();
988 fflush(stdout);
989 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000990 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +0000991 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000992 /* The error code should be in the `code' attribute. */
993 PyObject *code = PyObject_GetAttrString(value, "code");
994 if (code) {
995 Py_DECREF(value);
996 value = code;
997 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000998 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000999 }
1000 /* If we failed to dig out the 'code' attribute,
1001 just let the else clause below print the error. */
1002 }
1003 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +00001004 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001005 else {
1006 PyObject_Print(value, stderr, Py_PRINT_RAW);
1007 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001008 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001009 }
Tim Peterscf615b52003-04-19 18:47:02 +00001010 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001011 /* Restore and clear the exception info, in order to properly decref
1012 * the exception, value, and traceback. If we just exit instead,
1013 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1014 * some finalizers from running.
1015 */
Tim Peterscf615b52003-04-19 18:47:02 +00001016 PyErr_Restore(exception, value, tb);
1017 PyErr_Clear();
1018 Py_Exit(exitcode);
1019 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001020}
1021
1022void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001023PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001024{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001025 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001026
1027 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1028 handle_system_exit();
1029 }
Guido van Rossum82598051997-03-05 00:20:32 +00001030 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031 if (exception == NULL)
1032 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001033 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001034 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001035 return;
Guido van Rossum9d785502006-03-07 18:31:44 +00001036 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001037 if (set_sys_last_vars) {
1038 PySys_SetObject("last_type", exception);
1039 PySys_SetObject("last_value", v);
1040 PySys_SetObject("last_traceback", tb);
1041 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001042 hook = PySys_GetObject("excepthook");
1043 if (hook) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001044 PyObject *args = PyTuple_Pack(3,
Guido van Rossum9d785502006-03-07 18:31:44 +00001045 exception, v, tb ? tb : Py_None);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001046 PyObject *result = PyEval_CallObject(hook, args);
1047 if (result == NULL) {
1048 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001049 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1050 handle_system_exit();
1051 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001052 PyErr_Fetch(&exception2, &v2, &tb2);
1053 PyErr_NormalizeException(&exception2, &v2, &tb2);
1054 if (Py_FlushLine())
1055 PyErr_Clear();
1056 fflush(stdout);
1057 PySys_WriteStderr("Error in sys.excepthook:\n");
1058 PyErr_Display(exception2, v2, tb2);
1059 PySys_WriteStderr("\nOriginal exception was:\n");
1060 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +00001061 Py_XDECREF(exception2);
1062 Py_XDECREF(v2);
1063 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001064 }
1065 Py_XDECREF(result);
1066 Py_XDECREF(args);
1067 } else {
1068 PySys_WriteStderr("sys.excepthook is missing\n");
1069 PyErr_Display(exception, v, tb);
1070 }
1071 Py_XDECREF(exception);
1072 Py_XDECREF(v);
1073 Py_XDECREF(tb);
1074}
1075
1076void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1077{
1078 int err = 0;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001079 PyObject *f = PySys_GetObject("stderr");
Armin Rigo5d2c6832004-03-22 20:16:58 +00001080 Py_INCREF(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001081 if (f == NULL)
1082 fprintf(stderr, "lost sys.stderr\n");
1083 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001084 if (Py_FlushLine())
1085 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001086 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001087 if (tb && tb != Py_None)
1088 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001089 if (err == 0 &&
Armin Rigo5d2c6832004-03-22 20:16:58 +00001090 PyObject_HasAttrString(value, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001091 {
Guido van Rossum82598051997-03-05 00:20:32 +00001092 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001093 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001094 int lineno, offset;
Armin Rigo5d2c6832004-03-22 20:16:58 +00001095 if (!parse_syntax_error(value, &message, &filename,
Barry Warsaw035574d1997-08-29 22:07:17 +00001096 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001097 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001098 else {
1099 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001100 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001101 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001102 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001103 else
Guido van Rossum82598051997-03-05 00:20:32 +00001104 PyFile_WriteString(filename, f);
1105 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001106 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001107 PyFile_WriteString(buf, f);
1108 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001109 if (text != NULL)
1110 print_error_text(f, offset, text);
Armin Rigo5d2c6832004-03-22 20:16:58 +00001111 Py_DECREF(value);
1112 value = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001113 /* Can't be bothered to check all those
1114 PyFile_WriteString() calls */
1115 if (PyErr_Occurred())
1116 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001117 }
1118 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001119 if (err) {
1120 /* Don't do anything else */
1121 }
Brett Cannonbf364092006-03-01 04:25:17 +00001122 else if (PyExceptionClass_Check(exception)) {
1123 char* className = PyExceptionClass_Name(exception);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001124 PyObject* moduleName =
Brett Cannonbf364092006-03-01 04:25:17 +00001125 PyObject_GetAttrString(exception, "__module__");
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001126
1127 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001128 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001129 else {
1130 char* modstr = PyString_AsString(moduleName);
Brett Cannon2e63b732006-03-02 18:34:57 +00001131 Py_DECREF(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001132 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001133 {
1134 err = PyFile_WriteString(modstr, f);
1135 err += PyFile_WriteString(".", f);
1136 }
1137 }
1138 if (err == 0) {
1139 if (className == NULL)
1140 err = PyFile_WriteString("<unknown>", f);
1141 else
Brett Cannonbf364092006-03-01 04:25:17 +00001142 err = PyFile_WriteString(className, f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001143 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001144 }
1145 else
1146 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
Brett Cannon2e63b732006-03-02 18:34:57 +00001147 if (err == 0 && (value != Py_None)) {
1148 PyObject *s = PyObject_Str(value);
1149 /* only print colon if the str() of the
1150 object is not the empty string
1151 */
1152 if (s == NULL)
1153 err = -1;
1154 else if (!PyString_Check(s) ||
1155 PyString_GET_SIZE(s) != 0)
1156 err = PyFile_WriteString(": ", f);
1157 if (err == 0)
1158 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1159 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001160 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001161 if (err == 0)
1162 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001163 }
Armin Rigo5d2c6832004-03-22 20:16:58 +00001164 Py_DECREF(value);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001165 /* If an error happened here, don't show it.
1166 XXX This is wrong, but too many callers rely on this behavior. */
1167 if (err != 0)
1168 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001169}
1170
Guido van Rossum82598051997-03-05 00:20:32 +00001171PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172PyRun_StringFlags(const char *str, int start, PyObject *globals,
1173 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001174{
Neal Norwitze92fba02006-03-04 18:52:26 +00001175 PyObject *ret = NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001176 PyArena *arena = PyArena_New();
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001177 mod_ty mod = PyParser_ASTFromString(str, "<string>", start, flags,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001178 arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001179 if (mod != NULL)
1180 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001181 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001183}
1184
1185PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001186PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001187 PyObject *locals, int closeit, PyCompilerFlags *flags)
1188{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 PyObject *ret;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001190 PyArena *arena = PyArena_New();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001191 mod_ty mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001192 flags, NULL, arena);
1193 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001194 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001196 }
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001197 if (closeit)
1198 fclose(fp);
Neal Norwitze92fba02006-03-04 18:52:26 +00001199 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001200 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001202}
1203
Guido van Rossum82598051997-03-05 00:20:32 +00001204static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001206 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001207{
Guido van Rossum82598051997-03-05 00:20:32 +00001208 PyCodeObject *co;
1209 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001210 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001211 if (co == NULL)
1212 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001213 v = PyEval_EvalCode(co, globals, locals);
1214 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001215 return v;
1216}
1217
Guido van Rossum82598051997-03-05 00:20:32 +00001218static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
1220 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001221{
Guido van Rossum82598051997-03-05 00:20:32 +00001222 PyCodeObject *co;
1223 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001224 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001225 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001226
Guido van Rossum82598051997-03-05 00:20:32 +00001227 magic = PyMarshal_ReadLongFromFile(fp);
1228 if (magic != PyImport_GetMagicNumber()) {
1229 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001230 "Bad magic number in .pyc file");
1231 return NULL;
1232 }
Guido van Rossum82598051997-03-05 00:20:32 +00001233 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001234 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001235 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001236 if (v == NULL || !PyCode_Check(v)) {
1237 Py_XDECREF(v);
1238 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001239 "Bad code object in .pyc file");
1240 return NULL;
1241 }
Guido van Rossum82598051997-03-05 00:20:32 +00001242 co = (PyCodeObject *)v;
1243 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001244 if (v && flags)
1245 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001246 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001247 return v;
1248}
1249
Guido van Rossum82598051997-03-05 00:20:32 +00001250PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001251Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001252 PyCompilerFlags *flags)
1253{
Guido van Rossum82598051997-03-05 00:20:32 +00001254 PyCodeObject *co;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001255 PyArena *arena = PyArena_New();
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001256 mod_ty mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1257 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001258 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001259 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001260 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001261 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001262 PyObject *result = PyAST_mod2obj(mod);
1263 PyArena_Free(arena);
1264 return result;
1265 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001266 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001267 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001268 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001269}
1270
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001271struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001272Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001273{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001274 struct symtable *st;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001275 PyArena *arena = PyArena_New();
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001276 mod_ty mod = PyParser_ASTFromString(str, filename, start, NULL, arena);
1277 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001278 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001279 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001280 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001282 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001283 return st;
1284}
1285
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286/* Preferred access to parser is through AST. */
1287mod_ty
1288PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001289 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291 mod_ty mod;
1292 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001293 node *n = PyParser_ParseStringFlagsFilename(s, filename,
1294 &_PyParser_Grammar, start, &err,
1295 PARSER_FLAGS(flags));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296 if (n) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001297 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001298 PyNode_Free(n);
1299 return mod;
1300 }
1301 else {
1302 err_input(&err);
1303 return NULL;
1304 }
1305}
1306
1307mod_ty
1308PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001309 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001310 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312 mod_ty mod;
1313 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001314 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1315 start, ps1, ps2, &err, PARSER_FLAGS(flags));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001316 if (n) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001317 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318 PyNode_Free(n);
1319 return mod;
1320 }
1321 else {
1322 err_input(&err);
1323 if (errcode)
1324 *errcode = err.error;
1325 return NULL;
1326 }
1327}
1328
Guido van Rossuma110aa61994-08-29 12:50:44 +00001329/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001330
Guido van Rossuma110aa61994-08-29 12:50:44 +00001331node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001332PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001333{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001334 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001335 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1336 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001337 if (n == NULL)
1338 err_input(&err);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339
Guido van Rossuma110aa61994-08-29 12:50:44 +00001340 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001341}
1342
Guido van Rossuma110aa61994-08-29 12:50:44 +00001343/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001344
Guido van Rossuma110aa61994-08-29 12:50:44 +00001345node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001346PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001347{
Tim Petersfe2127d2001-07-16 05:37:24 +00001348 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001349 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1350 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001351 if (n == NULL)
1352 err_input(&err);
1353 return n;
1354}
1355
1356node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001357PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001358 int start, int flags)
1359{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001360 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001361 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1362 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001363 if (n == NULL)
1364 err_input(&err);
1365 return n;
1366}
1367
1368node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001369PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001370{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001371 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001372}
1373
Guido van Rossum66ebd912003-04-17 16:02:26 +00001374/* May want to move a more generalized form of this to parsetok.c or
1375 even parser modules. */
1376
1377void
1378PyParser_SetError(perrdetail *err)
1379{
1380 err_input(err);
1381}
1382
Guido van Rossuma110aa61994-08-29 12:50:44 +00001383/* Set the error appropriate to the given input error code (see errcode.h) */
1384
1385static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001386err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001387{
Fred Drake85f36392000-07-11 17:53:00 +00001388 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001389 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001390 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001391 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001392 switch (err->error) {
1393 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001394 errtype = PyExc_IndentationError;
1395 if (err->expected == INDENT)
1396 msg = "expected an indented block";
1397 else if (err->token == INDENT)
1398 msg = "unexpected indent";
1399 else if (err->token == DEDENT)
1400 msg = "unexpected unindent";
1401 else {
1402 errtype = PyExc_SyntaxError;
1403 msg = "invalid syntax";
1404 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001405 break;
1406 case E_TOKEN:
1407 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001408 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001409 case E_EOFS:
1410 msg = "EOF while scanning triple-quoted string";
1411 break;
1412 case E_EOLS:
1413 msg = "EOL while scanning single-quoted string";
1414 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001415 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001416 if (!PyErr_Occurred())
1417 PyErr_SetNone(PyExc_KeyboardInterrupt);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001418 return;
1419 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001420 PyErr_NoMemory();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001421 return;
1422 case E_EOF:
1423 msg = "unexpected EOF while parsing";
1424 break;
Fred Drake85f36392000-07-11 17:53:00 +00001425 case E_TABSPACE:
1426 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001427 msg = "inconsistent use of tabs and spaces in indentation";
1428 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001429 case E_OVERFLOW:
1430 msg = "expression too long";
1431 break;
Fred Drake85f36392000-07-11 17:53:00 +00001432 case E_DEDENT:
1433 errtype = PyExc_IndentationError;
1434 msg = "unindent does not match any outer indentation level";
1435 break;
1436 case E_TOODEEP:
1437 errtype = PyExc_IndentationError;
1438 msg = "too many levels of indentation";
1439 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001440 case E_DECODE: {
1441 PyObject *type, *value, *tb;
1442 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001443 if (value != NULL) {
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001444 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001445 if (u != NULL) {
1446 msg = PyString_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001447 }
1448 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001449 if (msg == NULL)
1450 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001451 Py_XDECREF(type);
1452 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001453 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001454 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001455 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001456 case E_LINECONT:
1457 msg = "unexpected character after line continuation character";
1458 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001459 default:
1460 fprintf(stderr, "error=%d\n", err->error);
1461 msg = "unknown parsing error";
1462 break;
1463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464 v = Py_BuildValue("(ziiz)", err->filename,
1465 err->lineno, err->offset, err->text);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001466 if (err->text != NULL) {
Tim Petersc9d78aa2006-03-26 23:27:58 +00001467 PyObject_FREE(err->text);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468 err->text = NULL;
1469 }
1470 w = NULL;
1471 if (v != NULL)
1472 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001473 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001474 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001475 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001476 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001477}
1478
1479/* Print fatal error message and abort */
1480
1481void
Tim Peters7c321a82002-07-09 02:57:01 +00001482Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001483{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001484 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001485#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001486 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001487 OutputDebugString(msg);
1488 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001489#ifdef _DEBUG
1490 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001491#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001492#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001493 abort();
1494}
1495
1496/* Clean up and exit */
1497
Guido van Rossuma110aa61994-08-29 12:50:44 +00001498#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001499#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001500#endif
1501
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001502#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001503static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001504static int nexitfuncs = 0;
1505
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001506int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001507{
1508 if (nexitfuncs >= NEXITFUNCS)
1509 return -1;
1510 exitfuncs[nexitfuncs++] = func;
1511 return 0;
1512}
1513
Guido van Rossumcc283f51997-08-05 02:22:03 +00001514static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001515call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001516{
Guido van Rossum82598051997-03-05 00:20:32 +00001517 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001518
1519 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001520 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001521 Py_INCREF(exitfunc);
1522 PySys_SetObject("exitfunc", (PyObject *)NULL);
1523 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001524 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001525 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1526 PySys_WriteStderr("Error in sys.exitfunc:\n");
1527 }
Guido van Rossum82598051997-03-05 00:20:32 +00001528 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001529 }
Guido van Rossum82598051997-03-05 00:20:32 +00001530 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001531 }
1532
Guido van Rossum0829c751998-02-28 04:31:39 +00001533 if (Py_FlushLine())
1534 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001535}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001536
Guido van Rossumcc283f51997-08-05 02:22:03 +00001537static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001538call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001539{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001540 while (nexitfuncs > 0)
1541 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001542
1543 fflush(stdout);
1544 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001545}
1546
1547void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001548Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001549{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001550 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001551
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001552 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001553}
1554
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001555static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001556initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001557{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001558#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001559 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001560#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001561#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001562 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001563#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001564#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001565 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001566#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001567 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001568}
1569
Guido van Rossum7433b121997-02-14 19:45:36 +00001570
1571/*
1572 * The file descriptor fd is considered ``interactive'' if either
1573 * a) isatty(fd) is TRUE, or
1574 * b) the -i flag was given, and the filename associated with
1575 * the descriptor is NULL or "<stdin>" or "???".
1576 */
1577int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001578Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001579{
1580 if (isatty((int)fileno(fp)))
1581 return 1;
1582 if (!Py_InteractiveFlag)
1583 return 0;
1584 return (filename == NULL) ||
1585 (strcmp(filename, "<stdin>") == 0) ||
1586 (strcmp(filename, "???") == 0);
1587}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001588
1589
Tim Petersd08e3822003-04-17 15:24:21 +00001590#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001591#if defined(WIN32) && defined(_MSC_VER)
1592
1593/* Stack checking for Microsoft C */
1594
1595#include <malloc.h>
1596#include <excpt.h>
1597
Fred Drakee8de31c2000-08-31 05:38:39 +00001598/*
1599 * Return non-zero when we run out of memory on the stack; zero otherwise.
1600 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001601int
Fred Drake399739f2000-08-31 05:52:44 +00001602PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001603{
1604 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001605 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001606 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001607 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001608 return 0;
1609 } __except (EXCEPTION_EXECUTE_HANDLER) {
1610 /* just ignore all errors */
1611 }
1612 return 1;
1613}
1614
1615#endif /* WIN32 && _MSC_VER */
1616
1617/* Alternate implementations can be added here... */
1618
1619#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001620
1621
1622/* Wrappers around sigaction() or signal(). */
1623
1624PyOS_sighandler_t
1625PyOS_getsig(int sig)
1626{
1627#ifdef HAVE_SIGACTION
1628 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001629 if (sigaction(sig, NULL, &context) == -1)
1630 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001631 return context.sa_handler;
1632#else
1633 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001634/* Special signal handling for the secure CRT in Visual Studio 2005 */
1635#if defined(_MSC_VER) && _MSC_VER >= 1400
1636 switch (sig) {
1637 /* Only these signals are valid */
1638 case SIGINT:
1639 case SIGILL:
1640 case SIGFPE:
1641 case SIGSEGV:
1642 case SIGTERM:
1643 case SIGBREAK:
1644 case SIGABRT:
1645 break;
1646 /* Don't call signal() with other values or it will assert */
1647 default:
1648 return SIG_ERR;
1649 }
1650#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00001651 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001652 if (handler != SIG_ERR)
1653 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00001654 return handler;
1655#endif
1656}
1657
1658PyOS_sighandler_t
1659PyOS_setsig(int sig, PyOS_sighandler_t handler)
1660{
1661#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001662 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00001663 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001664 sigemptyset(&context.sa_mask);
1665 context.sa_flags = 0;
1666 if (sigaction(sig, &context, &ocontext) == -1)
1667 return SIG_ERR;
1668 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001669#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001670 PyOS_sighandler_t oldhandler;
1671 oldhandler = signal(sig, handler);
1672#ifdef HAVE_SIGINTERRUPT
1673 siginterrupt(sig, 1);
1674#endif
1675 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001676#endif
1677}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678
1679/* Deprecated C API functions still provided for binary compatiblity */
1680
1681#undef PyParser_SimpleParseFile
1682#undef PyParser_SimpleParseString
1683
1684node *
1685PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1686{
1687 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1688}
1689
1690node *
1691PyParser_SimpleParseString(const char *str, int start)
1692{
1693 return PyParser_SimpleParseStringFlags(str, start, 0);
1694}