blob: 555c39d53372f8a0773d599e18c36978d0d7b398 [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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000020#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000021#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023
Martin v. Löwis73d538b2003-03-05 15:13:47 +000024#ifdef HAVE_LANGINFO_H
25#include <locale.h>
26#include <langinfo.h>
27#endif
28
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000029#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000030#undef BYTE
31#include "windows.h"
32#endif
33
Neal Norwitz4281cef2006-03-04 19:58:13 +000034#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000035#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000036#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000037#define PRINT_TOTAL_REFS() fprintf(stderr, \
38 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
39 _Py_GetRefTotal())
40#endif
41
42#ifdef __cplusplus
43extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000044#endif
45
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000046extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000047
Guido van Rossum82598051997-03-05 00:20:32 +000048extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000049
Guido van Rossumb73cc041993-11-01 16:28:59 +000050/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000051static void initmain(void);
52static void initsite(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000054 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000055static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000056 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void err_input(perrdetail *);
58static void initsigs(void);
59static void call_sys_exitfunc(void);
60static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000061extern void _PyUnicode_Init(void);
62extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000063
Mark Hammond8d98d2c2003-04-19 15:41:53 +000064#ifdef WITH_THREAD
65extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
66extern void _PyGILState_Fini(void);
67#endif /* WITH_THREAD */
68
Guido van Rossum82598051997-03-05 00:20:32 +000069int Py_DebugFlag; /* Needed by parser.c */
70int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000071int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000072int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000073int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000074int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000075int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000076int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000077
Mark Hammonda43fd0c2003-02-19 00:33:33 +000078/* Reference to 'warnings' module, to avoid importing it
Mark Hammondedd07732003-07-15 23:03:55 +000079 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000080*/
Mark Hammondedd07732003-07-15 23:03:55 +000081static PyObject *warnings_module = NULL;
82
83/* Returns a borrowed reference to the 'warnings' module, or NULL.
84 If the module is returned, it is guaranteed to have been obtained
85 without acquiring the import lock
86*/
Martin v. Löwisa2c17c52003-08-09 09:47:11 +000087PyObject *PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000088{
89 PyObject *typ, *val, *tb;
90 PyObject *all_modules;
91 /* If we managed to get the module at init time, just use it */
92 if (warnings_module)
93 return warnings_module;
94 /* If it wasn't available at init time, it may be available
95 now in sys.modules (common scenario is frozen apps: import
96 at init time fails, but the frozen init code sets up sys.path
97 correctly, then does an implicit import of warnings for us
98 */
99 /* Save and restore any exceptions */
100 PyErr_Fetch(&typ, &val, &tb);
101
Mark Hammond5f4e8ca2003-07-16 01:54:38 +0000102 all_modules = PySys_GetObject("modules");
Mark Hammondedd07732003-07-15 23:03:55 +0000103 if (all_modules) {
104 warnings_module = PyDict_GetItemString(all_modules, "warnings");
105 /* We keep a ref in the global */
106 Py_XINCREF(warnings_module);
107 }
108 PyErr_Restore(typ, val, tb);
109 return warnings_module;
110}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000111
Guido van Rossum25ce5661997-08-02 03:10:38 +0000112static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000113
Thomas Wouters7e474022000-07-16 12:04:32 +0000114/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000115
116int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000117Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000118{
119 return initialized;
120}
121
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122/* Global initializations. Can be undone by Py_Finalize(). Don't
123 call this twice without an intervening Py_Finalize() call. When
124 initializations fail, a fatal error is issued and the function does
125 not return. On return, the first thread and interpreter state have
126 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000127
Guido van Rossum25ce5661997-08-02 03:10:38 +0000128 Locking: you must hold the interpreter lock while calling this.
129 (If the lock has not yet been initialized, that's equivalent to
130 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000131
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000133
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000134static int
135add_flag(int flag, const char *envs)
136{
137 int env = atoi(envs);
138 if (flag < env)
139 flag = env;
140 if (flag < 1)
141 flag = 1;
142 return flag;
143}
144
Guido van Rossuma027efa1997-05-05 20:56:21 +0000145void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000146Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000147{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000148 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000149 PyThreadState *tstate;
150 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000151 char *p;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000152#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
153 char *codeset;
154 char *saved_locale;
155 PyObject *sys_stream, *sys_isatty;
156#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000157 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000158
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000159 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000160 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000161 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000162
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000163 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000164 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000165 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000166 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000167 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000168 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000169
Guido van Rossuma027efa1997-05-05 20:56:21 +0000170 interp = PyInterpreterState_New();
171 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000172 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000173
Guido van Rossuma027efa1997-05-05 20:56:21 +0000174 tstate = PyThreadState_New(interp);
175 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000176 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000177 (void) PyThreadState_Swap(tstate);
178
Guido van Rossum70d893a2001-08-16 08:21:42 +0000179 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000180
Neal Norwitzb2501f42002-12-31 03:42:13 +0000181 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000182 Py_FatalError("Py_Initialize: can't init frames");
183
Neal Norwitzb2501f42002-12-31 03:42:13 +0000184 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000185 Py_FatalError("Py_Initialize: can't init ints");
186
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000187 _PyFloat_Init();
188
Guido van Rossum25ce5661997-08-02 03:10:38 +0000189 interp->modules = PyDict_New();
190 if (interp->modules == NULL)
191 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000193#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000194 /* Init Unicode implementation; relies on the codec registry */
195 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000196#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000197
Barry Warsawf242aa02000-05-25 23:09:49 +0000198 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199 if (bimod == NULL)
200 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000201 interp->builtins = PyModule_GetDict(bimod);
202 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203
204 sysmod = _PySys_Init();
205 if (sysmod == NULL)
206 Py_FatalError("Py_Initialize: can't initialize sys");
207 interp->sysdict = PyModule_GetDict(sysmod);
208 Py_INCREF(interp->sysdict);
209 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000210 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000211 PyDict_SetItemString(interp->sysdict, "modules",
212 interp->modules);
213
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000214 _PyImport_Init();
215
Barry Warsawf242aa02000-05-25 23:09:49 +0000216 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000217 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000218 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000219
Barry Warsaw035574d1997-08-29 22:07:17 +0000220 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000221 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000222
Just van Rossum52e14d62002-12-30 22:08:05 +0000223 _PyImportHooks_Init();
224
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000225 if (install_sigs)
226 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000227
228 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000229 if (!Py_NoSiteFlag)
230 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000231
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000232 /* auto-thread-state API, if available */
233#ifdef WITH_THREAD
234 _PyGILState_Init(interp, tstate);
235#endif /* WITH_THREAD */
236
Mark Hammondedd07732003-07-15 23:03:55 +0000237 warnings_module = PyImport_ImportModule("warnings");
238 if (!warnings_module)
239 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000240
241#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
242 /* On Unix, set the file system encoding according to the
243 user's preference, if the CODESET names a well-known
244 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000245 initialized by other means. Also set the encoding of
246 stdin and stdout if these are terminals. */
247
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000248 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000249 setlocale(LC_CTYPE, "");
250 codeset = nl_langinfo(CODESET);
251 if (codeset && *codeset) {
252 PyObject *enc = PyCodec_Encoder(codeset);
253 if (enc) {
254 codeset = strdup(codeset);
255 Py_DECREF(enc);
256 } else {
257 codeset = NULL;
258 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000259 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000260 } else
261 codeset = NULL;
262 setlocale(LC_CTYPE, saved_locale);
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000263 free(saved_locale);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000264
265 if (codeset) {
Michael W. Hudson68debc92003-08-11 12:20:24 +0000266 sys_stream = PySys_GetObject("stdin");
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000267 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
268 if (!sys_isatty)
269 PyErr_Clear();
270 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
271 if (!PyFile_SetEncoding(sys_stream, codeset))
272 Py_FatalError("Cannot set codeset of stdin");
273 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000274 Py_XDECREF(sys_isatty);
275
276 sys_stream = PySys_GetObject("stdout");
277 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
278 if (!sys_isatty)
279 PyErr_Clear();
280 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
281 if (!PyFile_SetEncoding(sys_stream, codeset))
282 Py_FatalError("Cannot set codeset of stdout");
283 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000284 Py_XDECREF(sys_isatty);
285
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286 sys_stream = PySys_GetObject("stderr");
287 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
288 if (!sys_isatty)
289 PyErr_Clear();
290 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
291 if (!PyFile_SetEncoding(sys_stream, codeset))
292 Py_FatalError("Cannot set codeset of stderr");
293 }
294 Py_XDECREF(sys_isatty);
295
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000296 if (!Py_FileSystemDefaultEncoding)
297 Py_FileSystemDefaultEncoding = codeset;
298 else
299 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000300 }
301#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000302}
303
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000304void
305Py_Initialize(void)
306{
307 Py_InitializeEx(1);
308}
309
310
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000311#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000312extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000313#endif
314
Guido van Rossum25ce5661997-08-02 03:10:38 +0000315/* Undo the effect of Py_Initialize().
316
317 Beware: if multiple interpreter and/or thread states exist, these
318 are not wiped out; only the current thread and interpreter state
319 are deleted. But since everything else is deleted, those other
320 interpreter and thread states should no longer be used.
321
322 (XXX We should do better, e.g. wipe out all interpreters and
323 threads.)
324
325 Locking: as above.
326
327*/
328
329void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000330Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000331{
332 PyInterpreterState *interp;
333 PyThreadState *tstate;
334
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000335 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000336 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000337
Tim Peters384fd102001-01-21 03:40:37 +0000338 /* The interpreter is still entirely intact at this point, and the
339 * exit funcs may be relying on that. In particular, if some thread
340 * or exit func is still waiting to do an import, the import machinery
341 * expects Py_IsInitialized() to return true. So don't say the
342 * interpreter is uninitialized until after the exit funcs have run.
343 * Note that Threading.py uses an exit func to do a join on all the
344 * threads created thru it, so this also protects pending imports in
345 * the threads created via Threading.
346 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000347 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000348 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000349
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000350 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000351 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000352 interp = tstate->interp;
353
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000354 /* Disable signal handling */
355 PyOS_FiniInterrupts();
356
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000357 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000358 Py_XDECREF(warnings_module);
359 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000360
Guido van Rossume13ddc92003-04-17 17:29:22 +0000361 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000362 * before all modules are destroyed.
363 * XXX If a __del__ or weakref callback is triggered here, and tries to
364 * XXX import a module, bad things can happen, because Python no
365 * XXX longer believes it's initialized.
366 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
367 * XXX is easy to provoke that way. I've also seen, e.g.,
368 * XXX Exception exceptions.ImportError: 'No module named sha'
369 * XXX in <function callback at 0x008F5718> ignored
370 * XXX but I'm unclear on exactly how that one happens. In any case,
371 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000372 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000373 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000374#ifdef COUNT_ALLOCS
375 /* With COUNT_ALLOCS, it helps to run GC multiple times:
376 each collection might release some types from the type
377 list, so they become garbage. */
378 while (PyGC_Collect() > 0)
379 /* nothing */;
380#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000381
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000382 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000384
Guido van Rossume13ddc92003-04-17 17:29:22 +0000385 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000386 * new-style class definitions, for example.
387 * XXX This is disabled because it caused too many problems. If
388 * XXX a __del__ or weakref callback triggers here, Python code has
389 * XXX a hard time running, because even the sys module has been
390 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
391 * XXX One symptom is a sequence of information-free messages
392 * XXX coming from threads (if a __del__ or callback is invoked,
393 * XXX other threads can execute too, and any exception they encounter
394 * XXX triggers a comedy of errors as subsystem after subsystem
395 * XXX fails to find what it *expects* to find in sys to help report
396 * XXX the exception and consequent unexpected failures). I've also
397 * XXX seen segfaults then, after adding print statements to the
398 * XXX Python code getting called.
399 */
400#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000401 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000402#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000403
Guido van Rossum1707aad1997-12-08 23:43:45 +0000404 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
405 _PyImport_Fini();
406
407 /* Debugging stuff */
408#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000409 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000410#endif
411
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000412 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000413
Tim Peters9cf25ce2003-04-17 15:21:01 +0000414#ifdef Py_TRACE_REFS
415 /* Display all objects still alive -- this can invoke arbitrary
416 * __repr__ overrides, so requires a mostly-intact interpreter.
417 * Alas, a lot of stuff may still be alive now that will be cleaned
418 * up later.
419 */
Tim Peters269b2a62003-04-17 19:52:29 +0000420 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000421 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000422#endif /* Py_TRACE_REFS */
423
Mark Hammond6cb90292003-04-22 11:18:00 +0000424 /* Cleanup auto-thread-state */
425#ifdef WITH_THREAD
426 _PyGILState_Fini();
427#endif /* WITH_THREAD */
428
Guido van Rossumd922fa42003-04-15 14:10:09 +0000429 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000430 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000431
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000432 /* Now we decref the exception classes. After this point nothing
433 can raise an exception. That's okay, because each Fini() method
434 below has been checked to make sure no exceptions are ever
435 raised.
436 */
437
438 _PyExc_Fini();
439
Guido van Rossumd922fa42003-04-15 14:10:09 +0000440 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000441 PyThreadState_Swap(NULL);
442 PyInterpreterState_Delete(interp);
443
Guido van Rossumd922fa42003-04-15 14:10:09 +0000444 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000445 PyMethod_Fini();
446 PyFrame_Fini();
447 PyCFunction_Fini();
448 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000449 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000450 PySet_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000451 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000452 PyInt_Fini();
453 PyFloat_Fini();
454
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000455#ifdef Py_USING_UNICODE
456 /* Cleanup Unicode implementation */
457 _PyUnicode_Fini();
458#endif
459
Guido van Rossumcc283f51997-08-05 02:22:03 +0000460 /* XXX Still allocated:
461 - various static ad-hoc pointers to interned strings
462 - int and float free list blocks
463 - whatever various modules and libraries allocate
464 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000465
466 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000467
Tim Peters269b2a62003-04-17 19:52:29 +0000468#ifdef Py_TRACE_REFS
469 /* Display addresses (& refcnts) of all objects still alive.
470 * An address can be used to find the repr of the object, printed
471 * above by _Py_PrintReferences.
472 */
473 if (Py_GETENV("PYTHONDUMPREFS"))
474 _Py_PrintReferenceAddresses(stderr);
475#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000476#ifdef PYMALLOC_DEBUG
477 if (Py_GETENV("PYTHONMALLOCSTATS"))
478 _PyObject_DebugMallocStats();
479#endif
480
Guido van Rossumcc283f51997-08-05 02:22:03 +0000481 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000482}
483
484/* Create and initialize a new interpreter and thread, and return the
485 new thread. This requires that Py_Initialize() has been called
486 first.
487
488 Unsuccessful initialization yields a NULL pointer. Note that *no*
489 exception information is available even in this case -- the
490 exception information is held in the thread, and there is no
491 thread.
492
493 Locking: as above.
494
495*/
496
497PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000498Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000499{
500 PyInterpreterState *interp;
501 PyThreadState *tstate, *save_tstate;
502 PyObject *bimod, *sysmod;
503
504 if (!initialized)
505 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
506
507 interp = PyInterpreterState_New();
508 if (interp == NULL)
509 return NULL;
510
511 tstate = PyThreadState_New(interp);
512 if (tstate == NULL) {
513 PyInterpreterState_Delete(interp);
514 return NULL;
515 }
516
517 save_tstate = PyThreadState_Swap(tstate);
518
519 /* XXX The following is lax in error checking */
520
521 interp->modules = PyDict_New();
522
523 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
524 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000525 interp->builtins = PyModule_GetDict(bimod);
526 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000527 }
528 sysmod = _PyImport_FindExtension("sys", "sys");
529 if (bimod != NULL && sysmod != NULL) {
530 interp->sysdict = PyModule_GetDict(sysmod);
531 Py_INCREF(interp->sysdict);
532 PySys_SetPath(Py_GetPath());
533 PyDict_SetItemString(interp->sysdict, "modules",
534 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000535 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000536 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000537 if (!Py_NoSiteFlag)
538 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000539 }
540
541 if (!PyErr_Occurred())
542 return tstate;
543
544 /* Oops, it didn't work. Undo it all. */
545
546 PyErr_Print();
547 PyThreadState_Clear(tstate);
548 PyThreadState_Swap(save_tstate);
549 PyThreadState_Delete(tstate);
550 PyInterpreterState_Delete(interp);
551
552 return NULL;
553}
554
555/* Delete an interpreter and its last thread. This requires that the
556 given thread state is current, that the thread has no remaining
557 frames, and that it is its interpreter's only remaining thread.
558 It is a fatal error to violate these constraints.
559
560 (Py_Finalize() doesn't have these constraints -- it zaps
561 everything, regardless.)
562
563 Locking: as above.
564
565*/
566
567void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000568Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569{
570 PyInterpreterState *interp = tstate->interp;
571
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000572 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573 Py_FatalError("Py_EndInterpreter: thread is not current");
574 if (tstate->frame != NULL)
575 Py_FatalError("Py_EndInterpreter: thread still has a frame");
576 if (tstate != interp->tstate_head || tstate->next != NULL)
577 Py_FatalError("Py_EndInterpreter: not the last thread");
578
579 PyImport_Cleanup();
580 PyInterpreterState_Clear(interp);
581 PyThreadState_Swap(NULL);
582 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000583}
584
585static char *progname = "python";
586
587void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000588Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000589{
590 if (pn && *pn)
591 progname = pn;
592}
593
594char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000595Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000596{
597 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000598}
599
Guido van Rossuma61691e1998-02-06 22:27:24 +0000600static char *default_home = NULL;
601
602void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000603Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000604{
605 default_home = home;
606}
607
608char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000609Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000610{
611 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000612 if (home == NULL && !Py_IgnoreEnvironmentFlag)
613 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000614 return home;
615}
616
Guido van Rossum6135a871995-01-09 17:53:26 +0000617/* Create __main__ module */
618
619static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000620initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000621{
Guido van Rossum82598051997-03-05 00:20:32 +0000622 PyObject *m, *d;
623 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000624 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000625 Py_FatalError("can't create __main__ module");
626 d = PyModule_GetDict(m);
627 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000628 PyObject *bimod = PyImport_ImportModule("__builtin__");
629 if (bimod == NULL ||
630 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000631 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000632 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000633 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000634}
635
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000636/* Import the site module (not into __main__ though) */
637
638static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000639initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000640{
641 PyObject *m, *f;
642 m = PyImport_ImportModule("site");
643 if (m == NULL) {
644 f = PySys_GetObject("stderr");
645 if (Py_VerboseFlag) {
646 PyFile_WriteString(
647 "'import site' failed; traceback:\n", f);
648 PyErr_Print();
649 }
650 else {
651 PyFile_WriteString(
652 "'import site' failed; use -v for traceback\n", f);
653 PyErr_Clear();
654 }
655 }
656 else {
657 Py_DECREF(m);
658 }
659}
660
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000661/* Parse input from a file and execute it */
662
663int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000664PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000665 PyCompilerFlags *flags)
666{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000667 if (filename == NULL)
668 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000669 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000670 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000671 if (closeit)
672 fclose(fp);
673 return err;
674 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000675 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000676 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000677}
678
679int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000680PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000681{
Guido van Rossum82598051997-03-05 00:20:32 +0000682 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000683 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000684 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000685
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000686 if (flags == NULL) {
687 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000688 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000689 }
Guido van Rossum82598051997-03-05 00:20:32 +0000690 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000691 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000692 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
693 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000694 }
Guido van Rossum82598051997-03-05 00:20:32 +0000695 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000696 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000697 PySys_SetObject("ps2", v = PyString_FromString("... "));
698 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000699 }
700 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000701 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000702 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000703 if (ret == E_EOF)
704 return 0;
705 /*
706 if (ret == E_NOMEM)
707 return -1;
708 */
709 }
710}
711
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000712/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000713#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000714 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +0000715 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000716
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000717int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000718PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000719{
Guido van Rossum82598051997-03-05 00:20:32 +0000720 PyObject *m, *d, *v, *w;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000721 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000722 PyArena *arena;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000723 char *ps1 = "", *ps2 = "";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000724 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000725
Guido van Rossum82598051997-03-05 00:20:32 +0000726 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000727 if (v != NULL) {
728 v = PyObject_Str(v);
729 if (v == NULL)
730 PyErr_Clear();
731 else if (PyString_Check(v))
732 ps1 = PyString_AsString(v);
733 }
Guido van Rossum82598051997-03-05 00:20:32 +0000734 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000735 if (w != NULL) {
736 w = PyObject_Str(w);
737 if (w == NULL)
738 PyErr_Clear();
739 else if (PyString_Check(w))
740 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000741 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000742 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000743 if (arena == NULL) {
744 Py_XDECREF(v);
745 Py_XDECREF(w);
746 return -1;
747 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000748 mod = PyParser_ASTFromFile(fp, filename,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000749 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000750 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000751 Py_XDECREF(v);
752 Py_XDECREF(w);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000754 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755 if (errcode == E_EOF) {
756 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000757 return E_EOF;
758 }
Guido van Rossum82598051997-03-05 00:20:32 +0000759 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000760 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000761 }
Guido van Rossum82598051997-03-05 00:20:32 +0000762 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000763 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000764 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000765 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000766 }
Guido van Rossum82598051997-03-05 00:20:32 +0000767 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000768 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +0000769 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000770 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000771 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000772 return -1;
773 }
Guido van Rossum82598051997-03-05 00:20:32 +0000774 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000775 if (Py_FlushLine())
776 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000777 return 0;
778}
779
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000780/* Check whether a file maybe a pyc file: Look at the extension,
781 the file type, and, if we may close it, at the first few bytes. */
782
783static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000784maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000785{
786 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
787 return 1;
788
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000789 /* Only look into the file if we are allowed to close it, since
790 it then should also be seekable. */
791 if (closeit) {
792 /* Read only two bytes of the magic. If the file was opened in
793 text mode, the bytes 3 and 4 of the magic (\r\n) might not
794 be read as they are on disk. */
795 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
796 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000797 /* Mess: In case of -x, the stream is NOT at its start now,
798 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000799 which makes the current stream position formally undefined,
800 and a x-platform nightmare.
801 Unfortunately, we have no direct way to know whether -x
802 was specified. So we use a terrible hack: if the current
803 stream position is not 0, we assume -x was specified, and
804 give up. Bug 132850 on SourceForge spells out the
805 hopelessness of trying anything else (fseek and ftell
806 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000807 */
Tim Peters3e876562001-02-11 04:35:39 +0000808 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000809 if (ftell(fp) == 0) {
810 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000811 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000812 ispyc = 1;
813 rewind(fp);
814 }
Tim Peters3e876562001-02-11 04:35:39 +0000815 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000816 }
817 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000818}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000819
Guido van Rossum0df002c2000-08-27 19:21:52 +0000820int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000821PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000822 PyCompilerFlags *flags)
823{
Guido van Rossum82598051997-03-05 00:20:32 +0000824 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000825 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000826
Guido van Rossum82598051997-03-05 00:20:32 +0000827 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000828 if (m == NULL)
829 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000830 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000831 if (PyDict_GetItemString(d, "__file__") == NULL) {
832 PyObject *f = PyString_FromString(filename);
833 if (f == NULL)
834 return -1;
835 if (PyDict_SetItemString(d, "__file__", f) < 0) {
836 Py_DECREF(f);
837 return -1;
838 }
839 Py_DECREF(f);
840 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000841 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000842 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000843 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000844 if (closeit)
845 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000846 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000847 fprintf(stderr, "python: Can't reopen .pyc file\n");
848 return -1;
849 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000850 /* Turn on optimization if a .pyo file is given */
851 if (strcmp(ext, ".pyo") == 0)
852 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000853 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000854 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000855 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000856 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000857 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000858 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000859 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000860 return -1;
861 }
Guido van Rossum82598051997-03-05 00:20:32 +0000862 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000863 if (Py_FlushLine())
864 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000865 return 0;
866}
867
868int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000869PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000870{
Guido van Rossum82598051997-03-05 00:20:32 +0000871 PyObject *m, *d, *v;
872 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000873 if (m == NULL)
874 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000875 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000876 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000877 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000878 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000879 return -1;
880 }
Guido van Rossum82598051997-03-05 00:20:32 +0000881 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000882 if (Py_FlushLine())
883 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000884 return 0;
885}
886
Barry Warsaw035574d1997-08-29 22:07:17 +0000887static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000888parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
889 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000890{
891 long hold;
892 PyObject *v;
893
894 /* old style errors */
895 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000896 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +0000897 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000898
899 /* new style errors. `err' is an instance */
900
901 if (! (v = PyObject_GetAttrString(err, "msg")))
902 goto finally;
903 *message = v;
904
905 if (!(v = PyObject_GetAttrString(err, "filename")))
906 goto finally;
907 if (v == Py_None)
908 *filename = NULL;
909 else if (! (*filename = PyString_AsString(v)))
910 goto finally;
911
912 Py_DECREF(v);
913 if (!(v = PyObject_GetAttrString(err, "lineno")))
914 goto finally;
915 hold = PyInt_AsLong(v);
916 Py_DECREF(v);
917 v = NULL;
918 if (hold < 0 && PyErr_Occurred())
919 goto finally;
920 *lineno = (int)hold;
921
922 if (!(v = PyObject_GetAttrString(err, "offset")))
923 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000924 if (v == Py_None) {
925 *offset = -1;
926 Py_DECREF(v);
927 v = NULL;
928 } else {
929 hold = PyInt_AsLong(v);
930 Py_DECREF(v);
931 v = NULL;
932 if (hold < 0 && PyErr_Occurred())
933 goto finally;
934 *offset = (int)hold;
935 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000936
937 if (!(v = PyObject_GetAttrString(err, "text")))
938 goto finally;
939 if (v == Py_None)
940 *text = NULL;
941 else if (! (*text = PyString_AsString(v)))
942 goto finally;
943 Py_DECREF(v);
944 return 1;
945
946finally:
947 Py_XDECREF(v);
948 return 0;
949}
950
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000951void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000952PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000953{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000954 PyErr_PrintEx(1);
955}
956
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000957static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000958print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000959{
960 char *nl;
961 if (offset >= 0) {
962 if (offset > 0 && offset == (int)strlen(text))
963 offset--;
964 for (;;) {
965 nl = strchr(text, '\n');
966 if (nl == NULL || nl-text >= offset)
967 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000968 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000969 text = nl+1;
970 }
971 while (*text == ' ' || *text == '\t') {
972 text++;
973 offset--;
974 }
975 }
976 PyFile_WriteString(" ", f);
977 PyFile_WriteString(text, f);
978 if (*text == '\0' || text[strlen(text)-1] != '\n')
979 PyFile_WriteString("\n", f);
980 if (offset == -1)
981 return;
982 PyFile_WriteString(" ", f);
983 offset--;
984 while (offset > 0) {
985 PyFile_WriteString(" ", f);
986 offset--;
987 }
988 PyFile_WriteString("^\n", f);
989}
990
Guido van Rossum66e8e862001-03-23 17:54:43 +0000991static void
992handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000993{
Neal Norwitz9589ee22006-03-04 19:01:22 +0000994 PyObject *exception, *value, *tb;
995 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +0000996
Guido van Rossum66e8e862001-03-23 17:54:43 +0000997 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000998 if (Py_FlushLine())
999 PyErr_Clear();
1000 fflush(stdout);
1001 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001002 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001003 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001004 /* The error code should be in the `code' attribute. */
1005 PyObject *code = PyObject_GetAttrString(value, "code");
1006 if (code) {
1007 Py_DECREF(value);
1008 value = code;
1009 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001010 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001011 }
1012 /* If we failed to dig out the 'code' attribute,
1013 just let the else clause below print the error. */
1014 }
1015 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +00001016 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001017 else {
1018 PyObject_Print(value, stderr, Py_PRINT_RAW);
1019 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001020 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001021 }
Tim Peterscf615b52003-04-19 18:47:02 +00001022 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001023 /* Restore and clear the exception info, in order to properly decref
1024 * the exception, value, and traceback. If we just exit instead,
1025 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1026 * some finalizers from running.
1027 */
Tim Peterscf615b52003-04-19 18:47:02 +00001028 PyErr_Restore(exception, value, tb);
1029 PyErr_Clear();
1030 Py_Exit(exitcode);
1031 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001032}
1033
1034void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001035PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001036{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001037 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001038
1039 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1040 handle_system_exit();
1041 }
Guido van Rossum82598051997-03-05 00:20:32 +00001042 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001043 if (exception == NULL)
1044 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001045 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001046 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001047 return;
Guido van Rossum9d785502006-03-07 18:31:44 +00001048 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001049 if (set_sys_last_vars) {
1050 PySys_SetObject("last_type", exception);
1051 PySys_SetObject("last_value", v);
1052 PySys_SetObject("last_traceback", tb);
1053 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001054 hook = PySys_GetObject("excepthook");
1055 if (hook) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001056 PyObject *args = PyTuple_Pack(3,
Guido van Rossum9d785502006-03-07 18:31:44 +00001057 exception, v, tb ? tb : Py_None);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001058 PyObject *result = PyEval_CallObject(hook, args);
1059 if (result == NULL) {
1060 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001061 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1062 handle_system_exit();
1063 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001064 PyErr_Fetch(&exception2, &v2, &tb2);
1065 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001066 /* It should not be possible for exception2 or v2
1067 to be NULL. However PyErr_Display() can't
1068 tolerate NULLs, so just be safe. */
1069 if (exception2 == NULL) {
1070 exception2 = Py_None;
1071 Py_INCREF(exception2);
1072 }
1073 if (v2 == NULL) {
1074 v2 = Py_None;
1075 Py_INCREF(v2);
1076 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001077 if (Py_FlushLine())
1078 PyErr_Clear();
1079 fflush(stdout);
1080 PySys_WriteStderr("Error in sys.excepthook:\n");
1081 PyErr_Display(exception2, v2, tb2);
1082 PySys_WriteStderr("\nOriginal exception was:\n");
1083 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001084 Py_DECREF(exception2);
1085 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001086 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001087 }
1088 Py_XDECREF(result);
1089 Py_XDECREF(args);
1090 } else {
1091 PySys_WriteStderr("sys.excepthook is missing\n");
1092 PyErr_Display(exception, v, tb);
1093 }
1094 Py_XDECREF(exception);
1095 Py_XDECREF(v);
1096 Py_XDECREF(tb);
1097}
1098
Thomas Wouters477c8d52006-05-27 19:21:47 +00001099void
1100PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001101{
1102 int err = 0;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001103 PyObject *f = PySys_GetObject("stderr");
Armin Rigo5d2c6832004-03-22 20:16:58 +00001104 Py_INCREF(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001105 if (f == NULL)
1106 fprintf(stderr, "lost sys.stderr\n");
1107 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001108 if (Py_FlushLine())
1109 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001110 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001111 if (tb && tb != Py_None)
1112 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001113 if (err == 0 &&
Armin Rigo5d2c6832004-03-22 20:16:58 +00001114 PyObject_HasAttrString(value, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001115 {
Guido van Rossum82598051997-03-05 00:20:32 +00001116 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001117 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001118 int lineno, offset;
Armin Rigo5d2c6832004-03-22 20:16:58 +00001119 if (!parse_syntax_error(value, &message, &filename,
Barry Warsaw035574d1997-08-29 22:07:17 +00001120 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001121 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001122 else {
1123 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001124 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001125 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001126 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001127 else
Guido van Rossum82598051997-03-05 00:20:32 +00001128 PyFile_WriteString(filename, f);
1129 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001130 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001131 PyFile_WriteString(buf, f);
1132 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001133 if (text != NULL)
1134 print_error_text(f, offset, text);
Armin Rigo5d2c6832004-03-22 20:16:58 +00001135 Py_DECREF(value);
1136 value = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001137 /* Can't be bothered to check all those
1138 PyFile_WriteString() calls */
1139 if (PyErr_Occurred())
1140 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001141 }
1142 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001143 if (err) {
1144 /* Don't do anything else */
1145 }
Brett Cannonbf364092006-03-01 04:25:17 +00001146 else if (PyExceptionClass_Check(exception)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001147 PyObject* moduleName;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001148 char* className = PyExceptionClass_Name(exception);
1149 if (className != NULL) {
1150 char *dot = strrchr(className, '.');
1151 if (dot != NULL)
1152 className = dot+1;
1153 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001154
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001155 moduleName = PyObject_GetAttrString(exception, "__module__");
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001156 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001157 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001158 else {
1159 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001160 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001161 {
1162 err = PyFile_WriteString(modstr, f);
1163 err += PyFile_WriteString(".", f);
1164 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001165 Py_DECREF(moduleName);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001166 }
1167 if (err == 0) {
1168 if (className == NULL)
1169 err = PyFile_WriteString("<unknown>", f);
1170 else
Brett Cannonbf364092006-03-01 04:25:17 +00001171 err = PyFile_WriteString(className, f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001172 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001173 }
1174 else
1175 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
Brett Cannon2e63b732006-03-02 18:34:57 +00001176 if (err == 0 && (value != Py_None)) {
1177 PyObject *s = PyObject_Str(value);
1178 /* only print colon if the str() of the
1179 object is not the empty string
1180 */
1181 if (s == NULL)
1182 err = -1;
1183 else if (!PyString_Check(s) ||
1184 PyString_GET_SIZE(s) != 0)
1185 err = PyFile_WriteString(": ", f);
1186 if (err == 0)
1187 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1188 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001189 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001190 if (err == 0)
1191 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001192 }
Armin Rigo5d2c6832004-03-22 20:16:58 +00001193 Py_DECREF(value);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001194 /* If an error happened here, don't show it.
1195 XXX This is wrong, but too many callers rely on this behavior. */
1196 if (err != 0)
1197 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001198}
1199
Guido van Rossum82598051997-03-05 00:20:32 +00001200PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001201PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001203{
Neal Norwitze92fba02006-03-04 18:52:26 +00001204 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001205 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001206 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001207 if (arena == NULL)
1208 return NULL;
1209
1210 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001211 if (mod != NULL)
1212 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001213 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001215}
1216
1217PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001218PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001219 PyObject *locals, int closeit, PyCompilerFlags *flags)
1220{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001222 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001223 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001224 if (arena == NULL)
1225 return NULL;
1226
1227 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1228 flags, NULL, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001229 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001230 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001232 }
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001233 if (closeit)
1234 fclose(fp);
Neal Norwitze92fba02006-03-04 18:52:26 +00001235 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001236 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001237 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001238}
1239
Guido van Rossum82598051997-03-05 00:20:32 +00001240static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001242 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001243{
Guido van Rossum82598051997-03-05 00:20:32 +00001244 PyCodeObject *co;
1245 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001246 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001247 if (co == NULL)
1248 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001249 v = PyEval_EvalCode(co, globals, locals);
1250 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001251 return v;
1252}
1253
Guido van Rossum82598051997-03-05 00:20:32 +00001254static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001255run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001257{
Guido van Rossum82598051997-03-05 00:20:32 +00001258 PyCodeObject *co;
1259 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001260 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001261 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001262
Guido van Rossum82598051997-03-05 00:20:32 +00001263 magic = PyMarshal_ReadLongFromFile(fp);
1264 if (magic != PyImport_GetMagicNumber()) {
1265 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001266 "Bad magic number in .pyc file");
1267 return NULL;
1268 }
Guido van Rossum82598051997-03-05 00:20:32 +00001269 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001270 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001271 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001272 if (v == NULL || !PyCode_Check(v)) {
1273 Py_XDECREF(v);
1274 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001275 "Bad code object in .pyc file");
1276 return NULL;
1277 }
Guido van Rossum82598051997-03-05 00:20:32 +00001278 co = (PyCodeObject *)v;
1279 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001280 if (v && flags)
1281 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001282 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001283 return v;
1284}
1285
Guido van Rossum82598051997-03-05 00:20:32 +00001286PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001287Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001288 PyCompilerFlags *flags)
1289{
Guido van Rossum82598051997-03-05 00:20:32 +00001290 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001291 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001292 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001293 if (arena == NULL)
1294 return NULL;
1295
1296 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001297 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001298 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001299 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001300 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001301 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001302 PyObject *result = PyAST_mod2obj(mod);
1303 PyArena_Free(arena);
1304 return result;
1305 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001306 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001307 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001308 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001309}
1310
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001311struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001312Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001313{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001314 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001315 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001316 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001317 if (arena == NULL)
1318 return NULL;
1319
1320 mod = PyParser_ASTFromString(str, filename, start, NULL, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001321 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001322 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001323 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001324 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001326 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001327 return st;
1328}
1329
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330/* Preferred access to parser is through AST. */
1331mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001332PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001333 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335 mod_ty mod;
1336 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001337 node *n = PyParser_ParseStringFlagsFilename(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001338 &_PyParser_Grammar, start, &err,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001339 PARSER_FLAGS(flags));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340 if (n) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001341 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 PyNode_Free(n);
1343 return mod;
1344 }
1345 else {
1346 err_input(&err);
1347 return NULL;
1348 }
1349}
1350
1351mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001352PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001353 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001354 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356 mod_ty mod;
1357 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001358 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1359 start, ps1, ps2, &err, PARSER_FLAGS(flags));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360 if (n) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001361 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362 PyNode_Free(n);
1363 return mod;
1364 }
1365 else {
1366 err_input(&err);
1367 if (errcode)
1368 *errcode = err.error;
1369 return NULL;
1370 }
1371}
1372
Guido van Rossuma110aa61994-08-29 12:50:44 +00001373/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001374
Guido van Rossuma110aa61994-08-29 12:50:44 +00001375node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001376PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001377{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001378 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001379 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1380 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001381 if (n == NULL)
1382 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001383
Guido van Rossuma110aa61994-08-29 12:50:44 +00001384 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001385}
1386
Guido van Rossuma110aa61994-08-29 12:50:44 +00001387/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001388
Guido van Rossuma110aa61994-08-29 12:50:44 +00001389node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001390PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001391{
Tim Petersfe2127d2001-07-16 05:37:24 +00001392 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001393 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1394 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001395 if (n == NULL)
1396 err_input(&err);
1397 return n;
1398}
1399
1400node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001401PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001402 int start, int flags)
1403{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001404 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001405 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1406 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001407 if (n == NULL)
1408 err_input(&err);
1409 return n;
1410}
1411
1412node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001413PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001414{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001415 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001416}
1417
Guido van Rossum66ebd912003-04-17 16:02:26 +00001418/* May want to move a more generalized form of this to parsetok.c or
1419 even parser modules. */
1420
1421void
1422PyParser_SetError(perrdetail *err)
1423{
1424 err_input(err);
1425}
1426
Guido van Rossuma110aa61994-08-29 12:50:44 +00001427/* Set the error appropriate to the given input error code (see errcode.h) */
1428
1429static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001430err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001431{
Fred Drake85f36392000-07-11 17:53:00 +00001432 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001433 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001434 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001435 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001436 switch (err->error) {
1437 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001438 errtype = PyExc_IndentationError;
1439 if (err->expected == INDENT)
1440 msg = "expected an indented block";
1441 else if (err->token == INDENT)
1442 msg = "unexpected indent";
1443 else if (err->token == DEDENT)
1444 msg = "unexpected unindent";
1445 else {
1446 errtype = PyExc_SyntaxError;
1447 msg = "invalid syntax";
1448 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001449 break;
1450 case E_TOKEN:
1451 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001452 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001453 case E_EOFS:
1454 msg = "EOF while scanning triple-quoted string";
1455 break;
1456 case E_EOLS:
1457 msg = "EOL while scanning single-quoted string";
1458 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001459 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001460 if (!PyErr_Occurred())
1461 PyErr_SetNone(PyExc_KeyboardInterrupt);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001462 return;
1463 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001464 PyErr_NoMemory();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001465 return;
1466 case E_EOF:
1467 msg = "unexpected EOF while parsing";
1468 break;
Fred Drake85f36392000-07-11 17:53:00 +00001469 case E_TABSPACE:
1470 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001471 msg = "inconsistent use of tabs and spaces in indentation";
1472 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001473 case E_OVERFLOW:
1474 msg = "expression too long";
1475 break;
Fred Drake85f36392000-07-11 17:53:00 +00001476 case E_DEDENT:
1477 errtype = PyExc_IndentationError;
1478 msg = "unindent does not match any outer indentation level";
1479 break;
1480 case E_TOODEEP:
1481 errtype = PyExc_IndentationError;
1482 msg = "too many levels of indentation";
1483 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001484 case E_DECODE: {
1485 PyObject *type, *value, *tb;
1486 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001487 if (value != NULL) {
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001488 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001489 if (u != NULL) {
1490 msg = PyString_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001491 }
1492 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001493 if (msg == NULL)
1494 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001495 Py_XDECREF(type);
1496 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001497 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001498 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001499 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001500 case E_LINECONT:
1501 msg = "unexpected character after line continuation character";
1502 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001503 default:
1504 fprintf(stderr, "error=%d\n", err->error);
1505 msg = "unknown parsing error";
1506 break;
1507 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508 v = Py_BuildValue("(ziiz)", err->filename,
1509 err->lineno, err->offset, err->text);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001510 if (err->text != NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001511 PyObject_FREE(err->text);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512 err->text = NULL;
1513 }
1514 w = NULL;
1515 if (v != NULL)
1516 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001517 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001518 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001519 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001520 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001521}
1522
1523/* Print fatal error message and abort */
1524
1525void
Tim Peters7c321a82002-07-09 02:57:01 +00001526Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001527{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001528 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001529#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001530 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001531 OutputDebugString(msg);
1532 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001533#ifdef _DEBUG
1534 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001535#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001536#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001537 abort();
1538}
1539
1540/* Clean up and exit */
1541
Guido van Rossuma110aa61994-08-29 12:50:44 +00001542#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001543#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001544#endif
1545
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001546#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001547static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001548static int nexitfuncs = 0;
1549
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001550int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001551{
1552 if (nexitfuncs >= NEXITFUNCS)
1553 return -1;
1554 exitfuncs[nexitfuncs++] = func;
1555 return 0;
1556}
1557
Guido van Rossumcc283f51997-08-05 02:22:03 +00001558static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001559call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001560{
Guido van Rossum82598051997-03-05 00:20:32 +00001561 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001562
1563 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001564 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001565 Py_INCREF(exitfunc);
1566 PySys_SetObject("exitfunc", (PyObject *)NULL);
1567 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001568 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001569 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1570 PySys_WriteStderr("Error in sys.exitfunc:\n");
1571 }
Guido van Rossum82598051997-03-05 00:20:32 +00001572 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001573 }
Guido van Rossum82598051997-03-05 00:20:32 +00001574 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001575 }
1576
Guido van Rossum0829c751998-02-28 04:31:39 +00001577 if (Py_FlushLine())
1578 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001579}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001580
Guido van Rossumcc283f51997-08-05 02:22:03 +00001581static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001582call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001583{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001584 while (nexitfuncs > 0)
1585 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001586
1587 fflush(stdout);
1588 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001589}
1590
1591void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001592Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001593{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001594 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001595
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001596 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001597}
1598
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001599static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001600initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001601{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001602#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001603 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001604#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001605#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001606 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001607#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001608#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001609 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001610#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001611 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001612}
1613
Guido van Rossum7433b121997-02-14 19:45:36 +00001614
1615/*
1616 * The file descriptor fd is considered ``interactive'' if either
1617 * a) isatty(fd) is TRUE, or
1618 * b) the -i flag was given, and the filename associated with
1619 * the descriptor is NULL or "<stdin>" or "???".
1620 */
1621int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001622Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001623{
1624 if (isatty((int)fileno(fp)))
1625 return 1;
1626 if (!Py_InteractiveFlag)
1627 return 0;
1628 return (filename == NULL) ||
1629 (strcmp(filename, "<stdin>") == 0) ||
1630 (strcmp(filename, "???") == 0);
1631}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001632
1633
Tim Petersd08e3822003-04-17 15:24:21 +00001634#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001635#if defined(WIN32) && defined(_MSC_VER)
1636
1637/* Stack checking for Microsoft C */
1638
1639#include <malloc.h>
1640#include <excpt.h>
1641
Fred Drakee8de31c2000-08-31 05:38:39 +00001642/*
1643 * Return non-zero when we run out of memory on the stack; zero otherwise.
1644 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001645int
Fred Drake399739f2000-08-31 05:52:44 +00001646PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001647{
1648 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001649 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001650 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001651 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001652 return 0;
1653 } __except (EXCEPTION_EXECUTE_HANDLER) {
1654 /* just ignore all errors */
1655 }
1656 return 1;
1657}
1658
1659#endif /* WIN32 && _MSC_VER */
1660
1661/* Alternate implementations can be added here... */
1662
1663#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001664
1665
1666/* Wrappers around sigaction() or signal(). */
1667
1668PyOS_sighandler_t
1669PyOS_getsig(int sig)
1670{
1671#ifdef HAVE_SIGACTION
1672 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001673 if (sigaction(sig, NULL, &context) == -1)
1674 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001675 return context.sa_handler;
1676#else
1677 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001678/* Special signal handling for the secure CRT in Visual Studio 2005 */
1679#if defined(_MSC_VER) && _MSC_VER >= 1400
1680 switch (sig) {
1681 /* Only these signals are valid */
1682 case SIGINT:
1683 case SIGILL:
1684 case SIGFPE:
1685 case SIGSEGV:
1686 case SIGTERM:
1687 case SIGBREAK:
1688 case SIGABRT:
1689 break;
1690 /* Don't call signal() with other values or it will assert */
1691 default:
1692 return SIG_ERR;
1693 }
1694#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00001695 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001696 if (handler != SIG_ERR)
1697 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00001698 return handler;
1699#endif
1700}
1701
1702PyOS_sighandler_t
1703PyOS_setsig(int sig, PyOS_sighandler_t handler)
1704{
1705#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001706 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00001707 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001708 sigemptyset(&context.sa_mask);
1709 context.sa_flags = 0;
1710 if (sigaction(sig, &context, &ocontext) == -1)
1711 return SIG_ERR;
1712 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001713#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001714 PyOS_sighandler_t oldhandler;
1715 oldhandler = signal(sig, handler);
1716#ifdef HAVE_SIGINTERRUPT
1717 siginterrupt(sig, 1);
1718#endif
1719 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001720#endif
1721}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722
1723/* Deprecated C API functions still provided for binary compatiblity */
1724
1725#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001726PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001727PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1728{
1729 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1730}
1731
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001732#undef PyParser_SimpleParseString
1733PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001734PyParser_SimpleParseString(const char *str, int start)
1735{
1736 return PyParser_SimpleParseStringFlags(str, start, 0);
1737}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001738
1739#undef PyRun_AnyFile
1740PyAPI_FUNC(int)
1741PyRun_AnyFile(FILE *fp, const char *name)
1742{
1743 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
1744}
1745
1746#undef PyRun_AnyFileEx
1747PyAPI_FUNC(int)
1748PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1749{
1750 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
1751}
1752
1753#undef PyRun_AnyFileFlags
1754PyAPI_FUNC(int)
1755PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1756{
1757 return PyRun_AnyFileExFlags(fp, name, 0, flags);
1758}
1759
1760#undef PyRun_File
1761PyAPI_FUNC(PyObject *)
1762PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1763{
1764 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
1765}
1766
1767#undef PyRun_FileEx
1768PyAPI_FUNC(PyObject *)
1769PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1770{
1771 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
1772}
1773
1774#undef PyRun_FileFlags
1775PyAPI_FUNC(PyObject *)
1776PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
1777 PyCompilerFlags *flags)
1778{
1779 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
1780}
1781
1782#undef PyRun_SimpleFile
1783PyAPI_FUNC(int)
1784PyRun_SimpleFile(FILE *f, const char *p)
1785{
1786 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
1787}
1788
1789#undef PyRun_SimpleFileEx
1790PyAPI_FUNC(int)
1791PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1792{
1793 return PyRun_SimpleFileExFlags(f, p, c, NULL);
1794}
1795
1796
1797#undef PyRun_String
1798PyAPI_FUNC(PyObject *)
1799PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1800{
1801 return PyRun_StringFlags(str, s, g, l, NULL);
1802}
1803
1804#undef PyRun_SimpleString
1805PyAPI_FUNC(int)
1806PyRun_SimpleString(const char *s)
1807{
1808 return PyRun_SimpleStringFlags(s, NULL);
1809}
1810
1811#undef Py_CompileString
1812PyAPI_FUNC(PyObject *)
1813Py_CompileString(const char *str, const char *p, int s)
1814{
1815 return Py_CompileStringFlags(str, p, s, NULL);
1816}
1817
1818#undef PyRun_InteractiveOne
1819PyAPI_FUNC(int)
1820PyRun_InteractiveOne(FILE *f, const char *p)
1821{
1822 return PyRun_InteractiveOneFlags(f, p, NULL);
1823}
1824
1825#undef PyRun_InteractiveLoop
1826PyAPI_FUNC(int)
1827PyRun_InteractiveLoop(FILE *f, const char *p)
1828{
1829 return PyRun_InteractiveLoopFlags(f, p, NULL);
1830}
1831
1832#ifdef __cplusplus
1833}
1834#endif
1835