blob: 63e0e8e7662d710b76e8171f72699417df1f9910 [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);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000045
Guido van Rossumbffd6832000-01-20 22:32:56 +000046#ifdef Py_TRACE_REFS
47int _Py_AskYesNo(char *prompt);
48#endif
49
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000050extern void _PyUnicode_Init(void);
51extern void _PyUnicode_Fini(void);
52extern void _PyCodecRegistry_Init(void);
53extern void _PyCodecRegistry_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000054
Guido van Rossum82598051997-03-05 00:20:32 +000055int Py_DebugFlag; /* Needed by parser.c */
56int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000057int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000058int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000059int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000060int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000061int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000062int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000063/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
64 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
65 true divisions (which they will be in 2.3). */
66int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000067
Guido van Rossum25ce5661997-08-02 03:10:38 +000068static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000069
Thomas Wouters7e474022000-07-16 12:04:32 +000070/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000071
72int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000073Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000074{
75 return initialized;
76}
77
Guido van Rossum25ce5661997-08-02 03:10:38 +000078/* Global initializations. Can be undone by Py_Finalize(). Don't
79 call this twice without an intervening Py_Finalize() call. When
80 initializations fail, a fatal error is issued and the function does
81 not return. On return, the first thread and interpreter state have
82 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000083
Guido van Rossum25ce5661997-08-02 03:10:38 +000084 Locking: you must hold the interpreter lock while calling this.
85 (If the lock has not yet been initialized, that's equivalent to
86 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000087
Guido van Rossum25ce5661997-08-02 03:10:38 +000088*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000089
Guido van Rossum9abaf4d2001-10-12 22:17:56 +000090static int
91add_flag(int flag, const char *envs)
92{
93 int env = atoi(envs);
94 if (flag < env)
95 flag = env;
96 if (flag < 1)
97 flag = 1;
98 return flag;
99}
100
Guido van Rossuma027efa1997-05-05 20:56:21 +0000101void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000102Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000103{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000104 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000105 PyThreadState *tstate;
106 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000107 char *p;
Guido van Rossum70d893a2001-08-16 08:21:42 +0000108 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000109
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000110 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000111 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000112 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000114 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000115 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000116 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000117 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000118 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000119 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000120
Guido van Rossuma027efa1997-05-05 20:56:21 +0000121 interp = PyInterpreterState_New();
122 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000124
Guido van Rossuma027efa1997-05-05 20:56:21 +0000125 tstate = PyThreadState_New(interp);
126 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000128 (void) PyThreadState_Swap(tstate);
129
Guido van Rossum70d893a2001-08-16 08:21:42 +0000130 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000131
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132 interp->modules = PyDict_New();
133 if (interp->modules == NULL)
134 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000135
Guido van Rossumc94044c2000-03-10 23:03:54 +0000136 /* Init codec registry */
137 _PyCodecRegistry_Init();
138
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000139#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000140 /* Init Unicode implementation; relies on the codec registry */
141 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000142#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000143
Barry Warsawf242aa02000-05-25 23:09:49 +0000144 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000145 if (bimod == NULL)
146 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000147 interp->builtins = PyModule_GetDict(bimod);
148 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000149
150 sysmod = _PySys_Init();
151 if (sysmod == NULL)
152 Py_FatalError("Py_Initialize: can't initialize sys");
153 interp->sysdict = PyModule_GetDict(sysmod);
154 Py_INCREF(interp->sysdict);
155 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000156 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000157 PyDict_SetItemString(interp->sysdict, "modules",
158 interp->modules);
159
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000160 _PyImport_Init();
161
Barry Warsawf242aa02000-05-25 23:09:49 +0000162 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000163 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000164 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000165
Barry Warsaw035574d1997-08-29 22:07:17 +0000166 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000167 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000168
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169 initsigs(); /* Signal handling stuff, including initintr() */
170
171 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000172 if (!Py_NoSiteFlag)
173 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000174}
175
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000176#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000177extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000178#endif
179
Guido van Rossum25ce5661997-08-02 03:10:38 +0000180/* Undo the effect of Py_Initialize().
181
182 Beware: if multiple interpreter and/or thread states exist, these
183 are not wiped out; only the current thread and interpreter state
184 are deleted. But since everything else is deleted, those other
185 interpreter and thread states should no longer be used.
186
187 (XXX We should do better, e.g. wipe out all interpreters and
188 threads.)
189
190 Locking: as above.
191
192*/
193
194void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000195Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000196{
197 PyInterpreterState *interp;
198 PyThreadState *tstate;
199
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000200 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000201 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202
Tim Peters384fd102001-01-21 03:40:37 +0000203 /* The interpreter is still entirely intact at this point, and the
204 * exit funcs may be relying on that. In particular, if some thread
205 * or exit func is still waiting to do an import, the import machinery
206 * expects Py_IsInitialized() to return true. So don't say the
207 * interpreter is uninitialized until after the exit funcs have run.
208 * Note that Threading.py uses an exit func to do a join on all the
209 * threads created thru it, so this also protects pending imports in
210 * the threads created via Threading.
211 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000212 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000213 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000214
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000215 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000216 tstate = PyThreadState_Get();
217 interp = tstate->interp;
218
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000219 /* Disable signal handling */
220 PyOS_FiniInterrupts();
221
Guido van Rossumc94044c2000-03-10 23:03:54 +0000222 /* Cleanup Codec registry */
223 _PyCodecRegistry_Fini();
224
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000225 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000226 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000227
Guido van Rossum1707aad1997-12-08 23:43:45 +0000228 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
229 _PyImport_Fini();
230
231 /* Debugging stuff */
232#ifdef COUNT_ALLOCS
233 dump_counts();
234#endif
235
236#ifdef Py_REF_DEBUG
237 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
238#endif
239
240#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000241 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000242 _Py_PrintReferences(stderr);
243 }
244#endif /* Py_TRACE_REFS */
245
Barry Warsaw035574d1997-08-29 22:07:17 +0000246 /* Now we decref the exception classes. After this point nothing
247 can raise an exception. That's okay, because each Fini() method
248 below has been checked to make sure no exceptions are ever
249 raised.
250 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000251 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000252
253 /* Delete current thread */
254 PyInterpreterState_Clear(interp);
255 PyThreadState_Swap(NULL);
256 PyInterpreterState_Delete(interp);
257
Guido van Rossumcc283f51997-08-05 02:22:03 +0000258 PyMethod_Fini();
259 PyFrame_Fini();
260 PyCFunction_Fini();
261 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000262 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000263 PyInt_Fini();
264 PyFloat_Fini();
265
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000266#ifdef Py_USING_UNICODE
267 /* Cleanup Unicode implementation */
268 _PyUnicode_Fini();
269#endif
270
Guido van Rossumcc283f51997-08-05 02:22:03 +0000271 /* XXX Still allocated:
272 - various static ad-hoc pointers to interned strings
273 - int and float free list blocks
274 - whatever various modules and libraries allocate
275 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000276
277 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000278
Tim Peters0e871182002-04-13 08:29:14 +0000279#ifdef PYMALLOC_DEBUG
280 if (Py_GETENV("PYTHONMALLOCSTATS"))
281 _PyObject_DebugMallocStats();
282#endif
283
Guido van Rossumcc283f51997-08-05 02:22:03 +0000284 call_ll_exitfuncs();
285
Guido van Rossumcc283f51997-08-05 02:22:03 +0000286#ifdef Py_TRACE_REFS
Guido van Rossumcc283f51997-08-05 02:22:03 +0000287 _Py_ResetReferences();
288#endif /* Py_TRACE_REFS */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000289}
290
291/* Create and initialize a new interpreter and thread, and return the
292 new thread. This requires that Py_Initialize() has been called
293 first.
294
295 Unsuccessful initialization yields a NULL pointer. Note that *no*
296 exception information is available even in this case -- the
297 exception information is held in the thread, and there is no
298 thread.
299
300 Locking: as above.
301
302*/
303
304PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000305Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306{
307 PyInterpreterState *interp;
308 PyThreadState *tstate, *save_tstate;
309 PyObject *bimod, *sysmod;
310
311 if (!initialized)
312 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
313
314 interp = PyInterpreterState_New();
315 if (interp == NULL)
316 return NULL;
317
318 tstate = PyThreadState_New(interp);
319 if (tstate == NULL) {
320 PyInterpreterState_Delete(interp);
321 return NULL;
322 }
323
324 save_tstate = PyThreadState_Swap(tstate);
325
326 /* XXX The following is lax in error checking */
327
328 interp->modules = PyDict_New();
329
330 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
331 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000332 interp->builtins = PyModule_GetDict(bimod);
333 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000334 }
335 sysmod = _PyImport_FindExtension("sys", "sys");
336 if (bimod != NULL && sysmod != NULL) {
337 interp->sysdict = PyModule_GetDict(sysmod);
338 Py_INCREF(interp->sysdict);
339 PySys_SetPath(Py_GetPath());
340 PyDict_SetItemString(interp->sysdict, "modules",
341 interp->modules);
342 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000343 if (!Py_NoSiteFlag)
344 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000345 }
346
347 if (!PyErr_Occurred())
348 return tstate;
349
350 /* Oops, it didn't work. Undo it all. */
351
352 PyErr_Print();
353 PyThreadState_Clear(tstate);
354 PyThreadState_Swap(save_tstate);
355 PyThreadState_Delete(tstate);
356 PyInterpreterState_Delete(interp);
357
358 return NULL;
359}
360
361/* Delete an interpreter and its last thread. This requires that the
362 given thread state is current, that the thread has no remaining
363 frames, and that it is its interpreter's only remaining thread.
364 It is a fatal error to violate these constraints.
365
366 (Py_Finalize() doesn't have these constraints -- it zaps
367 everything, regardless.)
368
369 Locking: as above.
370
371*/
372
373void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000374Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000375{
376 PyInterpreterState *interp = tstate->interp;
377
378 if (tstate != PyThreadState_Get())
379 Py_FatalError("Py_EndInterpreter: thread is not current");
380 if (tstate->frame != NULL)
381 Py_FatalError("Py_EndInterpreter: thread still has a frame");
382 if (tstate != interp->tstate_head || tstate->next != NULL)
383 Py_FatalError("Py_EndInterpreter: not the last thread");
384
385 PyImport_Cleanup();
386 PyInterpreterState_Clear(interp);
387 PyThreadState_Swap(NULL);
388 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000389}
390
391static char *progname = "python";
392
393void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000394Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000395{
396 if (pn && *pn)
397 progname = pn;
398}
399
400char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000401Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000402{
403 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000404}
405
Guido van Rossuma61691e1998-02-06 22:27:24 +0000406static char *default_home = NULL;
407
408void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000409Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000410{
411 default_home = home;
412}
413
414char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000415Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000416{
417 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000418 if (home == NULL && !Py_IgnoreEnvironmentFlag)
419 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000420 return home;
421}
422
Guido van Rossum6135a871995-01-09 17:53:26 +0000423/* Create __main__ module */
424
425static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000426initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000427{
Guido van Rossum82598051997-03-05 00:20:32 +0000428 PyObject *m, *d;
429 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000430 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000431 Py_FatalError("can't create __main__ module");
432 d = PyModule_GetDict(m);
433 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000434 PyObject *bimod = PyImport_ImportModule("__builtin__");
435 if (bimod == NULL ||
436 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000437 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000438 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000439 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000440}
441
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000442/* Import the site module (not into __main__ though) */
443
444static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000445initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000446{
447 PyObject *m, *f;
448 m = PyImport_ImportModule("site");
449 if (m == NULL) {
450 f = PySys_GetObject("stderr");
451 if (Py_VerboseFlag) {
452 PyFile_WriteString(
453 "'import site' failed; traceback:\n", f);
454 PyErr_Print();
455 }
456 else {
457 PyFile_WriteString(
458 "'import site' failed; use -v for traceback\n", f);
459 PyErr_Clear();
460 }
461 }
462 else {
463 Py_DECREF(m);
464 }
465}
466
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000467/* Parse input from a file and execute it */
468
469int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000470PyRun_AnyFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000471{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000472 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
473}
474
475int
476PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
477{
478 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000479}
480
481int
482PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
483{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000484 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
485}
486
487int
488PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
489 PyCompilerFlags *flags)
490{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000491 if (filename == NULL)
492 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000493 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000494 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000495 if (closeit)
496 fclose(fp);
497 return err;
498 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000499 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000500 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000501}
502
503int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000504PyRun_InteractiveLoop(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000505{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000506 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
507}
508
509int
510PyRun_InteractiveLoopFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
511{
Guido van Rossum82598051997-03-05 00:20:32 +0000512 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000513 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000514 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000515
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000516 if (flags == NULL) {
517 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000518 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000519 }
Guido van Rossum82598051997-03-05 00:20:32 +0000520 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000521 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000522 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
523 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000524 }
Guido van Rossum82598051997-03-05 00:20:32 +0000525 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000526 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000527 PySys_SetObject("ps2", v = PyString_FromString("... "));
528 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000529 }
530 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000531 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000532#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000533 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000534#endif
535 if (ret == E_EOF)
536 return 0;
537 /*
538 if (ret == E_NOMEM)
539 return -1;
540 */
541 }
542}
543
544int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000545PyRun_InteractiveOne(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000546{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000547 return PyRun_InteractiveOneFlags(fp, filename, NULL);
548}
549
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000550/* compute parser flags based on compiler flags */
551#if 0 /* future keyword */
552#define PARSER_FLAGS(flags) \
553 (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \
554 PyPARSE_YIELD_IS_KEYWORD : 0)
555#else
556#define PARSER_FLAGS(flags) 0
557#endif
558
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000559int
560PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
561{
Guido van Rossum82598051997-03-05 00:20:32 +0000562 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000563 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000564 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000565 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000566
Guido van Rossum82598051997-03-05 00:20:32 +0000567 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000568 if (v != NULL) {
569 v = PyObject_Str(v);
570 if (v == NULL)
571 PyErr_Clear();
572 else if (PyString_Check(v))
573 ps1 = PyString_AsString(v);
574 }
Guido van Rossum82598051997-03-05 00:20:32 +0000575 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000576 if (w != NULL) {
577 w = PyObject_Str(w);
578 if (w == NULL)
579 PyErr_Clear();
580 else if (PyString_Check(w))
581 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000582 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000583 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
584 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000585 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000586 Py_XDECREF(v);
587 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000588 if (n == NULL) {
589 if (err.error == E_EOF) {
590 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000591 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000592 return E_EOF;
593 }
594 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000595 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000596 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000597 }
Guido van Rossum82598051997-03-05 00:20:32 +0000598 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000599 if (m == NULL)
600 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000601 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000602 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000603 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000604 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000605 return -1;
606 }
Guido van Rossum82598051997-03-05 00:20:32 +0000607 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000608 if (Py_FlushLine())
609 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000610 return 0;
611}
612
613int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000614PyRun_SimpleFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000615{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000616 return PyRun_SimpleFileEx(fp, filename, 0);
617}
618
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000619/* Check whether a file maybe a pyc file: Look at the extension,
620 the file type, and, if we may close it, at the first few bytes. */
621
622static int
623maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
624{
625 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
626 return 1;
627
628#ifdef macintosh
629 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
630 if (PyMac_getfiletype(filename) == 'PYC '
631 || PyMac_getfiletype(filename) == 'APPL')
632 return 1;
633#endif /* macintosh */
634
635 /* Only look into the file if we are allowed to close it, since
636 it then should also be seekable. */
637 if (closeit) {
638 /* Read only two bytes of the magic. If the file was opened in
639 text mode, the bytes 3 and 4 of the magic (\r\n) might not
640 be read as they are on disk. */
641 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
642 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000643 /* Mess: In case of -x, the stream is NOT at its start now,
644 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000645 which makes the current stream position formally undefined,
646 and a x-platform nightmare.
647 Unfortunately, we have no direct way to know whether -x
648 was specified. So we use a terrible hack: if the current
649 stream position is not 0, we assume -x was specified, and
650 give up. Bug 132850 on SourceForge spells out the
651 hopelessness of trying anything else (fseek and ftell
652 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000653 */
Tim Peters3e876562001-02-11 04:35:39 +0000654 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000655 if (ftell(fp) == 0) {
656 if (fread(buf, 1, 2, fp) == 2 &&
657 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
658 ispyc = 1;
659 rewind(fp);
660 }
Tim Peters3e876562001-02-11 04:35:39 +0000661 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000662 }
663 return 0;
664}
665
Guido van Rossum0df002c2000-08-27 19:21:52 +0000666int
667PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
668{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000669 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
670}
671
672int
673PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit,
674 PyCompilerFlags *flags)
675{
Guido van Rossum82598051997-03-05 00:20:32 +0000676 PyObject *m, *d, *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000677 char *ext;
678
Guido van Rossum82598051997-03-05 00:20:32 +0000679 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000680 if (m == NULL)
681 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000682 d = PyModule_GetDict(m);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000683 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000684 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000685 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000686 if (closeit)
687 fclose(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000688 if( (fp = fopen(filename, "rb")) == NULL ) {
689 fprintf(stderr, "python: Can't reopen .pyc file\n");
690 return -1;
691 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000692 /* Turn on optimization if a .pyo file is given */
693 if (strcmp(ext, ".pyo") == 0)
694 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000695 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000696 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000697 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
698 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000699 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000700 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000701 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000702 return -1;
703 }
Guido van Rossum82598051997-03-05 00:20:32 +0000704 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000705 if (Py_FlushLine())
706 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000707 return 0;
708}
709
710int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000712{
Guido van Rossum393661d2001-08-31 17:40:15 +0000713 return PyRun_SimpleStringFlags(command, NULL);
714}
715
716int
717PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
718{
Guido van Rossum82598051997-03-05 00:20:32 +0000719 PyObject *m, *d, *v;
720 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000721 if (m == NULL)
722 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000723 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000724 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000725 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000726 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000727 return -1;
728 }
Guido van Rossum82598051997-03-05 00:20:32 +0000729 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000730 if (Py_FlushLine())
731 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000732 return 0;
733}
734
Barry Warsaw035574d1997-08-29 22:07:17 +0000735static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000736parse_syntax_error(PyObject *err, PyObject **message, char **filename,
737 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000738{
739 long hold;
740 PyObject *v;
741
742 /* old style errors */
743 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000744 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
745 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000746
747 /* new style errors. `err' is an instance */
748
749 if (! (v = PyObject_GetAttrString(err, "msg")))
750 goto finally;
751 *message = v;
752
753 if (!(v = PyObject_GetAttrString(err, "filename")))
754 goto finally;
755 if (v == Py_None)
756 *filename = NULL;
757 else if (! (*filename = PyString_AsString(v)))
758 goto finally;
759
760 Py_DECREF(v);
761 if (!(v = PyObject_GetAttrString(err, "lineno")))
762 goto finally;
763 hold = PyInt_AsLong(v);
764 Py_DECREF(v);
765 v = NULL;
766 if (hold < 0 && PyErr_Occurred())
767 goto finally;
768 *lineno = (int)hold;
769
770 if (!(v = PyObject_GetAttrString(err, "offset")))
771 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000772 if (v == Py_None) {
773 *offset = -1;
774 Py_DECREF(v);
775 v = NULL;
776 } else {
777 hold = PyInt_AsLong(v);
778 Py_DECREF(v);
779 v = NULL;
780 if (hold < 0 && PyErr_Occurred())
781 goto finally;
782 *offset = (int)hold;
783 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000784
785 if (!(v = PyObject_GetAttrString(err, "text")))
786 goto finally;
787 if (v == Py_None)
788 *text = NULL;
789 else if (! (*text = PyString_AsString(v)))
790 goto finally;
791 Py_DECREF(v);
792 return 1;
793
794finally:
795 Py_XDECREF(v);
796 return 0;
797}
798
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000799void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000800PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000801{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000802 PyErr_PrintEx(1);
803}
804
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000805static void
806print_error_text(PyObject *f, int offset, char *text)
807{
808 char *nl;
809 if (offset >= 0) {
810 if (offset > 0 && offset == (int)strlen(text))
811 offset--;
812 for (;;) {
813 nl = strchr(text, '\n');
814 if (nl == NULL || nl-text >= offset)
815 break;
816 offset -= (nl+1-text);
817 text = nl+1;
818 }
819 while (*text == ' ' || *text == '\t') {
820 text++;
821 offset--;
822 }
823 }
824 PyFile_WriteString(" ", f);
825 PyFile_WriteString(text, f);
826 if (*text == '\0' || text[strlen(text)-1] != '\n')
827 PyFile_WriteString("\n", f);
828 if (offset == -1)
829 return;
830 PyFile_WriteString(" ", f);
831 offset--;
832 while (offset > 0) {
833 PyFile_WriteString(" ", f);
834 offset--;
835 }
836 PyFile_WriteString("^\n", f);
837}
838
Guido van Rossum66e8e862001-03-23 17:54:43 +0000839static void
840handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000841{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000842 PyObject *exception, *value, *tb;
843 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000844 if (Py_FlushLine())
845 PyErr_Clear();
846 fflush(stdout);
847 if (value == NULL || value == Py_None)
848 Py_Exit(0);
849 if (PyInstance_Check(value)) {
850 /* The error code should be in the `code' attribute. */
851 PyObject *code = PyObject_GetAttrString(value, "code");
852 if (code) {
853 Py_DECREF(value);
854 value = code;
855 if (value == Py_None)
856 Py_Exit(0);
857 }
858 /* If we failed to dig out the 'code' attribute,
859 just let the else clause below print the error. */
860 }
861 if (PyInt_Check(value))
862 Py_Exit((int)PyInt_AsLong(value));
863 else {
864 PyObject_Print(value, stderr, Py_PRINT_RAW);
865 PySys_WriteStderr("\n");
866 Py_Exit(1);
867 }
868}
869
870void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000871PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000872{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000873 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000874
875 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
876 handle_system_exit();
877 }
Guido van Rossum82598051997-03-05 00:20:32 +0000878 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000879 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000880 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000881 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000882 if (set_sys_last_vars) {
883 PySys_SetObject("last_type", exception);
884 PySys_SetObject("last_value", v);
885 PySys_SetObject("last_traceback", tb);
886 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000887 hook = PySys_GetObject("excepthook");
888 if (hook) {
889 PyObject *args = Py_BuildValue("(OOO)",
890 exception, v ? v : Py_None, tb ? tb : Py_None);
891 PyObject *result = PyEval_CallObject(hook, args);
892 if (result == NULL) {
893 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000894 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
895 handle_system_exit();
896 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000897 PyErr_Fetch(&exception2, &v2, &tb2);
898 PyErr_NormalizeException(&exception2, &v2, &tb2);
899 if (Py_FlushLine())
900 PyErr_Clear();
901 fflush(stdout);
902 PySys_WriteStderr("Error in sys.excepthook:\n");
903 PyErr_Display(exception2, v2, tb2);
904 PySys_WriteStderr("\nOriginal exception was:\n");
905 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000906 Py_XDECREF(exception2);
907 Py_XDECREF(v2);
908 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000909 }
910 Py_XDECREF(result);
911 Py_XDECREF(args);
912 } else {
913 PySys_WriteStderr("sys.excepthook is missing\n");
914 PyErr_Display(exception, v, tb);
915 }
916 Py_XDECREF(exception);
917 Py_XDECREF(v);
918 Py_XDECREF(tb);
919}
920
921void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
922{
923 int err = 0;
924 PyObject *v = value;
925 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000926 if (f == NULL)
927 fprintf(stderr, "lost sys.stderr\n");
928 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000929 if (Py_FlushLine())
930 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000931 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000932 if (tb && tb != Py_None)
933 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000934 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000935 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000936 {
Guido van Rossum82598051997-03-05 00:20:32 +0000937 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000938 char *filename, *text;
939 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000940 if (!parse_syntax_error(v, &message, &filename,
941 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000942 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000943 else {
944 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000945 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000946 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000947 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000948 else
Guido van Rossum82598051997-03-05 00:20:32 +0000949 PyFile_WriteString(filename, f);
950 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000951 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000952 PyFile_WriteString(buf, f);
953 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000954 if (text != NULL)
955 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000956 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000957 /* Can't be bothered to check all those
958 PyFile_WriteString() calls */
959 if (PyErr_Occurred())
960 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000961 }
962 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000963 if (err) {
964 /* Don't do anything else */
965 }
966 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000967 PyClassObject* exc = (PyClassObject*)exception;
968 PyObject* className = exc->cl_name;
969 PyObject* moduleName =
970 PyDict_GetItemString(exc->cl_dict, "__module__");
971
972 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000973 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000974 else {
975 char* modstr = PyString_AsString(moduleName);
976 if (modstr && strcmp(modstr, "exceptions"))
977 {
978 err = PyFile_WriteString(modstr, f);
979 err += PyFile_WriteString(".", f);
980 }
981 }
982 if (err == 0) {
983 if (className == NULL)
984 err = PyFile_WriteString("<unknown>", f);
985 else
986 err = PyFile_WriteObject(className, f,
987 Py_PRINT_RAW);
988 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000989 }
990 else
991 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
992 if (err == 0) {
993 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000994 PyObject *s = PyObject_Str(v);
995 /* only print colon if the str() of the
996 object is not the empty string
997 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000998 if (s == NULL)
999 err = -1;
1000 else if (!PyString_Check(s) ||
1001 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001002 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001003 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001004 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1005 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001006 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001007 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001008 if (err == 0)
1009 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001010 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001011 /* If an error happened here, don't show it.
1012 XXX This is wrong, but too many callers rely on this behavior. */
1013 if (err != 0)
1014 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001015}
1016
Guido van Rossum82598051997-03-05 00:20:32 +00001017PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001018PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001019{
Guido van Rossum82598051997-03-05 00:20:32 +00001020 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001021 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001022}
1023
Guido van Rossum82598051997-03-05 00:20:32 +00001024PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001025PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1026 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001027{
Tim Peterse8682112000-08-27 20:18:17 +00001028 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001029}
1030
1031PyObject *
1032PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001033 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001034{
1035 node *n = PyParser_SimpleParseFile(fp, filename, start);
1036 if (closeit)
1037 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001038 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001039}
1040
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001041PyObject *
1042PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1043 PyCompilerFlags *flags)
1044{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001045 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001046 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001047 "<string>", globals, locals, flags);
1048}
1049
1050PyObject *
1051PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1052 PyObject *locals, PyCompilerFlags *flags)
1053{
1054 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1055 flags);
1056}
1057
1058PyObject *
1059PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1060 PyObject *locals, int closeit, PyCompilerFlags *flags)
1061{
Tim Petersfe2127d2001-07-16 05:37:24 +00001062 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001063 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001064 if (closeit)
1065 fclose(fp);
1066 return run_err_node(n, filename, globals, locals, flags);
1067}
1068
Guido van Rossum82598051997-03-05 00:20:32 +00001069static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001070run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1071 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001072{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001073 if (n == NULL)
1074 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001075 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001076}
1077
Guido van Rossum82598051997-03-05 00:20:32 +00001078static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001079run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1080 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001081{
Guido van Rossum82598051997-03-05 00:20:32 +00001082 PyCodeObject *co;
1083 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001084 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001085 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001086 if (co == NULL)
1087 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001088 v = PyEval_EvalCode(co, globals, locals);
1089 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001090 return v;
1091}
1092
Guido van Rossum82598051997-03-05 00:20:32 +00001093static PyObject *
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001094run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1095 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001096{
Guido van Rossum82598051997-03-05 00:20:32 +00001097 PyCodeObject *co;
1098 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001099 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001100 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001101
Guido van Rossum82598051997-03-05 00:20:32 +00001102 magic = PyMarshal_ReadLongFromFile(fp);
1103 if (magic != PyImport_GetMagicNumber()) {
1104 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001105 "Bad magic number in .pyc file");
1106 return NULL;
1107 }
Guido van Rossum82598051997-03-05 00:20:32 +00001108 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001109 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001110 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001111 if (v == NULL || !PyCode_Check(v)) {
1112 Py_XDECREF(v);
1113 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001114 "Bad code object in .pyc file");
1115 return NULL;
1116 }
Guido van Rossum82598051997-03-05 00:20:32 +00001117 co = (PyCodeObject *)v;
1118 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001119 if (v && flags)
1120 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001121 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001122 return v;
1123}
1124
Guido van Rossum82598051997-03-05 00:20:32 +00001125PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001126Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001127{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001128 return Py_CompileStringFlags(str, filename, start, NULL);
1129}
1130
1131PyObject *
1132Py_CompileStringFlags(char *str, char *filename, int start,
1133 PyCompilerFlags *flags)
1134{
Guido van Rossum5b722181993-03-30 17:46:03 +00001135 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001136 PyCodeObject *co;
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001137 n = PyParser_SimpleParseStringFlags(str, start, PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001138 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001139 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001140 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001141 PyNode_Free(n);
1142 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001143}
1144
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001145struct symtable *
1146Py_SymtableString(char *str, char *filename, int start)
1147{
1148 node *n;
1149 struct symtable *st;
1150 n = PyParser_SimpleParseString(str, start);
1151 if (n == NULL)
1152 return NULL;
1153 st = PyNode_CompileSymtable(n, filename);
1154 PyNode_Free(n);
1155 return st;
1156}
1157
Guido van Rossuma110aa61994-08-29 12:50:44 +00001158/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001159
Guido van Rossuma110aa61994-08-29 12:50:44 +00001160node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001161PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001162{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001163 node *n;
1164 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001165 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1166 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001167 if (n == NULL)
1168 err_input(&err);
1169 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001170}
1171
Tim Petersfe2127d2001-07-16 05:37:24 +00001172node *
1173PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1174{
1175 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1176}
1177
Guido van Rossuma110aa61994-08-29 12:50:44 +00001178/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001179
Guido van Rossuma110aa61994-08-29 12:50:44 +00001180node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001181PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1182{
1183 node *n;
1184 perrdetail err;
1185 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1186 flags);
1187 if (n == NULL)
1188 err_input(&err);
1189 return n;
1190}
1191
1192node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001193PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001194{
Tim Petersfe2127d2001-07-16 05:37:24 +00001195 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001196}
1197
1198/* Set the error appropriate to the given input error code (see errcode.h) */
1199
1200static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001201err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001202{
Fred Drake85f36392000-07-11 17:53:00 +00001203 PyObject *v, *w, *errtype;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001204 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001205 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001206 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001207 err->lineno, err->offset, err->text);
1208 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001209 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001210 err->text = NULL;
1211 }
1212 switch (err->error) {
1213 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001214 errtype = PyExc_IndentationError;
1215 if (err->expected == INDENT)
1216 msg = "expected an indented block";
1217 else if (err->token == INDENT)
1218 msg = "unexpected indent";
1219 else if (err->token == DEDENT)
1220 msg = "unexpected unindent";
1221 else {
1222 errtype = PyExc_SyntaxError;
1223 msg = "invalid syntax";
1224 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001225 break;
1226 case E_TOKEN:
1227 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001228 break;
1229 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001230 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001231 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001232 return;
1233 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001234 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001235 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001236 return;
1237 case E_EOF:
1238 msg = "unexpected EOF while parsing";
1239 break;
Fred Drake85f36392000-07-11 17:53:00 +00001240 case E_TABSPACE:
1241 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001242 msg = "inconsistent use of tabs and spaces in indentation";
1243 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001244 case E_OVERFLOW:
1245 msg = "expression too long";
1246 break;
Fred Drake85f36392000-07-11 17:53:00 +00001247 case E_DEDENT:
1248 errtype = PyExc_IndentationError;
1249 msg = "unindent does not match any outer indentation level";
1250 break;
1251 case E_TOODEEP:
1252 errtype = PyExc_IndentationError;
1253 msg = "too many levels of indentation";
1254 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001255 default:
1256 fprintf(stderr, "error=%d\n", err->error);
1257 msg = "unknown parsing error";
1258 break;
1259 }
Guido van Rossum82598051997-03-05 00:20:32 +00001260 w = Py_BuildValue("(sO)", msg, v);
Guido van Rossum41318302001-03-23 04:01:07 +00001261 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001262 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001263 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001264}
1265
1266/* Print fatal error message and abort */
1267
1268void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001269Py_FatalError(char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001270{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001271 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001272#ifdef macintosh
1273 for (;;);
1274#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001275#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001276 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001277 OutputDebugString(msg);
1278 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001279#ifdef _DEBUG
1280 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001281#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001282#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001283 abort();
1284}
1285
1286/* Clean up and exit */
1287
Guido van Rossuma110aa61994-08-29 12:50:44 +00001288#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001289#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001290int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001291#endif
1292
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001293#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001294static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001295static int nexitfuncs = 0;
1296
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001297int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001298{
1299 if (nexitfuncs >= NEXITFUNCS)
1300 return -1;
1301 exitfuncs[nexitfuncs++] = func;
1302 return 0;
1303}
1304
Guido van Rossumcc283f51997-08-05 02:22:03 +00001305static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001306call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001307{
Guido van Rossum82598051997-03-05 00:20:32 +00001308 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001309
1310 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001311 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001312 Py_INCREF(exitfunc);
1313 PySys_SetObject("exitfunc", (PyObject *)NULL);
1314 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001315 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001316 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1317 PySys_WriteStderr("Error in sys.exitfunc:\n");
1318 }
Guido van Rossum82598051997-03-05 00:20:32 +00001319 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001320 }
Guido van Rossum82598051997-03-05 00:20:32 +00001321 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001322 }
1323
Guido van Rossum0829c751998-02-28 04:31:39 +00001324 if (Py_FlushLine())
1325 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001326}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001327
Guido van Rossumcc283f51997-08-05 02:22:03 +00001328static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001329call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001330{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001331 while (nexitfuncs > 0)
1332 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001333
1334 fflush(stdout);
1335 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001336}
1337
1338void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001339Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001340{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001341 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001342
Jack Jansen66a89771995-10-27 13:22:14 +00001343#ifdef macintosh
1344 PyMac_Exit(sts);
1345#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001346 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001347#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001348}
1349
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001350static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001351initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001352{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001353#ifdef HAVE_SIGNAL_H
1354#ifdef SIGPIPE
1355 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001356#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001357#ifdef SIGXFZ
1358 signal(SIGXFZ, SIG_IGN);
1359#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001360#ifdef SIGXFSZ
1361 signal(SIGXFSZ, SIG_IGN);
1362#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001363#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001364 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001365}
1366
Guido van Rossumaae0d321996-05-22 16:35:33 +00001367#ifdef Py_TRACE_REFS
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001368/* Ask a yes/no question */
1369
Guido van Rossum59bff391992-09-03 20:28:00 +00001370int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001371_Py_AskYesNo(char *prompt)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001372{
1373 char buf[256];
1374
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375 fprintf(stderr, "%s [ny] ", prompt);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001376 if (fgets(buf, sizeof buf, stdin) == NULL)
1377 return 0;
1378 return buf[0] == 'y' || buf[0] == 'Y';
1379}
1380#endif
1381
Guido van Rossuma110aa61994-08-29 12:50:44 +00001382#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001383
1384/* Check for file descriptor connected to interactive device.
1385 Pretend that stdin is always interactive, other files never. */
1386
1387int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001388isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001389{
1390 return fd == fileno(stdin);
1391}
1392
1393#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001394
1395/*
1396 * The file descriptor fd is considered ``interactive'' if either
1397 * a) isatty(fd) is TRUE, or
1398 * b) the -i flag was given, and the filename associated with
1399 * the descriptor is NULL or "<stdin>" or "???".
1400 */
1401int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001402Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001403{
1404 if (isatty((int)fileno(fp)))
1405 return 1;
1406 if (!Py_InteractiveFlag)
1407 return 0;
1408 return (filename == NULL) ||
1409 (strcmp(filename, "<stdin>") == 0) ||
1410 (strcmp(filename, "???") == 0);
1411}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001412
1413
1414#if defined(USE_STACKCHECK)
1415#if defined(WIN32) && defined(_MSC_VER)
1416
1417/* Stack checking for Microsoft C */
1418
1419#include <malloc.h>
1420#include <excpt.h>
1421
Fred Drakee8de31c2000-08-31 05:38:39 +00001422/*
1423 * Return non-zero when we run out of memory on the stack; zero otherwise.
1424 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001425int
Fred Drake399739f2000-08-31 05:52:44 +00001426PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001427{
1428 __try {
1429 /* _alloca throws a stack overflow exception if there's
1430 not enough space left on the stack */
1431 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1432 return 0;
1433 } __except (EXCEPTION_EXECUTE_HANDLER) {
1434 /* just ignore all errors */
1435 }
1436 return 1;
1437}
1438
1439#endif /* WIN32 && _MSC_VER */
1440
1441/* Alternate implementations can be added here... */
1442
1443#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001444
1445
1446/* Wrappers around sigaction() or signal(). */
1447
1448PyOS_sighandler_t
1449PyOS_getsig(int sig)
1450{
1451#ifdef HAVE_SIGACTION
1452 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001453 /* Initialize context.sa_handler to SIG_ERR which makes about as
1454 * much sense as anything else. It should get overwritten if
1455 * sigaction actually succeeds and otherwise we avoid an
1456 * uninitialized memory read.
1457 */
1458 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001459 sigaction(sig, NULL, &context);
1460 return context.sa_handler;
1461#else
1462 PyOS_sighandler_t handler;
1463 handler = signal(sig, SIG_IGN);
1464 signal(sig, handler);
1465 return handler;
1466#endif
1467}
1468
1469PyOS_sighandler_t
1470PyOS_setsig(int sig, PyOS_sighandler_t handler)
1471{
1472#ifdef HAVE_SIGACTION
1473 struct sigaction context;
1474 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001475 /* Initialize context.sa_handler to SIG_ERR which makes about as
1476 * much sense as anything else. It should get overwritten if
1477 * sigaction actually succeeds and otherwise we avoid an
1478 * uninitialized memory read.
1479 */
1480 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001481 sigaction(sig, NULL, &context);
1482 oldhandler = context.sa_handler;
1483 context.sa_handler = handler;
1484 sigaction(sig, &context, NULL);
1485 return oldhandler;
1486#else
1487 return signal(sig, handler);
1488#endif
1489}