blob: 7469cb8d430bb439ddeec8a351fa97225e24fe65 [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);
Martin v. Löwis95292d62002-12-11 14:04:59 +000035static PyObject *run_err_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000036 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000037static PyObject *run_node(node *, const char *, PyObject *, PyObject *,
Jeremy Hylton9f324e92001-03-01 22:59:14 +000038 PyCompilerFlags *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000039static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000040 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
Just van Rossum52e14d62002-12-30 22:08:05 +0000164 _PyImportHooks_Init();
165
Guido van Rossum25ce5661997-08-02 03:10:38 +0000166 initsigs(); /* Signal handling stuff, including initintr() */
167
168 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000169 if (!Py_NoSiteFlag)
170 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000171}
172
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000173#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000174extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000175#endif
176
Guido van Rossum25ce5661997-08-02 03:10:38 +0000177/* Undo the effect of Py_Initialize().
178
179 Beware: if multiple interpreter and/or thread states exist, these
180 are not wiped out; only the current thread and interpreter state
181 are deleted. But since everything else is deleted, those other
182 interpreter and thread states should no longer be used.
183
184 (XXX We should do better, e.g. wipe out all interpreters and
185 threads.)
186
187 Locking: as above.
188
189*/
190
191void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000192Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000193{
194 PyInterpreterState *interp;
195 PyThreadState *tstate;
196
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000197 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000198 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199
Tim Peters384fd102001-01-21 03:40:37 +0000200 /* The interpreter is still entirely intact at this point, and the
201 * exit funcs may be relying on that. In particular, if some thread
202 * or exit func is still waiting to do an import, the import machinery
203 * expects Py_IsInitialized() to return true. So don't say the
204 * interpreter is uninitialized until after the exit funcs have run.
205 * Note that Threading.py uses an exit func to do a join on all the
206 * threads created thru it, so this also protects pending imports in
207 * the threads created via Threading.
208 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000209 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000210 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000211
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000212 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000213 tstate = PyThreadState_Get();
214 interp = tstate->interp;
215
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000216 /* Disable signal handling */
217 PyOS_FiniInterrupts();
218
Guido van Rossumc94044c2000-03-10 23:03:54 +0000219 /* Cleanup Codec registry */
220 _PyCodecRegistry_Fini();
221
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000222 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000223 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000224
Guido van Rossum1707aad1997-12-08 23:43:45 +0000225 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
226 _PyImport_Fini();
227
228 /* Debugging stuff */
229#ifdef COUNT_ALLOCS
230 dump_counts();
231#endif
232
233#ifdef Py_REF_DEBUG
234 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
235#endif
236
237#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000238 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000239 _Py_PrintReferences(stderr);
240 }
241#endif /* Py_TRACE_REFS */
242
Barry Warsaw035574d1997-08-29 22:07:17 +0000243 /* Now we decref the exception classes. After this point nothing
244 can raise an exception. That's okay, because each Fini() method
245 below has been checked to make sure no exceptions are ever
246 raised.
247 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000248 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000249
250 /* Delete current thread */
251 PyInterpreterState_Clear(interp);
252 PyThreadState_Swap(NULL);
253 PyInterpreterState_Delete(interp);
254
Guido van Rossumcc283f51997-08-05 02:22:03 +0000255 PyMethod_Fini();
256 PyFrame_Fini();
257 PyCFunction_Fini();
258 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000259 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000260 PyInt_Fini();
261 PyFloat_Fini();
262
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000263#ifdef Py_USING_UNICODE
264 /* Cleanup Unicode implementation */
265 _PyUnicode_Fini();
266#endif
267
Guido van Rossumcc283f51997-08-05 02:22:03 +0000268 /* XXX Still allocated:
269 - various static ad-hoc pointers to interned strings
270 - int and float free list blocks
271 - whatever various modules and libraries allocate
272 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000273
274 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000275
Tim Peters0e871182002-04-13 08:29:14 +0000276#ifdef PYMALLOC_DEBUG
277 if (Py_GETENV("PYTHONMALLOCSTATS"))
278 _PyObject_DebugMallocStats();
279#endif
280
Guido van Rossumcc283f51997-08-05 02:22:03 +0000281 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000282}
283
284/* Create and initialize a new interpreter and thread, and return the
285 new thread. This requires that Py_Initialize() has been called
286 first.
287
288 Unsuccessful initialization yields a NULL pointer. Note that *no*
289 exception information is available even in this case -- the
290 exception information is held in the thread, and there is no
291 thread.
292
293 Locking: as above.
294
295*/
296
297PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000298Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000299{
300 PyInterpreterState *interp;
301 PyThreadState *tstate, *save_tstate;
302 PyObject *bimod, *sysmod;
303
304 if (!initialized)
305 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
306
307 interp = PyInterpreterState_New();
308 if (interp == NULL)
309 return NULL;
310
311 tstate = PyThreadState_New(interp);
312 if (tstate == NULL) {
313 PyInterpreterState_Delete(interp);
314 return NULL;
315 }
316
317 save_tstate = PyThreadState_Swap(tstate);
318
319 /* XXX The following is lax in error checking */
320
321 interp->modules = PyDict_New();
322
323 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
324 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000325 interp->builtins = PyModule_GetDict(bimod);
326 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000327 }
328 sysmod = _PyImport_FindExtension("sys", "sys");
329 if (bimod != NULL && sysmod != NULL) {
330 interp->sysdict = PyModule_GetDict(sysmod);
331 Py_INCREF(interp->sysdict);
332 PySys_SetPath(Py_GetPath());
333 PyDict_SetItemString(interp->sysdict, "modules",
334 interp->modules);
335 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000336 if (!Py_NoSiteFlag)
337 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000338 }
339
340 if (!PyErr_Occurred())
341 return tstate;
342
343 /* Oops, it didn't work. Undo it all. */
344
345 PyErr_Print();
346 PyThreadState_Clear(tstate);
347 PyThreadState_Swap(save_tstate);
348 PyThreadState_Delete(tstate);
349 PyInterpreterState_Delete(interp);
350
351 return NULL;
352}
353
354/* Delete an interpreter and its last thread. This requires that the
355 given thread state is current, that the thread has no remaining
356 frames, and that it is its interpreter's only remaining thread.
357 It is a fatal error to violate these constraints.
358
359 (Py_Finalize() doesn't have these constraints -- it zaps
360 everything, regardless.)
361
362 Locking: as above.
363
364*/
365
366void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000367Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368{
369 PyInterpreterState *interp = tstate->interp;
370
371 if (tstate != PyThreadState_Get())
372 Py_FatalError("Py_EndInterpreter: thread is not current");
373 if (tstate->frame != NULL)
374 Py_FatalError("Py_EndInterpreter: thread still has a frame");
375 if (tstate != interp->tstate_head || tstate->next != NULL)
376 Py_FatalError("Py_EndInterpreter: not the last thread");
377
378 PyImport_Cleanup();
379 PyInterpreterState_Clear(interp);
380 PyThreadState_Swap(NULL);
381 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000382}
383
384static char *progname = "python";
385
386void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000387Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000388{
389 if (pn && *pn)
390 progname = pn;
391}
392
393char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000394Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000395{
396 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000397}
398
Guido van Rossuma61691e1998-02-06 22:27:24 +0000399static char *default_home = NULL;
400
401void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000402Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000403{
404 default_home = home;
405}
406
407char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000408Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000409{
410 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000411 if (home == NULL && !Py_IgnoreEnvironmentFlag)
412 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000413 return home;
414}
415
Guido van Rossum6135a871995-01-09 17:53:26 +0000416/* Create __main__ module */
417
418static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000419initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000420{
Guido van Rossum82598051997-03-05 00:20:32 +0000421 PyObject *m, *d;
422 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000423 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000424 Py_FatalError("can't create __main__ module");
425 d = PyModule_GetDict(m);
426 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000427 PyObject *bimod = PyImport_ImportModule("__builtin__");
428 if (bimod == NULL ||
429 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000430 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000431 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000432 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000433}
434
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000435/* Import the site module (not into __main__ though) */
436
437static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000438initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000439{
440 PyObject *m, *f;
441 m = PyImport_ImportModule("site");
442 if (m == NULL) {
443 f = PySys_GetObject("stderr");
444 if (Py_VerboseFlag) {
445 PyFile_WriteString(
446 "'import site' failed; traceback:\n", f);
447 PyErr_Print();
448 }
449 else {
450 PyFile_WriteString(
451 "'import site' failed; use -v for traceback\n", f);
452 PyErr_Clear();
453 }
454 }
455 else {
456 Py_DECREF(m);
457 }
458}
459
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000460/* Parse input from a file and execute it */
461
462int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000463PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000464{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000465 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
466}
467
468int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000469PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000470{
471 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000472}
473
474int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000475PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000476{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000477 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
478}
479
480int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000481PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000482 PyCompilerFlags *flags)
483{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000484 if (filename == NULL)
485 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000486 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000487 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000488 if (closeit)
489 fclose(fp);
490 return err;
491 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000492 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000493 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000494}
495
496int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000497PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000498{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000499 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
500}
501
502int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000503PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000504{
Guido van Rossum82598051997-03-05 00:20:32 +0000505 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000506 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000507 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000508
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000509 if (flags == NULL) {
510 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000511 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000512 }
Guido van Rossum82598051997-03-05 00:20:32 +0000513 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000514 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000515 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
516 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000517 }
Guido van Rossum82598051997-03-05 00:20:32 +0000518 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000519 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000520 PySys_SetObject("ps2", v = PyString_FromString("... "));
521 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000522 }
523 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000524 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000525#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000526 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000527#endif
528 if (ret == E_EOF)
529 return 0;
530 /*
531 if (ret == E_NOMEM)
532 return -1;
533 */
534 }
535}
536
537int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000538PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000539{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000540 return PyRun_InteractiveOneFlags(fp, filename, NULL);
541}
542
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000543/* compute parser flags based on compiler flags */
544#if 0 /* future keyword */
545#define PARSER_FLAGS(flags) \
546 (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \
547 PyPARSE_YIELD_IS_KEYWORD : 0)
548#else
549#define PARSER_FLAGS(flags) 0
550#endif
551
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000552int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000553PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000554{
Guido van Rossum82598051997-03-05 00:20:32 +0000555 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000556 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000557 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000558 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000559
Guido van Rossum82598051997-03-05 00:20:32 +0000560 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000561 if (v != NULL) {
562 v = PyObject_Str(v);
563 if (v == NULL)
564 PyErr_Clear();
565 else if (PyString_Check(v))
566 ps1 = PyString_AsString(v);
567 }
Guido van Rossum82598051997-03-05 00:20:32 +0000568 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000569 if (w != NULL) {
570 w = PyObject_Str(w);
571 if (w == NULL)
572 PyErr_Clear();
573 else if (PyString_Check(w))
574 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000575 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000576 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
577 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000578 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000579 Py_XDECREF(v);
580 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000581 if (n == NULL) {
582 if (err.error == E_EOF) {
583 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000584 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000585 return E_EOF;
586 }
587 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000588 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000589 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000590 }
Guido van Rossum82598051997-03-05 00:20:32 +0000591 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000592 if (m == NULL)
593 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000594 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000595 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000596 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000597 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000598 return -1;
599 }
Guido van Rossum82598051997-03-05 00:20:32 +0000600 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000601 if (Py_FlushLine())
602 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000603 return 0;
604}
605
606int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000607PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000608{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000609 return PyRun_SimpleFileEx(fp, filename, 0);
610}
611
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000612/* Check whether a file maybe a pyc file: Look at the extension,
613 the file type, and, if we may close it, at the first few bytes. */
614
615static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000616maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000617{
618 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
619 return 1;
620
621#ifdef macintosh
622 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000623 if (PyMac_getfiletype((char *)filename) == 'PYC '
624 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000625 return 1;
626#endif /* macintosh */
627
628 /* Only look into the file if we are allowed to close it, since
629 it then should also be seekable. */
630 if (closeit) {
631 /* Read only two bytes of the magic. If the file was opened in
632 text mode, the bytes 3 and 4 of the magic (\r\n) might not
633 be read as they are on disk. */
634 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
635 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000636 /* Mess: In case of -x, the stream is NOT at its start now,
637 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000638 which makes the current stream position formally undefined,
639 and a x-platform nightmare.
640 Unfortunately, we have no direct way to know whether -x
641 was specified. So we use a terrible hack: if the current
642 stream position is not 0, we assume -x was specified, and
643 give up. Bug 132850 on SourceForge spells out the
644 hopelessness of trying anything else (fseek and ftell
645 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000646 */
Tim Peters3e876562001-02-11 04:35:39 +0000647 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000648 if (ftell(fp) == 0) {
649 if (fread(buf, 1, 2, fp) == 2 &&
650 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
651 ispyc = 1;
652 rewind(fp);
653 }
Tim Peters3e876562001-02-11 04:35:39 +0000654 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000655 }
656 return 0;
657}
658
Guido van Rossum0df002c2000-08-27 19:21:52 +0000659int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000660PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000661{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000662 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
663}
664
665int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000666PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000667 PyCompilerFlags *flags)
668{
Guido van Rossum82598051997-03-05 00:20:32 +0000669 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000670 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000671
Guido van Rossum82598051997-03-05 00:20:32 +0000672 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000673 if (m == NULL)
674 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000675 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000676 if (PyDict_GetItemString(d, "__file__") == NULL) {
677 PyObject *f = PyString_FromString(filename);
678 if (f == NULL)
679 return -1;
680 if (PyDict_SetItemString(d, "__file__", f) < 0) {
681 Py_DECREF(f);
682 return -1;
683 }
684 Py_DECREF(f);
685 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000686 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000687 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000688 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000689 if (closeit)
690 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000691 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000692 fprintf(stderr, "python: Can't reopen .pyc file\n");
693 return -1;
694 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000695 /* Turn on optimization if a .pyo file is given */
696 if (strcmp(ext, ".pyo") == 0)
697 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000698 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000699 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000700 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
701 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000702 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000703 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000704 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000705 return -1;
706 }
Guido van Rossum82598051997-03-05 00:20:32 +0000707 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000708 if (Py_FlushLine())
709 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000710 return 0;
711}
712
713int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000714PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000715{
Guido van Rossum393661d2001-08-31 17:40:15 +0000716 return PyRun_SimpleStringFlags(command, NULL);
717}
718
719int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000720PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000721{
Guido van Rossum82598051997-03-05 00:20:32 +0000722 PyObject *m, *d, *v;
723 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000724 if (m == NULL)
725 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000726 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000727 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000728 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000729 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000730 return -1;
731 }
Guido van Rossum82598051997-03-05 00:20:32 +0000732 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000733 if (Py_FlushLine())
734 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000735 return 0;
736}
737
Barry Warsaw035574d1997-08-29 22:07:17 +0000738static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000739parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
740 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000741{
742 long hold;
743 PyObject *v;
744
745 /* old style errors */
746 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000747 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
748 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000749
750 /* new style errors. `err' is an instance */
751
752 if (! (v = PyObject_GetAttrString(err, "msg")))
753 goto finally;
754 *message = v;
755
756 if (!(v = PyObject_GetAttrString(err, "filename")))
757 goto finally;
758 if (v == Py_None)
759 *filename = NULL;
760 else if (! (*filename = PyString_AsString(v)))
761 goto finally;
762
763 Py_DECREF(v);
764 if (!(v = PyObject_GetAttrString(err, "lineno")))
765 goto finally;
766 hold = PyInt_AsLong(v);
767 Py_DECREF(v);
768 v = NULL;
769 if (hold < 0 && PyErr_Occurred())
770 goto finally;
771 *lineno = (int)hold;
772
773 if (!(v = PyObject_GetAttrString(err, "offset")))
774 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000775 if (v == Py_None) {
776 *offset = -1;
777 Py_DECREF(v);
778 v = NULL;
779 } else {
780 hold = PyInt_AsLong(v);
781 Py_DECREF(v);
782 v = NULL;
783 if (hold < 0 && PyErr_Occurred())
784 goto finally;
785 *offset = (int)hold;
786 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000787
788 if (!(v = PyObject_GetAttrString(err, "text")))
789 goto finally;
790 if (v == Py_None)
791 *text = NULL;
792 else if (! (*text = PyString_AsString(v)))
793 goto finally;
794 Py_DECREF(v);
795 return 1;
796
797finally:
798 Py_XDECREF(v);
799 return 0;
800}
801
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000802void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000803PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000804{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000805 PyErr_PrintEx(1);
806}
807
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000808static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000809print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000810{
811 char *nl;
812 if (offset >= 0) {
813 if (offset > 0 && offset == (int)strlen(text))
814 offset--;
815 for (;;) {
816 nl = strchr(text, '\n');
817 if (nl == NULL || nl-text >= offset)
818 break;
819 offset -= (nl+1-text);
820 text = nl+1;
821 }
822 while (*text == ' ' || *text == '\t') {
823 text++;
824 offset--;
825 }
826 }
827 PyFile_WriteString(" ", f);
828 PyFile_WriteString(text, f);
829 if (*text == '\0' || text[strlen(text)-1] != '\n')
830 PyFile_WriteString("\n", f);
831 if (offset == -1)
832 return;
833 PyFile_WriteString(" ", f);
834 offset--;
835 while (offset > 0) {
836 PyFile_WriteString(" ", f);
837 offset--;
838 }
839 PyFile_WriteString("^\n", f);
840}
841
Guido van Rossum66e8e862001-03-23 17:54:43 +0000842static void
843handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000844{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000845 PyObject *exception, *value, *tb;
846 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000847 if (Py_FlushLine())
848 PyErr_Clear();
849 fflush(stdout);
850 if (value == NULL || value == Py_None)
851 Py_Exit(0);
852 if (PyInstance_Check(value)) {
853 /* The error code should be in the `code' attribute. */
854 PyObject *code = PyObject_GetAttrString(value, "code");
855 if (code) {
856 Py_DECREF(value);
857 value = code;
858 if (value == Py_None)
859 Py_Exit(0);
860 }
861 /* If we failed to dig out the 'code' attribute,
862 just let the else clause below print the error. */
863 }
864 if (PyInt_Check(value))
865 Py_Exit((int)PyInt_AsLong(value));
866 else {
867 PyObject_Print(value, stderr, Py_PRINT_RAW);
868 PySys_WriteStderr("\n");
869 Py_Exit(1);
870 }
871}
872
873void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000874PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000875{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000876 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000877
878 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
879 handle_system_exit();
880 }
Guido van Rossum82598051997-03-05 00:20:32 +0000881 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000882 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000883 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000884 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000885 if (set_sys_last_vars) {
886 PySys_SetObject("last_type", exception);
887 PySys_SetObject("last_value", v);
888 PySys_SetObject("last_traceback", tb);
889 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000890 hook = PySys_GetObject("excepthook");
891 if (hook) {
892 PyObject *args = Py_BuildValue("(OOO)",
893 exception, v ? v : Py_None, tb ? tb : Py_None);
894 PyObject *result = PyEval_CallObject(hook, args);
895 if (result == NULL) {
896 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000897 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
898 handle_system_exit();
899 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000900 PyErr_Fetch(&exception2, &v2, &tb2);
901 PyErr_NormalizeException(&exception2, &v2, &tb2);
902 if (Py_FlushLine())
903 PyErr_Clear();
904 fflush(stdout);
905 PySys_WriteStderr("Error in sys.excepthook:\n");
906 PyErr_Display(exception2, v2, tb2);
907 PySys_WriteStderr("\nOriginal exception was:\n");
908 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000909 Py_XDECREF(exception2);
910 Py_XDECREF(v2);
911 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000912 }
913 Py_XDECREF(result);
914 Py_XDECREF(args);
915 } else {
916 PySys_WriteStderr("sys.excepthook is missing\n");
917 PyErr_Display(exception, v, tb);
918 }
919 Py_XDECREF(exception);
920 Py_XDECREF(v);
921 Py_XDECREF(tb);
922}
923
924void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
925{
926 int err = 0;
927 PyObject *v = value;
928 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000929 if (f == NULL)
930 fprintf(stderr, "lost sys.stderr\n");
931 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000932 if (Py_FlushLine())
933 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000934 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000935 if (tb && tb != Py_None)
936 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000937 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000938 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000939 {
Guido van Rossum82598051997-03-05 00:20:32 +0000940 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000941 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000942 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000943 if (!parse_syntax_error(v, &message, &filename,
944 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000945 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000946 else {
947 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000948 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000949 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000950 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000951 else
Guido van Rossum82598051997-03-05 00:20:32 +0000952 PyFile_WriteString(filename, f);
953 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000954 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000955 PyFile_WriteString(buf, f);
956 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000957 if (text != NULL)
958 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000959 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000960 /* Can't be bothered to check all those
961 PyFile_WriteString() calls */
962 if (PyErr_Occurred())
963 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000964 }
965 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000966 if (err) {
967 /* Don't do anything else */
968 }
969 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000970 PyClassObject* exc = (PyClassObject*)exception;
971 PyObject* className = exc->cl_name;
972 PyObject* moduleName =
973 PyDict_GetItemString(exc->cl_dict, "__module__");
974
975 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000976 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000977 else {
978 char* modstr = PyString_AsString(moduleName);
979 if (modstr && strcmp(modstr, "exceptions"))
980 {
981 err = PyFile_WriteString(modstr, f);
982 err += PyFile_WriteString(".", f);
983 }
984 }
985 if (err == 0) {
986 if (className == NULL)
987 err = PyFile_WriteString("<unknown>", f);
988 else
989 err = PyFile_WriteObject(className, f,
990 Py_PRINT_RAW);
991 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000992 }
993 else
994 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
995 if (err == 0) {
996 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000997 PyObject *s = PyObject_Str(v);
998 /* only print colon if the str() of the
999 object is not the empty string
1000 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001001 if (s == NULL)
1002 err = -1;
1003 else if (!PyString_Check(s) ||
1004 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001005 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001006 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001007 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1008 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001009 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001010 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001011 if (err == 0)
1012 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001013 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001014 /* If an error happened here, don't show it.
1015 XXX This is wrong, but too many callers rely on this behavior. */
1016 if (err != 0)
1017 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001018}
1019
Guido van Rossum82598051997-03-05 00:20:32 +00001020PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001021PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001022{
Guido van Rossum82598051997-03-05 00:20:32 +00001023 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001024 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001025}
1026
Guido van Rossum82598051997-03-05 00:20:32 +00001027PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001028PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001029 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001030{
Tim Peterse8682112000-08-27 20:18:17 +00001031 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001032}
1033
1034PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001035PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001036 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001037{
1038 node *n = PyParser_SimpleParseFile(fp, filename, start);
1039 if (closeit)
1040 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001041 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001042}
1043
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001044PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001045PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001046 PyCompilerFlags *flags)
1047{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001048 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001049 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001050 "<string>", globals, locals, flags);
1051}
1052
1053PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001054PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001055 PyObject *locals, PyCompilerFlags *flags)
1056{
1057 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1058 flags);
1059}
1060
1061PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001062PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001063 PyObject *locals, int closeit, PyCompilerFlags *flags)
1064{
Tim Petersfe2127d2001-07-16 05:37:24 +00001065 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001066 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001067 if (closeit)
1068 fclose(fp);
1069 return run_err_node(n, filename, globals, locals, flags);
1070}
1071
Guido van Rossum82598051997-03-05 00:20:32 +00001072static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001073run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001074 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001075{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001076 if (n == NULL)
1077 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001078 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001079}
1080
Guido van Rossum82598051997-03-05 00:20:32 +00001081static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001082run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001083 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001084{
Guido van Rossum82598051997-03-05 00:20:32 +00001085 PyCodeObject *co;
1086 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001087 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001088 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001089 if (co == NULL)
1090 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001091 v = PyEval_EvalCode(co, globals, locals);
1092 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001093 return v;
1094}
1095
Guido van Rossum82598051997-03-05 00:20:32 +00001096static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001097run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001098 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001099{
Guido van Rossum82598051997-03-05 00:20:32 +00001100 PyCodeObject *co;
1101 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001102 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001103 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001104
Guido van Rossum82598051997-03-05 00:20:32 +00001105 magic = PyMarshal_ReadLongFromFile(fp);
1106 if (magic != PyImport_GetMagicNumber()) {
1107 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001108 "Bad magic number in .pyc file");
1109 return NULL;
1110 }
Guido van Rossum82598051997-03-05 00:20:32 +00001111 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001112 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001113 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001114 if (v == NULL || !PyCode_Check(v)) {
1115 Py_XDECREF(v);
1116 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001117 "Bad code object in .pyc file");
1118 return NULL;
1119 }
Guido van Rossum82598051997-03-05 00:20:32 +00001120 co = (PyCodeObject *)v;
1121 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001122 if (v && flags)
1123 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001124 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001125 return v;
1126}
1127
Guido van Rossum82598051997-03-05 00:20:32 +00001128PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001129Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001130{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001131 return Py_CompileStringFlags(str, filename, start, NULL);
1132}
1133
1134PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001135Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001136 PyCompilerFlags *flags)
1137{
Guido van Rossum5b722181993-03-30 17:46:03 +00001138 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001139 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001140
1141 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1142 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001143 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001144 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001145 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001146 PyNode_Free(n);
1147 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001148}
1149
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001150struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001151Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001152{
1153 node *n;
1154 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001155 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1156 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001157 if (n == NULL)
1158 return NULL;
1159 st = PyNode_CompileSymtable(n, filename);
1160 PyNode_Free(n);
1161 return st;
1162}
1163
Guido van Rossuma110aa61994-08-29 12:50:44 +00001164/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001165
Guido van Rossuma110aa61994-08-29 12:50:44 +00001166node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001167PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001168{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001169 node *n;
1170 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001171 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1172 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001173 if (n == NULL)
1174 err_input(&err);
1175 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001176}
1177
Tim Petersfe2127d2001-07-16 05:37:24 +00001178node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001179PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001180{
1181 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1182}
1183
Guido van Rossuma110aa61994-08-29 12:50:44 +00001184/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001185
Guido van Rossuma110aa61994-08-29 12:50:44 +00001186node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001187PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001188{
1189 node *n;
1190 perrdetail err;
1191 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1192 flags);
1193 if (n == NULL)
1194 err_input(&err);
1195 return n;
1196}
1197
1198node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001199PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001200{
Tim Petersfe2127d2001-07-16 05:37:24 +00001201 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001202}
1203
Thomas Heller6b17abf2002-07-09 09:23:27 +00001204node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001205PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001206 int start, int flags)
1207{
1208 node *n;
1209 perrdetail err;
1210
1211 n = PyParser_ParseStringFlagsFilename(str, filename,
1212 &_PyParser_Grammar,
1213 start, &err, flags);
1214 if (n == NULL)
1215 err_input(&err);
1216 return n;
1217}
1218
1219node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001220PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001221{
1222 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1223 start, 0);
1224}
1225
Guido van Rossuma110aa61994-08-29 12:50:44 +00001226/* Set the error appropriate to the given input error code (see errcode.h) */
1227
1228static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001229err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001230{
Fred Drake85f36392000-07-11 17:53:00 +00001231 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001232 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001233 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001234 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001235 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001236 err->lineno, err->offset, err->text);
1237 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001238 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001239 err->text = NULL;
1240 }
1241 switch (err->error) {
1242 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001243 errtype = PyExc_IndentationError;
1244 if (err->expected == INDENT)
1245 msg = "expected an indented block";
1246 else if (err->token == INDENT)
1247 msg = "unexpected indent";
1248 else if (err->token == DEDENT)
1249 msg = "unexpected unindent";
1250 else {
1251 errtype = PyExc_SyntaxError;
1252 msg = "invalid syntax";
1253 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001254 break;
1255 case E_TOKEN:
1256 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001257 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001258 case E_EOFS:
1259 msg = "EOF while scanning triple-quoted string";
1260 break;
1261 case E_EOLS:
1262 msg = "EOL while scanning single-quoted string";
1263 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001264 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001265 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001266 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001267 return;
1268 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001269 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001270 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001271 return;
1272 case E_EOF:
1273 msg = "unexpected EOF while parsing";
1274 break;
Fred Drake85f36392000-07-11 17:53:00 +00001275 case E_TABSPACE:
1276 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001277 msg = "inconsistent use of tabs and spaces in indentation";
1278 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001279 case E_OVERFLOW:
1280 msg = "expression too long";
1281 break;
Fred Drake85f36392000-07-11 17:53:00 +00001282 case E_DEDENT:
1283 errtype = PyExc_IndentationError;
1284 msg = "unindent does not match any outer indentation level";
1285 break;
1286 case E_TOODEEP:
1287 errtype = PyExc_IndentationError;
1288 msg = "too many levels of indentation";
1289 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001290 case E_DECODE: { /* XXX */
1291 PyThreadState* tstate = PyThreadState_Get();
1292 PyObject* value = tstate->curexc_value;
1293 if (value != NULL) {
1294 u = PyObject_Repr(value);
1295 if (u != NULL) {
1296 msg = PyString_AsString(u);
1297 break;
1298 }
1299 }
1300 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001301 default:
1302 fprintf(stderr, "error=%d\n", err->error);
1303 msg = "unknown parsing error";
1304 break;
1305 }
Guido van Rossum82598051997-03-05 00:20:32 +00001306 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001307 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001308 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001309 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001310 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001311}
1312
1313/* Print fatal error message and abort */
1314
1315void
Tim Peters7c321a82002-07-09 02:57:01 +00001316Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001317{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001318 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001319#ifdef macintosh
1320 for (;;);
1321#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001322#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001323 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001324 OutputDebugString(msg);
1325 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001326#ifdef _DEBUG
1327 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001328#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001329#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001330 abort();
1331}
1332
1333/* Clean up and exit */
1334
Guido van Rossuma110aa61994-08-29 12:50:44 +00001335#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001336#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001337int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001338#endif
1339
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001340#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001341static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001342static int nexitfuncs = 0;
1343
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001344int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001345{
1346 if (nexitfuncs >= NEXITFUNCS)
1347 return -1;
1348 exitfuncs[nexitfuncs++] = func;
1349 return 0;
1350}
1351
Guido van Rossumcc283f51997-08-05 02:22:03 +00001352static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001353call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001354{
Guido van Rossum82598051997-03-05 00:20:32 +00001355 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001356
1357 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001358 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001359 Py_INCREF(exitfunc);
1360 PySys_SetObject("exitfunc", (PyObject *)NULL);
1361 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001362 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001363 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1364 PySys_WriteStderr("Error in sys.exitfunc:\n");
1365 }
Guido van Rossum82598051997-03-05 00:20:32 +00001366 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001367 }
Guido van Rossum82598051997-03-05 00:20:32 +00001368 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001369 }
1370
Guido van Rossum0829c751998-02-28 04:31:39 +00001371 if (Py_FlushLine())
1372 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001373}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001374
Guido van Rossumcc283f51997-08-05 02:22:03 +00001375static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001376call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001377{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001378 while (nexitfuncs > 0)
1379 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001380
1381 fflush(stdout);
1382 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001383}
1384
1385void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001386Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001387{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001388 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001389
Jack Jansen66a89771995-10-27 13:22:14 +00001390#ifdef macintosh
1391 PyMac_Exit(sts);
1392#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001393 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001394#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001395}
1396
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001397static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001398initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001399{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001400#ifdef HAVE_SIGNAL_H
1401#ifdef SIGPIPE
1402 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001403#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001404#ifdef SIGXFZ
1405 signal(SIGXFZ, SIG_IGN);
1406#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001407#ifdef SIGXFSZ
1408 signal(SIGXFSZ, SIG_IGN);
1409#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001410#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001411 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001412}
1413
Guido van Rossuma110aa61994-08-29 12:50:44 +00001414#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001415
1416/* Check for file descriptor connected to interactive device.
1417 Pretend that stdin is always interactive, other files never. */
1418
1419int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001420isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001421{
1422 return fd == fileno(stdin);
1423}
1424
1425#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001426
1427/*
1428 * The file descriptor fd is considered ``interactive'' if either
1429 * a) isatty(fd) is TRUE, or
1430 * b) the -i flag was given, and the filename associated with
1431 * the descriptor is NULL or "<stdin>" or "???".
1432 */
1433int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001434Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001435{
1436 if (isatty((int)fileno(fp)))
1437 return 1;
1438 if (!Py_InteractiveFlag)
1439 return 0;
1440 return (filename == NULL) ||
1441 (strcmp(filename, "<stdin>") == 0) ||
1442 (strcmp(filename, "???") == 0);
1443}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001444
1445
1446#if defined(USE_STACKCHECK)
1447#if defined(WIN32) && defined(_MSC_VER)
1448
1449/* Stack checking for Microsoft C */
1450
1451#include <malloc.h>
1452#include <excpt.h>
1453
Fred Drakee8de31c2000-08-31 05:38:39 +00001454/*
1455 * Return non-zero when we run out of memory on the stack; zero otherwise.
1456 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001457int
Fred Drake399739f2000-08-31 05:52:44 +00001458PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001459{
1460 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001461 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001462 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001463 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001464 return 0;
1465 } __except (EXCEPTION_EXECUTE_HANDLER) {
1466 /* just ignore all errors */
1467 }
1468 return 1;
1469}
1470
1471#endif /* WIN32 && _MSC_VER */
1472
1473/* Alternate implementations can be added here... */
1474
1475#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001476
1477
1478/* Wrappers around sigaction() or signal(). */
1479
1480PyOS_sighandler_t
1481PyOS_getsig(int sig)
1482{
1483#ifdef HAVE_SIGACTION
1484 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001485 /* Initialize context.sa_handler to SIG_ERR which makes about as
1486 * much sense as anything else. It should get overwritten if
1487 * sigaction actually succeeds and otherwise we avoid an
1488 * uninitialized memory read.
1489 */
1490 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001491 sigaction(sig, NULL, &context);
1492 return context.sa_handler;
1493#else
1494 PyOS_sighandler_t handler;
1495 handler = signal(sig, SIG_IGN);
1496 signal(sig, handler);
1497 return handler;
1498#endif
1499}
1500
1501PyOS_sighandler_t
1502PyOS_setsig(int sig, PyOS_sighandler_t handler)
1503{
1504#ifdef HAVE_SIGACTION
1505 struct sigaction context;
1506 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001507 /* Initialize context.sa_handler to SIG_ERR which makes about as
1508 * much sense as anything else. It should get overwritten if
1509 * sigaction actually succeeds and otherwise we avoid an
1510 * uninitialized memory read.
1511 */
1512 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001513 sigaction(sig, NULL, &context);
1514 oldhandler = context.sa_handler;
1515 context.sa_handler = handler;
1516 sigaction(sig, &context, NULL);
1517 return oldhandler;
1518#else
1519 return signal(sig, handler);
1520#endif
1521}