blob: ad92004f9a5f694623ed46e246c66da7fa0d5136 [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
Guido van Rossum9b38a141996-09-11 23:12:24 +000020#ifdef MS_WIN32
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
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000222#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000223 /* Cleanup Unicode implementation */
224 _PyUnicode_Fini();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000225#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000226
227 /* Cleanup Codec registry */
228 _PyCodecRegistry_Fini();
229
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000230 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000231 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000232
Guido van Rossum1707aad1997-12-08 23:43:45 +0000233 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
234 _PyImport_Fini();
235
236 /* Debugging stuff */
237#ifdef COUNT_ALLOCS
238 dump_counts();
239#endif
240
241#ifdef Py_REF_DEBUG
242 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
243#endif
244
245#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000246 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000247 _Py_PrintReferences(stderr);
248 }
249#endif /* Py_TRACE_REFS */
250
Barry Warsaw035574d1997-08-29 22:07:17 +0000251 /* Now we decref the exception classes. After this point nothing
252 can raise an exception. That's okay, because each Fini() method
253 below has been checked to make sure no exceptions are ever
254 raised.
255 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000256 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000257
258 /* Delete current thread */
259 PyInterpreterState_Clear(interp);
260 PyThreadState_Swap(NULL);
261 PyInterpreterState_Delete(interp);
262
Guido van Rossumcc283f51997-08-05 02:22:03 +0000263 PyMethod_Fini();
264 PyFrame_Fini();
265 PyCFunction_Fini();
266 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000267 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000268 PyInt_Fini();
269 PyFloat_Fini();
270
271 /* 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
279 call_ll_exitfuncs();
280
Guido van Rossumcc283f51997-08-05 02:22:03 +0000281#ifdef Py_TRACE_REFS
Guido van Rossumcc283f51997-08-05 02:22:03 +0000282 _Py_ResetReferences();
283#endif /* Py_TRACE_REFS */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000284}
285
286/* Create and initialize a new interpreter and thread, and return the
287 new thread. This requires that Py_Initialize() has been called
288 first.
289
290 Unsuccessful initialization yields a NULL pointer. Note that *no*
291 exception information is available even in this case -- the
292 exception information is held in the thread, and there is no
293 thread.
294
295 Locking: as above.
296
297*/
298
299PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000300Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000301{
302 PyInterpreterState *interp;
303 PyThreadState *tstate, *save_tstate;
304 PyObject *bimod, *sysmod;
305
306 if (!initialized)
307 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
308
309 interp = PyInterpreterState_New();
310 if (interp == NULL)
311 return NULL;
312
313 tstate = PyThreadState_New(interp);
314 if (tstate == NULL) {
315 PyInterpreterState_Delete(interp);
316 return NULL;
317 }
318
319 save_tstate = PyThreadState_Swap(tstate);
320
321 /* XXX The following is lax in error checking */
322
323 interp->modules = PyDict_New();
324
325 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
326 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000327 interp->builtins = PyModule_GetDict(bimod);
328 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000329 }
330 sysmod = _PyImport_FindExtension("sys", "sys");
331 if (bimod != NULL && sysmod != NULL) {
332 interp->sysdict = PyModule_GetDict(sysmod);
333 Py_INCREF(interp->sysdict);
334 PySys_SetPath(Py_GetPath());
335 PyDict_SetItemString(interp->sysdict, "modules",
336 interp->modules);
337 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000338 if (!Py_NoSiteFlag)
339 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000340 }
341
342 if (!PyErr_Occurred())
343 return tstate;
344
345 /* Oops, it didn't work. Undo it all. */
346
347 PyErr_Print();
348 PyThreadState_Clear(tstate);
349 PyThreadState_Swap(save_tstate);
350 PyThreadState_Delete(tstate);
351 PyInterpreterState_Delete(interp);
352
353 return NULL;
354}
355
356/* Delete an interpreter and its last thread. This requires that the
357 given thread state is current, that the thread has no remaining
358 frames, and that it is its interpreter's only remaining thread.
359 It is a fatal error to violate these constraints.
360
361 (Py_Finalize() doesn't have these constraints -- it zaps
362 everything, regardless.)
363
364 Locking: as above.
365
366*/
367
368void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000369Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000370{
371 PyInterpreterState *interp = tstate->interp;
372
373 if (tstate != PyThreadState_Get())
374 Py_FatalError("Py_EndInterpreter: thread is not current");
375 if (tstate->frame != NULL)
376 Py_FatalError("Py_EndInterpreter: thread still has a frame");
377 if (tstate != interp->tstate_head || tstate->next != NULL)
378 Py_FatalError("Py_EndInterpreter: not the last thread");
379
380 PyImport_Cleanup();
381 PyInterpreterState_Clear(interp);
382 PyThreadState_Swap(NULL);
383 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000384}
385
386static char *progname = "python";
387
388void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000389Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000390{
391 if (pn && *pn)
392 progname = pn;
393}
394
395char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000396Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000397{
398 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000399}
400
Guido van Rossuma61691e1998-02-06 22:27:24 +0000401static char *default_home = NULL;
402
403void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000404Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000405{
406 default_home = home;
407}
408
409char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000410Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000411{
412 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000413 if (home == NULL && !Py_IgnoreEnvironmentFlag)
414 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000415 return home;
416}
417
Guido van Rossum6135a871995-01-09 17:53:26 +0000418/* Create __main__ module */
419
420static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000421initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000422{
Guido van Rossum82598051997-03-05 00:20:32 +0000423 PyObject *m, *d;
424 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000425 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000426 Py_FatalError("can't create __main__ module");
427 d = PyModule_GetDict(m);
428 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000429 PyObject *bimod = PyImport_ImportModule("__builtin__");
430 if (bimod == NULL ||
431 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000432 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000433 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000434 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000435}
436
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000437/* Import the site module (not into __main__ though) */
438
439static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000440initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000441{
442 PyObject *m, *f;
443 m = PyImport_ImportModule("site");
444 if (m == NULL) {
445 f = PySys_GetObject("stderr");
446 if (Py_VerboseFlag) {
447 PyFile_WriteString(
448 "'import site' failed; traceback:\n", f);
449 PyErr_Print();
450 }
451 else {
452 PyFile_WriteString(
453 "'import site' failed; use -v for traceback\n", f);
454 PyErr_Clear();
455 }
456 }
457 else {
458 Py_DECREF(m);
459 }
460}
461
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000462/* Parse input from a file and execute it */
463
464int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000465PyRun_AnyFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000466{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000467 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
468}
469
470int
471PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
472{
473 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000474}
475
476int
477PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
478{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000479 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
480}
481
482int
483PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
484 PyCompilerFlags *flags)
485{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000486 if (filename == NULL)
487 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000488 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000489 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000490 if (closeit)
491 fclose(fp);
492 return err;
493 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000494 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000495 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000496}
497
498int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000499PyRun_InteractiveLoop(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000500{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000501 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
502}
503
504int
505PyRun_InteractiveLoopFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
506{
Guido van Rossum82598051997-03-05 00:20:32 +0000507 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000508 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000509 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000510
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000511 if (flags == NULL) {
512 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000513 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000514 }
Guido van Rossum82598051997-03-05 00:20:32 +0000515 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000516 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000517 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
518 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000519 }
Guido van Rossum82598051997-03-05 00:20:32 +0000520 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000521 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000522 PySys_SetObject("ps2", v = PyString_FromString("... "));
523 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000524 }
525 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000526 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000527#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000528 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000529#endif
530 if (ret == E_EOF)
531 return 0;
532 /*
533 if (ret == E_NOMEM)
534 return -1;
535 */
536 }
537}
538
539int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000540PyRun_InteractiveOne(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000541{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000542 return PyRun_InteractiveOneFlags(fp, filename, NULL);
543}
544
545int
546PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
547{
Guido van Rossum82598051997-03-05 00:20:32 +0000548 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000549 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000550 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000551 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000552
Guido van Rossum82598051997-03-05 00:20:32 +0000553 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000554 if (v != NULL) {
555 v = PyObject_Str(v);
556 if (v == NULL)
557 PyErr_Clear();
558 else if (PyString_Check(v))
559 ps1 = PyString_AsString(v);
560 }
Guido van Rossum82598051997-03-05 00:20:32 +0000561 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000562 if (w != NULL) {
563 w = PyObject_Str(w);
564 if (w == NULL)
565 PyErr_Clear();
566 else if (PyString_Check(w))
567 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000568 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000569 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
570 Py_single_input, ps1, ps2, &err,
571 (flags &&
Jeremy Hyltonb857ba22001-08-10 21:41:33 +0000572 flags->cf_flags & CO_GENERATOR_ALLOWED) ?
Tim Petersfe2127d2001-07-16 05:37:24 +0000573 PyPARSE_YIELD_IS_KEYWORD : 0);
Guido van Rossum82598051997-03-05 00:20:32 +0000574 Py_XDECREF(v);
575 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000576 if (n == NULL) {
577 if (err.error == E_EOF) {
578 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000579 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000580 return E_EOF;
581 }
582 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000583 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000584 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000585 }
Guido van Rossum82598051997-03-05 00:20:32 +0000586 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000587 if (m == NULL)
588 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000589 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000590 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000591 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000592 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000593 return -1;
594 }
Guido van Rossum82598051997-03-05 00:20:32 +0000595 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000596 if (Py_FlushLine())
597 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000598 return 0;
599}
600
601int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000602PyRun_SimpleFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000603{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000604 return PyRun_SimpleFileEx(fp, filename, 0);
605}
606
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000607/* Check whether a file maybe a pyc file: Look at the extension,
608 the file type, and, if we may close it, at the first few bytes. */
609
610static int
611maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
612{
613 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
614 return 1;
615
616#ifdef macintosh
617 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
618 if (PyMac_getfiletype(filename) == 'PYC '
619 || PyMac_getfiletype(filename) == 'APPL')
620 return 1;
621#endif /* macintosh */
622
623 /* Only look into the file if we are allowed to close it, since
624 it then should also be seekable. */
625 if (closeit) {
626 /* Read only two bytes of the magic. If the file was opened in
627 text mode, the bytes 3 and 4 of the magic (\r\n) might not
628 be read as they are on disk. */
629 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
630 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000631 /* Mess: In case of -x, the stream is NOT at its start now,
632 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000633 which makes the current stream position formally undefined,
634 and a x-platform nightmare.
635 Unfortunately, we have no direct way to know whether -x
636 was specified. So we use a terrible hack: if the current
637 stream position is not 0, we assume -x was specified, and
638 give up. Bug 132850 on SourceForge spells out the
639 hopelessness of trying anything else (fseek and ftell
640 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000641 */
Tim Peters3e876562001-02-11 04:35:39 +0000642 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000643 if (ftell(fp) == 0) {
644 if (fread(buf, 1, 2, fp) == 2 &&
645 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
646 ispyc = 1;
647 rewind(fp);
648 }
Tim Peters3e876562001-02-11 04:35:39 +0000649 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000650 }
651 return 0;
652}
653
Guido van Rossum0df002c2000-08-27 19:21:52 +0000654int
655PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
656{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000657 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
658}
659
660int
661PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit,
662 PyCompilerFlags *flags)
663{
Guido van Rossum82598051997-03-05 00:20:32 +0000664 PyObject *m, *d, *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000665 char *ext;
666
Guido van Rossum82598051997-03-05 00:20:32 +0000667 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000668 if (m == NULL)
669 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000670 d = PyModule_GetDict(m);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000671 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000672 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000673 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000674 if (closeit)
675 fclose(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000676 if( (fp = fopen(filename, "rb")) == NULL ) {
677 fprintf(stderr, "python: Can't reopen .pyc file\n");
678 return -1;
679 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000680 /* Turn on optimization if a .pyo file is given */
681 if (strcmp(ext, ".pyo") == 0)
682 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000683 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000684 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000685 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
686 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000687 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000688 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000689 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000690 return -1;
691 }
Guido van Rossum82598051997-03-05 00:20:32 +0000692 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000693 if (Py_FlushLine())
694 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000695 return 0;
696}
697
698int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000699PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000700{
Guido van Rossum393661d2001-08-31 17:40:15 +0000701 return PyRun_SimpleStringFlags(command, NULL);
702}
703
704int
705PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
706{
Guido van Rossum82598051997-03-05 00:20:32 +0000707 PyObject *m, *d, *v;
708 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000709 if (m == NULL)
710 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000711 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000712 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000713 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000714 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000715 return -1;
716 }
Guido van Rossum82598051997-03-05 00:20:32 +0000717 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000718 if (Py_FlushLine())
719 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000720 return 0;
721}
722
Barry Warsaw035574d1997-08-29 22:07:17 +0000723static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000724parse_syntax_error(PyObject *err, PyObject **message, char **filename,
725 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000726{
727 long hold;
728 PyObject *v;
729
730 /* old style errors */
731 if (PyTuple_Check(err))
732 return PyArg_Parse(err, "(O(ziiz))", message, filename,
733 lineno, offset, text);
734
735 /* new style errors. `err' is an instance */
736
737 if (! (v = PyObject_GetAttrString(err, "msg")))
738 goto finally;
739 *message = v;
740
741 if (!(v = PyObject_GetAttrString(err, "filename")))
742 goto finally;
743 if (v == Py_None)
744 *filename = NULL;
745 else if (! (*filename = PyString_AsString(v)))
746 goto finally;
747
748 Py_DECREF(v);
749 if (!(v = PyObject_GetAttrString(err, "lineno")))
750 goto finally;
751 hold = PyInt_AsLong(v);
752 Py_DECREF(v);
753 v = NULL;
754 if (hold < 0 && PyErr_Occurred())
755 goto finally;
756 *lineno = (int)hold;
757
758 if (!(v = PyObject_GetAttrString(err, "offset")))
759 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000760 if (v == Py_None) {
761 *offset = -1;
762 Py_DECREF(v);
763 v = NULL;
764 } else {
765 hold = PyInt_AsLong(v);
766 Py_DECREF(v);
767 v = NULL;
768 if (hold < 0 && PyErr_Occurred())
769 goto finally;
770 *offset = (int)hold;
771 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000772
773 if (!(v = PyObject_GetAttrString(err, "text")))
774 goto finally;
775 if (v == Py_None)
776 *text = NULL;
777 else if (! (*text = PyString_AsString(v)))
778 goto finally;
779 Py_DECREF(v);
780 return 1;
781
782finally:
783 Py_XDECREF(v);
784 return 0;
785}
786
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000787void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000788PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000789{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000790 PyErr_PrintEx(1);
791}
792
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000793static void
794print_error_text(PyObject *f, int offset, char *text)
795{
796 char *nl;
797 if (offset >= 0) {
798 if (offset > 0 && offset == (int)strlen(text))
799 offset--;
800 for (;;) {
801 nl = strchr(text, '\n');
802 if (nl == NULL || nl-text >= offset)
803 break;
804 offset -= (nl+1-text);
805 text = nl+1;
806 }
807 while (*text == ' ' || *text == '\t') {
808 text++;
809 offset--;
810 }
811 }
812 PyFile_WriteString(" ", f);
813 PyFile_WriteString(text, f);
814 if (*text == '\0' || text[strlen(text)-1] != '\n')
815 PyFile_WriteString("\n", f);
816 if (offset == -1)
817 return;
818 PyFile_WriteString(" ", f);
819 offset--;
820 while (offset > 0) {
821 PyFile_WriteString(" ", f);
822 offset--;
823 }
824 PyFile_WriteString("^\n", f);
825}
826
Guido van Rossum66e8e862001-03-23 17:54:43 +0000827static void
828handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000829{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000830 PyObject *exception, *value, *tb;
831 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000832 if (Py_FlushLine())
833 PyErr_Clear();
834 fflush(stdout);
835 if (value == NULL || value == Py_None)
836 Py_Exit(0);
837 if (PyInstance_Check(value)) {
838 /* The error code should be in the `code' attribute. */
839 PyObject *code = PyObject_GetAttrString(value, "code");
840 if (code) {
841 Py_DECREF(value);
842 value = code;
843 if (value == Py_None)
844 Py_Exit(0);
845 }
846 /* If we failed to dig out the 'code' attribute,
847 just let the else clause below print the error. */
848 }
849 if (PyInt_Check(value))
850 Py_Exit((int)PyInt_AsLong(value));
851 else {
852 PyObject_Print(value, stderr, Py_PRINT_RAW);
853 PySys_WriteStderr("\n");
854 Py_Exit(1);
855 }
856}
857
858void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000859PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000860{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000861 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000862
863 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
864 handle_system_exit();
865 }
Guido van Rossum82598051997-03-05 00:20:32 +0000866 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000867 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000868 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000869 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000870 if (set_sys_last_vars) {
871 PySys_SetObject("last_type", exception);
872 PySys_SetObject("last_value", v);
873 PySys_SetObject("last_traceback", tb);
874 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000875 hook = PySys_GetObject("excepthook");
876 if (hook) {
877 PyObject *args = Py_BuildValue("(OOO)",
878 exception, v ? v : Py_None, tb ? tb : Py_None);
879 PyObject *result = PyEval_CallObject(hook, args);
880 if (result == NULL) {
881 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000882 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
883 handle_system_exit();
884 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000885 PyErr_Fetch(&exception2, &v2, &tb2);
886 PyErr_NormalizeException(&exception2, &v2, &tb2);
887 if (Py_FlushLine())
888 PyErr_Clear();
889 fflush(stdout);
890 PySys_WriteStderr("Error in sys.excepthook:\n");
891 PyErr_Display(exception2, v2, tb2);
892 PySys_WriteStderr("\nOriginal exception was:\n");
893 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000894 Py_XDECREF(exception2);
895 Py_XDECREF(v2);
896 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000897 }
898 Py_XDECREF(result);
899 Py_XDECREF(args);
900 } else {
901 PySys_WriteStderr("sys.excepthook is missing\n");
902 PyErr_Display(exception, v, tb);
903 }
904 Py_XDECREF(exception);
905 Py_XDECREF(v);
906 Py_XDECREF(tb);
907}
908
909void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
910{
911 int err = 0;
912 PyObject *v = value;
913 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000914 if (f == NULL)
915 fprintf(stderr, "lost sys.stderr\n");
916 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000917 if (Py_FlushLine())
918 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000919 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000920 if (tb && tb != Py_None)
921 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000922 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000923 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000924 {
Guido van Rossum82598051997-03-05 00:20:32 +0000925 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000926 char *filename, *text;
927 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000928 if (!parse_syntax_error(v, &message, &filename,
929 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000930 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000931 else {
932 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000933 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000934 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000935 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000936 else
Guido van Rossum82598051997-03-05 00:20:32 +0000937 PyFile_WriteString(filename, f);
938 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000939 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000940 PyFile_WriteString(buf, f);
941 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000942 if (text != NULL)
943 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000944 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000945 /* Can't be bothered to check all those
946 PyFile_WriteString() calls */
947 if (PyErr_Occurred())
948 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000949 }
950 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000951 if (err) {
952 /* Don't do anything else */
953 }
954 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000955 PyClassObject* exc = (PyClassObject*)exception;
956 PyObject* className = exc->cl_name;
957 PyObject* moduleName =
958 PyDict_GetItemString(exc->cl_dict, "__module__");
959
960 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000961 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000962 else {
963 char* modstr = PyString_AsString(moduleName);
964 if (modstr && strcmp(modstr, "exceptions"))
965 {
966 err = PyFile_WriteString(modstr, f);
967 err += PyFile_WriteString(".", f);
968 }
969 }
970 if (err == 0) {
971 if (className == NULL)
972 err = PyFile_WriteString("<unknown>", f);
973 else
974 err = PyFile_WriteObject(className, f,
975 Py_PRINT_RAW);
976 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000977 }
978 else
979 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
980 if (err == 0) {
981 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000982 PyObject *s = PyObject_Str(v);
983 /* only print colon if the str() of the
984 object is not the empty string
985 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000986 if (s == NULL)
987 err = -1;
988 else if (!PyString_Check(s) ||
989 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +0000990 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000991 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000992 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
993 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +0000994 }
Guido van Rossum262e1241995-02-07 15:30:45 +0000995 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000996 if (err == 0)
997 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000998 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000999 /* If an error happened here, don't show it.
1000 XXX This is wrong, but too many callers rely on this behavior. */
1001 if (err != 0)
1002 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001003}
1004
Guido van Rossum82598051997-03-05 00:20:32 +00001005PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001006PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001007{
Guido van Rossum82598051997-03-05 00:20:32 +00001008 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001009 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001010}
1011
Guido van Rossum82598051997-03-05 00:20:32 +00001012PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001013PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1014 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001015{
Tim Peterse8682112000-08-27 20:18:17 +00001016 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001017}
1018
1019PyObject *
1020PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001021 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001022{
1023 node *n = PyParser_SimpleParseFile(fp, filename, start);
1024 if (closeit)
1025 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001026 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001027}
1028
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001029PyObject *
1030PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1031 PyCompilerFlags *flags)
1032{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001033 return run_err_node(PyParser_SimpleParseStringFlags(
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001034 str, start,
1035 (flags && flags->cf_flags & CO_GENERATOR_ALLOWED) ?
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001036 PyPARSE_YIELD_IS_KEYWORD : 0),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001037 "<string>", globals, locals, flags);
1038}
1039
1040PyObject *
1041PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1042 PyObject *locals, PyCompilerFlags *flags)
1043{
1044 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1045 flags);
1046}
1047
1048PyObject *
1049PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1050 PyObject *locals, int closeit, PyCompilerFlags *flags)
1051{
Tim Petersfe2127d2001-07-16 05:37:24 +00001052 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001053 (flags && flags->cf_flags & CO_GENERATOR_ALLOWED) ?
Tim Petersfe2127d2001-07-16 05:37:24 +00001054 PyPARSE_YIELD_IS_KEYWORD : 0);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001055 if (closeit)
1056 fclose(fp);
1057 return run_err_node(n, filename, globals, locals, flags);
1058}
1059
Guido van Rossum82598051997-03-05 00:20:32 +00001060static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001061run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1062 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001063{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001064 if (n == NULL)
1065 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001066 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001067}
1068
Guido van Rossum82598051997-03-05 00:20:32 +00001069static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001070run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1071 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001072{
Guido van Rossum82598051997-03-05 00:20:32 +00001073 PyCodeObject *co;
1074 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001075 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001076 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001077 if (co == NULL)
1078 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001079 v = PyEval_EvalCode(co, globals, locals);
1080 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001081 return v;
1082}
1083
Guido van Rossum82598051997-03-05 00:20:32 +00001084static PyObject *
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001085run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1086 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001087{
Guido van Rossum82598051997-03-05 00:20:32 +00001088 PyCodeObject *co;
1089 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001090 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001091 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001092
Guido van Rossum82598051997-03-05 00:20:32 +00001093 magic = PyMarshal_ReadLongFromFile(fp);
1094 if (magic != PyImport_GetMagicNumber()) {
1095 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001096 "Bad magic number in .pyc file");
1097 return NULL;
1098 }
Guido van Rossum82598051997-03-05 00:20:32 +00001099 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001100 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001101 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001102 if (v == NULL || !PyCode_Check(v)) {
1103 Py_XDECREF(v);
1104 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001105 "Bad code object in .pyc file");
1106 return NULL;
1107 }
Guido van Rossum82598051997-03-05 00:20:32 +00001108 co = (PyCodeObject *)v;
1109 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001110 if (v && flags)
1111 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001112 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001113 return v;
1114}
1115
Guido van Rossum82598051997-03-05 00:20:32 +00001116PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001117Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001118{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001119 return Py_CompileStringFlags(str, filename, start, NULL);
1120}
1121
1122PyObject *
1123Py_CompileStringFlags(char *str, char *filename, int start,
1124 PyCompilerFlags *flags)
1125{
Guido van Rossum5b722181993-03-30 17:46:03 +00001126 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001127 PyCodeObject *co;
Tim Petersfe2127d2001-07-16 05:37:24 +00001128 n = PyParser_SimpleParseStringFlags(str, start,
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001129 (flags && flags->cf_flags & CO_GENERATOR_ALLOWED) ?
Tim Petersfe2127d2001-07-16 05:37:24 +00001130 PyPARSE_YIELD_IS_KEYWORD : 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001131 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001132 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001133 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001134 PyNode_Free(n);
1135 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001136}
1137
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001138struct symtable *
1139Py_SymtableString(char *str, char *filename, int start)
1140{
1141 node *n;
1142 struct symtable *st;
1143 n = PyParser_SimpleParseString(str, start);
1144 if (n == NULL)
1145 return NULL;
1146 st = PyNode_CompileSymtable(n, filename);
1147 PyNode_Free(n);
1148 return st;
1149}
1150
Guido van Rossuma110aa61994-08-29 12:50:44 +00001151/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001152
Guido van Rossuma110aa61994-08-29 12:50:44 +00001153node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001154PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001155{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001156 node *n;
1157 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001158 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1159 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001160 if (n == NULL)
1161 err_input(&err);
1162 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001163}
1164
Tim Petersfe2127d2001-07-16 05:37:24 +00001165node *
1166PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1167{
1168 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1169}
1170
Guido van Rossuma110aa61994-08-29 12:50:44 +00001171/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001172
Guido van Rossuma110aa61994-08-29 12:50:44 +00001173node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001174PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1175{
1176 node *n;
1177 perrdetail err;
1178 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1179 flags);
1180 if (n == NULL)
1181 err_input(&err);
1182 return n;
1183}
1184
1185node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001186PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001187{
Tim Petersfe2127d2001-07-16 05:37:24 +00001188 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001189}
1190
1191/* Set the error appropriate to the given input error code (see errcode.h) */
1192
1193static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001194err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001195{
Fred Drake85f36392000-07-11 17:53:00 +00001196 PyObject *v, *w, *errtype;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001197 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001198 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001199 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001200 err->lineno, err->offset, err->text);
1201 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001202 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001203 err->text = NULL;
1204 }
1205 switch (err->error) {
1206 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001207 errtype = PyExc_IndentationError;
1208 if (err->expected == INDENT)
1209 msg = "expected an indented block";
1210 else if (err->token == INDENT)
1211 msg = "unexpected indent";
1212 else if (err->token == DEDENT)
1213 msg = "unexpected unindent";
1214 else {
1215 errtype = PyExc_SyntaxError;
1216 msg = "invalid syntax";
1217 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001218 break;
1219 case E_TOKEN:
1220 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001221 break;
1222 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001223 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001224 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001225 return;
1226 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001227 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001228 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001229 return;
1230 case E_EOF:
1231 msg = "unexpected EOF while parsing";
1232 break;
Fred Drake85f36392000-07-11 17:53:00 +00001233 case E_TABSPACE:
1234 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001235 msg = "inconsistent use of tabs and spaces in indentation";
1236 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001237 case E_OVERFLOW:
1238 msg = "expression too long";
1239 break;
Fred Drake85f36392000-07-11 17:53:00 +00001240 case E_DEDENT:
1241 errtype = PyExc_IndentationError;
1242 msg = "unindent does not match any outer indentation level";
1243 break;
1244 case E_TOODEEP:
1245 errtype = PyExc_IndentationError;
1246 msg = "too many levels of indentation";
1247 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001248 default:
1249 fprintf(stderr, "error=%d\n", err->error);
1250 msg = "unknown parsing error";
1251 break;
1252 }
Guido van Rossum82598051997-03-05 00:20:32 +00001253 w = Py_BuildValue("(sO)", msg, v);
Guido van Rossum41318302001-03-23 04:01:07 +00001254 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001255 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001256 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001257}
1258
1259/* Print fatal error message and abort */
1260
1261void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001262Py_FatalError(char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001263{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001264 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001265#ifdef macintosh
1266 for (;;);
1267#endif
Guido van Rossum9b38a141996-09-11 23:12:24 +00001268#ifdef MS_WIN32
Guido van Rossum23c94461997-05-22 20:21:30 +00001269 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001270 OutputDebugString(msg);
1271 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001272#ifdef _DEBUG
1273 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001274#endif
Guido van Rossum0ba35361998-08-13 13:33:16 +00001275#endif /* MS_WIN32 */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001276 abort();
1277}
1278
1279/* Clean up and exit */
1280
Guido van Rossuma110aa61994-08-29 12:50:44 +00001281#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001282#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001283int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001284#endif
1285
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001286#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001287static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001288static int nexitfuncs = 0;
1289
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001290int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001291{
1292 if (nexitfuncs >= NEXITFUNCS)
1293 return -1;
1294 exitfuncs[nexitfuncs++] = func;
1295 return 0;
1296}
1297
Guido van Rossumcc283f51997-08-05 02:22:03 +00001298static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001299call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001300{
Guido van Rossum82598051997-03-05 00:20:32 +00001301 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001302
1303 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001304 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001305 Py_INCREF(exitfunc);
1306 PySys_SetObject("exitfunc", (PyObject *)NULL);
1307 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001308 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001309 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1310 PySys_WriteStderr("Error in sys.exitfunc:\n");
1311 }
Guido van Rossum82598051997-03-05 00:20:32 +00001312 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001313 }
Guido van Rossum82598051997-03-05 00:20:32 +00001314 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001315 }
1316
Guido van Rossum0829c751998-02-28 04:31:39 +00001317 if (Py_FlushLine())
1318 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001319}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001320
Guido van Rossumcc283f51997-08-05 02:22:03 +00001321static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001322call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001323{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001324 while (nexitfuncs > 0)
1325 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001326
1327 fflush(stdout);
1328 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001329}
1330
1331void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001332Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001333{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001334 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001335
Jack Jansen66a89771995-10-27 13:22:14 +00001336#ifdef macintosh
1337 PyMac_Exit(sts);
1338#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001339 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001340#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001341}
1342
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001343static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001344initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001345{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001346#ifdef HAVE_SIGNAL_H
1347#ifdef SIGPIPE
1348 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001349#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001350#ifdef SIGXFZ
1351 signal(SIGXFZ, SIG_IGN);
1352#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001353#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001354 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001355}
1356
Guido van Rossumaae0d321996-05-22 16:35:33 +00001357#ifdef Py_TRACE_REFS
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001358/* Ask a yes/no question */
1359
Guido van Rossum59bff391992-09-03 20:28:00 +00001360int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001361_Py_AskYesNo(char *prompt)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001362{
1363 char buf[256];
1364
Tim Peters6d6c1a32001-08-02 04:15:00 +00001365 fprintf(stderr, "%s [ny] ", prompt);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001366 if (fgets(buf, sizeof buf, stdin) == NULL)
1367 return 0;
1368 return buf[0] == 'y' || buf[0] == 'Y';
1369}
1370#endif
1371
Guido van Rossuma110aa61994-08-29 12:50:44 +00001372#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001373
1374/* Check for file descriptor connected to interactive device.
1375 Pretend that stdin is always interactive, other files never. */
1376
1377int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001378isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001379{
1380 return fd == fileno(stdin);
1381}
1382
1383#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001384
1385/*
1386 * The file descriptor fd is considered ``interactive'' if either
1387 * a) isatty(fd) is TRUE, or
1388 * b) the -i flag was given, and the filename associated with
1389 * the descriptor is NULL or "<stdin>" or "???".
1390 */
1391int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001392Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001393{
1394 if (isatty((int)fileno(fp)))
1395 return 1;
1396 if (!Py_InteractiveFlag)
1397 return 0;
1398 return (filename == NULL) ||
1399 (strcmp(filename, "<stdin>") == 0) ||
1400 (strcmp(filename, "???") == 0);
1401}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001402
1403
1404#if defined(USE_STACKCHECK)
1405#if defined(WIN32) && defined(_MSC_VER)
1406
1407/* Stack checking for Microsoft C */
1408
1409#include <malloc.h>
1410#include <excpt.h>
1411
Fred Drakee8de31c2000-08-31 05:38:39 +00001412/*
1413 * Return non-zero when we run out of memory on the stack; zero otherwise.
1414 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001415int
Fred Drake399739f2000-08-31 05:52:44 +00001416PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001417{
1418 __try {
1419 /* _alloca throws a stack overflow exception if there's
1420 not enough space left on the stack */
1421 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1422 return 0;
1423 } __except (EXCEPTION_EXECUTE_HANDLER) {
1424 /* just ignore all errors */
1425 }
1426 return 1;
1427}
1428
1429#endif /* WIN32 && _MSC_VER */
1430
1431/* Alternate implementations can be added here... */
1432
1433#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001434
1435
1436/* Wrappers around sigaction() or signal(). */
1437
1438PyOS_sighandler_t
1439PyOS_getsig(int sig)
1440{
1441#ifdef HAVE_SIGACTION
1442 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001443 /* Initialize context.sa_handler to SIG_ERR which makes about as
1444 * much sense as anything else. It should get overwritten if
1445 * sigaction actually succeeds and otherwise we avoid an
1446 * uninitialized memory read.
1447 */
1448 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001449 sigaction(sig, NULL, &context);
1450 return context.sa_handler;
1451#else
1452 PyOS_sighandler_t handler;
1453 handler = signal(sig, SIG_IGN);
1454 signal(sig, handler);
1455 return handler;
1456#endif
1457}
1458
1459PyOS_sighandler_t
1460PyOS_setsig(int sig, PyOS_sighandler_t handler)
1461{
1462#ifdef HAVE_SIGACTION
1463 struct sigaction context;
1464 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001465 /* Initialize context.sa_handler to SIG_ERR which makes about as
1466 * much sense as anything else. It should get overwritten if
1467 * sigaction actually succeeds and otherwise we avoid an
1468 * uninitialized memory read.
1469 */
1470 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001471 sigaction(sig, NULL, &context);
1472 oldhandler = context.sa_handler;
1473 context.sa_handler = handler;
1474 sigaction(sig, &context, NULL);
1475 return oldhandler;
1476#else
1477 return signal(sig, handler);
1478#endif
1479}