blob: 64418e417d447d8ee09397cb3809d7ef4df8df50 [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
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000545/* compute parser flags based on compiler flags */
546#if 0 /* future keyword */
547#define PARSER_FLAGS(flags) \
548 (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \
549 PyPARSE_YIELD_IS_KEYWORD : 0)
550#else
551#define PARSER_FLAGS(flags) 0
552#endif
553
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000554int
555PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
556{
Guido van Rossum82598051997-03-05 00:20:32 +0000557 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000558 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000559 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000560 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000561
Guido van Rossum82598051997-03-05 00:20:32 +0000562 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000563 if (v != NULL) {
564 v = PyObject_Str(v);
565 if (v == NULL)
566 PyErr_Clear();
567 else if (PyString_Check(v))
568 ps1 = PyString_AsString(v);
569 }
Guido van Rossum82598051997-03-05 00:20:32 +0000570 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000571 if (w != NULL) {
572 w = PyObject_Str(w);
573 if (w == NULL)
574 PyErr_Clear();
575 else if (PyString_Check(w))
576 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000577 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000578 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
579 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000580 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000581 Py_XDECREF(v);
582 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000583 if (n == NULL) {
584 if (err.error == E_EOF) {
585 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000586 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000587 return E_EOF;
588 }
589 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000590 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000591 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000592 }
Guido van Rossum82598051997-03-05 00:20:32 +0000593 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000594 if (m == NULL)
595 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000596 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000597 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000598 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000599 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000600 return -1;
601 }
Guido van Rossum82598051997-03-05 00:20:32 +0000602 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000603 if (Py_FlushLine())
604 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000605 return 0;
606}
607
608int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000609PyRun_SimpleFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000610{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000611 return PyRun_SimpleFileEx(fp, filename, 0);
612}
613
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000614/* Check whether a file maybe a pyc file: Look at the extension,
615 the file type, and, if we may close it, at the first few bytes. */
616
617static int
618maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
619{
620 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
621 return 1;
622
623#ifdef macintosh
624 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
625 if (PyMac_getfiletype(filename) == 'PYC '
626 || PyMac_getfiletype(filename) == 'APPL')
627 return 1;
628#endif /* macintosh */
629
630 /* Only look into the file if we are allowed to close it, since
631 it then should also be seekable. */
632 if (closeit) {
633 /* Read only two bytes of the magic. If the file was opened in
634 text mode, the bytes 3 and 4 of the magic (\r\n) might not
635 be read as they are on disk. */
636 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
637 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000638 /* Mess: In case of -x, the stream is NOT at its start now,
639 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000640 which makes the current stream position formally undefined,
641 and a x-platform nightmare.
642 Unfortunately, we have no direct way to know whether -x
643 was specified. So we use a terrible hack: if the current
644 stream position is not 0, we assume -x was specified, and
645 give up. Bug 132850 on SourceForge spells out the
646 hopelessness of trying anything else (fseek and ftell
647 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000648 */
Tim Peters3e876562001-02-11 04:35:39 +0000649 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000650 if (ftell(fp) == 0) {
651 if (fread(buf, 1, 2, fp) == 2 &&
652 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
653 ispyc = 1;
654 rewind(fp);
655 }
Tim Peters3e876562001-02-11 04:35:39 +0000656 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000657 }
658 return 0;
659}
660
Guido van Rossum0df002c2000-08-27 19:21:52 +0000661int
662PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
663{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000664 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
665}
666
667int
668PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit,
669 PyCompilerFlags *flags)
670{
Guido van Rossum82598051997-03-05 00:20:32 +0000671 PyObject *m, *d, *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000672 char *ext;
673
Guido van Rossum82598051997-03-05 00:20:32 +0000674 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000675 if (m == NULL)
676 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000677 d = PyModule_GetDict(m);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000678 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000679 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000680 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000681 if (closeit)
682 fclose(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000683 if( (fp = fopen(filename, "rb")) == NULL ) {
684 fprintf(stderr, "python: Can't reopen .pyc file\n");
685 return -1;
686 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000687 /* Turn on optimization if a .pyo file is given */
688 if (strcmp(ext, ".pyo") == 0)
689 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000690 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000691 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000692 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
693 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000694 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000695 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000696 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000697 return -1;
698 }
Guido van Rossum82598051997-03-05 00:20:32 +0000699 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000700 if (Py_FlushLine())
701 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000702 return 0;
703}
704
705int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000706PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000707{
Guido van Rossum393661d2001-08-31 17:40:15 +0000708 return PyRun_SimpleStringFlags(command, NULL);
709}
710
711int
712PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
713{
Guido van Rossum82598051997-03-05 00:20:32 +0000714 PyObject *m, *d, *v;
715 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000716 if (m == NULL)
717 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000718 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000719 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000720 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000721 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000722 return -1;
723 }
Guido van Rossum82598051997-03-05 00:20:32 +0000724 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000725 if (Py_FlushLine())
726 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000727 return 0;
728}
729
Barry Warsaw035574d1997-08-29 22:07:17 +0000730static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000731parse_syntax_error(PyObject *err, PyObject **message, char **filename,
732 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000733{
734 long hold;
735 PyObject *v;
736
737 /* old style errors */
738 if (PyTuple_Check(err))
739 return PyArg_Parse(err, "(O(ziiz))", message, filename,
740 lineno, offset, text);
741
742 /* new style errors. `err' is an instance */
743
744 if (! (v = PyObject_GetAttrString(err, "msg")))
745 goto finally;
746 *message = v;
747
748 if (!(v = PyObject_GetAttrString(err, "filename")))
749 goto finally;
750 if (v == Py_None)
751 *filename = NULL;
752 else if (! (*filename = PyString_AsString(v)))
753 goto finally;
754
755 Py_DECREF(v);
756 if (!(v = PyObject_GetAttrString(err, "lineno")))
757 goto finally;
758 hold = PyInt_AsLong(v);
759 Py_DECREF(v);
760 v = NULL;
761 if (hold < 0 && PyErr_Occurred())
762 goto finally;
763 *lineno = (int)hold;
764
765 if (!(v = PyObject_GetAttrString(err, "offset")))
766 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000767 if (v == Py_None) {
768 *offset = -1;
769 Py_DECREF(v);
770 v = NULL;
771 } else {
772 hold = PyInt_AsLong(v);
773 Py_DECREF(v);
774 v = NULL;
775 if (hold < 0 && PyErr_Occurred())
776 goto finally;
777 *offset = (int)hold;
778 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000779
780 if (!(v = PyObject_GetAttrString(err, "text")))
781 goto finally;
782 if (v == Py_None)
783 *text = NULL;
784 else if (! (*text = PyString_AsString(v)))
785 goto finally;
786 Py_DECREF(v);
787 return 1;
788
789finally:
790 Py_XDECREF(v);
791 return 0;
792}
793
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000794void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000795PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000796{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000797 PyErr_PrintEx(1);
798}
799
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000800static void
801print_error_text(PyObject *f, int offset, char *text)
802{
803 char *nl;
804 if (offset >= 0) {
805 if (offset > 0 && offset == (int)strlen(text))
806 offset--;
807 for (;;) {
808 nl = strchr(text, '\n');
809 if (nl == NULL || nl-text >= offset)
810 break;
811 offset -= (nl+1-text);
812 text = nl+1;
813 }
814 while (*text == ' ' || *text == '\t') {
815 text++;
816 offset--;
817 }
818 }
819 PyFile_WriteString(" ", f);
820 PyFile_WriteString(text, f);
821 if (*text == '\0' || text[strlen(text)-1] != '\n')
822 PyFile_WriteString("\n", f);
823 if (offset == -1)
824 return;
825 PyFile_WriteString(" ", f);
826 offset--;
827 while (offset > 0) {
828 PyFile_WriteString(" ", f);
829 offset--;
830 }
831 PyFile_WriteString("^\n", f);
832}
833
Guido van Rossum66e8e862001-03-23 17:54:43 +0000834static void
835handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000836{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000837 PyObject *exception, *value, *tb;
838 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000839 if (Py_FlushLine())
840 PyErr_Clear();
841 fflush(stdout);
842 if (value == NULL || value == Py_None)
843 Py_Exit(0);
844 if (PyInstance_Check(value)) {
845 /* The error code should be in the `code' attribute. */
846 PyObject *code = PyObject_GetAttrString(value, "code");
847 if (code) {
848 Py_DECREF(value);
849 value = code;
850 if (value == Py_None)
851 Py_Exit(0);
852 }
853 /* If we failed to dig out the 'code' attribute,
854 just let the else clause below print the error. */
855 }
856 if (PyInt_Check(value))
857 Py_Exit((int)PyInt_AsLong(value));
858 else {
859 PyObject_Print(value, stderr, Py_PRINT_RAW);
860 PySys_WriteStderr("\n");
861 Py_Exit(1);
862 }
863}
864
865void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000866PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000867{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000868 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000869
870 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
871 handle_system_exit();
872 }
Guido van Rossum82598051997-03-05 00:20:32 +0000873 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000874 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000875 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000876 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000877 if (set_sys_last_vars) {
878 PySys_SetObject("last_type", exception);
879 PySys_SetObject("last_value", v);
880 PySys_SetObject("last_traceback", tb);
881 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000882 hook = PySys_GetObject("excepthook");
883 if (hook) {
884 PyObject *args = Py_BuildValue("(OOO)",
885 exception, v ? v : Py_None, tb ? tb : Py_None);
886 PyObject *result = PyEval_CallObject(hook, args);
887 if (result == NULL) {
888 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000889 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
890 handle_system_exit();
891 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000892 PyErr_Fetch(&exception2, &v2, &tb2);
893 PyErr_NormalizeException(&exception2, &v2, &tb2);
894 if (Py_FlushLine())
895 PyErr_Clear();
896 fflush(stdout);
897 PySys_WriteStderr("Error in sys.excepthook:\n");
898 PyErr_Display(exception2, v2, tb2);
899 PySys_WriteStderr("\nOriginal exception was:\n");
900 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000901 Py_XDECREF(exception2);
902 Py_XDECREF(v2);
903 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000904 }
905 Py_XDECREF(result);
906 Py_XDECREF(args);
907 } else {
908 PySys_WriteStderr("sys.excepthook is missing\n");
909 PyErr_Display(exception, v, tb);
910 }
911 Py_XDECREF(exception);
912 Py_XDECREF(v);
913 Py_XDECREF(tb);
914}
915
916void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
917{
918 int err = 0;
919 PyObject *v = value;
920 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000921 if (f == NULL)
922 fprintf(stderr, "lost sys.stderr\n");
923 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000924 if (Py_FlushLine())
925 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000926 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000927 if (tb && tb != Py_None)
928 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000929 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000930 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000931 {
Guido van Rossum82598051997-03-05 00:20:32 +0000932 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000933 char *filename, *text;
934 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000935 if (!parse_syntax_error(v, &message, &filename,
936 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000937 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000938 else {
939 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000940 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000941 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000942 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000943 else
Guido van Rossum82598051997-03-05 00:20:32 +0000944 PyFile_WriteString(filename, f);
945 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000946 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000947 PyFile_WriteString(buf, f);
948 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000949 if (text != NULL)
950 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000951 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000952 /* Can't be bothered to check all those
953 PyFile_WriteString() calls */
954 if (PyErr_Occurred())
955 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000956 }
957 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000958 if (err) {
959 /* Don't do anything else */
960 }
961 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000962 PyClassObject* exc = (PyClassObject*)exception;
963 PyObject* className = exc->cl_name;
964 PyObject* moduleName =
965 PyDict_GetItemString(exc->cl_dict, "__module__");
966
967 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000968 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000969 else {
970 char* modstr = PyString_AsString(moduleName);
971 if (modstr && strcmp(modstr, "exceptions"))
972 {
973 err = PyFile_WriteString(modstr, f);
974 err += PyFile_WriteString(".", f);
975 }
976 }
977 if (err == 0) {
978 if (className == NULL)
979 err = PyFile_WriteString("<unknown>", f);
980 else
981 err = PyFile_WriteObject(className, f,
982 Py_PRINT_RAW);
983 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000984 }
985 else
986 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
987 if (err == 0) {
988 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000989 PyObject *s = PyObject_Str(v);
990 /* only print colon if the str() of the
991 object is not the empty string
992 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000993 if (s == NULL)
994 err = -1;
995 else if (!PyString_Check(s) ||
996 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +0000997 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000998 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000999 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1000 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001001 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001002 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001003 if (err == 0)
1004 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001005 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001006 /* If an error happened here, don't show it.
1007 XXX This is wrong, but too many callers rely on this behavior. */
1008 if (err != 0)
1009 PyErr_Clear();
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_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001014{
Guido van Rossum82598051997-03-05 00:20:32 +00001015 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001016 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001017}
1018
Guido van Rossum82598051997-03-05 00:20:32 +00001019PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001020PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1021 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001022{
Tim Peterse8682112000-08-27 20:18:17 +00001023 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001024}
1025
1026PyObject *
1027PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001028 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001029{
1030 node *n = PyParser_SimpleParseFile(fp, filename, start);
1031 if (closeit)
1032 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001033 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001034}
1035
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001036PyObject *
1037PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1038 PyCompilerFlags *flags)
1039{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001040 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001041 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001042 "<string>", globals, locals, flags);
1043}
1044
1045PyObject *
1046PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1047 PyObject *locals, PyCompilerFlags *flags)
1048{
1049 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1050 flags);
1051}
1052
1053PyObject *
1054PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1055 PyObject *locals, int closeit, PyCompilerFlags *flags)
1056{
Tim Petersfe2127d2001-07-16 05:37:24 +00001057 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001058 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001059 if (closeit)
1060 fclose(fp);
1061 return run_err_node(n, filename, globals, locals, flags);
1062}
1063
Guido van Rossum82598051997-03-05 00:20:32 +00001064static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001065run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1066 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001067{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001068 if (n == NULL)
1069 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001070 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001071}
1072
Guido van Rossum82598051997-03-05 00:20:32 +00001073static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001074run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1075 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001076{
Guido van Rossum82598051997-03-05 00:20:32 +00001077 PyCodeObject *co;
1078 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001079 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001080 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001081 if (co == NULL)
1082 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001083 v = PyEval_EvalCode(co, globals, locals);
1084 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001085 return v;
1086}
1087
Guido van Rossum82598051997-03-05 00:20:32 +00001088static PyObject *
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001089run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1090 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001091{
Guido van Rossum82598051997-03-05 00:20:32 +00001092 PyCodeObject *co;
1093 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001094 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001095 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001096
Guido van Rossum82598051997-03-05 00:20:32 +00001097 magic = PyMarshal_ReadLongFromFile(fp);
1098 if (magic != PyImport_GetMagicNumber()) {
1099 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001100 "Bad magic number in .pyc file");
1101 return NULL;
1102 }
Guido van Rossum82598051997-03-05 00:20:32 +00001103 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001104 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001105 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001106 if (v == NULL || !PyCode_Check(v)) {
1107 Py_XDECREF(v);
1108 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001109 "Bad code object in .pyc file");
1110 return NULL;
1111 }
Guido van Rossum82598051997-03-05 00:20:32 +00001112 co = (PyCodeObject *)v;
1113 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001114 if (v && flags)
1115 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001116 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001117 return v;
1118}
1119
Guido van Rossum82598051997-03-05 00:20:32 +00001120PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001121Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001122{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001123 return Py_CompileStringFlags(str, filename, start, NULL);
1124}
1125
1126PyObject *
1127Py_CompileStringFlags(char *str, char *filename, int start,
1128 PyCompilerFlags *flags)
1129{
Guido van Rossum5b722181993-03-30 17:46:03 +00001130 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001131 PyCodeObject *co;
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001132 n = PyParser_SimpleParseStringFlags(str, start, PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001133 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001134 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001135 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001136 PyNode_Free(n);
1137 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001138}
1139
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001140struct symtable *
1141Py_SymtableString(char *str, char *filename, int start)
1142{
1143 node *n;
1144 struct symtable *st;
1145 n = PyParser_SimpleParseString(str, start);
1146 if (n == NULL)
1147 return NULL;
1148 st = PyNode_CompileSymtable(n, filename);
1149 PyNode_Free(n);
1150 return st;
1151}
1152
Guido van Rossuma110aa61994-08-29 12:50:44 +00001153/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001154
Guido van Rossuma110aa61994-08-29 12:50:44 +00001155node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001156PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001157{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001158 node *n;
1159 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001160 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1161 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001162 if (n == NULL)
1163 err_input(&err);
1164 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001165}
1166
Tim Petersfe2127d2001-07-16 05:37:24 +00001167node *
1168PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1169{
1170 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1171}
1172
Guido van Rossuma110aa61994-08-29 12:50:44 +00001173/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001174
Guido van Rossuma110aa61994-08-29 12:50:44 +00001175node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001176PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1177{
1178 node *n;
1179 perrdetail err;
1180 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1181 flags);
1182 if (n == NULL)
1183 err_input(&err);
1184 return n;
1185}
1186
1187node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001188PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001189{
Tim Petersfe2127d2001-07-16 05:37:24 +00001190 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001191}
1192
1193/* Set the error appropriate to the given input error code (see errcode.h) */
1194
1195static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001196err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001197{
Fred Drake85f36392000-07-11 17:53:00 +00001198 PyObject *v, *w, *errtype;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001199 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001200 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001201 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001202 err->lineno, err->offset, err->text);
1203 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001204 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001205 err->text = NULL;
1206 }
1207 switch (err->error) {
1208 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001209 errtype = PyExc_IndentationError;
1210 if (err->expected == INDENT)
1211 msg = "expected an indented block";
1212 else if (err->token == INDENT)
1213 msg = "unexpected indent";
1214 else if (err->token == DEDENT)
1215 msg = "unexpected unindent";
1216 else {
1217 errtype = PyExc_SyntaxError;
1218 msg = "invalid syntax";
1219 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001220 break;
1221 case E_TOKEN:
1222 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001223 break;
1224 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001225 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001226 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001227 return;
1228 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001229 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001230 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001231 return;
1232 case E_EOF:
1233 msg = "unexpected EOF while parsing";
1234 break;
Fred Drake85f36392000-07-11 17:53:00 +00001235 case E_TABSPACE:
1236 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001237 msg = "inconsistent use of tabs and spaces in indentation";
1238 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001239 case E_OVERFLOW:
1240 msg = "expression too long";
1241 break;
Fred Drake85f36392000-07-11 17:53:00 +00001242 case E_DEDENT:
1243 errtype = PyExc_IndentationError;
1244 msg = "unindent does not match any outer indentation level";
1245 break;
1246 case E_TOODEEP:
1247 errtype = PyExc_IndentationError;
1248 msg = "too many levels of indentation";
1249 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001250 default:
1251 fprintf(stderr, "error=%d\n", err->error);
1252 msg = "unknown parsing error";
1253 break;
1254 }
Guido van Rossum82598051997-03-05 00:20:32 +00001255 w = Py_BuildValue("(sO)", msg, v);
Guido van Rossum41318302001-03-23 04:01:07 +00001256 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001257 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001258 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001259}
1260
1261/* Print fatal error message and abort */
1262
1263void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001264Py_FatalError(char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001265{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001266 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001267#ifdef macintosh
1268 for (;;);
1269#endif
Guido van Rossum9b38a141996-09-11 23:12:24 +00001270#ifdef MS_WIN32
Guido van Rossum23c94461997-05-22 20:21:30 +00001271 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001272 OutputDebugString(msg);
1273 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001274#ifdef _DEBUG
1275 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001276#endif
Guido van Rossum0ba35361998-08-13 13:33:16 +00001277#endif /* MS_WIN32 */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001278 abort();
1279}
1280
1281/* Clean up and exit */
1282
Guido van Rossuma110aa61994-08-29 12:50:44 +00001283#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001284#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001285int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001286#endif
1287
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001288#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001289static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001290static int nexitfuncs = 0;
1291
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001292int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001293{
1294 if (nexitfuncs >= NEXITFUNCS)
1295 return -1;
1296 exitfuncs[nexitfuncs++] = func;
1297 return 0;
1298}
1299
Guido van Rossumcc283f51997-08-05 02:22:03 +00001300static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001301call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001302{
Guido van Rossum82598051997-03-05 00:20:32 +00001303 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001304
1305 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001306 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001307 Py_INCREF(exitfunc);
1308 PySys_SetObject("exitfunc", (PyObject *)NULL);
1309 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001310 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001311 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1312 PySys_WriteStderr("Error in sys.exitfunc:\n");
1313 }
Guido van Rossum82598051997-03-05 00:20:32 +00001314 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001315 }
Guido van Rossum82598051997-03-05 00:20:32 +00001316 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001317 }
1318
Guido van Rossum0829c751998-02-28 04:31:39 +00001319 if (Py_FlushLine())
1320 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001321}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001322
Guido van Rossumcc283f51997-08-05 02:22:03 +00001323static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001324call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001325{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001326 while (nexitfuncs > 0)
1327 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001328
1329 fflush(stdout);
1330 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001331}
1332
1333void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001334Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001335{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001336 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001337
Jack Jansen66a89771995-10-27 13:22:14 +00001338#ifdef macintosh
1339 PyMac_Exit(sts);
1340#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001341 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001342#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001343}
1344
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001345static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001346initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001347{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001348#ifdef HAVE_SIGNAL_H
1349#ifdef SIGPIPE
1350 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001351#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001352#ifdef SIGXFZ
1353 signal(SIGXFZ, SIG_IGN);
1354#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001355#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001356 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001357}
1358
Guido van Rossumaae0d321996-05-22 16:35:33 +00001359#ifdef Py_TRACE_REFS
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001360/* Ask a yes/no question */
1361
Guido van Rossum59bff391992-09-03 20:28:00 +00001362int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001363_Py_AskYesNo(char *prompt)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001364{
1365 char buf[256];
1366
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367 fprintf(stderr, "%s [ny] ", prompt);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001368 if (fgets(buf, sizeof buf, stdin) == NULL)
1369 return 0;
1370 return buf[0] == 'y' || buf[0] == 'Y';
1371}
1372#endif
1373
Guido van Rossuma110aa61994-08-29 12:50:44 +00001374#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001375
1376/* Check for file descriptor connected to interactive device.
1377 Pretend that stdin is always interactive, other files never. */
1378
1379int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001380isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001381{
1382 return fd == fileno(stdin);
1383}
1384
1385#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001386
1387/*
1388 * The file descriptor fd is considered ``interactive'' if either
1389 * a) isatty(fd) is TRUE, or
1390 * b) the -i flag was given, and the filename associated with
1391 * the descriptor is NULL or "<stdin>" or "???".
1392 */
1393int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001394Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001395{
1396 if (isatty((int)fileno(fp)))
1397 return 1;
1398 if (!Py_InteractiveFlag)
1399 return 0;
1400 return (filename == NULL) ||
1401 (strcmp(filename, "<stdin>") == 0) ||
1402 (strcmp(filename, "???") == 0);
1403}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001404
1405
1406#if defined(USE_STACKCHECK)
1407#if defined(WIN32) && defined(_MSC_VER)
1408
1409/* Stack checking for Microsoft C */
1410
1411#include <malloc.h>
1412#include <excpt.h>
1413
Fred Drakee8de31c2000-08-31 05:38:39 +00001414/*
1415 * Return non-zero when we run out of memory on the stack; zero otherwise.
1416 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001417int
Fred Drake399739f2000-08-31 05:52:44 +00001418PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001419{
1420 __try {
1421 /* _alloca throws a stack overflow exception if there's
1422 not enough space left on the stack */
1423 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1424 return 0;
1425 } __except (EXCEPTION_EXECUTE_HANDLER) {
1426 /* just ignore all errors */
1427 }
1428 return 1;
1429}
1430
1431#endif /* WIN32 && _MSC_VER */
1432
1433/* Alternate implementations can be added here... */
1434
1435#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001436
1437
1438/* Wrappers around sigaction() or signal(). */
1439
1440PyOS_sighandler_t
1441PyOS_getsig(int sig)
1442{
1443#ifdef HAVE_SIGACTION
1444 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001445 /* Initialize context.sa_handler to SIG_ERR which makes about as
1446 * much sense as anything else. It should get overwritten if
1447 * sigaction actually succeeds and otherwise we avoid an
1448 * uninitialized memory read.
1449 */
1450 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001451 sigaction(sig, NULL, &context);
1452 return context.sa_handler;
1453#else
1454 PyOS_sighandler_t handler;
1455 handler = signal(sig, SIG_IGN);
1456 signal(sig, handler);
1457 return handler;
1458#endif
1459}
1460
1461PyOS_sighandler_t
1462PyOS_setsig(int sig, PyOS_sighandler_t handler)
1463{
1464#ifdef HAVE_SIGACTION
1465 struct sigaction context;
1466 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001467 /* Initialize context.sa_handler to SIG_ERR which makes about as
1468 * much sense as anything else. It should get overwritten if
1469 * sigaction actually succeeds and otherwise we avoid an
1470 * uninitialized memory read.
1471 */
1472 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001473 sigaction(sig, NULL, &context);
1474 oldhandler = context.sa_handler;
1475 context.sa_handler = handler;
1476 sigaction(sig, &context, NULL);
1477 return oldhandler;
1478#else
1479 return signal(sig, handler);
1480#endif
1481}