blob: b85c390a770214a022656af0b13bdb7498aa8526 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
6#include "grammar.h"
7#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +00008#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00009#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010#include "errcode.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000012#include "symtable.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000013#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000014#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000015
Guido van Rossuma110aa61994-08-29 12:50:44 +000016#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000017#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000018#endif
19
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000020#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000021#undef BYTE
22#include "windows.h"
23#endif
24
Jack Jansencbf630f2000-07-11 21:59:16 +000025#ifdef macintosh
26#include "macglue.h"
27#endif
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000028extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000029
Guido van Rossum82598051997-03-05 00:20:32 +000030extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000031
Guido van Rossumb73cc041993-11-01 16:28:59 +000032/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000033static void initmain(void);
34static void initsite(void);
Jeremy Hylton9f324e92001-03-01 22:59:14 +000035static PyObject *run_err_node(node *, char *, PyObject *, PyObject *,
36 PyCompilerFlags *);
37static PyObject *run_node(node *, char *, PyObject *, PyObject *,
38 PyCompilerFlags *);
Jeremy Hyltonbc320242001-03-22 02:47:58 +000039static PyObject *run_pyc_file(FILE *, char *, PyObject *, PyObject *,
40 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000041static void err_input(perrdetail *);
42static void initsigs(void);
43static void call_sys_exitfunc(void);
44static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000045extern void _PyUnicode_Init(void);
46extern void _PyUnicode_Fini(void);
47extern void _PyCodecRegistry_Init(void);
48extern void _PyCodecRegistry_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000049
Guido van Rossum82598051997-03-05 00:20:32 +000050int Py_DebugFlag; /* Needed by parser.c */
51int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000052int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000053int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000054int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000055int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000056int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000057int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000058/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
59 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
60 true divisions (which they will be in 2.3). */
61int _Py_QnewFlag = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000062
Guido van Rossum25ce5661997-08-02 03:10:38 +000063static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000064
Thomas Wouters7e474022000-07-16 12:04:32 +000065/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000066
67int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000068Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000069{
70 return initialized;
71}
72
Guido van Rossum25ce5661997-08-02 03:10:38 +000073/* Global initializations. Can be undone by Py_Finalize(). Don't
74 call this twice without an intervening Py_Finalize() call. When
75 initializations fail, a fatal error is issued and the function does
76 not return. On return, the first thread and interpreter state have
77 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000078
Guido van Rossum25ce5661997-08-02 03:10:38 +000079 Locking: you must hold the interpreter lock while calling this.
80 (If the lock has not yet been initialized, that's equivalent to
81 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000082
Guido van Rossum25ce5661997-08-02 03:10:38 +000083*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000084
Guido van Rossum9abaf4d2001-10-12 22:17:56 +000085static int
86add_flag(int flag, const char *envs)
87{
88 int env = atoi(envs);
89 if (flag < env)
90 flag = env;
91 if (flag < 1)
92 flag = 1;
93 return flag;
94}
95
Guido van Rossuma027efa1997-05-05 20:56:21 +000096void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000097Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000098{
Guido van Rossuma027efa1997-05-05 20:56:21 +000099 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000100 PyThreadState *tstate;
101 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000102 char *p;
Guido van Rossum70d893a2001-08-16 08:21:42 +0000103 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000104
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000105 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000106 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000107 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000108
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000109 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000110 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000111 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000112 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000113 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000114 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000115
Guido van Rossuma027efa1997-05-05 20:56:21 +0000116 interp = PyInterpreterState_New();
117 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000119
Guido van Rossuma027efa1997-05-05 20:56:21 +0000120 tstate = PyThreadState_New(interp);
121 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000123 (void) PyThreadState_Swap(tstate);
124
Guido van Rossum70d893a2001-08-16 08:21:42 +0000125 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127 interp->modules = PyDict_New();
128 if (interp->modules == NULL)
129 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000130
Guido van Rossumc94044c2000-03-10 23:03:54 +0000131 /* Init codec registry */
132 _PyCodecRegistry_Init();
133
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000134#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000135 /* Init Unicode implementation; relies on the codec registry */
136 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000137#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000138
Barry Warsawf242aa02000-05-25 23:09:49 +0000139 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140 if (bimod == NULL)
141 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000142 interp->builtins = PyModule_GetDict(bimod);
143 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000144
145 sysmod = _PySys_Init();
146 if (sysmod == NULL)
147 Py_FatalError("Py_Initialize: can't initialize sys");
148 interp->sysdict = PyModule_GetDict(sysmod);
149 Py_INCREF(interp->sysdict);
150 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000151 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000152 PyDict_SetItemString(interp->sysdict, "modules",
153 interp->modules);
154
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000155 _PyImport_Init();
156
Barry Warsawf242aa02000-05-25 23:09:49 +0000157 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000158 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000159 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000160
Barry Warsaw035574d1997-08-29 22:07:17 +0000161 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000162 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000163
Guido van Rossum25ce5661997-08-02 03:10:38 +0000164 initsigs(); /* Signal handling stuff, including initintr() */
165
166 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000167 if (!Py_NoSiteFlag)
168 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169}
170
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000171#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000172extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000173#endif
174
Guido van Rossum25ce5661997-08-02 03:10:38 +0000175/* Undo the effect of Py_Initialize().
176
177 Beware: if multiple interpreter and/or thread states exist, these
178 are not wiped out; only the current thread and interpreter state
179 are deleted. But since everything else is deleted, those other
180 interpreter and thread states should no longer be used.
181
182 (XXX We should do better, e.g. wipe out all interpreters and
183 threads.)
184
185 Locking: as above.
186
187*/
188
189void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000190Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191{
192 PyInterpreterState *interp;
193 PyThreadState *tstate;
194
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000195 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000196 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000197
Tim Peters384fd102001-01-21 03:40:37 +0000198 /* The interpreter is still entirely intact at this point, and the
199 * exit funcs may be relying on that. In particular, if some thread
200 * or exit func is still waiting to do an import, the import machinery
201 * expects Py_IsInitialized() to return true. So don't say the
202 * interpreter is uninitialized until after the exit funcs have run.
203 * Note that Threading.py uses an exit func to do a join on all the
204 * threads created thru it, so this also protects pending imports in
205 * the threads created via Threading.
206 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000207 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000208 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000209
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000210 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000211 tstate = PyThreadState_Get();
212 interp = tstate->interp;
213
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000214 /* Disable signal handling */
215 PyOS_FiniInterrupts();
216
Guido van Rossumc94044c2000-03-10 23:03:54 +0000217 /* Cleanup Codec registry */
218 _PyCodecRegistry_Fini();
219
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000220 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000221 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000222
Guido van Rossum1707aad1997-12-08 23:43:45 +0000223 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
224 _PyImport_Fini();
225
226 /* Debugging stuff */
227#ifdef COUNT_ALLOCS
228 dump_counts();
229#endif
230
231#ifdef Py_REF_DEBUG
232 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
233#endif
234
235#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000236 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000237 _Py_PrintReferences(stderr);
238 }
239#endif /* Py_TRACE_REFS */
240
Barry Warsaw035574d1997-08-29 22:07:17 +0000241 /* Now we decref the exception classes. After this point nothing
242 can raise an exception. That's okay, because each Fini() method
243 below has been checked to make sure no exceptions are ever
244 raised.
245 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000246 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000247
248 /* Delete current thread */
249 PyInterpreterState_Clear(interp);
250 PyThreadState_Swap(NULL);
251 PyInterpreterState_Delete(interp);
252
Guido van Rossumcc283f51997-08-05 02:22:03 +0000253 PyMethod_Fini();
254 PyFrame_Fini();
255 PyCFunction_Fini();
256 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000257 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000258 PyInt_Fini();
259 PyFloat_Fini();
260
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000261#ifdef Py_USING_UNICODE
262 /* Cleanup Unicode implementation */
263 _PyUnicode_Fini();
264#endif
265
Guido van Rossumcc283f51997-08-05 02:22:03 +0000266 /* XXX Still allocated:
267 - various static ad-hoc pointers to interned strings
268 - int and float free list blocks
269 - whatever various modules and libraries allocate
270 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000271
272 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000273
Tim Peters0e871182002-04-13 08:29:14 +0000274#ifdef PYMALLOC_DEBUG
275 if (Py_GETENV("PYTHONMALLOCSTATS"))
276 _PyObject_DebugMallocStats();
277#endif
278
Guido van Rossumcc283f51997-08-05 02:22:03 +0000279 call_ll_exitfuncs();
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);
Fred Drake8ed02042002-10-17 21:24:58 +0000678 if (PyDict_GetItemString(d, "__file__") == NULL) {
679 PyObject *f = PyString_FromString(filename);
680 if (f == NULL)
681 return -1;
682 if (PyDict_SetItemString(d, "__file__", f) < 0) {
683 Py_DECREF(f);
684 return -1;
685 }
686 Py_DECREF(f);
687 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000688 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000689 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000690 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000691 if (closeit)
692 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000693 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000694 fprintf(stderr, "python: Can't reopen .pyc file\n");
695 return -1;
696 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000697 /* Turn on optimization if a .pyo file is given */
698 if (strcmp(ext, ".pyo") == 0)
699 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000700 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000701 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000702 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
703 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000704 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000705 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000706 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000707 return -1;
708 }
Guido van Rossum82598051997-03-05 00:20:32 +0000709 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000710 if (Py_FlushLine())
711 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000712 return 0;
713}
714
715int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000716PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000717{
Guido van Rossum393661d2001-08-31 17:40:15 +0000718 return PyRun_SimpleStringFlags(command, NULL);
719}
720
721int
722PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
723{
Guido van Rossum82598051997-03-05 00:20:32 +0000724 PyObject *m, *d, *v;
725 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000726 if (m == NULL)
727 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000728 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000729 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000730 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000731 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000732 return -1;
733 }
Guido van Rossum82598051997-03-05 00:20:32 +0000734 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000735 if (Py_FlushLine())
736 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000737 return 0;
738}
739
Barry Warsaw035574d1997-08-29 22:07:17 +0000740static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000741parse_syntax_error(PyObject *err, PyObject **message, char **filename,
742 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000743{
744 long hold;
745 PyObject *v;
746
747 /* old style errors */
748 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000749 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
750 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000751
752 /* new style errors. `err' is an instance */
753
754 if (! (v = PyObject_GetAttrString(err, "msg")))
755 goto finally;
756 *message = v;
757
758 if (!(v = PyObject_GetAttrString(err, "filename")))
759 goto finally;
760 if (v == Py_None)
761 *filename = NULL;
762 else if (! (*filename = PyString_AsString(v)))
763 goto finally;
764
765 Py_DECREF(v);
766 if (!(v = PyObject_GetAttrString(err, "lineno")))
767 goto finally;
768 hold = PyInt_AsLong(v);
769 Py_DECREF(v);
770 v = NULL;
771 if (hold < 0 && PyErr_Occurred())
772 goto finally;
773 *lineno = (int)hold;
774
775 if (!(v = PyObject_GetAttrString(err, "offset")))
776 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000777 if (v == Py_None) {
778 *offset = -1;
779 Py_DECREF(v);
780 v = NULL;
781 } else {
782 hold = PyInt_AsLong(v);
783 Py_DECREF(v);
784 v = NULL;
785 if (hold < 0 && PyErr_Occurred())
786 goto finally;
787 *offset = (int)hold;
788 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000789
790 if (!(v = PyObject_GetAttrString(err, "text")))
791 goto finally;
792 if (v == Py_None)
793 *text = NULL;
794 else if (! (*text = PyString_AsString(v)))
795 goto finally;
796 Py_DECREF(v);
797 return 1;
798
799finally:
800 Py_XDECREF(v);
801 return 0;
802}
803
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000804void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000805PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000806{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000807 PyErr_PrintEx(1);
808}
809
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000810static void
811print_error_text(PyObject *f, int offset, char *text)
812{
813 char *nl;
814 if (offset >= 0) {
815 if (offset > 0 && offset == (int)strlen(text))
816 offset--;
817 for (;;) {
818 nl = strchr(text, '\n');
819 if (nl == NULL || nl-text >= offset)
820 break;
821 offset -= (nl+1-text);
822 text = nl+1;
823 }
824 while (*text == ' ' || *text == '\t') {
825 text++;
826 offset--;
827 }
828 }
829 PyFile_WriteString(" ", f);
830 PyFile_WriteString(text, f);
831 if (*text == '\0' || text[strlen(text)-1] != '\n')
832 PyFile_WriteString("\n", f);
833 if (offset == -1)
834 return;
835 PyFile_WriteString(" ", f);
836 offset--;
837 while (offset > 0) {
838 PyFile_WriteString(" ", f);
839 offset--;
840 }
841 PyFile_WriteString("^\n", f);
842}
843
Guido van Rossum66e8e862001-03-23 17:54:43 +0000844static void
845handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000846{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000847 PyObject *exception, *value, *tb;
848 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000849 if (Py_FlushLine())
850 PyErr_Clear();
851 fflush(stdout);
852 if (value == NULL || value == Py_None)
853 Py_Exit(0);
854 if (PyInstance_Check(value)) {
855 /* The error code should be in the `code' attribute. */
856 PyObject *code = PyObject_GetAttrString(value, "code");
857 if (code) {
858 Py_DECREF(value);
859 value = code;
860 if (value == Py_None)
861 Py_Exit(0);
862 }
863 /* If we failed to dig out the 'code' attribute,
864 just let the else clause below print the error. */
865 }
866 if (PyInt_Check(value))
867 Py_Exit((int)PyInt_AsLong(value));
868 else {
869 PyObject_Print(value, stderr, Py_PRINT_RAW);
870 PySys_WriteStderr("\n");
871 Py_Exit(1);
872 }
873}
874
875void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000876PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000877{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000878 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000879
880 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
881 handle_system_exit();
882 }
Guido van Rossum82598051997-03-05 00:20:32 +0000883 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000884 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000886 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000887 if (set_sys_last_vars) {
888 PySys_SetObject("last_type", exception);
889 PySys_SetObject("last_value", v);
890 PySys_SetObject("last_traceback", tb);
891 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000892 hook = PySys_GetObject("excepthook");
893 if (hook) {
894 PyObject *args = Py_BuildValue("(OOO)",
895 exception, v ? v : Py_None, tb ? tb : Py_None);
896 PyObject *result = PyEval_CallObject(hook, args);
897 if (result == NULL) {
898 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000899 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
900 handle_system_exit();
901 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000902 PyErr_Fetch(&exception2, &v2, &tb2);
903 PyErr_NormalizeException(&exception2, &v2, &tb2);
904 if (Py_FlushLine())
905 PyErr_Clear();
906 fflush(stdout);
907 PySys_WriteStderr("Error in sys.excepthook:\n");
908 PyErr_Display(exception2, v2, tb2);
909 PySys_WriteStderr("\nOriginal exception was:\n");
910 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000911 Py_XDECREF(exception2);
912 Py_XDECREF(v2);
913 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000914 }
915 Py_XDECREF(result);
916 Py_XDECREF(args);
917 } else {
918 PySys_WriteStderr("sys.excepthook is missing\n");
919 PyErr_Display(exception, v, tb);
920 }
921 Py_XDECREF(exception);
922 Py_XDECREF(v);
923 Py_XDECREF(tb);
924}
925
926void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
927{
928 int err = 0;
929 PyObject *v = value;
930 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000931 if (f == NULL)
932 fprintf(stderr, "lost sys.stderr\n");
933 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000934 if (Py_FlushLine())
935 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000936 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000937 if (tb && tb != Py_None)
938 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000939 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000940 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000941 {
Guido van Rossum82598051997-03-05 00:20:32 +0000942 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000943 char *filename, *text;
944 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000945 if (!parse_syntax_error(v, &message, &filename,
946 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000947 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000948 else {
949 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000950 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000951 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000952 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000953 else
Guido van Rossum82598051997-03-05 00:20:32 +0000954 PyFile_WriteString(filename, f);
955 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000956 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000957 PyFile_WriteString(buf, f);
958 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000959 if (text != NULL)
960 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000961 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000962 /* Can't be bothered to check all those
963 PyFile_WriteString() calls */
964 if (PyErr_Occurred())
965 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000966 }
967 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000968 if (err) {
969 /* Don't do anything else */
970 }
971 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000972 PyClassObject* exc = (PyClassObject*)exception;
973 PyObject* className = exc->cl_name;
974 PyObject* moduleName =
975 PyDict_GetItemString(exc->cl_dict, "__module__");
976
977 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000978 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000979 else {
980 char* modstr = PyString_AsString(moduleName);
981 if (modstr && strcmp(modstr, "exceptions"))
982 {
983 err = PyFile_WriteString(modstr, f);
984 err += PyFile_WriteString(".", f);
985 }
986 }
987 if (err == 0) {
988 if (className == NULL)
989 err = PyFile_WriteString("<unknown>", f);
990 else
991 err = PyFile_WriteObject(className, f,
992 Py_PRINT_RAW);
993 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000994 }
995 else
996 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
997 if (err == 0) {
998 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000999 PyObject *s = PyObject_Str(v);
1000 /* only print colon if the str() of the
1001 object is not the empty string
1002 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001003 if (s == NULL)
1004 err = -1;
1005 else if (!PyString_Check(s) ||
1006 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001007 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001008 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001009 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1010 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001011 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001012 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001013 if (err == 0)
1014 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001015 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001016 /* If an error happened here, don't show it.
1017 XXX This is wrong, but too many callers rely on this behavior. */
1018 if (err != 0)
1019 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001020}
1021
Guido van Rossum82598051997-03-05 00:20:32 +00001022PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001023PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001024{
Guido van Rossum82598051997-03-05 00:20:32 +00001025 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001026 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001027}
1028
Guido van Rossum82598051997-03-05 00:20:32 +00001029PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001030PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1031 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001032{
Tim Peterse8682112000-08-27 20:18:17 +00001033 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001034}
1035
1036PyObject *
1037PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001038 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001039{
1040 node *n = PyParser_SimpleParseFile(fp, filename, start);
1041 if (closeit)
1042 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001043 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001044}
1045
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001046PyObject *
1047PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1048 PyCompilerFlags *flags)
1049{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001050 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001051 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001052 "<string>", globals, locals, flags);
1053}
1054
1055PyObject *
1056PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1057 PyObject *locals, PyCompilerFlags *flags)
1058{
1059 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1060 flags);
1061}
1062
1063PyObject *
1064PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1065 PyObject *locals, int closeit, PyCompilerFlags *flags)
1066{
Tim Petersfe2127d2001-07-16 05:37:24 +00001067 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001068 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001069 if (closeit)
1070 fclose(fp);
1071 return run_err_node(n, filename, globals, locals, flags);
1072}
1073
Guido van Rossum82598051997-03-05 00:20:32 +00001074static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001075run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1076 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001077{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001078 if (n == NULL)
1079 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001080 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001081}
1082
Guido van Rossum82598051997-03-05 00:20:32 +00001083static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001084run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1085 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001086{
Guido van Rossum82598051997-03-05 00:20:32 +00001087 PyCodeObject *co;
1088 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001089 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001090 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001091 if (co == NULL)
1092 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001093 v = PyEval_EvalCode(co, globals, locals);
1094 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001095 return v;
1096}
1097
Guido van Rossum82598051997-03-05 00:20:32 +00001098static PyObject *
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001099run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1100 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001101{
Guido van Rossum82598051997-03-05 00:20:32 +00001102 PyCodeObject *co;
1103 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001104 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001105 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001106
Guido van Rossum82598051997-03-05 00:20:32 +00001107 magic = PyMarshal_ReadLongFromFile(fp);
1108 if (magic != PyImport_GetMagicNumber()) {
1109 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001110 "Bad magic number in .pyc file");
1111 return NULL;
1112 }
Guido van Rossum82598051997-03-05 00:20:32 +00001113 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001114 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001115 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001116 if (v == NULL || !PyCode_Check(v)) {
1117 Py_XDECREF(v);
1118 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001119 "Bad code object in .pyc file");
1120 return NULL;
1121 }
Guido van Rossum82598051997-03-05 00:20:32 +00001122 co = (PyCodeObject *)v;
1123 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001124 if (v && flags)
1125 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001126 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001127 return v;
1128}
1129
Guido van Rossum82598051997-03-05 00:20:32 +00001130PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001131Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001132{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001133 return Py_CompileStringFlags(str, filename, start, NULL);
1134}
1135
1136PyObject *
1137Py_CompileStringFlags(char *str, char *filename, int start,
1138 PyCompilerFlags *flags)
1139{
Guido van Rossum5b722181993-03-30 17:46:03 +00001140 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001141 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001142
1143 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1144 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001145 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001146 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001147 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001148 PyNode_Free(n);
1149 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001150}
1151
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001152struct symtable *
1153Py_SymtableString(char *str, char *filename, int start)
1154{
1155 node *n;
1156 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001157 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1158 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001159 if (n == NULL)
1160 return NULL;
1161 st = PyNode_CompileSymtable(n, filename);
1162 PyNode_Free(n);
1163 return st;
1164}
1165
Guido van Rossuma110aa61994-08-29 12:50:44 +00001166/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001167
Guido van Rossuma110aa61994-08-29 12:50:44 +00001168node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001169PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001170{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001171 node *n;
1172 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001173 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1174 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001175 if (n == NULL)
1176 err_input(&err);
1177 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001178}
1179
Tim Petersfe2127d2001-07-16 05:37:24 +00001180node *
1181PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1182{
1183 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1184}
1185
Guido van Rossuma110aa61994-08-29 12:50:44 +00001186/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001187
Guido van Rossuma110aa61994-08-29 12:50:44 +00001188node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001189PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1190{
1191 node *n;
1192 perrdetail err;
1193 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1194 flags);
1195 if (n == NULL)
1196 err_input(&err);
1197 return n;
1198}
1199
1200node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001201PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001202{
Tim Petersfe2127d2001-07-16 05:37:24 +00001203 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001204}
1205
Thomas Heller6b17abf2002-07-09 09:23:27 +00001206node *
1207PyParser_SimpleParseStringFlagsFilename(char *str, char *filename,
1208 int start, int flags)
1209{
1210 node *n;
1211 perrdetail err;
1212
1213 n = PyParser_ParseStringFlagsFilename(str, filename,
1214 &_PyParser_Grammar,
1215 start, &err, flags);
1216 if (n == NULL)
1217 err_input(&err);
1218 return n;
1219}
1220
1221node *
1222PyParser_SimpleParseStringFilename(char *str, char *filename, int start)
1223{
1224 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1225 start, 0);
1226}
1227
Guido van Rossuma110aa61994-08-29 12:50:44 +00001228/* Set the error appropriate to the given input error code (see errcode.h) */
1229
1230static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001231err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001232{
Fred Drake85f36392000-07-11 17:53:00 +00001233 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001234 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001235 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001236 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001237 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001238 err->lineno, err->offset, err->text);
1239 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001240 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001241 err->text = NULL;
1242 }
1243 switch (err->error) {
1244 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001245 errtype = PyExc_IndentationError;
1246 if (err->expected == INDENT)
1247 msg = "expected an indented block";
1248 else if (err->token == INDENT)
1249 msg = "unexpected indent";
1250 else if (err->token == DEDENT)
1251 msg = "unexpected unindent";
1252 else {
1253 errtype = PyExc_SyntaxError;
1254 msg = "invalid syntax";
1255 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001256 break;
1257 case E_TOKEN:
1258 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001259 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001260 case E_EOFS:
1261 msg = "EOF while scanning triple-quoted string";
1262 break;
1263 case E_EOLS:
1264 msg = "EOL while scanning single-quoted string";
1265 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001266 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001267 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001268 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001269 return;
1270 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001271 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001272 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001273 return;
1274 case E_EOF:
1275 msg = "unexpected EOF while parsing";
1276 break;
Fred Drake85f36392000-07-11 17:53:00 +00001277 case E_TABSPACE:
1278 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001279 msg = "inconsistent use of tabs and spaces in indentation";
1280 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001281 case E_OVERFLOW:
1282 msg = "expression too long";
1283 break;
Fred Drake85f36392000-07-11 17:53:00 +00001284 case E_DEDENT:
1285 errtype = PyExc_IndentationError;
1286 msg = "unindent does not match any outer indentation level";
1287 break;
1288 case E_TOODEEP:
1289 errtype = PyExc_IndentationError;
1290 msg = "too many levels of indentation";
1291 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001292 case E_DECODE: { /* XXX */
1293 PyThreadState* tstate = PyThreadState_Get();
1294 PyObject* value = tstate->curexc_value;
1295 if (value != NULL) {
1296 u = PyObject_Repr(value);
1297 if (u != NULL) {
1298 msg = PyString_AsString(u);
1299 break;
1300 }
1301 }
1302 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001303 default:
1304 fprintf(stderr, "error=%d\n", err->error);
1305 msg = "unknown parsing error";
1306 break;
1307 }
Guido van Rossum82598051997-03-05 00:20:32 +00001308 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001309 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001310 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001311 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001312 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001313}
1314
1315/* Print fatal error message and abort */
1316
1317void
Tim Peters7c321a82002-07-09 02:57:01 +00001318Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001319{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001320 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001321#ifdef macintosh
1322 for (;;);
1323#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001324#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001325 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001326 OutputDebugString(msg);
1327 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001328#ifdef _DEBUG
1329 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001330#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001331#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001332 abort();
1333}
1334
1335/* Clean up and exit */
1336
Guido van Rossuma110aa61994-08-29 12:50:44 +00001337#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001338#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001339int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001340#endif
1341
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001342#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001343static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001344static int nexitfuncs = 0;
1345
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001346int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001347{
1348 if (nexitfuncs >= NEXITFUNCS)
1349 return -1;
1350 exitfuncs[nexitfuncs++] = func;
1351 return 0;
1352}
1353
Guido van Rossumcc283f51997-08-05 02:22:03 +00001354static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001355call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001356{
Guido van Rossum82598051997-03-05 00:20:32 +00001357 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001358
1359 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001360 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001361 Py_INCREF(exitfunc);
1362 PySys_SetObject("exitfunc", (PyObject *)NULL);
1363 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001364 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001365 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1366 PySys_WriteStderr("Error in sys.exitfunc:\n");
1367 }
Guido van Rossum82598051997-03-05 00:20:32 +00001368 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001369 }
Guido van Rossum82598051997-03-05 00:20:32 +00001370 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001371 }
1372
Guido van Rossum0829c751998-02-28 04:31:39 +00001373 if (Py_FlushLine())
1374 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001375}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001376
Guido van Rossumcc283f51997-08-05 02:22:03 +00001377static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001378call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001379{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001380 while (nexitfuncs > 0)
1381 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001382
1383 fflush(stdout);
1384 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001385}
1386
1387void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001388Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001389{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001390 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001391
Jack Jansen66a89771995-10-27 13:22:14 +00001392#ifdef macintosh
1393 PyMac_Exit(sts);
1394#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001395 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001396#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001397}
1398
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001399static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001400initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001401{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001402#ifdef HAVE_SIGNAL_H
1403#ifdef SIGPIPE
1404 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001405#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001406#ifdef SIGXFZ
1407 signal(SIGXFZ, SIG_IGN);
1408#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001409#ifdef SIGXFSZ
1410 signal(SIGXFSZ, SIG_IGN);
1411#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001412#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001413 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001414}
1415
Guido van Rossuma110aa61994-08-29 12:50:44 +00001416#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001417
1418/* Check for file descriptor connected to interactive device.
1419 Pretend that stdin is always interactive, other files never. */
1420
1421int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001422isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001423{
1424 return fd == fileno(stdin);
1425}
1426
1427#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001428
1429/*
1430 * The file descriptor fd is considered ``interactive'' if either
1431 * a) isatty(fd) is TRUE, or
1432 * b) the -i flag was given, and the filename associated with
1433 * the descriptor is NULL or "<stdin>" or "???".
1434 */
1435int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001436Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001437{
1438 if (isatty((int)fileno(fp)))
1439 return 1;
1440 if (!Py_InteractiveFlag)
1441 return 0;
1442 return (filename == NULL) ||
1443 (strcmp(filename, "<stdin>") == 0) ||
1444 (strcmp(filename, "???") == 0);
1445}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001446
1447
1448#if defined(USE_STACKCHECK)
1449#if defined(WIN32) && defined(_MSC_VER)
1450
1451/* Stack checking for Microsoft C */
1452
1453#include <malloc.h>
1454#include <excpt.h>
1455
Fred Drakee8de31c2000-08-31 05:38:39 +00001456/*
1457 * Return non-zero when we run out of memory on the stack; zero otherwise.
1458 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001459int
Fred Drake399739f2000-08-31 05:52:44 +00001460PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001461{
1462 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001463 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001464 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001465 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001466 return 0;
1467 } __except (EXCEPTION_EXECUTE_HANDLER) {
1468 /* just ignore all errors */
1469 }
1470 return 1;
1471}
1472
1473#endif /* WIN32 && _MSC_VER */
1474
1475/* Alternate implementations can be added here... */
1476
1477#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001478
1479
1480/* Wrappers around sigaction() or signal(). */
1481
1482PyOS_sighandler_t
1483PyOS_getsig(int sig)
1484{
1485#ifdef HAVE_SIGACTION
1486 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001487 /* Initialize context.sa_handler to SIG_ERR which makes about as
1488 * much sense as anything else. It should get overwritten if
1489 * sigaction actually succeeds and otherwise we avoid an
1490 * uninitialized memory read.
1491 */
1492 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001493 sigaction(sig, NULL, &context);
1494 return context.sa_handler;
1495#else
1496 PyOS_sighandler_t handler;
1497 handler = signal(sig, SIG_IGN);
1498 signal(sig, handler);
1499 return handler;
1500#endif
1501}
1502
1503PyOS_sighandler_t
1504PyOS_setsig(int sig, PyOS_sighandler_t handler)
1505{
1506#ifdef HAVE_SIGACTION
1507 struct sigaction context;
1508 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001509 /* Initialize context.sa_handler to SIG_ERR which makes about as
1510 * much sense as anything else. It should get overwritten if
1511 * sigaction actually succeeds and otherwise we avoid an
1512 * uninitialized memory read.
1513 */
1514 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001515 sigaction(sig, NULL, &context);
1516 oldhandler = context.sa_handler;
1517 context.sa_handler = handler;
1518 sigaction(sig, &context, NULL);
1519 return oldhandler;
1520#else
1521 return signal(sig, handler);
1522#endif
1523}