blob: a8ad84503df20a846134321713832515b07c4c7b [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 Rossum80bb9651996-12-05 23:27:02 +000016#ifdef HAVE_UNISTD_H
17#include <unistd.h>
18#endif
19
Guido van Rossuma110aa61994-08-29 12:50:44 +000020#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000021#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022#endif
23
Guido van Rossum9b38a141996-09-11 23:12:24 +000024#ifdef MS_WIN32
Guido van Rossuma44823b1995-03-14 15:01:17 +000025#undef BYTE
26#include "windows.h"
27#endif
28
Jack Jansencbf630f2000-07-11 21:59:16 +000029#ifdef macintosh
30#include "macglue.h"
31#endif
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000032extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000033
Guido van Rossum82598051997-03-05 00:20:32 +000034extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000035
Guido van Rossumb73cc041993-11-01 16:28:59 +000036/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000037static void initmain(void);
38static void initsite(void);
Jeremy Hylton9f324e92001-03-01 22:59:14 +000039static PyObject *run_err_node(node *, char *, PyObject *, PyObject *,
40 PyCompilerFlags *);
41static PyObject *run_node(node *, char *, PyObject *, PyObject *,
42 PyCompilerFlags *);
Jeremy Hyltonbc320242001-03-22 02:47:58 +000043static PyObject *run_pyc_file(FILE *, char *, PyObject *, PyObject *,
44 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000045static void err_input(perrdetail *);
46static void initsigs(void);
47static void call_sys_exitfunc(void);
48static void call_ll_exitfuncs(void);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000049
Guido van Rossumbffd6832000-01-20 22:32:56 +000050#ifdef Py_TRACE_REFS
51int _Py_AskYesNo(char *prompt);
52#endif
53
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000054extern void _PyUnicode_Init(void);
55extern void _PyUnicode_Fini(void);
56extern void _PyCodecRegistry_Init(void);
57extern void _PyCodecRegistry_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000058
Guido van Rossum82598051997-03-05 00:20:32 +000059int Py_DebugFlag; /* Needed by parser.c */
60int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000061int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000062int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000063int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000064int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000065int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000066int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000067/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
68 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
69 true divisions (which they will be in 2.3). */
70int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000071
Guido van Rossum25ce5661997-08-02 03:10:38 +000072static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000073
Thomas Wouters7e474022000-07-16 12:04:32 +000074/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000075
76int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000077Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000078{
79 return initialized;
80}
81
Guido van Rossum25ce5661997-08-02 03:10:38 +000082/* Global initializations. Can be undone by Py_Finalize(). Don't
83 call this twice without an intervening Py_Finalize() call. When
84 initializations fail, a fatal error is issued and the function does
85 not return. On return, the first thread and interpreter state have
86 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000087
Guido van Rossum25ce5661997-08-02 03:10:38 +000088 Locking: you must hold the interpreter lock while calling this.
89 (If the lock has not yet been initialized, that's equivalent to
90 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000091
Guido van Rossum25ce5661997-08-02 03:10:38 +000092*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000093
Guido van Rossum9abaf4d2001-10-12 22:17:56 +000094static int
95add_flag(int flag, const char *envs)
96{
97 int env = atoi(envs);
98 if (flag < env)
99 flag = env;
100 if (flag < 1)
101 flag = 1;
102 return flag;
103}
104
Guido van Rossuma027efa1997-05-05 20:56:21 +0000105void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000106Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000107{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000108 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000109 PyThreadState *tstate;
110 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000111 char *p;
Guido van Rossum70d893a2001-08-16 08:21:42 +0000112 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000113
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000114 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000115 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000116 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000118 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000119 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000120 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000121 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000122 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000123 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000124
Guido van Rossuma027efa1997-05-05 20:56:21 +0000125 interp = PyInterpreterState_New();
126 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000128
Guido van Rossuma027efa1997-05-05 20:56:21 +0000129 tstate = PyThreadState_New(interp);
130 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000131 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000132 (void) PyThreadState_Swap(tstate);
133
Guido van Rossum70d893a2001-08-16 08:21:42 +0000134 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000135
Guido van Rossum25ce5661997-08-02 03:10:38 +0000136 interp->modules = PyDict_New();
137 if (interp->modules == NULL)
138 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000139
Guido van Rossumc94044c2000-03-10 23:03:54 +0000140 /* Init codec registry */
141 _PyCodecRegistry_Init();
142
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000143#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000144 /* Init Unicode implementation; relies on the codec registry */
145 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000146#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000147
Barry Warsawf242aa02000-05-25 23:09:49 +0000148 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000149 if (bimod == NULL)
150 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000151 interp->builtins = PyModule_GetDict(bimod);
152 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000153
154 sysmod = _PySys_Init();
155 if (sysmod == NULL)
156 Py_FatalError("Py_Initialize: can't initialize sys");
157 interp->sysdict = PyModule_GetDict(sysmod);
158 Py_INCREF(interp->sysdict);
159 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000160 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000161 PyDict_SetItemString(interp->sysdict, "modules",
162 interp->modules);
163
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000164 _PyImport_Init();
165
Barry Warsawf242aa02000-05-25 23:09:49 +0000166 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000167 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000168 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000169
Barry Warsaw035574d1997-08-29 22:07:17 +0000170 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000171 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000172
Guido van Rossum25ce5661997-08-02 03:10:38 +0000173 initsigs(); /* Signal handling stuff, including initintr() */
174
175 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000176 if (!Py_NoSiteFlag)
177 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000178}
179
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000180#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000181extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000182#endif
183
Guido van Rossum25ce5661997-08-02 03:10:38 +0000184/* Undo the effect of Py_Initialize().
185
186 Beware: if multiple interpreter and/or thread states exist, these
187 are not wiped out; only the current thread and interpreter state
188 are deleted. But since everything else is deleted, those other
189 interpreter and thread states should no longer be used.
190
191 (XXX We should do better, e.g. wipe out all interpreters and
192 threads.)
193
194 Locking: as above.
195
196*/
197
198void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000199Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000200{
201 PyInterpreterState *interp;
202 PyThreadState *tstate;
203
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000204 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000205 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000206
Tim Peters384fd102001-01-21 03:40:37 +0000207 /* The interpreter is still entirely intact at this point, and the
208 * exit funcs may be relying on that. In particular, if some thread
209 * or exit func is still waiting to do an import, the import machinery
210 * expects Py_IsInitialized() to return true. So don't say the
211 * interpreter is uninitialized until after the exit funcs have run.
212 * Note that Threading.py uses an exit func to do a join on all the
213 * threads created thru it, so this also protects pending imports in
214 * the threads created via Threading.
215 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000216 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000217 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000218
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000219 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000220 tstate = PyThreadState_Get();
221 interp = tstate->interp;
222
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000223 /* Disable signal handling */
224 PyOS_FiniInterrupts();
225
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000226#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000227 /* Cleanup Unicode implementation */
228 _PyUnicode_Fini();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000229#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000230
231 /* Cleanup Codec registry */
232 _PyCodecRegistry_Fini();
233
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000234 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000236
Guido van Rossum1707aad1997-12-08 23:43:45 +0000237 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
238 _PyImport_Fini();
239
240 /* Debugging stuff */
241#ifdef COUNT_ALLOCS
242 dump_counts();
243#endif
244
245#ifdef Py_REF_DEBUG
246 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
247#endif
248
249#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000250 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000251 _Py_PrintReferences(stderr);
252 }
253#endif /* Py_TRACE_REFS */
254
Barry Warsaw035574d1997-08-29 22:07:17 +0000255 /* Now we decref the exception classes. After this point nothing
256 can raise an exception. That's okay, because each Fini() method
257 below has been checked to make sure no exceptions are ever
258 raised.
259 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000260 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000261
262 /* Delete current thread */
263 PyInterpreterState_Clear(interp);
264 PyThreadState_Swap(NULL);
265 PyInterpreterState_Delete(interp);
266
Guido van Rossumcc283f51997-08-05 02:22:03 +0000267 PyMethod_Fini();
268 PyFrame_Fini();
269 PyCFunction_Fini();
270 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000271 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000272 PyInt_Fini();
273 PyFloat_Fini();
274
275 /* XXX Still allocated:
276 - various static ad-hoc pointers to interned strings
277 - int and float free list blocks
278 - whatever various modules and libraries allocate
279 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000280
281 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000282
283 call_ll_exitfuncs();
284
Guido van Rossumcc283f51997-08-05 02:22:03 +0000285#ifdef Py_TRACE_REFS
Guido van Rossumcc283f51997-08-05 02:22:03 +0000286 _Py_ResetReferences();
287#endif /* Py_TRACE_REFS */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000288}
289
290/* Create and initialize a new interpreter and thread, and return the
291 new thread. This requires that Py_Initialize() has been called
292 first.
293
294 Unsuccessful initialization yields a NULL pointer. Note that *no*
295 exception information is available even in this case -- the
296 exception information is held in the thread, and there is no
297 thread.
298
299 Locking: as above.
300
301*/
302
303PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000304Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000305{
306 PyInterpreterState *interp;
307 PyThreadState *tstate, *save_tstate;
308 PyObject *bimod, *sysmod;
309
310 if (!initialized)
311 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
312
313 interp = PyInterpreterState_New();
314 if (interp == NULL)
315 return NULL;
316
317 tstate = PyThreadState_New(interp);
318 if (tstate == NULL) {
319 PyInterpreterState_Delete(interp);
320 return NULL;
321 }
322
323 save_tstate = PyThreadState_Swap(tstate);
324
325 /* XXX The following is lax in error checking */
326
327 interp->modules = PyDict_New();
328
329 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
330 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000331 interp->builtins = PyModule_GetDict(bimod);
332 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000333 }
334 sysmod = _PyImport_FindExtension("sys", "sys");
335 if (bimod != NULL && sysmod != NULL) {
336 interp->sysdict = PyModule_GetDict(sysmod);
337 Py_INCREF(interp->sysdict);
338 PySys_SetPath(Py_GetPath());
339 PyDict_SetItemString(interp->sysdict, "modules",
340 interp->modules);
341 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000342 if (!Py_NoSiteFlag)
343 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000344 }
345
346 if (!PyErr_Occurred())
347 return tstate;
348
349 /* Oops, it didn't work. Undo it all. */
350
351 PyErr_Print();
352 PyThreadState_Clear(tstate);
353 PyThreadState_Swap(save_tstate);
354 PyThreadState_Delete(tstate);
355 PyInterpreterState_Delete(interp);
356
357 return NULL;
358}
359
360/* Delete an interpreter and its last thread. This requires that the
361 given thread state is current, that the thread has no remaining
362 frames, and that it is its interpreter's only remaining thread.
363 It is a fatal error to violate these constraints.
364
365 (Py_Finalize() doesn't have these constraints -- it zaps
366 everything, regardless.)
367
368 Locking: as above.
369
370*/
371
372void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000373Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374{
375 PyInterpreterState *interp = tstate->interp;
376
377 if (tstate != PyThreadState_Get())
378 Py_FatalError("Py_EndInterpreter: thread is not current");
379 if (tstate->frame != NULL)
380 Py_FatalError("Py_EndInterpreter: thread still has a frame");
381 if (tstate != interp->tstate_head || tstate->next != NULL)
382 Py_FatalError("Py_EndInterpreter: not the last thread");
383
384 PyImport_Cleanup();
385 PyInterpreterState_Clear(interp);
386 PyThreadState_Swap(NULL);
387 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000388}
389
390static char *progname = "python";
391
392void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000393Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000394{
395 if (pn && *pn)
396 progname = pn;
397}
398
399char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000400Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000401{
402 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000403}
404
Guido van Rossuma61691e1998-02-06 22:27:24 +0000405static char *default_home = NULL;
406
407void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000408Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000409{
410 default_home = home;
411}
412
413char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000414Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000415{
416 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000417 if (home == NULL && !Py_IgnoreEnvironmentFlag)
418 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000419 return home;
420}
421
Guido van Rossum6135a871995-01-09 17:53:26 +0000422/* Create __main__ module */
423
424static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000425initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000426{
Guido van Rossum82598051997-03-05 00:20:32 +0000427 PyObject *m, *d;
428 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000429 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000430 Py_FatalError("can't create __main__ module");
431 d = PyModule_GetDict(m);
432 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000433 PyObject *bimod = PyImport_ImportModule("__builtin__");
434 if (bimod == NULL ||
435 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000436 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000437 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000438 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000439}
440
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000441/* Import the site module (not into __main__ though) */
442
443static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000444initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000445{
446 PyObject *m, *f;
447 m = PyImport_ImportModule("site");
448 if (m == NULL) {
449 f = PySys_GetObject("stderr");
450 if (Py_VerboseFlag) {
451 PyFile_WriteString(
452 "'import site' failed; traceback:\n", f);
453 PyErr_Print();
454 }
455 else {
456 PyFile_WriteString(
457 "'import site' failed; use -v for traceback\n", f);
458 PyErr_Clear();
459 }
460 }
461 else {
462 Py_DECREF(m);
463 }
464}
465
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000466/* Parse input from a file and execute it */
467
468int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000469PyRun_AnyFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000470{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000471 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
472}
473
474int
475PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
476{
477 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000478}
479
480int
481PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
482{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000483 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
484}
485
486int
487PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
488 PyCompilerFlags *flags)
489{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000490 if (filename == NULL)
491 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000492 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000493 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000494 if (closeit)
495 fclose(fp);
496 return err;
497 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000498 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000499 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000500}
501
502int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000503PyRun_InteractiveLoop(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000504{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000505 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
506}
507
508int
509PyRun_InteractiveLoopFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
510{
Guido van Rossum82598051997-03-05 00:20:32 +0000511 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000512 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000513 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000514
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000515 if (flags == NULL) {
516 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000517 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000518 }
Guido van Rossum82598051997-03-05 00:20:32 +0000519 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000520 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000521 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
522 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000523 }
Guido van Rossum82598051997-03-05 00:20:32 +0000524 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000525 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000526 PySys_SetObject("ps2", v = PyString_FromString("... "));
527 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000528 }
529 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000530 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000531#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000532 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000533#endif
534 if (ret == E_EOF)
535 return 0;
536 /*
537 if (ret == E_NOMEM)
538 return -1;
539 */
540 }
541}
542
543int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000544PyRun_InteractiveOne(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000545{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000546 return PyRun_InteractiveOneFlags(fp, filename, NULL);
547}
548
549int
550PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
551{
Guido van Rossum82598051997-03-05 00:20:32 +0000552 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000553 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000554 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000555 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000556
Guido van Rossum82598051997-03-05 00:20:32 +0000557 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000558 if (v != NULL) {
559 v = PyObject_Str(v);
560 if (v == NULL)
561 PyErr_Clear();
562 else if (PyString_Check(v))
563 ps1 = PyString_AsString(v);
564 }
Guido van Rossum82598051997-03-05 00:20:32 +0000565 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000566 if (w != NULL) {
567 w = PyObject_Str(w);
568 if (w == NULL)
569 PyErr_Clear();
570 else if (PyString_Check(w))
571 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000572 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000573 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
574 Py_single_input, ps1, ps2, &err,
575 (flags &&
Jeremy Hyltonb857ba22001-08-10 21:41:33 +0000576 flags->cf_flags & CO_GENERATOR_ALLOWED) ?
Tim Petersfe2127d2001-07-16 05:37:24 +0000577 PyPARSE_YIELD_IS_KEYWORD : 0);
Guido van Rossum82598051997-03-05 00:20:32 +0000578 Py_XDECREF(v);
579 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000580 if (n == NULL) {
581 if (err.error == E_EOF) {
582 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000583 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000584 return E_EOF;
585 }
586 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000587 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000588 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000589 }
Guido van Rossum82598051997-03-05 00:20:32 +0000590 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000591 if (m == NULL)
592 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000593 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000594 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000595 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000596 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000597 return -1;
598 }
Guido van Rossum82598051997-03-05 00:20:32 +0000599 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000600 if (Py_FlushLine())
601 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000602 return 0;
603}
604
605int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000606PyRun_SimpleFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000607{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000608 return PyRun_SimpleFileEx(fp, filename, 0);
609}
610
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000611/* Check whether a file maybe a pyc file: Look at the extension,
612 the file type, and, if we may close it, at the first few bytes. */
613
614static int
615maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
616{
617 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
618 return 1;
619
620#ifdef macintosh
621 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
622 if (PyMac_getfiletype(filename) == 'PYC '
623 || PyMac_getfiletype(filename) == 'APPL')
624 return 1;
625#endif /* macintosh */
626
627 /* Only look into the file if we are allowed to close it, since
628 it then should also be seekable. */
629 if (closeit) {
630 /* Read only two bytes of the magic. If the file was opened in
631 text mode, the bytes 3 and 4 of the magic (\r\n) might not
632 be read as they are on disk. */
633 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
634 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000635 /* Mess: In case of -x, the stream is NOT at its start now,
636 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000637 which makes the current stream position formally undefined,
638 and a x-platform nightmare.
639 Unfortunately, we have no direct way to know whether -x
640 was specified. So we use a terrible hack: if the current
641 stream position is not 0, we assume -x was specified, and
642 give up. Bug 132850 on SourceForge spells out the
643 hopelessness of trying anything else (fseek and ftell
644 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000645 */
Tim Peters3e876562001-02-11 04:35:39 +0000646 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000647 if (ftell(fp) == 0) {
648 if (fread(buf, 1, 2, fp) == 2 &&
649 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
650 ispyc = 1;
651 rewind(fp);
652 }
Tim Peters3e876562001-02-11 04:35:39 +0000653 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000654 }
655 return 0;
656}
657
Guido van Rossum0df002c2000-08-27 19:21:52 +0000658int
659PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
660{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000661 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
662}
663
664int
665PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit,
666 PyCompilerFlags *flags)
667{
Guido van Rossum82598051997-03-05 00:20:32 +0000668 PyObject *m, *d, *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000669 char *ext;
670
Guido van Rossum82598051997-03-05 00:20:32 +0000671 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000672 if (m == NULL)
673 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000674 d = PyModule_GetDict(m);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000675 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000676 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000677 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000678 if (closeit)
679 fclose(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000680 if( (fp = fopen(filename, "rb")) == NULL ) {
681 fprintf(stderr, "python: Can't reopen .pyc file\n");
682 return -1;
683 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000684 /* Turn on optimization if a .pyo file is given */
685 if (strcmp(ext, ".pyo") == 0)
686 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000687 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000688 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000689 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
690 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000691 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000692 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000693 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000694 return -1;
695 }
Guido van Rossum82598051997-03-05 00:20:32 +0000696 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000697 if (Py_FlushLine())
698 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000699 return 0;
700}
701
702int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000703PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000704{
Guido van Rossum393661d2001-08-31 17:40:15 +0000705 return PyRun_SimpleStringFlags(command, NULL);
706}
707
708int
709PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
710{
Guido van Rossum82598051997-03-05 00:20:32 +0000711 PyObject *m, *d, *v;
712 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000713 if (m == NULL)
714 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000715 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000716 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000717 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000718 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000719 return -1;
720 }
Guido van Rossum82598051997-03-05 00:20:32 +0000721 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000722 if (Py_FlushLine())
723 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000724 return 0;
725}
726
Barry Warsaw035574d1997-08-29 22:07:17 +0000727static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000728parse_syntax_error(PyObject *err, PyObject **message, char **filename,
729 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000730{
731 long hold;
732 PyObject *v;
733
734 /* old style errors */
735 if (PyTuple_Check(err))
736 return PyArg_Parse(err, "(O(ziiz))", message, filename,
737 lineno, offset, text);
738
739 /* new style errors. `err' is an instance */
740
741 if (! (v = PyObject_GetAttrString(err, "msg")))
742 goto finally;
743 *message = v;
744
745 if (!(v = PyObject_GetAttrString(err, "filename")))
746 goto finally;
747 if (v == Py_None)
748 *filename = NULL;
749 else if (! (*filename = PyString_AsString(v)))
750 goto finally;
751
752 Py_DECREF(v);
753 if (!(v = PyObject_GetAttrString(err, "lineno")))
754 goto finally;
755 hold = PyInt_AsLong(v);
756 Py_DECREF(v);
757 v = NULL;
758 if (hold < 0 && PyErr_Occurred())
759 goto finally;
760 *lineno = (int)hold;
761
762 if (!(v = PyObject_GetAttrString(err, "offset")))
763 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000764 if (v == Py_None) {
765 *offset = -1;
766 Py_DECREF(v);
767 v = NULL;
768 } else {
769 hold = PyInt_AsLong(v);
770 Py_DECREF(v);
771 v = NULL;
772 if (hold < 0 && PyErr_Occurred())
773 goto finally;
774 *offset = (int)hold;
775 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000776
777 if (!(v = PyObject_GetAttrString(err, "text")))
778 goto finally;
779 if (v == Py_None)
780 *text = NULL;
781 else if (! (*text = PyString_AsString(v)))
782 goto finally;
783 Py_DECREF(v);
784 return 1;
785
786finally:
787 Py_XDECREF(v);
788 return 0;
789}
790
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000791void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000792PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000793{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000794 PyErr_PrintEx(1);
795}
796
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000797static void
798print_error_text(PyObject *f, int offset, char *text)
799{
800 char *nl;
801 if (offset >= 0) {
802 if (offset > 0 && offset == (int)strlen(text))
803 offset--;
804 for (;;) {
805 nl = strchr(text, '\n');
806 if (nl == NULL || nl-text >= offset)
807 break;
808 offset -= (nl+1-text);
809 text = nl+1;
810 }
811 while (*text == ' ' || *text == '\t') {
812 text++;
813 offset--;
814 }
815 }
816 PyFile_WriteString(" ", f);
817 PyFile_WriteString(text, f);
818 if (*text == '\0' || text[strlen(text)-1] != '\n')
819 PyFile_WriteString("\n", f);
820 if (offset == -1)
821 return;
822 PyFile_WriteString(" ", f);
823 offset--;
824 while (offset > 0) {
825 PyFile_WriteString(" ", f);
826 offset--;
827 }
828 PyFile_WriteString("^\n", f);
829}
830
Guido van Rossum66e8e862001-03-23 17:54:43 +0000831static void
832handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000833{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000834 PyObject *exception, *value, *tb;
835 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000836 if (Py_FlushLine())
837 PyErr_Clear();
838 fflush(stdout);
839 if (value == NULL || value == Py_None)
840 Py_Exit(0);
841 if (PyInstance_Check(value)) {
842 /* The error code should be in the `code' attribute. */
843 PyObject *code = PyObject_GetAttrString(value, "code");
844 if (code) {
845 Py_DECREF(value);
846 value = code;
847 if (value == Py_None)
848 Py_Exit(0);
849 }
850 /* If we failed to dig out the 'code' attribute,
851 just let the else clause below print the error. */
852 }
853 if (PyInt_Check(value))
854 Py_Exit((int)PyInt_AsLong(value));
855 else {
856 PyObject_Print(value, stderr, Py_PRINT_RAW);
857 PySys_WriteStderr("\n");
858 Py_Exit(1);
859 }
860}
861
862void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000863PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000864{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000865 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000866
867 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
868 handle_system_exit();
869 }
Guido van Rossum82598051997-03-05 00:20:32 +0000870 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000871 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000872 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000873 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000874 if (set_sys_last_vars) {
875 PySys_SetObject("last_type", exception);
876 PySys_SetObject("last_value", v);
877 PySys_SetObject("last_traceback", tb);
878 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000879 hook = PySys_GetObject("excepthook");
880 if (hook) {
881 PyObject *args = Py_BuildValue("(OOO)",
882 exception, v ? v : Py_None, tb ? tb : Py_None);
883 PyObject *result = PyEval_CallObject(hook, args);
884 if (result == NULL) {
885 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000886 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
887 handle_system_exit();
888 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000889 PyErr_Fetch(&exception2, &v2, &tb2);
890 PyErr_NormalizeException(&exception2, &v2, &tb2);
891 if (Py_FlushLine())
892 PyErr_Clear();
893 fflush(stdout);
894 PySys_WriteStderr("Error in sys.excepthook:\n");
895 PyErr_Display(exception2, v2, tb2);
896 PySys_WriteStderr("\nOriginal exception was:\n");
897 PyErr_Display(exception, v, tb);
898 }
899 Py_XDECREF(result);
900 Py_XDECREF(args);
901 } else {
902 PySys_WriteStderr("sys.excepthook is missing\n");
903 PyErr_Display(exception, v, tb);
904 }
905 Py_XDECREF(exception);
906 Py_XDECREF(v);
907 Py_XDECREF(tb);
908}
909
910void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
911{
912 int err = 0;
913 PyObject *v = value;
914 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000915 if (f == NULL)
916 fprintf(stderr, "lost sys.stderr\n");
917 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000918 if (Py_FlushLine())
919 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000920 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000921 if (tb && tb != Py_None)
922 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000923 if (err == 0 &&
924 PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
925 {
Guido van Rossum82598051997-03-05 00:20:32 +0000926 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000927 char *filename, *text;
928 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000929 if (!parse_syntax_error(v, &message, &filename,
930 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000931 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000932 else {
933 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000934 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000935 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000936 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000937 else
Guido van Rossum82598051997-03-05 00:20:32 +0000938 PyFile_WriteString(filename, f);
939 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000940 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000941 PyFile_WriteString(buf, f);
942 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000943 if (text != NULL)
944 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000945 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000946 /* Can't be bothered to check all those
947 PyFile_WriteString() calls */
948 if (PyErr_Occurred())
949 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000950 }
951 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000952 if (err) {
953 /* Don't do anything else */
954 }
955 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000956 PyClassObject* exc = (PyClassObject*)exception;
957 PyObject* className = exc->cl_name;
958 PyObject* moduleName =
959 PyDict_GetItemString(exc->cl_dict, "__module__");
960
961 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000962 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000963 else {
964 char* modstr = PyString_AsString(moduleName);
965 if (modstr && strcmp(modstr, "exceptions"))
966 {
967 err = PyFile_WriteString(modstr, f);
968 err += PyFile_WriteString(".", f);
969 }
970 }
971 if (err == 0) {
972 if (className == NULL)
973 err = PyFile_WriteString("<unknown>", f);
974 else
975 err = PyFile_WriteObject(className, f,
976 Py_PRINT_RAW);
977 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000978 }
979 else
980 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
981 if (err == 0) {
982 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000983 PyObject *s = PyObject_Str(v);
984 /* only print colon if the str() of the
985 object is not the empty string
986 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000987 if (s == NULL)
988 err = -1;
989 else if (!PyString_Check(s) ||
990 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +0000991 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000992 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000993 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
994 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +0000995 }
Guido van Rossum262e1241995-02-07 15:30:45 +0000996 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000997 if (err == 0)
998 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000999 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001000 /* If an error happened here, don't show it.
1001 XXX This is wrong, but too many callers rely on this behavior. */
1002 if (err != 0)
1003 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001004}
1005
Guido van Rossum82598051997-03-05 00:20:32 +00001006PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001007PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001008{
Guido van Rossum82598051997-03-05 00:20:32 +00001009 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001010 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001011}
1012
Guido van Rossum82598051997-03-05 00:20:32 +00001013PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001014PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1015 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001016{
Tim Peterse8682112000-08-27 20:18:17 +00001017 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001018}
1019
1020PyObject *
1021PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001022 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001023{
1024 node *n = PyParser_SimpleParseFile(fp, filename, start);
1025 if (closeit)
1026 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001027 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001028}
1029
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001030PyObject *
1031PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1032 PyCompilerFlags *flags)
1033{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001034 return run_err_node(PyParser_SimpleParseStringFlags(
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001035 str, start,
1036 (flags && flags->cf_flags & CO_GENERATOR_ALLOWED) ?
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001037 PyPARSE_YIELD_IS_KEYWORD : 0),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001038 "<string>", globals, locals, flags);
1039}
1040
1041PyObject *
1042PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1043 PyObject *locals, PyCompilerFlags *flags)
1044{
1045 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1046 flags);
1047}
1048
1049PyObject *
1050PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1051 PyObject *locals, int closeit, PyCompilerFlags *flags)
1052{
Tim Petersfe2127d2001-07-16 05:37:24 +00001053 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001054 (flags && flags->cf_flags & CO_GENERATOR_ALLOWED) ?
Tim Petersfe2127d2001-07-16 05:37:24 +00001055 PyPARSE_YIELD_IS_KEYWORD : 0);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001056 if (closeit)
1057 fclose(fp);
1058 return run_err_node(n, filename, globals, locals, flags);
1059}
1060
Guido van Rossum82598051997-03-05 00:20:32 +00001061static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001062run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1063 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001064{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001065 if (n == NULL)
1066 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001067 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001068}
1069
Guido van Rossum82598051997-03-05 00:20:32 +00001070static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001071run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1072 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001073{
Guido van Rossum82598051997-03-05 00:20:32 +00001074 PyCodeObject *co;
1075 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001076 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001077 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001078 if (co == NULL)
1079 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001080 v = PyEval_EvalCode(co, globals, locals);
1081 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001082 return v;
1083}
1084
Guido van Rossum82598051997-03-05 00:20:32 +00001085static PyObject *
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001086run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1087 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001088{
Guido van Rossum82598051997-03-05 00:20:32 +00001089 PyCodeObject *co;
1090 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001091 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001092 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001093
Guido van Rossum82598051997-03-05 00:20:32 +00001094 magic = PyMarshal_ReadLongFromFile(fp);
1095 if (magic != PyImport_GetMagicNumber()) {
1096 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001097 "Bad magic number in .pyc file");
1098 return NULL;
1099 }
Guido van Rossum82598051997-03-05 00:20:32 +00001100 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001101 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001102 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001103 if (v == NULL || !PyCode_Check(v)) {
1104 Py_XDECREF(v);
1105 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001106 "Bad code object in .pyc file");
1107 return NULL;
1108 }
Guido van Rossum82598051997-03-05 00:20:32 +00001109 co = (PyCodeObject *)v;
1110 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001111 if (v && flags)
1112 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001113 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001114 return v;
1115}
1116
Guido van Rossum82598051997-03-05 00:20:32 +00001117PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001118Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001119{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001120 return Py_CompileStringFlags(str, filename, start, NULL);
1121}
1122
1123PyObject *
1124Py_CompileStringFlags(char *str, char *filename, int start,
1125 PyCompilerFlags *flags)
1126{
Guido van Rossum5b722181993-03-30 17:46:03 +00001127 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001128 PyCodeObject *co;
Tim Petersfe2127d2001-07-16 05:37:24 +00001129 n = PyParser_SimpleParseStringFlags(str, start,
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001130 (flags && flags->cf_flags & CO_GENERATOR_ALLOWED) ?
Tim Petersfe2127d2001-07-16 05:37:24 +00001131 PyPARSE_YIELD_IS_KEYWORD : 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001132 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001133 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001134 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001135 PyNode_Free(n);
1136 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001137}
1138
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001139struct symtable *
1140Py_SymtableString(char *str, char *filename, int start)
1141{
1142 node *n;
1143 struct symtable *st;
1144 n = PyParser_SimpleParseString(str, start);
1145 if (n == NULL)
1146 return NULL;
1147 st = PyNode_CompileSymtable(n, filename);
1148 PyNode_Free(n);
1149 return st;
1150}
1151
Guido van Rossuma110aa61994-08-29 12:50:44 +00001152/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001153
Guido van Rossuma110aa61994-08-29 12:50:44 +00001154node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001155PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001156{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001157 node *n;
1158 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001159 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1160 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001161 if (n == NULL)
1162 err_input(&err);
1163 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001164}
1165
Tim Petersfe2127d2001-07-16 05:37:24 +00001166node *
1167PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1168{
1169 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1170}
1171
Guido van Rossuma110aa61994-08-29 12:50:44 +00001172/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001173
Guido van Rossuma110aa61994-08-29 12:50:44 +00001174node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001175PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1176{
1177 node *n;
1178 perrdetail err;
1179 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1180 flags);
1181 if (n == NULL)
1182 err_input(&err);
1183 return n;
1184}
1185
1186node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001187PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001188{
Tim Petersfe2127d2001-07-16 05:37:24 +00001189 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001190}
1191
1192/* Set the error appropriate to the given input error code (see errcode.h) */
1193
1194static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001195err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001196{
Fred Drake85f36392000-07-11 17:53:00 +00001197 PyObject *v, *w, *errtype;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001198 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001199 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001200 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001201 err->lineno, err->offset, err->text);
1202 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001203 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001204 err->text = NULL;
1205 }
1206 switch (err->error) {
1207 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001208 errtype = PyExc_IndentationError;
1209 if (err->expected == INDENT)
1210 msg = "expected an indented block";
1211 else if (err->token == INDENT)
1212 msg = "unexpected indent";
1213 else if (err->token == DEDENT)
1214 msg = "unexpected unindent";
1215 else {
1216 errtype = PyExc_SyntaxError;
1217 msg = "invalid syntax";
1218 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001219 break;
1220 case E_TOKEN:
1221 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001222 break;
1223 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001224 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001225 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001226 return;
1227 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001228 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001229 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001230 return;
1231 case E_EOF:
1232 msg = "unexpected EOF while parsing";
1233 break;
Fred Drake85f36392000-07-11 17:53:00 +00001234 case E_TABSPACE:
1235 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001236 msg = "inconsistent use of tabs and spaces in indentation";
1237 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001238 case E_OVERFLOW:
1239 msg = "expression too long";
1240 break;
Fred Drake85f36392000-07-11 17:53:00 +00001241 case E_DEDENT:
1242 errtype = PyExc_IndentationError;
1243 msg = "unindent does not match any outer indentation level";
1244 break;
1245 case E_TOODEEP:
1246 errtype = PyExc_IndentationError;
1247 msg = "too many levels of indentation";
1248 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001249 default:
1250 fprintf(stderr, "error=%d\n", err->error);
1251 msg = "unknown parsing error";
1252 break;
1253 }
Guido van Rossum82598051997-03-05 00:20:32 +00001254 w = Py_BuildValue("(sO)", msg, v);
Guido van Rossum41318302001-03-23 04:01:07 +00001255 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001256 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001257 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001258}
1259
1260/* Print fatal error message and abort */
1261
1262void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001263Py_FatalError(char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001264{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001265 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001266#ifdef macintosh
1267 for (;;);
1268#endif
Guido van Rossum9b38a141996-09-11 23:12:24 +00001269#ifdef MS_WIN32
Guido van Rossum23c94461997-05-22 20:21:30 +00001270 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001271 OutputDebugString(msg);
1272 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001273#ifdef _DEBUG
1274 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001275#endif
Guido van Rossum0ba35361998-08-13 13:33:16 +00001276#endif /* MS_WIN32 */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001277 abort();
1278}
1279
1280/* Clean up and exit */
1281
Guido van Rossuma110aa61994-08-29 12:50:44 +00001282#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001283#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001284int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001285#endif
1286
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001287#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001288static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001289static int nexitfuncs = 0;
1290
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001291int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001292{
1293 if (nexitfuncs >= NEXITFUNCS)
1294 return -1;
1295 exitfuncs[nexitfuncs++] = func;
1296 return 0;
1297}
1298
Guido van Rossumcc283f51997-08-05 02:22:03 +00001299static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001300call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001301{
Guido van Rossum82598051997-03-05 00:20:32 +00001302 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001303
1304 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001305 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001306 Py_INCREF(exitfunc);
1307 PySys_SetObject("exitfunc", (PyObject *)NULL);
1308 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001309 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001310 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1311 PySys_WriteStderr("Error in sys.exitfunc:\n");
1312 }
Guido van Rossum82598051997-03-05 00:20:32 +00001313 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001314 }
Guido van Rossum82598051997-03-05 00:20:32 +00001315 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001316 }
1317
Guido van Rossum0829c751998-02-28 04:31:39 +00001318 if (Py_FlushLine())
1319 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001320}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001321
Guido van Rossumcc283f51997-08-05 02:22:03 +00001322static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001323call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001324{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001325 while (nexitfuncs > 0)
1326 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001327
1328 fflush(stdout);
1329 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001330}
1331
1332void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001333Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001334{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001335 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001336
Jack Jansen66a89771995-10-27 13:22:14 +00001337#ifdef macintosh
1338 PyMac_Exit(sts);
1339#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001340 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001341#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001342}
1343
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001344static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001345initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001346{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001347#ifdef HAVE_SIGNAL_H
1348#ifdef SIGPIPE
1349 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001350#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001351#ifdef SIGXFZ
1352 signal(SIGXFZ, SIG_IGN);
1353#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001354#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001355 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001356}
1357
Guido van Rossumaae0d321996-05-22 16:35:33 +00001358#ifdef Py_TRACE_REFS
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001359/* Ask a yes/no question */
1360
Guido van Rossum59bff391992-09-03 20:28:00 +00001361int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001362_Py_AskYesNo(char *prompt)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001363{
1364 char buf[256];
1365
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 fprintf(stderr, "%s [ny] ", prompt);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001367 if (fgets(buf, sizeof buf, stdin) == NULL)
1368 return 0;
1369 return buf[0] == 'y' || buf[0] == 'Y';
1370}
1371#endif
1372
Guido van Rossuma110aa61994-08-29 12:50:44 +00001373#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001374
1375/* Check for file descriptor connected to interactive device.
1376 Pretend that stdin is always interactive, other files never. */
1377
1378int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001379isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001380{
1381 return fd == fileno(stdin);
1382}
1383
1384#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001385
1386/*
1387 * The file descriptor fd is considered ``interactive'' if either
1388 * a) isatty(fd) is TRUE, or
1389 * b) the -i flag was given, and the filename associated with
1390 * the descriptor is NULL or "<stdin>" or "???".
1391 */
1392int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001393Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001394{
1395 if (isatty((int)fileno(fp)))
1396 return 1;
1397 if (!Py_InteractiveFlag)
1398 return 0;
1399 return (filename == NULL) ||
1400 (strcmp(filename, "<stdin>") == 0) ||
1401 (strcmp(filename, "???") == 0);
1402}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001403
1404
1405#if defined(USE_STACKCHECK)
1406#if defined(WIN32) && defined(_MSC_VER)
1407
1408/* Stack checking for Microsoft C */
1409
1410#include <malloc.h>
1411#include <excpt.h>
1412
Fred Drakee8de31c2000-08-31 05:38:39 +00001413/*
1414 * Return non-zero when we run out of memory on the stack; zero otherwise.
1415 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001416int
Fred Drake399739f2000-08-31 05:52:44 +00001417PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001418{
1419 __try {
1420 /* _alloca throws a stack overflow exception if there's
1421 not enough space left on the stack */
1422 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1423 return 0;
1424 } __except (EXCEPTION_EXECUTE_HANDLER) {
1425 /* just ignore all errors */
1426 }
1427 return 1;
1428}
1429
1430#endif /* WIN32 && _MSC_VER */
1431
1432/* Alternate implementations can be added here... */
1433
1434#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001435
1436
1437/* Wrappers around sigaction() or signal(). */
1438
1439PyOS_sighandler_t
1440PyOS_getsig(int sig)
1441{
1442#ifdef HAVE_SIGACTION
1443 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001444 /* Initialize context.sa_handler to SIG_ERR which makes about as
1445 * much sense as anything else. It should get overwritten if
1446 * sigaction actually succeeds and otherwise we avoid an
1447 * uninitialized memory read.
1448 */
1449 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001450 sigaction(sig, NULL, &context);
1451 return context.sa_handler;
1452#else
1453 PyOS_sighandler_t handler;
1454 handler = signal(sig, SIG_IGN);
1455 signal(sig, handler);
1456 return handler;
1457#endif
1458}
1459
1460PyOS_sighandler_t
1461PyOS_setsig(int sig, PyOS_sighandler_t handler)
1462{
1463#ifdef HAVE_SIGACTION
1464 struct sigaction context;
1465 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001466 /* Initialize context.sa_handler to SIG_ERR which makes about as
1467 * much sense as anything else. It should get overwritten if
1468 * sigaction actually succeeds and otherwise we avoid an
1469 * uninitialized memory read.
1470 */
1471 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001472 sigaction(sig, NULL, &context);
1473 oldhandler = context.sa_handler;
1474 context.sa_handler = handler;
1475 sigaction(sig, &context, NULL);
1476 return oldhandler;
1477#else
1478 return signal(sig, handler);
1479#endif
1480}