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