blob: c2508fa579da1a0e9a830a1141c0eef9bc36a70d [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
6#include "grammar.h"
7#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +00008#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00009#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010#include "errcode.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000012#include "symtable.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000013#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000014#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000015
Guido van Rossuma110aa61994-08-29 12:50:44 +000016#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000017#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000018#endif
19
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000020#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000021#undef BYTE
22#include "windows.h"
23#endif
24
Jack Jansencbf630f2000-07-11 21:59:16 +000025#ifdef macintosh
26#include "macglue.h"
27#endif
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000028extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000029
Guido van Rossum82598051997-03-05 00:20:32 +000030extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000031
Guido van Rossumb73cc041993-11-01 16:28:59 +000032/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000033static void initmain(void);
34static void initsite(void);
Jeremy Hylton9f324e92001-03-01 22:59:14 +000035static PyObject *run_err_node(node *, char *, PyObject *, PyObject *,
36 PyCompilerFlags *);
37static PyObject *run_node(node *, char *, PyObject *, PyObject *,
38 PyCompilerFlags *);
Jeremy Hyltonbc320242001-03-22 02:47:58 +000039static PyObject *run_pyc_file(FILE *, char *, PyObject *, PyObject *,
40 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000041static void err_input(perrdetail *);
42static void initsigs(void);
43static void call_sys_exitfunc(void);
44static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000045extern void _PyUnicode_Init(void);
46extern void _PyUnicode_Fini(void);
47extern void _PyCodecRegistry_Init(void);
48extern void _PyCodecRegistry_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000049
Guido van Rossum82598051997-03-05 00:20:32 +000050int Py_DebugFlag; /* Needed by parser.c */
51int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000052int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000053int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000054int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000055int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000056int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000057int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000058/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
59 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
60 true divisions (which they will be in 2.3). */
61int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000062
Guido van Rossum25ce5661997-08-02 03:10:38 +000063static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000064
Thomas Wouters7e474022000-07-16 12:04:32 +000065/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000066
67int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000068Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000069{
70 return initialized;
71}
72
Guido van Rossum25ce5661997-08-02 03:10:38 +000073/* Global initializations. Can be undone by Py_Finalize(). Don't
74 call this twice without an intervening Py_Finalize() call. When
75 initializations fail, a fatal error is issued and the function does
76 not return. On return, the first thread and interpreter state have
77 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000078
Guido van Rossum25ce5661997-08-02 03:10:38 +000079 Locking: you must hold the interpreter lock while calling this.
80 (If the lock has not yet been initialized, that's equivalent to
81 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000082
Guido van Rossum25ce5661997-08-02 03:10:38 +000083*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000084
Guido van Rossum9abaf4d2001-10-12 22:17:56 +000085static int
86add_flag(int flag, const char *envs)
87{
88 int env = atoi(envs);
89 if (flag < env)
90 flag = env;
91 if (flag < 1)
92 flag = 1;
93 return flag;
94}
95
Guido van Rossuma027efa1997-05-05 20:56:21 +000096void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000097Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000098{
Guido van Rossuma027efa1997-05-05 20:56:21 +000099 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000100 PyThreadState *tstate;
101 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000102 char *p;
Guido van Rossum70d893a2001-08-16 08:21:42 +0000103 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000104
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000105 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000106 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000107 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000108
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000109 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000110 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000111 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000112 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000113 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000114 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000115
Guido van Rossuma027efa1997-05-05 20:56:21 +0000116 interp = PyInterpreterState_New();
117 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000119
Guido van Rossuma027efa1997-05-05 20:56:21 +0000120 tstate = PyThreadState_New(interp);
121 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000123 (void) PyThreadState_Swap(tstate);
124
Guido van Rossum70d893a2001-08-16 08:21:42 +0000125 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127 interp->modules = PyDict_New();
128 if (interp->modules == NULL)
129 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000130
Guido van Rossumc94044c2000-03-10 23:03:54 +0000131 /* Init codec registry */
132 _PyCodecRegistry_Init();
133
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000134#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000135 /* Init Unicode implementation; relies on the codec registry */
136 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000137#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000138
Barry Warsawf242aa02000-05-25 23:09:49 +0000139 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140 if (bimod == NULL)
141 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000142 interp->builtins = PyModule_GetDict(bimod);
143 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000144
145 sysmod = _PySys_Init();
146 if (sysmod == NULL)
147 Py_FatalError("Py_Initialize: can't initialize sys");
148 interp->sysdict = PyModule_GetDict(sysmod);
149 Py_INCREF(interp->sysdict);
150 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000151 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000152 PyDict_SetItemString(interp->sysdict, "modules",
153 interp->modules);
154
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000155 _PyImport_Init();
156
Barry Warsawf242aa02000-05-25 23:09:49 +0000157 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000158 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000159 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000160
Barry Warsaw035574d1997-08-29 22:07:17 +0000161 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000162 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000163
Guido van Rossum25ce5661997-08-02 03:10:38 +0000164 initsigs(); /* Signal handling stuff, including initintr() */
165
166 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000167 if (!Py_NoSiteFlag)
168 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169}
170
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000171#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000172extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000173#endif
174
Guido van Rossum25ce5661997-08-02 03:10:38 +0000175/* Undo the effect of Py_Initialize().
176
177 Beware: if multiple interpreter and/or thread states exist, these
178 are not wiped out; only the current thread and interpreter state
179 are deleted. But since everything else is deleted, those other
180 interpreter and thread states should no longer be used.
181
182 (XXX We should do better, e.g. wipe out all interpreters and
183 threads.)
184
185 Locking: as above.
186
187*/
188
189void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000190Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191{
192 PyInterpreterState *interp;
193 PyThreadState *tstate;
194
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000195 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000196 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000197
Tim Peters384fd102001-01-21 03:40:37 +0000198 /* The interpreter is still entirely intact at this point, and the
199 * exit funcs may be relying on that. In particular, if some thread
200 * or exit func is still waiting to do an import, the import machinery
201 * expects Py_IsInitialized() to return true. So don't say the
202 * interpreter is uninitialized until after the exit funcs have run.
203 * Note that Threading.py uses an exit func to do a join on all the
204 * threads created thru it, so this also protects pending imports in
205 * the threads created via Threading.
206 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000207 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000208 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000209
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000210 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000211 tstate = PyThreadState_Get();
212 interp = tstate->interp;
213
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000214 /* Disable signal handling */
215 PyOS_FiniInterrupts();
216
Guido van Rossumc94044c2000-03-10 23:03:54 +0000217 /* Cleanup Codec registry */
218 _PyCodecRegistry_Fini();
219
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000220 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000221 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000222
Guido van Rossum1707aad1997-12-08 23:43:45 +0000223 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
224 _PyImport_Fini();
225
226 /* Debugging stuff */
227#ifdef COUNT_ALLOCS
228 dump_counts();
229#endif
230
231#ifdef Py_REF_DEBUG
232 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
233#endif
234
235#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000236 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000237 _Py_PrintReferences(stderr);
238 }
239#endif /* Py_TRACE_REFS */
240
Barry Warsaw035574d1997-08-29 22:07:17 +0000241 /* Now we decref the exception classes. After this point nothing
242 can raise an exception. That's okay, because each Fini() method
243 below has been checked to make sure no exceptions are ever
244 raised.
245 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000246 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000247
248 /* Delete current thread */
249 PyInterpreterState_Clear(interp);
250 PyThreadState_Swap(NULL);
251 PyInterpreterState_Delete(interp);
252
Guido van Rossumcc283f51997-08-05 02:22:03 +0000253 PyMethod_Fini();
254 PyFrame_Fini();
255 PyCFunction_Fini();
256 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000257 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000258 PyInt_Fini();
259 PyFloat_Fini();
260
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000261#ifdef Py_USING_UNICODE
262 /* Cleanup Unicode implementation */
263 _PyUnicode_Fini();
264#endif
265
Guido van Rossumcc283f51997-08-05 02:22:03 +0000266 /* XXX Still allocated:
267 - various static ad-hoc pointers to interned strings
268 - int and float free list blocks
269 - whatever various modules and libraries allocate
270 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000271
272 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000273
Tim Peters0e871182002-04-13 08:29:14 +0000274#ifdef PYMALLOC_DEBUG
275 if (Py_GETENV("PYTHONMALLOCSTATS"))
276 _PyObject_DebugMallocStats();
277#endif
278
Guido van Rossumcc283f51997-08-05 02:22:03 +0000279 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000280}
281
282/* Create and initialize a new interpreter and thread, and return the
283 new thread. This requires that Py_Initialize() has been called
284 first.
285
286 Unsuccessful initialization yields a NULL pointer. Note that *no*
287 exception information is available even in this case -- the
288 exception information is held in the thread, and there is no
289 thread.
290
291 Locking: as above.
292
293*/
294
295PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000296Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000297{
298 PyInterpreterState *interp;
299 PyThreadState *tstate, *save_tstate;
300 PyObject *bimod, *sysmod;
301
302 if (!initialized)
303 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
304
305 interp = PyInterpreterState_New();
306 if (interp == NULL)
307 return NULL;
308
309 tstate = PyThreadState_New(interp);
310 if (tstate == NULL) {
311 PyInterpreterState_Delete(interp);
312 return NULL;
313 }
314
315 save_tstate = PyThreadState_Swap(tstate);
316
317 /* XXX The following is lax in error checking */
318
319 interp->modules = PyDict_New();
320
321 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
322 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000323 interp->builtins = PyModule_GetDict(bimod);
324 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000325 }
326 sysmod = _PyImport_FindExtension("sys", "sys");
327 if (bimod != NULL && sysmod != NULL) {
328 interp->sysdict = PyModule_GetDict(sysmod);
329 Py_INCREF(interp->sysdict);
330 PySys_SetPath(Py_GetPath());
331 PyDict_SetItemString(interp->sysdict, "modules",
332 interp->modules);
333 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000334 if (!Py_NoSiteFlag)
335 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000336 }
337
338 if (!PyErr_Occurred())
339 return tstate;
340
341 /* Oops, it didn't work. Undo it all. */
342
343 PyErr_Print();
344 PyThreadState_Clear(tstate);
345 PyThreadState_Swap(save_tstate);
346 PyThreadState_Delete(tstate);
347 PyInterpreterState_Delete(interp);
348
349 return NULL;
350}
351
352/* Delete an interpreter and its last thread. This requires that the
353 given thread state is current, that the thread has no remaining
354 frames, and that it is its interpreter's only remaining thread.
355 It is a fatal error to violate these constraints.
356
357 (Py_Finalize() doesn't have these constraints -- it zaps
358 everything, regardless.)
359
360 Locking: as above.
361
362*/
363
364void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000365Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000366{
367 PyInterpreterState *interp = tstate->interp;
368
369 if (tstate != PyThreadState_Get())
370 Py_FatalError("Py_EndInterpreter: thread is not current");
371 if (tstate->frame != NULL)
372 Py_FatalError("Py_EndInterpreter: thread still has a frame");
373 if (tstate != interp->tstate_head || tstate->next != NULL)
374 Py_FatalError("Py_EndInterpreter: not the last thread");
375
376 PyImport_Cleanup();
377 PyInterpreterState_Clear(interp);
378 PyThreadState_Swap(NULL);
379 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000380}
381
382static char *progname = "python";
383
384void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000385Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000386{
387 if (pn && *pn)
388 progname = pn;
389}
390
391char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000392Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000393{
394 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000395}
396
Guido van Rossuma61691e1998-02-06 22:27:24 +0000397static char *default_home = NULL;
398
399void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000400Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000401{
402 default_home = home;
403}
404
405char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000406Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000407{
408 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000409 if (home == NULL && !Py_IgnoreEnvironmentFlag)
410 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000411 return home;
412}
413
Guido van Rossum6135a871995-01-09 17:53:26 +0000414/* Create __main__ module */
415
416static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000417initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000418{
Guido van Rossum82598051997-03-05 00:20:32 +0000419 PyObject *m, *d;
420 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000421 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000422 Py_FatalError("can't create __main__ module");
423 d = PyModule_GetDict(m);
424 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000425 PyObject *bimod = PyImport_ImportModule("__builtin__");
426 if (bimod == NULL ||
427 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000428 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000429 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000430 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000431}
432
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000433/* Import the site module (not into __main__ though) */
434
435static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000436initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000437{
438 PyObject *m, *f;
439 m = PyImport_ImportModule("site");
440 if (m == NULL) {
441 f = PySys_GetObject("stderr");
442 if (Py_VerboseFlag) {
443 PyFile_WriteString(
444 "'import site' failed; traceback:\n", f);
445 PyErr_Print();
446 }
447 else {
448 PyFile_WriteString(
449 "'import site' failed; use -v for traceback\n", f);
450 PyErr_Clear();
451 }
452 }
453 else {
454 Py_DECREF(m);
455 }
456}
457
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000458/* Parse input from a file and execute it */
459
460int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000461PyRun_AnyFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000462{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000463 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
464}
465
466int
467PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
468{
469 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000470}
471
472int
473PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
474{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000475 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
476}
477
478int
479PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
480 PyCompilerFlags *flags)
481{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000482 if (filename == NULL)
483 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000484 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000485 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000486 if (closeit)
487 fclose(fp);
488 return err;
489 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000490 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000491 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000492}
493
494int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000495PyRun_InteractiveLoop(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000496{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000497 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
498}
499
500int
501PyRun_InteractiveLoopFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
502{
Guido van Rossum82598051997-03-05 00:20:32 +0000503 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000504 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000505 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000506
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000507 if (flags == NULL) {
508 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000509 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000510 }
Guido van Rossum82598051997-03-05 00:20:32 +0000511 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000512 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000513 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
514 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000515 }
Guido van Rossum82598051997-03-05 00:20:32 +0000516 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000517 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000518 PySys_SetObject("ps2", v = PyString_FromString("... "));
519 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000520 }
521 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000522 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000523#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000524 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000525#endif
526 if (ret == E_EOF)
527 return 0;
528 /*
529 if (ret == E_NOMEM)
530 return -1;
531 */
532 }
533}
534
535int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000536PyRun_InteractiveOne(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000537{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000538 return PyRun_InteractiveOneFlags(fp, filename, NULL);
539}
540
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000541/* compute parser flags based on compiler flags */
542#if 0 /* future keyword */
543#define PARSER_FLAGS(flags) \
544 (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \
545 PyPARSE_YIELD_IS_KEYWORD : 0)
546#else
547#define PARSER_FLAGS(flags) 0
548#endif
549
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000550int
551PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
552{
Guido van Rossum82598051997-03-05 00:20:32 +0000553 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000554 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000555 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000556 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000557
Guido van Rossum82598051997-03-05 00:20:32 +0000558 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000559 if (v != NULL) {
560 v = PyObject_Str(v);
561 if (v == NULL)
562 PyErr_Clear();
563 else if (PyString_Check(v))
564 ps1 = PyString_AsString(v);
565 }
Guido van Rossum82598051997-03-05 00:20:32 +0000566 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000567 if (w != NULL) {
568 w = PyObject_Str(w);
569 if (w == NULL)
570 PyErr_Clear();
571 else if (PyString_Check(w))
572 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000573 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000574 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
575 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000576 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000577 Py_XDECREF(v);
578 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000579 if (n == NULL) {
580 if (err.error == E_EOF) {
581 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000582 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000583 return E_EOF;
584 }
585 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000586 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000587 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000588 }
Guido van Rossum82598051997-03-05 00:20:32 +0000589 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000590 if (m == NULL)
591 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000592 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000593 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000594 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000595 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000596 return -1;
597 }
Guido van Rossum82598051997-03-05 00:20:32 +0000598 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000599 if (Py_FlushLine())
600 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000601 return 0;
602}
603
604int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000605PyRun_SimpleFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000606{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000607 return PyRun_SimpleFileEx(fp, filename, 0);
608}
609
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000610/* Check whether a file maybe a pyc file: Look at the extension,
611 the file type, and, if we may close it, at the first few bytes. */
612
613static int
614maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
615{
616 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
617 return 1;
618
619#ifdef macintosh
620 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
621 if (PyMac_getfiletype(filename) == 'PYC '
622 || PyMac_getfiletype(filename) == 'APPL')
623 return 1;
624#endif /* macintosh */
625
626 /* Only look into the file if we are allowed to close it, since
627 it then should also be seekable. */
628 if (closeit) {
629 /* Read only two bytes of the magic. If the file was opened in
630 text mode, the bytes 3 and 4 of the magic (\r\n) might not
631 be read as they are on disk. */
632 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
633 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000634 /* Mess: In case of -x, the stream is NOT at its start now,
635 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000636 which makes the current stream position formally undefined,
637 and a x-platform nightmare.
638 Unfortunately, we have no direct way to know whether -x
639 was specified. So we use a terrible hack: if the current
640 stream position is not 0, we assume -x was specified, and
641 give up. Bug 132850 on SourceForge spells out the
642 hopelessness of trying anything else (fseek and ftell
643 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000644 */
Tim Peters3e876562001-02-11 04:35:39 +0000645 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000646 if (ftell(fp) == 0) {
647 if (fread(buf, 1, 2, fp) == 2 &&
648 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
649 ispyc = 1;
650 rewind(fp);
651 }
Tim Peters3e876562001-02-11 04:35:39 +0000652 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000653 }
654 return 0;
655}
656
Guido van Rossum0df002c2000-08-27 19:21:52 +0000657int
658PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
659{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000660 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
661}
662
663int
664PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit,
665 PyCompilerFlags *flags)
666{
Guido van Rossum82598051997-03-05 00:20:32 +0000667 PyObject *m, *d, *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000668 char *ext;
669
Guido van Rossum82598051997-03-05 00:20:32 +0000670 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000671 if (m == NULL)
672 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000673 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000674 if (PyDict_GetItemString(d, "__file__") == NULL) {
675 PyObject *f = PyString_FromString(filename);
676 if (f == NULL)
677 return -1;
678 if (PyDict_SetItemString(d, "__file__", f) < 0) {
679 Py_DECREF(f);
680 return -1;
681 }
682 Py_DECREF(f);
683 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000684 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000685 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000686 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000687 if (closeit)
688 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000689 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000690 fprintf(stderr, "python: Can't reopen .pyc file\n");
691 return -1;
692 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000693 /* Turn on optimization if a .pyo file is given */
694 if (strcmp(ext, ".pyo") == 0)
695 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000696 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000697 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000698 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
699 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000700 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000701 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000702 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000703 return -1;
704 }
Guido van Rossum82598051997-03-05 00:20:32 +0000705 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000706 if (Py_FlushLine())
707 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000708 return 0;
709}
710
711int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000712PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000713{
Guido van Rossum393661d2001-08-31 17:40:15 +0000714 return PyRun_SimpleStringFlags(command, NULL);
715}
716
717int
718PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
719{
Guido van Rossum82598051997-03-05 00:20:32 +0000720 PyObject *m, *d, *v;
721 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000722 if (m == NULL)
723 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000724 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000725 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000726 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000727 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000728 return -1;
729 }
Guido van Rossum82598051997-03-05 00:20:32 +0000730 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000731 if (Py_FlushLine())
732 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000733 return 0;
734}
735
Barry Warsaw035574d1997-08-29 22:07:17 +0000736static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000737parse_syntax_error(PyObject *err, PyObject **message, char **filename,
738 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000739{
740 long hold;
741 PyObject *v;
742
743 /* old style errors */
744 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000745 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
746 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000747
748 /* new style errors. `err' is an instance */
749
750 if (! (v = PyObject_GetAttrString(err, "msg")))
751 goto finally;
752 *message = v;
753
754 if (!(v = PyObject_GetAttrString(err, "filename")))
755 goto finally;
756 if (v == Py_None)
757 *filename = NULL;
758 else if (! (*filename = PyString_AsString(v)))
759 goto finally;
760
761 Py_DECREF(v);
762 if (!(v = PyObject_GetAttrString(err, "lineno")))
763 goto finally;
764 hold = PyInt_AsLong(v);
765 Py_DECREF(v);
766 v = NULL;
767 if (hold < 0 && PyErr_Occurred())
768 goto finally;
769 *lineno = (int)hold;
770
771 if (!(v = PyObject_GetAttrString(err, "offset")))
772 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000773 if (v == Py_None) {
774 *offset = -1;
775 Py_DECREF(v);
776 v = NULL;
777 } else {
778 hold = PyInt_AsLong(v);
779 Py_DECREF(v);
780 v = NULL;
781 if (hold < 0 && PyErr_Occurred())
782 goto finally;
783 *offset = (int)hold;
784 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000785
786 if (!(v = PyObject_GetAttrString(err, "text")))
787 goto finally;
788 if (v == Py_None)
789 *text = NULL;
790 else if (! (*text = PyString_AsString(v)))
791 goto finally;
792 Py_DECREF(v);
793 return 1;
794
795finally:
796 Py_XDECREF(v);
797 return 0;
798}
799
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000800void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000801PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000802{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000803 PyErr_PrintEx(1);
804}
805
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000806static void
807print_error_text(PyObject *f, int offset, char *text)
808{
809 char *nl;
810 if (offset >= 0) {
811 if (offset > 0 && offset == (int)strlen(text))
812 offset--;
813 for (;;) {
814 nl = strchr(text, '\n');
815 if (nl == NULL || nl-text >= offset)
816 break;
817 offset -= (nl+1-text);
818 text = nl+1;
819 }
820 while (*text == ' ' || *text == '\t') {
821 text++;
822 offset--;
823 }
824 }
825 PyFile_WriteString(" ", f);
826 PyFile_WriteString(text, f);
827 if (*text == '\0' || text[strlen(text)-1] != '\n')
828 PyFile_WriteString("\n", f);
829 if (offset == -1)
830 return;
831 PyFile_WriteString(" ", f);
832 offset--;
833 while (offset > 0) {
834 PyFile_WriteString(" ", f);
835 offset--;
836 }
837 PyFile_WriteString("^\n", f);
838}
839
Guido van Rossum66e8e862001-03-23 17:54:43 +0000840static void
841handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000842{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000843 PyObject *exception, *value, *tb;
844 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000845 if (Py_FlushLine())
846 PyErr_Clear();
847 fflush(stdout);
848 if (value == NULL || value == Py_None)
849 Py_Exit(0);
850 if (PyInstance_Check(value)) {
851 /* The error code should be in the `code' attribute. */
852 PyObject *code = PyObject_GetAttrString(value, "code");
853 if (code) {
854 Py_DECREF(value);
855 value = code;
856 if (value == Py_None)
857 Py_Exit(0);
858 }
859 /* If we failed to dig out the 'code' attribute,
860 just let the else clause below print the error. */
861 }
862 if (PyInt_Check(value))
863 Py_Exit((int)PyInt_AsLong(value));
864 else {
865 PyObject_Print(value, stderr, Py_PRINT_RAW);
866 PySys_WriteStderr("\n");
867 Py_Exit(1);
868 }
869}
870
871void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000872PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000873{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000874 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000875
876 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
877 handle_system_exit();
878 }
Guido van Rossum82598051997-03-05 00:20:32 +0000879 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000880 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000881 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000882 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000883 if (set_sys_last_vars) {
884 PySys_SetObject("last_type", exception);
885 PySys_SetObject("last_value", v);
886 PySys_SetObject("last_traceback", tb);
887 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000888 hook = PySys_GetObject("excepthook");
889 if (hook) {
890 PyObject *args = Py_BuildValue("(OOO)",
891 exception, v ? v : Py_None, tb ? tb : Py_None);
892 PyObject *result = PyEval_CallObject(hook, args);
893 if (result == NULL) {
894 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000895 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
896 handle_system_exit();
897 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000898 PyErr_Fetch(&exception2, &v2, &tb2);
899 PyErr_NormalizeException(&exception2, &v2, &tb2);
900 if (Py_FlushLine())
901 PyErr_Clear();
902 fflush(stdout);
903 PySys_WriteStderr("Error in sys.excepthook:\n");
904 PyErr_Display(exception2, v2, tb2);
905 PySys_WriteStderr("\nOriginal exception was:\n");
906 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000907 Py_XDECREF(exception2);
908 Py_XDECREF(v2);
909 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000910 }
911 Py_XDECREF(result);
912 Py_XDECREF(args);
913 } else {
914 PySys_WriteStderr("sys.excepthook is missing\n");
915 PyErr_Display(exception, v, tb);
916 }
917 Py_XDECREF(exception);
918 Py_XDECREF(v);
919 Py_XDECREF(tb);
920}
921
922void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
923{
924 int err = 0;
925 PyObject *v = value;
926 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000927 if (f == NULL)
928 fprintf(stderr, "lost sys.stderr\n");
929 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000930 if (Py_FlushLine())
931 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000932 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000933 if (tb && tb != Py_None)
934 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000935 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000936 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000937 {
Guido van Rossum82598051997-03-05 00:20:32 +0000938 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000939 char *filename, *text;
940 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000941 if (!parse_syntax_error(v, &message, &filename,
942 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000943 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000944 else {
945 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000946 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000947 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000948 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000949 else
Guido van Rossum82598051997-03-05 00:20:32 +0000950 PyFile_WriteString(filename, f);
951 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000952 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000953 PyFile_WriteString(buf, f);
954 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000955 if (text != NULL)
956 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000957 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000958 /* Can't be bothered to check all those
959 PyFile_WriteString() calls */
960 if (PyErr_Occurred())
961 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000962 }
963 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000964 if (err) {
965 /* Don't do anything else */
966 }
967 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000968 PyClassObject* exc = (PyClassObject*)exception;
969 PyObject* className = exc->cl_name;
970 PyObject* moduleName =
971 PyDict_GetItemString(exc->cl_dict, "__module__");
972
973 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000974 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000975 else {
976 char* modstr = PyString_AsString(moduleName);
977 if (modstr && strcmp(modstr, "exceptions"))
978 {
979 err = PyFile_WriteString(modstr, f);
980 err += PyFile_WriteString(".", f);
981 }
982 }
983 if (err == 0) {
984 if (className == NULL)
985 err = PyFile_WriteString("<unknown>", f);
986 else
987 err = PyFile_WriteObject(className, f,
988 Py_PRINT_RAW);
989 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000990 }
991 else
992 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
993 if (err == 0) {
994 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000995 PyObject *s = PyObject_Str(v);
996 /* only print colon if the str() of the
997 object is not the empty string
998 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000999 if (s == NULL)
1000 err = -1;
1001 else if (!PyString_Check(s) ||
1002 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001003 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001004 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001005 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1006 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001007 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001008 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001009 if (err == 0)
1010 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001011 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001012 /* If an error happened here, don't show it.
1013 XXX This is wrong, but too many callers rely on this behavior. */
1014 if (err != 0)
1015 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001016}
1017
Guido van Rossum82598051997-03-05 00:20:32 +00001018PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001019PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001020{
Guido van Rossum82598051997-03-05 00:20:32 +00001021 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001022 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001023}
1024
Guido van Rossum82598051997-03-05 00:20:32 +00001025PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001026PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1027 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001028{
Tim Peterse8682112000-08-27 20:18:17 +00001029 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001030}
1031
1032PyObject *
1033PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001034 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001035{
1036 node *n = PyParser_SimpleParseFile(fp, filename, start);
1037 if (closeit)
1038 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001039 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001040}
1041
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001042PyObject *
1043PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1044 PyCompilerFlags *flags)
1045{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001046 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001047 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001048 "<string>", globals, locals, flags);
1049}
1050
1051PyObject *
1052PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1053 PyObject *locals, PyCompilerFlags *flags)
1054{
1055 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1056 flags);
1057}
1058
1059PyObject *
1060PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1061 PyObject *locals, int closeit, PyCompilerFlags *flags)
1062{
Tim Petersfe2127d2001-07-16 05:37:24 +00001063 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001064 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001065 if (closeit)
1066 fclose(fp);
1067 return run_err_node(n, filename, globals, locals, flags);
1068}
1069
Guido van Rossum82598051997-03-05 00:20:32 +00001070static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001071run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1072 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001073{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001074 if (n == NULL)
1075 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001076 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001077}
1078
Guido van Rossum82598051997-03-05 00:20:32 +00001079static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001080run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1081 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001082{
Guido van Rossum82598051997-03-05 00:20:32 +00001083 PyCodeObject *co;
1084 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001085 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001086 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001087 if (co == NULL)
1088 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001089 v = PyEval_EvalCode(co, globals, locals);
1090 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001091 return v;
1092}
1093
Guido van Rossum82598051997-03-05 00:20:32 +00001094static PyObject *
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001095run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1096 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001097{
Guido van Rossum82598051997-03-05 00:20:32 +00001098 PyCodeObject *co;
1099 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001100 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001101 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001102
Guido van Rossum82598051997-03-05 00:20:32 +00001103 magic = PyMarshal_ReadLongFromFile(fp);
1104 if (magic != PyImport_GetMagicNumber()) {
1105 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001106 "Bad magic number in .pyc file");
1107 return NULL;
1108 }
Guido van Rossum82598051997-03-05 00:20:32 +00001109 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001110 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001111 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001112 if (v == NULL || !PyCode_Check(v)) {
1113 Py_XDECREF(v);
1114 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001115 "Bad code object in .pyc file");
1116 return NULL;
1117 }
Guido van Rossum82598051997-03-05 00:20:32 +00001118 co = (PyCodeObject *)v;
1119 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001120 if (v && flags)
1121 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001122 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001123 return v;
1124}
1125
Guido van Rossum82598051997-03-05 00:20:32 +00001126PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001127Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001128{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001129 return Py_CompileStringFlags(str, filename, start, NULL);
1130}
1131
1132PyObject *
1133Py_CompileStringFlags(char *str, char *filename, int start,
1134 PyCompilerFlags *flags)
1135{
Guido van Rossum5b722181993-03-30 17:46:03 +00001136 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001137 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001138
1139 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1140 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001141 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001142 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001143 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001144 PyNode_Free(n);
1145 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001146}
1147
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001148struct symtable *
1149Py_SymtableString(char *str, char *filename, int start)
1150{
1151 node *n;
1152 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001153 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1154 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001155 if (n == NULL)
1156 return NULL;
1157 st = PyNode_CompileSymtable(n, filename);
1158 PyNode_Free(n);
1159 return st;
1160}
1161
Guido van Rossuma110aa61994-08-29 12:50:44 +00001162/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001163
Guido van Rossuma110aa61994-08-29 12:50:44 +00001164node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001165PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001166{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001167 node *n;
1168 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001169 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1170 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001171 if (n == NULL)
1172 err_input(&err);
1173 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001174}
1175
Tim Petersfe2127d2001-07-16 05:37:24 +00001176node *
1177PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1178{
1179 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1180}
1181
Guido van Rossuma110aa61994-08-29 12:50:44 +00001182/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001183
Guido van Rossuma110aa61994-08-29 12:50:44 +00001184node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001185PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1186{
1187 node *n;
1188 perrdetail err;
1189 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1190 flags);
1191 if (n == NULL)
1192 err_input(&err);
1193 return n;
1194}
1195
1196node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001197PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001198{
Tim Petersfe2127d2001-07-16 05:37:24 +00001199 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001200}
1201
Thomas Heller6b17abf2002-07-09 09:23:27 +00001202node *
1203PyParser_SimpleParseStringFlagsFilename(char *str, char *filename,
1204 int start, int flags)
1205{
1206 node *n;
1207 perrdetail err;
1208
1209 n = PyParser_ParseStringFlagsFilename(str, filename,
1210 &_PyParser_Grammar,
1211 start, &err, flags);
1212 if (n == NULL)
1213 err_input(&err);
1214 return n;
1215}
1216
1217node *
1218PyParser_SimpleParseStringFilename(char *str, char *filename, int start)
1219{
1220 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1221 start, 0);
1222}
1223
Guido van Rossuma110aa61994-08-29 12:50:44 +00001224/* Set the error appropriate to the given input error code (see errcode.h) */
1225
1226static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001227err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001228{
Fred Drake85f36392000-07-11 17:53:00 +00001229 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001230 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001231 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001232 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001233 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001234 err->lineno, err->offset, err->text);
1235 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001236 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001237 err->text = NULL;
1238 }
1239 switch (err->error) {
1240 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001241 errtype = PyExc_IndentationError;
1242 if (err->expected == INDENT)
1243 msg = "expected an indented block";
1244 else if (err->token == INDENT)
1245 msg = "unexpected indent";
1246 else if (err->token == DEDENT)
1247 msg = "unexpected unindent";
1248 else {
1249 errtype = PyExc_SyntaxError;
1250 msg = "invalid syntax";
1251 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001252 break;
1253 case E_TOKEN:
1254 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001255 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001256 case E_EOFS:
1257 msg = "EOF while scanning triple-quoted string";
1258 break;
1259 case E_EOLS:
1260 msg = "EOL while scanning single-quoted string";
1261 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001262 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001263 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001264 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001265 return;
1266 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001267 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001268 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001269 return;
1270 case E_EOF:
1271 msg = "unexpected EOF while parsing";
1272 break;
Fred Drake85f36392000-07-11 17:53:00 +00001273 case E_TABSPACE:
1274 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001275 msg = "inconsistent use of tabs and spaces in indentation";
1276 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001277 case E_OVERFLOW:
1278 msg = "expression too long";
1279 break;
Fred Drake85f36392000-07-11 17:53:00 +00001280 case E_DEDENT:
1281 errtype = PyExc_IndentationError;
1282 msg = "unindent does not match any outer indentation level";
1283 break;
1284 case E_TOODEEP:
1285 errtype = PyExc_IndentationError;
1286 msg = "too many levels of indentation";
1287 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001288 case E_DECODE: { /* XXX */
1289 PyThreadState* tstate = PyThreadState_Get();
1290 PyObject* value = tstate->curexc_value;
1291 if (value != NULL) {
1292 u = PyObject_Repr(value);
1293 if (u != NULL) {
1294 msg = PyString_AsString(u);
1295 break;
1296 }
1297 }
1298 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001299 default:
1300 fprintf(stderr, "error=%d\n", err->error);
1301 msg = "unknown parsing error";
1302 break;
1303 }
Guido van Rossum82598051997-03-05 00:20:32 +00001304 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001305 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001306 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001307 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001308 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001309}
1310
1311/* Print fatal error message and abort */
1312
1313void
Tim Peters7c321a82002-07-09 02:57:01 +00001314Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001315{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001316 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001317#ifdef macintosh
1318 for (;;);
1319#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001320#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001321 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001322 OutputDebugString(msg);
1323 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001324#ifdef _DEBUG
1325 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001326#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001327#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001328 abort();
1329}
1330
1331/* Clean up and exit */
1332
Guido van Rossuma110aa61994-08-29 12:50:44 +00001333#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001334#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001335int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001336#endif
1337
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001338#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001339static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001340static int nexitfuncs = 0;
1341
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001342int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001343{
1344 if (nexitfuncs >= NEXITFUNCS)
1345 return -1;
1346 exitfuncs[nexitfuncs++] = func;
1347 return 0;
1348}
1349
Guido van Rossumcc283f51997-08-05 02:22:03 +00001350static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001351call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001352{
Guido van Rossum82598051997-03-05 00:20:32 +00001353 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001354
1355 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001356 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001357 Py_INCREF(exitfunc);
1358 PySys_SetObject("exitfunc", (PyObject *)NULL);
1359 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001360 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001361 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1362 PySys_WriteStderr("Error in sys.exitfunc:\n");
1363 }
Guido van Rossum82598051997-03-05 00:20:32 +00001364 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001365 }
Guido van Rossum82598051997-03-05 00:20:32 +00001366 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001367 }
1368
Guido van Rossum0829c751998-02-28 04:31:39 +00001369 if (Py_FlushLine())
1370 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001371}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001372
Guido van Rossumcc283f51997-08-05 02:22:03 +00001373static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001374call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001375{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001376 while (nexitfuncs > 0)
1377 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001378
1379 fflush(stdout);
1380 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001381}
1382
1383void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001384Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001385{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001386 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001387
Jack Jansen66a89771995-10-27 13:22:14 +00001388#ifdef macintosh
1389 PyMac_Exit(sts);
1390#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001391 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001392#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001393}
1394
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001395static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001396initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001397{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001398#ifdef HAVE_SIGNAL_H
1399#ifdef SIGPIPE
1400 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001401#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001402#ifdef SIGXFZ
1403 signal(SIGXFZ, SIG_IGN);
1404#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001405#ifdef SIGXFSZ
1406 signal(SIGXFSZ, SIG_IGN);
1407#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001408#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001409 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001410}
1411
Guido van Rossuma110aa61994-08-29 12:50:44 +00001412#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001413
1414/* Check for file descriptor connected to interactive device.
1415 Pretend that stdin is always interactive, other files never. */
1416
1417int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001418isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001419{
1420 return fd == fileno(stdin);
1421}
1422
1423#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001424
1425/*
1426 * The file descriptor fd is considered ``interactive'' if either
1427 * a) isatty(fd) is TRUE, or
1428 * b) the -i flag was given, and the filename associated with
1429 * the descriptor is NULL or "<stdin>" or "???".
1430 */
1431int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001432Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001433{
1434 if (isatty((int)fileno(fp)))
1435 return 1;
1436 if (!Py_InteractiveFlag)
1437 return 0;
1438 return (filename == NULL) ||
1439 (strcmp(filename, "<stdin>") == 0) ||
1440 (strcmp(filename, "???") == 0);
1441}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001442
1443
1444#if defined(USE_STACKCHECK)
1445#if defined(WIN32) && defined(_MSC_VER)
1446
1447/* Stack checking for Microsoft C */
1448
1449#include <malloc.h>
1450#include <excpt.h>
1451
Fred Drakee8de31c2000-08-31 05:38:39 +00001452/*
1453 * Return non-zero when we run out of memory on the stack; zero otherwise.
1454 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001455int
Fred Drake399739f2000-08-31 05:52:44 +00001456PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001457{
1458 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001459 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001460 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001461 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001462 return 0;
1463 } __except (EXCEPTION_EXECUTE_HANDLER) {
1464 /* just ignore all errors */
1465 }
1466 return 1;
1467}
1468
1469#endif /* WIN32 && _MSC_VER */
1470
1471/* Alternate implementations can be added here... */
1472
1473#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001474
1475
1476/* Wrappers around sigaction() or signal(). */
1477
1478PyOS_sighandler_t
1479PyOS_getsig(int sig)
1480{
1481#ifdef HAVE_SIGACTION
1482 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001483 /* Initialize context.sa_handler to SIG_ERR which makes about as
1484 * much sense as anything else. It should get overwritten if
1485 * sigaction actually succeeds and otherwise we avoid an
1486 * uninitialized memory read.
1487 */
1488 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001489 sigaction(sig, NULL, &context);
1490 return context.sa_handler;
1491#else
1492 PyOS_sighandler_t handler;
1493 handler = signal(sig, SIG_IGN);
1494 signal(sig, handler);
1495 return handler;
1496#endif
1497}
1498
1499PyOS_sighandler_t
1500PyOS_setsig(int sig, PyOS_sighandler_t handler)
1501{
1502#ifdef HAVE_SIGACTION
1503 struct sigaction context;
1504 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001505 /* Initialize context.sa_handler to SIG_ERR which makes about as
1506 * much sense as anything else. It should get overwritten if
1507 * sigaction actually succeeds and otherwise we avoid an
1508 * uninitialized memory read.
1509 */
1510 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001511 sigaction(sig, NULL, &context);
1512 oldhandler = context.sa_handler;
1513 context.sa_handler = handler;
1514 sigaction(sig, &context, NULL);
1515 return oldhandler;
1516#else
1517 return signal(sig, handler);
1518#endif
1519}