blob: 006ff083d252746b5f73fd526885afeda5b9c11d [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);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000678 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000679 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000680 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000681 if (closeit)
682 fclose(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000683 if( (fp = fopen(filename, "rb")) == NULL ) {
684 fprintf(stderr, "python: Can't reopen .pyc file\n");
685 return -1;
686 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000687 /* Turn on optimization if a .pyo file is given */
688 if (strcmp(ext, ".pyo") == 0)
689 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000690 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000691 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000692 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
693 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000694 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000695 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000696 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000697 return -1;
698 }
Guido van Rossum82598051997-03-05 00:20:32 +0000699 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000700 if (Py_FlushLine())
701 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000702 return 0;
703}
704
705int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000706PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000707{
Guido van Rossum393661d2001-08-31 17:40:15 +0000708 return PyRun_SimpleStringFlags(command, NULL);
709}
710
711int
712PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
713{
Guido van Rossum82598051997-03-05 00:20:32 +0000714 PyObject *m, *d, *v;
715 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000716 if (m == NULL)
717 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000718 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000719 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000720 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000721 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000722 return -1;
723 }
Guido van Rossum82598051997-03-05 00:20:32 +0000724 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000725 if (Py_FlushLine())
726 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000727 return 0;
728}
729
Barry Warsaw035574d1997-08-29 22:07:17 +0000730static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000731parse_syntax_error(PyObject *err, PyObject **message, char **filename,
732 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000733{
734 long hold;
735 PyObject *v;
736
737 /* old style errors */
738 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000739 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
740 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000741
742 /* new style errors. `err' is an instance */
743
744 if (! (v = PyObject_GetAttrString(err, "msg")))
745 goto finally;
746 *message = v;
747
748 if (!(v = PyObject_GetAttrString(err, "filename")))
749 goto finally;
750 if (v == Py_None)
751 *filename = NULL;
752 else if (! (*filename = PyString_AsString(v)))
753 goto finally;
754
755 Py_DECREF(v);
756 if (!(v = PyObject_GetAttrString(err, "lineno")))
757 goto finally;
758 hold = PyInt_AsLong(v);
759 Py_DECREF(v);
760 v = NULL;
761 if (hold < 0 && PyErr_Occurred())
762 goto finally;
763 *lineno = (int)hold;
764
765 if (!(v = PyObject_GetAttrString(err, "offset")))
766 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000767 if (v == Py_None) {
768 *offset = -1;
769 Py_DECREF(v);
770 v = NULL;
771 } else {
772 hold = PyInt_AsLong(v);
773 Py_DECREF(v);
774 v = NULL;
775 if (hold < 0 && PyErr_Occurred())
776 goto finally;
777 *offset = (int)hold;
778 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000779
780 if (!(v = PyObject_GetAttrString(err, "text")))
781 goto finally;
782 if (v == Py_None)
783 *text = NULL;
784 else if (! (*text = PyString_AsString(v)))
785 goto finally;
786 Py_DECREF(v);
787 return 1;
788
789finally:
790 Py_XDECREF(v);
791 return 0;
792}
793
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000794void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000795PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000796{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000797 PyErr_PrintEx(1);
798}
799
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000800static void
801print_error_text(PyObject *f, int offset, char *text)
802{
803 char *nl;
804 if (offset >= 0) {
805 if (offset > 0 && offset == (int)strlen(text))
806 offset--;
807 for (;;) {
808 nl = strchr(text, '\n');
809 if (nl == NULL || nl-text >= offset)
810 break;
811 offset -= (nl+1-text);
812 text = nl+1;
813 }
814 while (*text == ' ' || *text == '\t') {
815 text++;
816 offset--;
817 }
818 }
819 PyFile_WriteString(" ", f);
820 PyFile_WriteString(text, f);
821 if (*text == '\0' || text[strlen(text)-1] != '\n')
822 PyFile_WriteString("\n", f);
823 if (offset == -1)
824 return;
825 PyFile_WriteString(" ", f);
826 offset--;
827 while (offset > 0) {
828 PyFile_WriteString(" ", f);
829 offset--;
830 }
831 PyFile_WriteString("^\n", f);
832}
833
Guido van Rossum66e8e862001-03-23 17:54:43 +0000834static void
835handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000836{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000837 PyObject *exception, *value, *tb;
838 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000839 if (Py_FlushLine())
840 PyErr_Clear();
841 fflush(stdout);
842 if (value == NULL || value == Py_None)
843 Py_Exit(0);
844 if (PyInstance_Check(value)) {
845 /* The error code should be in the `code' attribute. */
846 PyObject *code = PyObject_GetAttrString(value, "code");
847 if (code) {
848 Py_DECREF(value);
849 value = code;
850 if (value == Py_None)
851 Py_Exit(0);
852 }
853 /* If we failed to dig out the 'code' attribute,
854 just let the else clause below print the error. */
855 }
856 if (PyInt_Check(value))
857 Py_Exit((int)PyInt_AsLong(value));
858 else {
859 PyObject_Print(value, stderr, Py_PRINT_RAW);
860 PySys_WriteStderr("\n");
861 Py_Exit(1);
862 }
863}
864
865void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000866PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000867{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000868 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000869
870 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
871 handle_system_exit();
872 }
Guido van Rossum82598051997-03-05 00:20:32 +0000873 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000874 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000875 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000876 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000877 if (set_sys_last_vars) {
878 PySys_SetObject("last_type", exception);
879 PySys_SetObject("last_value", v);
880 PySys_SetObject("last_traceback", tb);
881 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000882 hook = PySys_GetObject("excepthook");
883 if (hook) {
884 PyObject *args = Py_BuildValue("(OOO)",
885 exception, v ? v : Py_None, tb ? tb : Py_None);
886 PyObject *result = PyEval_CallObject(hook, args);
887 if (result == NULL) {
888 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000889 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
890 handle_system_exit();
891 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000892 PyErr_Fetch(&exception2, &v2, &tb2);
893 PyErr_NormalizeException(&exception2, &v2, &tb2);
894 if (Py_FlushLine())
895 PyErr_Clear();
896 fflush(stdout);
897 PySys_WriteStderr("Error in sys.excepthook:\n");
898 PyErr_Display(exception2, v2, tb2);
899 PySys_WriteStderr("\nOriginal exception was:\n");
900 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000901 Py_XDECREF(exception2);
902 Py_XDECREF(v2);
903 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000904 }
905 Py_XDECREF(result);
906 Py_XDECREF(args);
907 } else {
908 PySys_WriteStderr("sys.excepthook is missing\n");
909 PyErr_Display(exception, v, tb);
910 }
911 Py_XDECREF(exception);
912 Py_XDECREF(v);
913 Py_XDECREF(tb);
914}
915
916void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
917{
918 int err = 0;
919 PyObject *v = value;
920 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000921 if (f == NULL)
922 fprintf(stderr, "lost sys.stderr\n");
923 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000924 if (Py_FlushLine())
925 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000926 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000927 if (tb && tb != Py_None)
928 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000929 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000930 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000931 {
Guido van Rossum82598051997-03-05 00:20:32 +0000932 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000933 char *filename, *text;
934 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000935 if (!parse_syntax_error(v, &message, &filename,
936 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000937 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000938 else {
939 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000940 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000941 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000942 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000943 else
Guido van Rossum82598051997-03-05 00:20:32 +0000944 PyFile_WriteString(filename, f);
945 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000946 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000947 PyFile_WriteString(buf, f);
948 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000949 if (text != NULL)
950 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000951 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000952 /* Can't be bothered to check all those
953 PyFile_WriteString() calls */
954 if (PyErr_Occurred())
955 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000956 }
957 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000958 if (err) {
959 /* Don't do anything else */
960 }
961 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000962 PyClassObject* exc = (PyClassObject*)exception;
963 PyObject* className = exc->cl_name;
964 PyObject* moduleName =
965 PyDict_GetItemString(exc->cl_dict, "__module__");
966
967 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000968 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000969 else {
970 char* modstr = PyString_AsString(moduleName);
971 if (modstr && strcmp(modstr, "exceptions"))
972 {
973 err = PyFile_WriteString(modstr, f);
974 err += PyFile_WriteString(".", f);
975 }
976 }
977 if (err == 0) {
978 if (className == NULL)
979 err = PyFile_WriteString("<unknown>", f);
980 else
981 err = PyFile_WriteObject(className, f,
982 Py_PRINT_RAW);
983 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000984 }
985 else
986 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
987 if (err == 0) {
988 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000989 PyObject *s = PyObject_Str(v);
990 /* only print colon if the str() of the
991 object is not the empty string
992 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000993 if (s == NULL)
994 err = -1;
995 else if (!PyString_Check(s) ||
996 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +0000997 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000998 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000999 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1000 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001001 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001002 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001003 if (err == 0)
1004 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001005 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001006 /* If an error happened here, don't show it.
1007 XXX This is wrong, but too many callers rely on this behavior. */
1008 if (err != 0)
1009 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001010}
1011
Guido van Rossum82598051997-03-05 00:20:32 +00001012PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001013PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001014{
Guido van Rossum82598051997-03-05 00:20:32 +00001015 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001016 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001017}
1018
Guido van Rossum82598051997-03-05 00:20:32 +00001019PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001020PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1021 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001022{
Tim Peterse8682112000-08-27 20:18:17 +00001023 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001024}
1025
1026PyObject *
1027PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001028 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001029{
1030 node *n = PyParser_SimpleParseFile(fp, filename, start);
1031 if (closeit)
1032 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001033 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001034}
1035
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001036PyObject *
1037PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1038 PyCompilerFlags *flags)
1039{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001040 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001041 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001042 "<string>", globals, locals, flags);
1043}
1044
1045PyObject *
1046PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1047 PyObject *locals, PyCompilerFlags *flags)
1048{
1049 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1050 flags);
1051}
1052
1053PyObject *
1054PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1055 PyObject *locals, int closeit, PyCompilerFlags *flags)
1056{
Tim Petersfe2127d2001-07-16 05:37:24 +00001057 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001058 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001059 if (closeit)
1060 fclose(fp);
1061 return run_err_node(n, filename, globals, locals, flags);
1062}
1063
Guido van Rossum82598051997-03-05 00:20:32 +00001064static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001065run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1066 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001067{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001068 if (n == NULL)
1069 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001070 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001071}
1072
Guido van Rossum82598051997-03-05 00:20:32 +00001073static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001074run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1075 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001076{
Guido van Rossum82598051997-03-05 00:20:32 +00001077 PyCodeObject *co;
1078 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001079 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001080 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001081 if (co == NULL)
1082 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001083 v = PyEval_EvalCode(co, globals, locals);
1084 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001085 return v;
1086}
1087
Guido van Rossum82598051997-03-05 00:20:32 +00001088static PyObject *
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001089run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1090 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001091{
Guido van Rossum82598051997-03-05 00:20:32 +00001092 PyCodeObject *co;
1093 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001094 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001095 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001096
Guido van Rossum82598051997-03-05 00:20:32 +00001097 magic = PyMarshal_ReadLongFromFile(fp);
1098 if (magic != PyImport_GetMagicNumber()) {
1099 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001100 "Bad magic number in .pyc file");
1101 return NULL;
1102 }
Guido van Rossum82598051997-03-05 00:20:32 +00001103 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001104 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001105 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001106 if (v == NULL || !PyCode_Check(v)) {
1107 Py_XDECREF(v);
1108 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001109 "Bad code object in .pyc file");
1110 return NULL;
1111 }
Guido van Rossum82598051997-03-05 00:20:32 +00001112 co = (PyCodeObject *)v;
1113 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001114 if (v && flags)
1115 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001116 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001117 return v;
1118}
1119
Guido van Rossum82598051997-03-05 00:20:32 +00001120PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001121Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001122{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001123 return Py_CompileStringFlags(str, filename, start, NULL);
1124}
1125
1126PyObject *
1127Py_CompileStringFlags(char *str, char *filename, int start,
1128 PyCompilerFlags *flags)
1129{
Guido van Rossum5b722181993-03-30 17:46:03 +00001130 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001131 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001132
1133 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1134 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001135 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001136 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001137 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001138 PyNode_Free(n);
1139 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001140}
1141
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001142struct symtable *
1143Py_SymtableString(char *str, char *filename, int start)
1144{
1145 node *n;
1146 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001147 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1148 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001149 if (n == NULL)
1150 return NULL;
1151 st = PyNode_CompileSymtable(n, filename);
1152 PyNode_Free(n);
1153 return st;
1154}
1155
Guido van Rossuma110aa61994-08-29 12:50:44 +00001156/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001157
Guido van Rossuma110aa61994-08-29 12:50:44 +00001158node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001159PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001160{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001161 node *n;
1162 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001163 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1164 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001165 if (n == NULL)
1166 err_input(&err);
1167 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001168}
1169
Tim Petersfe2127d2001-07-16 05:37:24 +00001170node *
1171PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1172{
1173 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1174}
1175
Guido van Rossuma110aa61994-08-29 12:50:44 +00001176/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001177
Guido van Rossuma110aa61994-08-29 12:50:44 +00001178node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001179PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1180{
1181 node *n;
1182 perrdetail err;
1183 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1184 flags);
1185 if (n == NULL)
1186 err_input(&err);
1187 return n;
1188}
1189
1190node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001191PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001192{
Tim Petersfe2127d2001-07-16 05:37:24 +00001193 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001194}
1195
Thomas Heller6b17abf2002-07-09 09:23:27 +00001196node *
1197PyParser_SimpleParseStringFlagsFilename(char *str, char *filename,
1198 int start, int flags)
1199{
1200 node *n;
1201 perrdetail err;
1202
1203 n = PyParser_ParseStringFlagsFilename(str, filename,
1204 &_PyParser_Grammar,
1205 start, &err, flags);
1206 if (n == NULL)
1207 err_input(&err);
1208 return n;
1209}
1210
1211node *
1212PyParser_SimpleParseStringFilename(char *str, char *filename, int start)
1213{
1214 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1215 start, 0);
1216}
1217
Guido van Rossuma110aa61994-08-29 12:50:44 +00001218/* Set the error appropriate to the given input error code (see errcode.h) */
1219
1220static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001221err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001222{
Fred Drake85f36392000-07-11 17:53:00 +00001223 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001224 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001225 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001226 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001227 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001228 err->lineno, err->offset, err->text);
1229 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001230 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001231 err->text = NULL;
1232 }
1233 switch (err->error) {
1234 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001235 errtype = PyExc_IndentationError;
1236 if (err->expected == INDENT)
1237 msg = "expected an indented block";
1238 else if (err->token == INDENT)
1239 msg = "unexpected indent";
1240 else if (err->token == DEDENT)
1241 msg = "unexpected unindent";
1242 else {
1243 errtype = PyExc_SyntaxError;
1244 msg = "invalid syntax";
1245 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001246 break;
1247 case E_TOKEN:
1248 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001249 break;
1250 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001251 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001252 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001253 return;
1254 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001255 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001256 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001257 return;
1258 case E_EOF:
1259 msg = "unexpected EOF while parsing";
1260 break;
Fred Drake85f36392000-07-11 17:53:00 +00001261 case E_TABSPACE:
1262 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001263 msg = "inconsistent use of tabs and spaces in indentation";
1264 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001265 case E_OVERFLOW:
1266 msg = "expression too long";
1267 break;
Fred Drake85f36392000-07-11 17:53:00 +00001268 case E_DEDENT:
1269 errtype = PyExc_IndentationError;
1270 msg = "unindent does not match any outer indentation level";
1271 break;
1272 case E_TOODEEP:
1273 errtype = PyExc_IndentationError;
1274 msg = "too many levels of indentation";
1275 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001276 case E_DECODE: { /* XXX */
1277 PyThreadState* tstate = PyThreadState_Get();
1278 PyObject* value = tstate->curexc_value;
1279 if (value != NULL) {
1280 u = PyObject_Repr(value);
1281 if (u != NULL) {
1282 msg = PyString_AsString(u);
1283 break;
1284 }
1285 }
1286 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001287 default:
1288 fprintf(stderr, "error=%d\n", err->error);
1289 msg = "unknown parsing error";
1290 break;
1291 }
Guido van Rossum82598051997-03-05 00:20:32 +00001292 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001293 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001294 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001295 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001296 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001297}
1298
1299/* Print fatal error message and abort */
1300
1301void
Tim Peters7c321a82002-07-09 02:57:01 +00001302Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001303{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001304 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001305#ifdef macintosh
1306 for (;;);
1307#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001308#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001309 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001310 OutputDebugString(msg);
1311 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001312#ifdef _DEBUG
1313 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001314#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001315#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001316 abort();
1317}
1318
1319/* Clean up and exit */
1320
Guido van Rossuma110aa61994-08-29 12:50:44 +00001321#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001322#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001323int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001324#endif
1325
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001326#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001327static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001328static int nexitfuncs = 0;
1329
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001330int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001331{
1332 if (nexitfuncs >= NEXITFUNCS)
1333 return -1;
1334 exitfuncs[nexitfuncs++] = func;
1335 return 0;
1336}
1337
Guido van Rossumcc283f51997-08-05 02:22:03 +00001338static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001339call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001340{
Guido van Rossum82598051997-03-05 00:20:32 +00001341 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001342
1343 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001344 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001345 Py_INCREF(exitfunc);
1346 PySys_SetObject("exitfunc", (PyObject *)NULL);
1347 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001348 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001349 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1350 PySys_WriteStderr("Error in sys.exitfunc:\n");
1351 }
Guido van Rossum82598051997-03-05 00:20:32 +00001352 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001353 }
Guido van Rossum82598051997-03-05 00:20:32 +00001354 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001355 }
1356
Guido van Rossum0829c751998-02-28 04:31:39 +00001357 if (Py_FlushLine())
1358 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001359}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001360
Guido van Rossumcc283f51997-08-05 02:22:03 +00001361static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001362call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001363{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001364 while (nexitfuncs > 0)
1365 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001366
1367 fflush(stdout);
1368 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001369}
1370
1371void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001372Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001373{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001374 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001375
Jack Jansen66a89771995-10-27 13:22:14 +00001376#ifdef macintosh
1377 PyMac_Exit(sts);
1378#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001379 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001380#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001381}
1382
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001383static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001384initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001385{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001386#ifdef HAVE_SIGNAL_H
1387#ifdef SIGPIPE
1388 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001389#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001390#ifdef SIGXFZ
1391 signal(SIGXFZ, SIG_IGN);
1392#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001393#ifdef SIGXFSZ
1394 signal(SIGXFSZ, SIG_IGN);
1395#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001396#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001397 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001398}
1399
Guido van Rossuma110aa61994-08-29 12:50:44 +00001400#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001401
1402/* Check for file descriptor connected to interactive device.
1403 Pretend that stdin is always interactive, other files never. */
1404
1405int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001406isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001407{
1408 return fd == fileno(stdin);
1409}
1410
1411#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001412
1413/*
1414 * The file descriptor fd is considered ``interactive'' if either
1415 * a) isatty(fd) is TRUE, or
1416 * b) the -i flag was given, and the filename associated with
1417 * the descriptor is NULL or "<stdin>" or "???".
1418 */
1419int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001420Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001421{
1422 if (isatty((int)fileno(fp)))
1423 return 1;
1424 if (!Py_InteractiveFlag)
1425 return 0;
1426 return (filename == NULL) ||
1427 (strcmp(filename, "<stdin>") == 0) ||
1428 (strcmp(filename, "???") == 0);
1429}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001430
1431
1432#if defined(USE_STACKCHECK)
1433#if defined(WIN32) && defined(_MSC_VER)
1434
1435/* Stack checking for Microsoft C */
1436
1437#include <malloc.h>
1438#include <excpt.h>
1439
Fred Drakee8de31c2000-08-31 05:38:39 +00001440/*
1441 * Return non-zero when we run out of memory on the stack; zero otherwise.
1442 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001443int
Fred Drake399739f2000-08-31 05:52:44 +00001444PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001445{
1446 __try {
1447 /* _alloca throws a stack overflow exception if there's
1448 not enough space left on the stack */
1449 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1450 return 0;
1451 } __except (EXCEPTION_EXECUTE_HANDLER) {
1452 /* just ignore all errors */
1453 }
1454 return 1;
1455}
1456
1457#endif /* WIN32 && _MSC_VER */
1458
1459/* Alternate implementations can be added here... */
1460
1461#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001462
1463
1464/* Wrappers around sigaction() or signal(). */
1465
1466PyOS_sighandler_t
1467PyOS_getsig(int sig)
1468{
1469#ifdef HAVE_SIGACTION
1470 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001471 /* Initialize context.sa_handler to SIG_ERR which makes about as
1472 * much sense as anything else. It should get overwritten if
1473 * sigaction actually succeeds and otherwise we avoid an
1474 * uninitialized memory read.
1475 */
1476 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001477 sigaction(sig, NULL, &context);
1478 return context.sa_handler;
1479#else
1480 PyOS_sighandler_t handler;
1481 handler = signal(sig, SIG_IGN);
1482 signal(sig, handler);
1483 return handler;
1484#endif
1485}
1486
1487PyOS_sighandler_t
1488PyOS_setsig(int sig, PyOS_sighandler_t handler)
1489{
1490#ifdef HAVE_SIGACTION
1491 struct sigaction context;
1492 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001493 /* Initialize context.sa_handler to SIG_ERR which makes about as
1494 * much sense as anything else. It should get overwritten if
1495 * sigaction actually succeeds and otherwise we avoid an
1496 * uninitialized memory read.
1497 */
1498 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001499 sigaction(sig, NULL, &context);
1500 oldhandler = context.sa_handler;
1501 context.sa_handler = handler;
1502 sigaction(sig, &context, NULL);
1503 return oldhandler;
1504#else
1505 return signal(sig, handler);
1506#endif
1507}