blob: ad837d28f628f940efcdadb34dc0def26abad2fa [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"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000016#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000017#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000019#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020
Martin v. Löwis73d538b2003-03-05 15:13:47 +000021#ifdef HAVE_LANGINFO_H
22#include <locale.h>
23#include <langinfo.h>
24#endif
25
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000026#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000027#undef BYTE
28#include "windows.h"
29#endif
30
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000031extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000032
Guido van Rossum82598051997-03-05 00:20:32 +000033extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000034
Guido van Rossumb73cc041993-11-01 16:28:59 +000035/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000036static void initmain(void);
37static void initsite(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000038static PyObject *run_err_mod(mod_ty, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000039 PyCompilerFlags *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000040static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000041 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000042static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000043 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000044static void err_input(perrdetail *);
45static void initsigs(void);
46static void call_sys_exitfunc(void);
47static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000048extern void _PyUnicode_Init(void);
49extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000050
Mark Hammond8d98d2c2003-04-19 15:41:53 +000051#ifdef WITH_THREAD
52extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
53extern void _PyGILState_Fini(void);
54#endif /* WITH_THREAD */
55
Guido van Rossum82598051997-03-05 00:20:32 +000056int Py_DebugFlag; /* Needed by parser.c */
57int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000058int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000059int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000060int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000061int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000062int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000063int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000064/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
65 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
66 true divisions (which they will be in 2.3). */
67int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000068
Mark Hammonda43fd0c2003-02-19 00:33:33 +000069/* Reference to 'warnings' module, to avoid importing it
Mark Hammondedd07732003-07-15 23:03:55 +000070 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000071*/
Mark Hammondedd07732003-07-15 23:03:55 +000072static PyObject *warnings_module = NULL;
73
74/* Returns a borrowed reference to the 'warnings' module, or NULL.
75 If the module is returned, it is guaranteed to have been obtained
76 without acquiring the import lock
77*/
Martin v. Löwisa2c17c52003-08-09 09:47:11 +000078PyObject *PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000079{
80 PyObject *typ, *val, *tb;
81 PyObject *all_modules;
82 /* If we managed to get the module at init time, just use it */
83 if (warnings_module)
84 return warnings_module;
85 /* If it wasn't available at init time, it may be available
86 now in sys.modules (common scenario is frozen apps: import
87 at init time fails, but the frozen init code sets up sys.path
88 correctly, then does an implicit import of warnings for us
89 */
90 /* Save and restore any exceptions */
91 PyErr_Fetch(&typ, &val, &tb);
92
Mark Hammond5f4e8ca2003-07-16 01:54:38 +000093 all_modules = PySys_GetObject("modules");
Mark Hammondedd07732003-07-15 23:03:55 +000094 if (all_modules) {
95 warnings_module = PyDict_GetItemString(all_modules, "warnings");
96 /* We keep a ref in the global */
97 Py_XINCREF(warnings_module);
98 }
99 PyErr_Restore(typ, val, tb);
100 return warnings_module;
101}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000102
Guido van Rossum25ce5661997-08-02 03:10:38 +0000103static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000104
Thomas Wouters7e474022000-07-16 12:04:32 +0000105/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106
107int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000108Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109{
110 return initialized;
111}
112
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113/* Global initializations. Can be undone by Py_Finalize(). Don't
114 call this twice without an intervening Py_Finalize() call. When
115 initializations fail, a fatal error is issued and the function does
116 not return. On return, the first thread and interpreter state have
117 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119 Locking: you must hold the interpreter lock while calling this.
120 (If the lock has not yet been initialized, that's equivalent to
121 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000125static int
126add_flag(int flag, const char *envs)
127{
128 int env = atoi(envs);
129 if (flag < env)
130 flag = env;
131 if (flag < 1)
132 flag = 1;
133 return flag;
134}
135
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000137Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000138{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000139 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140 PyThreadState *tstate;
141 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000142 char *p;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000143#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
144 char *codeset;
145 char *saved_locale;
146 PyObject *sys_stream, *sys_isatty;
147#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000148 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000149
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000150 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000151 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000152 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000153
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000154 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000155 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000156 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000157 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000158 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000159 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000160
Guido van Rossuma027efa1997-05-05 20:56:21 +0000161 interp = PyInterpreterState_New();
162 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000163 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000164
Guido van Rossuma027efa1997-05-05 20:56:21 +0000165 tstate = PyThreadState_New(interp);
166 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000167 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000168 (void) PyThreadState_Swap(tstate);
169
Guido van Rossum70d893a2001-08-16 08:21:42 +0000170 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000171
Neal Norwitzb2501f42002-12-31 03:42:13 +0000172 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000173 Py_FatalError("Py_Initialize: can't init frames");
174
Neal Norwitzb2501f42002-12-31 03:42:13 +0000175 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000176 Py_FatalError("Py_Initialize: can't init ints");
177
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000178 _PyFloat_Init();
179
Guido van Rossum25ce5661997-08-02 03:10:38 +0000180 interp->modules = PyDict_New();
181 if (interp->modules == NULL)
182 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000183
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000184#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000185 /* Init Unicode implementation; relies on the codec registry */
186 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000187#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000188
Barry Warsawf242aa02000-05-25 23:09:49 +0000189 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000190 if (bimod == NULL)
191 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000192 interp->builtins = PyModule_GetDict(bimod);
193 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000194
195 sysmod = _PySys_Init();
196 if (sysmod == NULL)
197 Py_FatalError("Py_Initialize: can't initialize sys");
198 interp->sysdict = PyModule_GetDict(sysmod);
199 Py_INCREF(interp->sysdict);
200 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000201 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202 PyDict_SetItemString(interp->sysdict, "modules",
203 interp->modules);
204
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000205 _PyImport_Init();
206
Barry Warsawf242aa02000-05-25 23:09:49 +0000207 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000208 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000209 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000210
Barry Warsaw035574d1997-08-29 22:07:17 +0000211 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000212 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000213
Just van Rossum52e14d62002-12-30 22:08:05 +0000214 _PyImportHooks_Init();
215
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000216 if (install_sigs)
217 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218
219 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000220 if (!Py_NoSiteFlag)
221 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000222
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000223 /* auto-thread-state API, if available */
224#ifdef WITH_THREAD
225 _PyGILState_Init(interp, tstate);
226#endif /* WITH_THREAD */
227
Mark Hammondedd07732003-07-15 23:03:55 +0000228 warnings_module = PyImport_ImportModule("warnings");
229 if (!warnings_module)
230 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000231
232#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
233 /* On Unix, set the file system encoding according to the
234 user's preference, if the CODESET names a well-known
235 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000236 initialized by other means. Also set the encoding of
237 stdin and stdout if these are terminals. */
238
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000239 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000240 setlocale(LC_CTYPE, "");
241 codeset = nl_langinfo(CODESET);
242 if (codeset && *codeset) {
243 PyObject *enc = PyCodec_Encoder(codeset);
244 if (enc) {
245 codeset = strdup(codeset);
246 Py_DECREF(enc);
247 } else {
248 codeset = NULL;
249 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000250 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000251 } else
252 codeset = NULL;
253 setlocale(LC_CTYPE, saved_locale);
Martin v. Löwisf56d0152003-11-13 07:43:21 +0000254 free(saved_locale);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000255
256 if (codeset) {
Michael W. Hudson68debc92003-08-11 12:20:24 +0000257 sys_stream = PySys_GetObject("stdin");
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000258 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
259 if (!sys_isatty)
260 PyErr_Clear();
261 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
262 if (!PyFile_SetEncoding(sys_stream, codeset))
263 Py_FatalError("Cannot set codeset of stdin");
264 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000265 Py_XDECREF(sys_isatty);
266
267 sys_stream = PySys_GetObject("stdout");
268 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
269 if (!sys_isatty)
270 PyErr_Clear();
271 if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
272 if (!PyFile_SetEncoding(sys_stream, codeset))
273 Py_FatalError("Cannot set codeset of stdout");
274 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000275 Py_XDECREF(sys_isatty);
276
277 if (!Py_FileSystemDefaultEncoding)
278 Py_FileSystemDefaultEncoding = codeset;
279 else
280 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000281 }
282#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000283}
284
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000285void
286Py_Initialize(void)
287{
288 Py_InitializeEx(1);
289}
290
291
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000292#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000293extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000294#endif
295
Guido van Rossum25ce5661997-08-02 03:10:38 +0000296/* Undo the effect of Py_Initialize().
297
298 Beware: if multiple interpreter and/or thread states exist, these
299 are not wiped out; only the current thread and interpreter state
300 are deleted. But since everything else is deleted, those other
301 interpreter and thread states should no longer be used.
302
303 (XXX We should do better, e.g. wipe out all interpreters and
304 threads.)
305
306 Locking: as above.
307
308*/
309
310void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000311Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000312{
313 PyInterpreterState *interp;
314 PyThreadState *tstate;
315
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000316 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000317 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000318
Tim Peters384fd102001-01-21 03:40:37 +0000319 /* The interpreter is still entirely intact at this point, and the
320 * exit funcs may be relying on that. In particular, if some thread
321 * or exit func is still waiting to do an import, the import machinery
322 * expects Py_IsInitialized() to return true. So don't say the
323 * interpreter is uninitialized until after the exit funcs have run.
324 * Note that Threading.py uses an exit func to do a join on all the
325 * threads created thru it, so this also protects pending imports in
326 * the threads created via Threading.
327 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000328 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000329 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000330
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000331 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000332 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000333 interp = tstate->interp;
334
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000335 /* Disable signal handling */
336 PyOS_FiniInterrupts();
337
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000338 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000339 Py_XDECREF(warnings_module);
340 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000341
Guido van Rossume13ddc92003-04-17 17:29:22 +0000342 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000343 * before all modules are destroyed.
344 * XXX If a __del__ or weakref callback is triggered here, and tries to
345 * XXX import a module, bad things can happen, because Python no
346 * XXX longer believes it's initialized.
347 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
348 * XXX is easy to provoke that way. I've also seen, e.g.,
349 * XXX Exception exceptions.ImportError: 'No module named sha'
350 * XXX in <function callback at 0x008F5718> ignored
351 * XXX but I'm unclear on exactly how that one happens. In any case,
352 * XXX I haven't seen a real-life report of either of these.
353 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000354 PyGC_Collect();
355
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000356 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000357 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000358
Guido van Rossume13ddc92003-04-17 17:29:22 +0000359 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000360 * new-style class definitions, for example.
361 * XXX This is disabled because it caused too many problems. If
362 * XXX a __del__ or weakref callback triggers here, Python code has
363 * XXX a hard time running, because even the sys module has been
364 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
365 * XXX One symptom is a sequence of information-free messages
366 * XXX coming from threads (if a __del__ or callback is invoked,
367 * XXX other threads can execute too, and any exception they encounter
368 * XXX triggers a comedy of errors as subsystem after subsystem
369 * XXX fails to find what it *expects* to find in sys to help report
370 * XXX the exception and consequent unexpected failures). I've also
371 * XXX seen segfaults then, after adding print statements to the
372 * XXX Python code getting called.
373 */
374#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000375 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000376#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000377
Guido van Rossum1707aad1997-12-08 23:43:45 +0000378 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
379 _PyImport_Fini();
380
381 /* Debugging stuff */
382#ifdef COUNT_ALLOCS
383 dump_counts();
384#endif
385
386#ifdef Py_REF_DEBUG
387 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
388#endif
389
Tim Peters9cf25ce2003-04-17 15:21:01 +0000390#ifdef Py_TRACE_REFS
391 /* Display all objects still alive -- this can invoke arbitrary
392 * __repr__ overrides, so requires a mostly-intact interpreter.
393 * Alas, a lot of stuff may still be alive now that will be cleaned
394 * up later.
395 */
Tim Peters269b2a62003-04-17 19:52:29 +0000396 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000397 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000398#endif /* Py_TRACE_REFS */
399
Mark Hammond6cb90292003-04-22 11:18:00 +0000400 /* Cleanup auto-thread-state */
401#ifdef WITH_THREAD
402 _PyGILState_Fini();
403#endif /* WITH_THREAD */
404
Guido van Rossumd922fa42003-04-15 14:10:09 +0000405 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000406 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000407
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000408 /* Now we decref the exception classes. After this point nothing
409 can raise an exception. That's okay, because each Fini() method
410 below has been checked to make sure no exceptions are ever
411 raised.
412 */
413
414 _PyExc_Fini();
415
Guido van Rossumd922fa42003-04-15 14:10:09 +0000416 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000417 PyThreadState_Swap(NULL);
418 PyInterpreterState_Delete(interp);
419
Guido van Rossumd922fa42003-04-15 14:10:09 +0000420 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000421 PyMethod_Fini();
422 PyFrame_Fini();
423 PyCFunction_Fini();
424 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000425 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000426 PySet_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000427 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000428 PyInt_Fini();
429 PyFloat_Fini();
430
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000431#ifdef Py_USING_UNICODE
432 /* Cleanup Unicode implementation */
433 _PyUnicode_Fini();
434#endif
435
Guido van Rossumcc283f51997-08-05 02:22:03 +0000436 /* XXX Still allocated:
437 - various static ad-hoc pointers to interned strings
438 - int and float free list blocks
439 - whatever various modules and libraries allocate
440 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000441
442 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000443
Tim Peters269b2a62003-04-17 19:52:29 +0000444#ifdef Py_TRACE_REFS
445 /* Display addresses (& refcnts) of all objects still alive.
446 * An address can be used to find the repr of the object, printed
447 * above by _Py_PrintReferences.
448 */
449 if (Py_GETENV("PYTHONDUMPREFS"))
450 _Py_PrintReferenceAddresses(stderr);
451#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000452#ifdef PYMALLOC_DEBUG
453 if (Py_GETENV("PYTHONMALLOCSTATS"))
454 _PyObject_DebugMallocStats();
455#endif
456
Guido van Rossumcc283f51997-08-05 02:22:03 +0000457 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000458}
459
460/* Create and initialize a new interpreter and thread, and return the
461 new thread. This requires that Py_Initialize() has been called
462 first.
463
464 Unsuccessful initialization yields a NULL pointer. Note that *no*
465 exception information is available even in this case -- the
466 exception information is held in the thread, and there is no
467 thread.
468
469 Locking: as above.
470
471*/
472
473PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000474Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000475{
476 PyInterpreterState *interp;
477 PyThreadState *tstate, *save_tstate;
478 PyObject *bimod, *sysmod;
479
480 if (!initialized)
481 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
482
483 interp = PyInterpreterState_New();
484 if (interp == NULL)
485 return NULL;
486
487 tstate = PyThreadState_New(interp);
488 if (tstate == NULL) {
489 PyInterpreterState_Delete(interp);
490 return NULL;
491 }
492
493 save_tstate = PyThreadState_Swap(tstate);
494
495 /* XXX The following is lax in error checking */
496
497 interp->modules = PyDict_New();
498
499 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
500 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000501 interp->builtins = PyModule_GetDict(bimod);
502 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000503 }
504 sysmod = _PyImport_FindExtension("sys", "sys");
505 if (bimod != NULL && sysmod != NULL) {
506 interp->sysdict = PyModule_GetDict(sysmod);
507 Py_INCREF(interp->sysdict);
508 PySys_SetPath(Py_GetPath());
509 PyDict_SetItemString(interp->sysdict, "modules",
510 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000511 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000512 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000513 if (!Py_NoSiteFlag)
514 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000515 }
516
517 if (!PyErr_Occurred())
518 return tstate;
519
520 /* Oops, it didn't work. Undo it all. */
521
522 PyErr_Print();
523 PyThreadState_Clear(tstate);
524 PyThreadState_Swap(save_tstate);
525 PyThreadState_Delete(tstate);
526 PyInterpreterState_Delete(interp);
527
528 return NULL;
529}
530
531/* Delete an interpreter and its last thread. This requires that the
532 given thread state is current, that the thread has no remaining
533 frames, and that it is its interpreter's only remaining thread.
534 It is a fatal error to violate these constraints.
535
536 (Py_Finalize() doesn't have these constraints -- it zaps
537 everything, regardless.)
538
539 Locking: as above.
540
541*/
542
543void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000544Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545{
546 PyInterpreterState *interp = tstate->interp;
547
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000548 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000549 Py_FatalError("Py_EndInterpreter: thread is not current");
550 if (tstate->frame != NULL)
551 Py_FatalError("Py_EndInterpreter: thread still has a frame");
552 if (tstate != interp->tstate_head || tstate->next != NULL)
553 Py_FatalError("Py_EndInterpreter: not the last thread");
554
555 PyImport_Cleanup();
556 PyInterpreterState_Clear(interp);
557 PyThreadState_Swap(NULL);
558 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000559}
560
561static char *progname = "python";
562
563void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000564Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000565{
566 if (pn && *pn)
567 progname = pn;
568}
569
570char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000571Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000572{
573 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000574}
575
Guido van Rossuma61691e1998-02-06 22:27:24 +0000576static char *default_home = NULL;
577
578void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000579Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000580{
581 default_home = home;
582}
583
584char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000585Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000586{
587 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000588 if (home == NULL && !Py_IgnoreEnvironmentFlag)
589 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000590 return home;
591}
592
Guido van Rossum6135a871995-01-09 17:53:26 +0000593/* Create __main__ module */
594
595static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000596initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000597{
Guido van Rossum82598051997-03-05 00:20:32 +0000598 PyObject *m, *d;
599 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000600 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000601 Py_FatalError("can't create __main__ module");
602 d = PyModule_GetDict(m);
603 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000604 PyObject *bimod = PyImport_ImportModule("__builtin__");
605 if (bimod == NULL ||
606 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000607 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000608 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000609 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000610}
611
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000612/* Import the site module (not into __main__ though) */
613
614static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000615initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000616{
617 PyObject *m, *f;
618 m = PyImport_ImportModule("site");
619 if (m == NULL) {
620 f = PySys_GetObject("stderr");
621 if (Py_VerboseFlag) {
622 PyFile_WriteString(
623 "'import site' failed; traceback:\n", f);
624 PyErr_Print();
625 }
626 else {
627 PyFile_WriteString(
628 "'import site' failed; use -v for traceback\n", f);
629 PyErr_Clear();
630 }
631 }
632 else {
633 Py_DECREF(m);
634 }
635}
636
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000637/* Parse input from a file and execute it */
638
639int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000641 PyCompilerFlags *flags)
642{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000643 if (filename == NULL)
644 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000645 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000646 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000647 if (closeit)
648 fclose(fp);
649 return err;
650 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000651 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000652 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000653}
654
655int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000656PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000657{
Guido van Rossum82598051997-03-05 00:20:32 +0000658 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000659 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000660 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000661
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000662 if (flags == NULL) {
663 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000664 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000665 }
Guido van Rossum82598051997-03-05 00:20:32 +0000666 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000667 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000668 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
669 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000670 }
Guido van Rossum82598051997-03-05 00:20:32 +0000671 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000672 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000673 PySys_SetObject("ps2", v = PyString_FromString("... "));
674 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000675 }
676 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000677 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000678#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000679 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000680#endif
681 if (ret == E_EOF)
682 return 0;
683 /*
684 if (ret == E_NOMEM)
685 return -1;
686 */
687 }
688}
689
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000690/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000691#define PARSER_FLAGS(flags) \
Guido van Rossum4b499dd32003-02-13 22:07:59 +0000692 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
693 PyPARSE_DONT_IMPLY_DEDENT : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000694
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000695int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000696PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000697{
Guido van Rossum82598051997-03-05 00:20:32 +0000698 PyObject *m, *d, *v, *w;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000699 mod_ty mod;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000700 char *ps1 = "", *ps2 = "";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000701 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000702
Guido van Rossum82598051997-03-05 00:20:32 +0000703 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000704 if (v != NULL) {
705 v = PyObject_Str(v);
706 if (v == NULL)
707 PyErr_Clear();
708 else if (PyString_Check(v))
709 ps1 = PyString_AsString(v);
710 }
Guido van Rossum82598051997-03-05 00:20:32 +0000711 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000712 if (w != NULL) {
713 w = PyObject_Str(w);
714 if (w == NULL)
715 PyErr_Clear();
716 else if (PyString_Check(w))
717 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000718 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000719 mod = PyParser_ASTFromFile(fp, filename,
720 Py_single_input, ps1, ps2,
721 flags, &errcode);
Guido van Rossum82598051997-03-05 00:20:32 +0000722 Py_XDECREF(v);
723 Py_XDECREF(w);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000724 if (mod == NULL) {
725 if (errcode == E_EOF) {
726 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000727 return E_EOF;
728 }
Guido van Rossum82598051997-03-05 00:20:32 +0000729 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000730 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000731 }
Guido van Rossum82598051997-03-05 00:20:32 +0000732 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000733 if (m == NULL)
734 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000735 d = PyModule_GetDict(m);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000736 v = run_mod(mod, filename, d, d, flags);
737 free_mod(mod);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000738 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000739 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000740 return -1;
741 }
Guido van Rossum82598051997-03-05 00:20:32 +0000742 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000743 if (Py_FlushLine())
744 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000745 return 0;
746}
747
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000748/* Check whether a file maybe a pyc file: Look at the extension,
749 the file type, and, if we may close it, at the first few bytes. */
750
751static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000752maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000753{
754 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
755 return 1;
756
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000757 /* Only look into the file if we are allowed to close it, since
758 it then should also be seekable. */
759 if (closeit) {
760 /* Read only two bytes of the magic. If the file was opened in
761 text mode, the bytes 3 and 4 of the magic (\r\n) might not
762 be read as they are on disk. */
763 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
764 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000765 /* Mess: In case of -x, the stream is NOT at its start now,
766 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000767 which makes the current stream position formally undefined,
768 and a x-platform nightmare.
769 Unfortunately, we have no direct way to know whether -x
770 was specified. So we use a terrible hack: if the current
771 stream position is not 0, we assume -x was specified, and
772 give up. Bug 132850 on SourceForge spells out the
773 hopelessness of trying anything else (fseek and ftell
774 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000775 */
Tim Peters3e876562001-02-11 04:35:39 +0000776 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000777 if (ftell(fp) == 0) {
778 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +0000779 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000780 ispyc = 1;
781 rewind(fp);
782 }
Tim Peters3e876562001-02-11 04:35:39 +0000783 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000784 }
785 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000786}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000787
Guido van Rossum0df002c2000-08-27 19:21:52 +0000788int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000789PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000790 PyCompilerFlags *flags)
791{
Guido van Rossum82598051997-03-05 00:20:32 +0000792 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000793 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000794
Guido van Rossum82598051997-03-05 00:20:32 +0000795 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000796 if (m == NULL)
797 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000798 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000799 if (PyDict_GetItemString(d, "__file__") == NULL) {
800 PyObject *f = PyString_FromString(filename);
801 if (f == NULL)
802 return -1;
803 if (PyDict_SetItemString(d, "__file__", f) < 0) {
804 Py_DECREF(f);
805 return -1;
806 }
807 Py_DECREF(f);
808 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000809 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000810 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000811 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000812 if (closeit)
813 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000814 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000815 fprintf(stderr, "python: Can't reopen .pyc file\n");
816 return -1;
817 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000818 /* Turn on optimization if a .pyo file is given */
819 if (strcmp(ext, ".pyo") == 0)
820 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000821 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000822 } else {
Tim Petersd08e3822003-04-17 15:24:21 +0000823 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000824 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000825 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000826 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000827 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000828 return -1;
829 }
Guido van Rossum82598051997-03-05 00:20:32 +0000830 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000831 if (Py_FlushLine())
832 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000833 return 0;
834}
835
836int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000837PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000838{
Guido van Rossum82598051997-03-05 00:20:32 +0000839 PyObject *m, *d, *v;
840 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000841 if (m == NULL)
842 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000843 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000844 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000845 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000846 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000847 return -1;
848 }
Guido van Rossum82598051997-03-05 00:20:32 +0000849 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000850 if (Py_FlushLine())
851 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000852 return 0;
853}
854
Barry Warsaw035574d1997-08-29 22:07:17 +0000855static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000856parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
857 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000858{
859 long hold;
860 PyObject *v;
861
862 /* old style errors */
863 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000864 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
865 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000866
867 /* new style errors. `err' is an instance */
868
869 if (! (v = PyObject_GetAttrString(err, "msg")))
870 goto finally;
871 *message = v;
872
873 if (!(v = PyObject_GetAttrString(err, "filename")))
874 goto finally;
875 if (v == Py_None)
876 *filename = NULL;
877 else if (! (*filename = PyString_AsString(v)))
878 goto finally;
879
880 Py_DECREF(v);
881 if (!(v = PyObject_GetAttrString(err, "lineno")))
882 goto finally;
883 hold = PyInt_AsLong(v);
884 Py_DECREF(v);
885 v = NULL;
886 if (hold < 0 && PyErr_Occurred())
887 goto finally;
888 *lineno = (int)hold;
889
890 if (!(v = PyObject_GetAttrString(err, "offset")))
891 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000892 if (v == Py_None) {
893 *offset = -1;
894 Py_DECREF(v);
895 v = NULL;
896 } else {
897 hold = PyInt_AsLong(v);
898 Py_DECREF(v);
899 v = NULL;
900 if (hold < 0 && PyErr_Occurred())
901 goto finally;
902 *offset = (int)hold;
903 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000904
905 if (!(v = PyObject_GetAttrString(err, "text")))
906 goto finally;
907 if (v == Py_None)
908 *text = NULL;
909 else if (! (*text = PyString_AsString(v)))
910 goto finally;
911 Py_DECREF(v);
912 return 1;
913
914finally:
915 Py_XDECREF(v);
916 return 0;
917}
918
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000919void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000920PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000921{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000922 PyErr_PrintEx(1);
923}
924
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000925static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000926print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000927{
928 char *nl;
929 if (offset >= 0) {
930 if (offset > 0 && offset == (int)strlen(text))
931 offset--;
932 for (;;) {
933 nl = strchr(text, '\n');
934 if (nl == NULL || nl-text >= offset)
935 break;
936 offset -= (nl+1-text);
937 text = nl+1;
938 }
939 while (*text == ' ' || *text == '\t') {
940 text++;
941 offset--;
942 }
943 }
944 PyFile_WriteString(" ", f);
945 PyFile_WriteString(text, f);
946 if (*text == '\0' || text[strlen(text)-1] != '\n')
947 PyFile_WriteString("\n", f);
948 if (offset == -1)
949 return;
950 PyFile_WriteString(" ", f);
951 offset--;
952 while (offset > 0) {
953 PyFile_WriteString(" ", f);
954 offset--;
955 }
956 PyFile_WriteString("^\n", f);
957}
958
Guido van Rossum66e8e862001-03-23 17:54:43 +0000959static void
960handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000961{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000962 PyObject *exception, *value, *tb;
Tim Peterscf615b52003-04-19 18:47:02 +0000963 int exitcode = 0;
964
Guido van Rossum66e8e862001-03-23 17:54:43 +0000965 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000966 if (Py_FlushLine())
967 PyErr_Clear();
968 fflush(stdout);
969 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000970 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000971 if (PyInstance_Check(value)) {
972 /* The error code should be in the `code' attribute. */
973 PyObject *code = PyObject_GetAttrString(value, "code");
974 if (code) {
975 Py_DECREF(value);
976 value = code;
977 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +0000978 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000979 }
980 /* If we failed to dig out the 'code' attribute,
981 just let the else clause below print the error. */
982 }
983 if (PyInt_Check(value))
Tim Peterscf615b52003-04-19 18:47:02 +0000984 exitcode = (int)PyInt_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000985 else {
986 PyObject_Print(value, stderr, Py_PRINT_RAW);
987 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +0000988 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000989 }
Tim Peterscf615b52003-04-19 18:47:02 +0000990 done:
991 /* Restore and clear the exception info, in order to properly decref
992 * the exception, value, and traceback. If we just exit instead,
993 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
994 * some finalizers from running.
995 */
996 PyErr_Restore(exception, value, tb);
997 PyErr_Clear();
998 Py_Exit(exitcode);
999 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001000}
1001
1002void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001003PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001004{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001005 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001006
1007 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1008 handle_system_exit();
1009 }
Guido van Rossum82598051997-03-05 00:20:32 +00001010 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011 if (exception == NULL)
1012 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001013 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001014 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001015 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +00001016 if (set_sys_last_vars) {
1017 PySys_SetObject("last_type", exception);
1018 PySys_SetObject("last_value", v);
1019 PySys_SetObject("last_traceback", tb);
1020 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001021 hook = PySys_GetObject("excepthook");
1022 if (hook) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001023 PyObject *args = PyTuple_Pack(3,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001024 exception, v ? v : Py_None, tb ? tb : Py_None);
1025 PyObject *result = PyEval_CallObject(hook, args);
1026 if (result == NULL) {
1027 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001028 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1029 handle_system_exit();
1030 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001031 PyErr_Fetch(&exception2, &v2, &tb2);
1032 PyErr_NormalizeException(&exception2, &v2, &tb2);
1033 if (Py_FlushLine())
1034 PyErr_Clear();
1035 fflush(stdout);
1036 PySys_WriteStderr("Error in sys.excepthook:\n");
1037 PyErr_Display(exception2, v2, tb2);
1038 PySys_WriteStderr("\nOriginal exception was:\n");
1039 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +00001040 Py_XDECREF(exception2);
1041 Py_XDECREF(v2);
1042 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001043 }
1044 Py_XDECREF(result);
1045 Py_XDECREF(args);
1046 } else {
1047 PySys_WriteStderr("sys.excepthook is missing\n");
1048 PyErr_Display(exception, v, tb);
1049 }
1050 Py_XDECREF(exception);
1051 Py_XDECREF(v);
1052 Py_XDECREF(tb);
1053}
1054
1055void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
1056{
1057 int err = 0;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001058 PyObject *f = PySys_GetObject("stderr");
Armin Rigo5d2c6832004-03-22 20:16:58 +00001059 Py_INCREF(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001060 if (f == NULL)
1061 fprintf(stderr, "lost sys.stderr\n");
1062 else {
Guido van Rossum0829c751998-02-28 04:31:39 +00001063 if (Py_FlushLine())
1064 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001065 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001066 if (tb && tb != Py_None)
1067 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001068 if (err == 0 &&
Armin Rigo5d2c6832004-03-22 20:16:58 +00001069 PyObject_HasAttrString(value, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001070 {
Guido van Rossum82598051997-03-05 00:20:32 +00001071 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001072 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001073 int lineno, offset;
Armin Rigo5d2c6832004-03-22 20:16:58 +00001074 if (!parse_syntax_error(value, &message, &filename,
Barry Warsaw035574d1997-08-29 22:07:17 +00001075 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001076 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001077 else {
1078 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001079 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001080 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001081 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001082 else
Guido van Rossum82598051997-03-05 00:20:32 +00001083 PyFile_WriteString(filename, f);
1084 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001085 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001086 PyFile_WriteString(buf, f);
1087 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001088 if (text != NULL)
1089 print_error_text(f, offset, text);
Armin Rigo5d2c6832004-03-22 20:16:58 +00001090 Py_DECREF(value);
1091 value = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001092 /* Can't be bothered to check all those
1093 PyFile_WriteString() calls */
1094 if (PyErr_Occurred())
1095 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001096 }
1097 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001098 if (err) {
1099 /* Don't do anything else */
1100 }
1101 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001102 PyClassObject* exc = (PyClassObject*)exception;
1103 PyObject* className = exc->cl_name;
1104 PyObject* moduleName =
1105 PyDict_GetItemString(exc->cl_dict, "__module__");
1106
1107 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001108 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001109 else {
1110 char* modstr = PyString_AsString(moduleName);
Tim Petersd08e3822003-04-17 15:24:21 +00001111 if (modstr && strcmp(modstr, "exceptions"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001112 {
1113 err = PyFile_WriteString(modstr, f);
1114 err += PyFile_WriteString(".", f);
1115 }
1116 }
1117 if (err == 0) {
1118 if (className == NULL)
1119 err = PyFile_WriteString("<unknown>", f);
1120 else
1121 err = PyFile_WriteObject(className, f,
1122 Py_PRINT_RAW);
1123 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001124 }
1125 else
1126 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1127 if (err == 0) {
Armin Rigo5d2c6832004-03-22 20:16:58 +00001128 if (value != Py_None) {
1129 PyObject *s = PyObject_Str(value);
Barry Warsaw035574d1997-08-29 22:07:17 +00001130 /* only print colon if the str() of the
1131 object is not the empty string
1132 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001133 if (s == NULL)
1134 err = -1;
1135 else if (!PyString_Check(s) ||
1136 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001137 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001138 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001139 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1140 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001141 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001142 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001143 if (err == 0)
1144 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001145 }
Armin Rigo5d2c6832004-03-22 20:16:58 +00001146 Py_DECREF(value);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001147 /* If an error happened here, don't show it.
1148 XXX This is wrong, but too many callers rely on this behavior. */
1149 if (err != 0)
1150 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001151}
1152
Guido van Rossum82598051997-03-05 00:20:32 +00001153PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154PyRun_StringFlags(const char *str, int start, PyObject *globals,
1155 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001156{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 PyObject *ret;
1158 mod_ty mod = PyParser_ASTFromString(str, "<string>", start, flags);
1159 ret = run_err_mod(mod, "<string>", globals, locals, flags);
1160 free_mod(mod);
1161 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001162}
1163
1164PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001165PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001166 PyObject *locals, int closeit, PyCompilerFlags *flags)
1167{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168 PyObject *ret;
1169 mod_ty mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1170 flags, NULL);
1171 if (mod == NULL)
1172 return NULL;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001173 if (closeit)
1174 fclose(fp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175 ret = run_err_mod(mod, filename, globals, locals, flags);
1176 free_mod(mod);
1177 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001178}
1179
Guido van Rossum82598051997-03-05 00:20:32 +00001180static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181run_err_mod(mod_ty mod, const char *filename, PyObject *globals,
1182 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001183{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184 if (mod == NULL)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001185 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186 return run_mod(mod, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001187}
1188
Guido van Rossum82598051997-03-05 00:20:32 +00001189static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001190run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001191 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001192{
Guido van Rossum82598051997-03-05 00:20:32 +00001193 PyCodeObject *co;
1194 PyObject *v;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 co = PyAST_Compile(mod, filename, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001196 if (co == NULL)
1197 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001198 v = PyEval_EvalCode(co, globals, locals);
1199 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001200 return v;
1201}
1202
Guido van Rossum82598051997-03-05 00:20:32 +00001203static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
1205 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001206{
Guido van Rossum82598051997-03-05 00:20:32 +00001207 PyCodeObject *co;
1208 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001209 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001210 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001211
Guido van Rossum82598051997-03-05 00:20:32 +00001212 magic = PyMarshal_ReadLongFromFile(fp);
1213 if (magic != PyImport_GetMagicNumber()) {
1214 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001215 "Bad magic number in .pyc file");
1216 return NULL;
1217 }
Guido van Rossum82598051997-03-05 00:20:32 +00001218 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001219 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001220 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001221 if (v == NULL || !PyCode_Check(v)) {
1222 Py_XDECREF(v);
1223 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001224 "Bad code object in .pyc file");
1225 return NULL;
1226 }
Guido van Rossum82598051997-03-05 00:20:32 +00001227 co = (PyCodeObject *)v;
1228 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001229 if (v && flags)
1230 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001231 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001232 return v;
1233}
1234
Guido van Rossum82598051997-03-05 00:20:32 +00001235PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001236Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001237 PyCompilerFlags *flags)
1238{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239 mod_ty mod;
Guido van Rossum82598051997-03-05 00:20:32 +00001240 PyCodeObject *co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241 mod = PyParser_ASTFromString(str, filename, start, flags);
1242 if (mod == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001243 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 co = PyAST_Compile(mod, filename, flags);
1245 free_mod(mod);
Guido van Rossum82598051997-03-05 00:20:32 +00001246 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001247}
1248
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001249struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001250Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001251{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252 mod_ty mod;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001253 struct symtable *st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254
1255 mod = PyParser_ASTFromString(str, filename, start, NULL);
1256 if (mod == NULL)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001257 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258 st = PySymtable_Build(mod, filename, 0);
1259 free_mod(mod);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001260 return st;
1261}
1262
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263/* Preferred access to parser is through AST. */
1264mod_ty
1265PyParser_ASTFromString(const char *s, const char *filename, int start,
1266 PyCompilerFlags *flags)
1267{
1268 node *n;
1269 mod_ty mod;
1270 perrdetail err;
1271 n = PyParser_ParseStringFlagsFilename(s, filename, &_PyParser_Grammar,
1272 start, &err,
1273 PARSER_FLAGS(flags));
1274 if (n) {
1275 mod = PyAST_FromNode(n, flags, filename);
1276 PyNode_Free(n);
1277 return mod;
1278 }
1279 else {
1280 err_input(&err);
1281 return NULL;
1282 }
1283}
1284
1285mod_ty
1286PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
1287 char *ps2, PyCompilerFlags *flags, int *errcode)
1288{
1289 node *n;
1290 mod_ty mod;
1291 perrdetail err;
1292 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1293 ps1, ps2, &err, PARSER_FLAGS(flags));
1294 if (n) {
1295 mod = PyAST_FromNode(n, flags, filename);
1296 PyNode_Free(n);
1297 return mod;
1298 }
1299 else {
1300 err_input(&err);
1301 if (errcode)
1302 *errcode = err.error;
1303 return NULL;
1304 }
1305}
1306
Guido van Rossuma110aa61994-08-29 12:50:44 +00001307/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001308
Guido van Rossuma110aa61994-08-29 12:50:44 +00001309node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001310PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001311{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001312 node *n;
1313 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001314 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1315 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001316 if (n == NULL)
1317 err_input(&err);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318
Guido van Rossuma110aa61994-08-29 12:50:44 +00001319 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001320}
1321
Guido van Rossuma110aa61994-08-29 12:50:44 +00001322/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001323
Guido van Rossuma110aa61994-08-29 12:50:44 +00001324node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001325PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001326{
1327 node *n;
1328 perrdetail err;
1329 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1330 flags);
1331 if (n == NULL)
1332 err_input(&err);
1333 return n;
1334}
1335
1336node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001337PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001338 int start, int flags)
1339{
1340 node *n;
1341 perrdetail err;
1342
Tim Petersd08e3822003-04-17 15:24:21 +00001343 n = PyParser_ParseStringFlagsFilename(str, filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001344 &_PyParser_Grammar,
1345 start, &err, flags);
1346 if (n == NULL)
1347 err_input(&err);
1348 return n;
1349}
1350
1351node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001352PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001353{
1354 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1355 start, 0);
1356}
1357
Guido van Rossum66ebd912003-04-17 16:02:26 +00001358/* May want to move a more generalized form of this to parsetok.c or
1359 even parser modules. */
1360
1361void
1362PyParser_SetError(perrdetail *err)
1363{
1364 err_input(err);
1365}
1366
Guido van Rossuma110aa61994-08-29 12:50:44 +00001367/* Set the error appropriate to the given input error code (see errcode.h) */
1368
1369static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001370err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001371{
Fred Drake85f36392000-07-11 17:53:00 +00001372 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001373 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001374 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001375 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001376 switch (err->error) {
1377 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001378 errtype = PyExc_IndentationError;
1379 if (err->expected == INDENT)
1380 msg = "expected an indented block";
1381 else if (err->token == INDENT)
1382 msg = "unexpected indent";
1383 else if (err->token == DEDENT)
1384 msg = "unexpected unindent";
1385 else {
1386 errtype = PyExc_SyntaxError;
1387 msg = "invalid syntax";
1388 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001389 break;
1390 case E_TOKEN:
1391 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001392 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001393 case E_EOFS:
1394 msg = "EOF while scanning triple-quoted string";
1395 break;
1396 case E_EOLS:
1397 msg = "EOL while scanning single-quoted string";
1398 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001399 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001400 if (!PyErr_Occurred())
1401 PyErr_SetNone(PyExc_KeyboardInterrupt);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001402 return;
1403 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001404 PyErr_NoMemory();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001405 return;
1406 case E_EOF:
1407 msg = "unexpected EOF while parsing";
1408 break;
Fred Drake85f36392000-07-11 17:53:00 +00001409 case E_TABSPACE:
1410 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001411 msg = "inconsistent use of tabs and spaces in indentation";
1412 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001413 case E_OVERFLOW:
1414 msg = "expression too long";
1415 break;
Fred Drake85f36392000-07-11 17:53:00 +00001416 case E_DEDENT:
1417 errtype = PyExc_IndentationError;
1418 msg = "unindent does not match any outer indentation level";
1419 break;
1420 case E_TOODEEP:
1421 errtype = PyExc_IndentationError;
1422 msg = "too many levels of indentation";
1423 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001424 case E_DECODE: {
1425 PyObject *type, *value, *tb;
1426 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001427 if (value != NULL) {
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001428 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001429 if (u != NULL) {
1430 msg = PyString_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001431 }
1432 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001433 if (msg == NULL)
1434 msg = "unknown decode error";
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001435 Py_DECREF(type);
1436 Py_DECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001437 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001438 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001439 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001440 case E_LINECONT:
1441 msg = "unexpected character after line continuation character";
1442 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001443 default:
1444 fprintf(stderr, "error=%d\n", err->error);
1445 msg = "unknown parsing error";
1446 break;
1447 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448 v = Py_BuildValue("(ziiz)", err->filename,
1449 err->lineno, err->offset, err->text);
1450 if (err->text != NULL) {
1451 PyMem_DEL(err->text);
1452 err->text = NULL;
1453 }
1454 w = NULL;
1455 if (v != NULL)
1456 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001457 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001458 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001459 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001460 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001461}
1462
1463/* Print fatal error message and abort */
1464
1465void
Tim Peters7c321a82002-07-09 02:57:01 +00001466Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001467{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001468 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001469#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001470 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001471 OutputDebugString(msg);
1472 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001473#ifdef _DEBUG
1474 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001475#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001476#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001477 abort();
1478}
1479
1480/* Clean up and exit */
1481
Guido van Rossuma110aa61994-08-29 12:50:44 +00001482#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001483#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001484#endif
1485
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001486#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001487static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001488static int nexitfuncs = 0;
1489
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001490int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001491{
1492 if (nexitfuncs >= NEXITFUNCS)
1493 return -1;
1494 exitfuncs[nexitfuncs++] = func;
1495 return 0;
1496}
1497
Guido van Rossumcc283f51997-08-05 02:22:03 +00001498static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001499call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001500{
Guido van Rossum82598051997-03-05 00:20:32 +00001501 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001502
1503 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001504 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001505 Py_INCREF(exitfunc);
1506 PySys_SetObject("exitfunc", (PyObject *)NULL);
1507 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001508 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001509 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1510 PySys_WriteStderr("Error in sys.exitfunc:\n");
1511 }
Guido van Rossum82598051997-03-05 00:20:32 +00001512 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001513 }
Guido van Rossum82598051997-03-05 00:20:32 +00001514 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001515 }
1516
Guido van Rossum0829c751998-02-28 04:31:39 +00001517 if (Py_FlushLine())
1518 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001519}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001520
Guido van Rossumcc283f51997-08-05 02:22:03 +00001521static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001522call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001523{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001524 while (nexitfuncs > 0)
1525 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001526
1527 fflush(stdout);
1528 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001529}
1530
1531void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001532Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001533{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001534 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001535
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001536 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001537}
1538
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001539static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001540initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001541{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001542#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001543 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001544#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001545#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001546 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001547#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001548#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001549 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001550#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001551 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001552}
1553
Guido van Rossum7433b121997-02-14 19:45:36 +00001554
1555/*
1556 * The file descriptor fd is considered ``interactive'' if either
1557 * a) isatty(fd) is TRUE, or
1558 * b) the -i flag was given, and the filename associated with
1559 * the descriptor is NULL or "<stdin>" or "???".
1560 */
1561int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001562Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001563{
1564 if (isatty((int)fileno(fp)))
1565 return 1;
1566 if (!Py_InteractiveFlag)
1567 return 0;
1568 return (filename == NULL) ||
1569 (strcmp(filename, "<stdin>") == 0) ||
1570 (strcmp(filename, "???") == 0);
1571}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001572
1573
Tim Petersd08e3822003-04-17 15:24:21 +00001574#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001575#if defined(WIN32) && defined(_MSC_VER)
1576
1577/* Stack checking for Microsoft C */
1578
1579#include <malloc.h>
1580#include <excpt.h>
1581
Fred Drakee8de31c2000-08-31 05:38:39 +00001582/*
1583 * Return non-zero when we run out of memory on the stack; zero otherwise.
1584 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001585int
Fred Drake399739f2000-08-31 05:52:44 +00001586PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001587{
1588 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001589 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001590 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001591 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001592 return 0;
1593 } __except (EXCEPTION_EXECUTE_HANDLER) {
1594 /* just ignore all errors */
1595 }
1596 return 1;
1597}
1598
1599#endif /* WIN32 && _MSC_VER */
1600
1601/* Alternate implementations can be added here... */
1602
1603#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001604
1605
1606/* Wrappers around sigaction() or signal(). */
1607
1608PyOS_sighandler_t
1609PyOS_getsig(int sig)
1610{
1611#ifdef HAVE_SIGACTION
1612 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001613 if (sigaction(sig, NULL, &context) == -1)
1614 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001615 return context.sa_handler;
1616#else
1617 PyOS_sighandler_t handler;
1618 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001619 if (handler != SIG_ERR)
1620 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00001621 return handler;
1622#endif
1623}
1624
1625PyOS_sighandler_t
1626PyOS_setsig(int sig, PyOS_sighandler_t handler)
1627{
1628#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001629 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00001630 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001631 sigemptyset(&context.sa_mask);
1632 context.sa_flags = 0;
1633 if (sigaction(sig, &context, &ocontext) == -1)
1634 return SIG_ERR;
1635 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001636#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001637 PyOS_sighandler_t oldhandler;
1638 oldhandler = signal(sig, handler);
1639#ifdef HAVE_SIGINTERRUPT
1640 siginterrupt(sig, 1);
1641#endif
1642 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001643#endif
1644}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001645
1646/* Deprecated C API functions still provided for binary compatiblity */
1647
1648#undef PyParser_SimpleParseFile
1649#undef PyParser_SimpleParseString
1650
1651node *
1652PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1653{
1654 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1655}
1656
1657node *
1658PyParser_SimpleParseString(const char *str, int start)
1659{
1660 return PyParser_SimpleParseStringFlags(str, start, 0);
1661}