blob: fa72fe8813f6d1877286d12683e6e9ec6206f61e [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
Neal Norwitzb2501f42002-12-31 03:42:13 +0000127 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000128 Py_FatalError("Py_Initialize: can't init frames");
129
Neal Norwitzb2501f42002-12-31 03:42:13 +0000130 if (!_PyInt_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000131 Py_FatalError("Py_Initialize: can't init ints");
132
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133 interp->modules = PyDict_New();
134 if (interp->modules == NULL)
135 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136
Guido van Rossumc94044c2000-03-10 23:03:54 +0000137 /* Init codec registry */
138 _PyCodecRegistry_Init();
139
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000140#ifdef Py_USING_UNICODE
Guido van Rossumc94044c2000-03-10 23:03:54 +0000141 /* Init Unicode implementation; relies on the codec registry */
142 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000143#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000144
Barry Warsawf242aa02000-05-25 23:09:49 +0000145 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000146 if (bimod == NULL)
147 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000148 interp->builtins = PyModule_GetDict(bimod);
149 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000150
151 sysmod = _PySys_Init();
152 if (sysmod == NULL)
153 Py_FatalError("Py_Initialize: can't initialize sys");
154 interp->sysdict = PyModule_GetDict(sysmod);
155 Py_INCREF(interp->sysdict);
156 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000157 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000158 PyDict_SetItemString(interp->sysdict, "modules",
159 interp->modules);
160
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000161 _PyImport_Init();
162
Barry Warsawf242aa02000-05-25 23:09:49 +0000163 /* initialize builtin exceptions */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000164 _PyExc_Init();
Barry Warsaw5821bc52001-08-13 23:04:56 +0000165 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000166
Barry Warsaw035574d1997-08-29 22:07:17 +0000167 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000168 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000169
Just van Rossum52e14d62002-12-30 22:08:05 +0000170 _PyImportHooks_Init();
171
Guido van Rossum25ce5661997-08-02 03:10:38 +0000172 initsigs(); /* Signal handling stuff, including initintr() */
173
174 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000175 if (!Py_NoSiteFlag)
176 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000177}
178
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000179#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000180extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000181#endif
182
Guido van Rossum25ce5661997-08-02 03:10:38 +0000183/* Undo the effect of Py_Initialize().
184
185 Beware: if multiple interpreter and/or thread states exist, these
186 are not wiped out; only the current thread and interpreter state
187 are deleted. But since everything else is deleted, those other
188 interpreter and thread states should no longer be used.
189
190 (XXX We should do better, e.g. wipe out all interpreters and
191 threads.)
192
193 Locking: as above.
194
195*/
196
197void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000198Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199{
200 PyInterpreterState *interp;
201 PyThreadState *tstate;
202
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000203 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000204 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000205
Tim Peters384fd102001-01-21 03:40:37 +0000206 /* The interpreter is still entirely intact at this point, and the
207 * exit funcs may be relying on that. In particular, if some thread
208 * or exit func is still waiting to do an import, the import machinery
209 * expects Py_IsInitialized() to return true. So don't say the
210 * interpreter is uninitialized until after the exit funcs have run.
211 * Note that Threading.py uses an exit func to do a join on all the
212 * threads created thru it, so this also protects pending imports in
213 * the threads created via Threading.
214 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000215 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000216 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000217
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000218 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000219 tstate = PyThreadState_Get();
220 interp = tstate->interp;
221
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000222 /* Disable signal handling */
223 PyOS_FiniInterrupts();
224
Guido van Rossumc94044c2000-03-10 23:03:54 +0000225 /* Cleanup Codec registry */
226 _PyCodecRegistry_Fini();
227
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000228 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000230
Guido van Rossum1707aad1997-12-08 23:43:45 +0000231 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
232 _PyImport_Fini();
233
234 /* Debugging stuff */
235#ifdef COUNT_ALLOCS
236 dump_counts();
237#endif
238
239#ifdef Py_REF_DEBUG
240 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
241#endif
242
243#ifdef Py_TRACE_REFS
Guido van Rossum92e2d5c2001-08-09 16:37:16 +0000244 if (Py_GETENV("PYTHONDUMPREFS")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000245 _Py_PrintReferences(stderr);
246 }
247#endif /* Py_TRACE_REFS */
248
Barry Warsaw035574d1997-08-29 22:07:17 +0000249 /* Now we decref the exception classes. After this point nothing
250 can raise an exception. That's okay, because each Fini() method
251 below has been checked to make sure no exceptions are ever
252 raised.
253 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000254 _PyExc_Fini();
Barry Warsawf242aa02000-05-25 23:09:49 +0000255
256 /* Delete current thread */
257 PyInterpreterState_Clear(interp);
258 PyThreadState_Swap(NULL);
259 PyInterpreterState_Delete(interp);
260
Guido van Rossumcc283f51997-08-05 02:22:03 +0000261 PyMethod_Fini();
262 PyFrame_Fini();
263 PyCFunction_Fini();
264 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000265 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000266 PyInt_Fini();
267 PyFloat_Fini();
268
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000269#ifdef Py_USING_UNICODE
270 /* Cleanup Unicode implementation */
271 _PyUnicode_Fini();
272#endif
273
Guido van Rossumcc283f51997-08-05 02:22:03 +0000274 /* XXX Still allocated:
275 - various static ad-hoc pointers to interned strings
276 - int and float free list blocks
277 - whatever various modules and libraries allocate
278 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000279
280 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000281
Tim Peters0e871182002-04-13 08:29:14 +0000282#ifdef PYMALLOC_DEBUG
283 if (Py_GETENV("PYTHONMALLOCSTATS"))
284 _PyObject_DebugMallocStats();
285#endif
286
Guido van Rossumcc283f51997-08-05 02:22:03 +0000287 call_ll_exitfuncs();
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);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000341 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000342 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000343 if (!Py_NoSiteFlag)
344 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000345 }
346
347 if (!PyErr_Occurred())
348 return tstate;
349
350 /* Oops, it didn't work. Undo it all. */
351
352 PyErr_Print();
353 PyThreadState_Clear(tstate);
354 PyThreadState_Swap(save_tstate);
355 PyThreadState_Delete(tstate);
356 PyInterpreterState_Delete(interp);
357
358 return NULL;
359}
360
361/* Delete an interpreter and its last thread. This requires that the
362 given thread state is current, that the thread has no remaining
363 frames, and that it is its interpreter's only remaining thread.
364 It is a fatal error to violate these constraints.
365
366 (Py_Finalize() doesn't have these constraints -- it zaps
367 everything, regardless.)
368
369 Locking: as above.
370
371*/
372
373void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000374Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000375{
376 PyInterpreterState *interp = tstate->interp;
377
378 if (tstate != PyThreadState_Get())
379 Py_FatalError("Py_EndInterpreter: thread is not current");
380 if (tstate->frame != NULL)
381 Py_FatalError("Py_EndInterpreter: thread still has a frame");
382 if (tstate != interp->tstate_head || tstate->next != NULL)
383 Py_FatalError("Py_EndInterpreter: not the last thread");
384
385 PyImport_Cleanup();
386 PyInterpreterState_Clear(interp);
387 PyThreadState_Swap(NULL);
388 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000389}
390
391static char *progname = "python";
392
393void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000394Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000395{
396 if (pn && *pn)
397 progname = pn;
398}
399
400char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000401Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000402{
403 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000404}
405
Guido van Rossuma61691e1998-02-06 22:27:24 +0000406static char *default_home = NULL;
407
408void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000409Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000410{
411 default_home = home;
412}
413
414char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000415Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000416{
417 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000418 if (home == NULL && !Py_IgnoreEnvironmentFlag)
419 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000420 return home;
421}
422
Guido van Rossum6135a871995-01-09 17:53:26 +0000423/* Create __main__ module */
424
425static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000426initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000427{
Guido van Rossum82598051997-03-05 00:20:32 +0000428 PyObject *m, *d;
429 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000430 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000431 Py_FatalError("can't create __main__ module");
432 d = PyModule_GetDict(m);
433 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000434 PyObject *bimod = PyImport_ImportModule("__builtin__");
435 if (bimod == NULL ||
436 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000437 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000438 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000439 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000440}
441
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000442/* Import the site module (not into __main__ though) */
443
444static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000445initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000446{
447 PyObject *m, *f;
448 m = PyImport_ImportModule("site");
449 if (m == NULL) {
450 f = PySys_GetObject("stderr");
451 if (Py_VerboseFlag) {
452 PyFile_WriteString(
453 "'import site' failed; traceback:\n", f);
454 PyErr_Print();
455 }
456 else {
457 PyFile_WriteString(
458 "'import site' failed; use -v for traceback\n", f);
459 PyErr_Clear();
460 }
461 }
462 else {
463 Py_DECREF(m);
464 }
465}
466
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000467/* Parse input from a file and execute it */
468
469int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000470PyRun_AnyFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000471{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000472 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
473}
474
475int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000476PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000477{
478 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000479}
480
481int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000482PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000483{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000484 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
485}
486
487int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000488PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000489 PyCompilerFlags *flags)
490{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000491 if (filename == NULL)
492 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000493 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000494 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000495 if (closeit)
496 fclose(fp);
497 return err;
498 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000499 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000500 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000501}
502
503int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000504PyRun_InteractiveLoop(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000505{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000506 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
507}
508
509int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000510PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000511{
Guido van Rossum82598051997-03-05 00:20:32 +0000512 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000513 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000514 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000515
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000516 if (flags == NULL) {
517 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000518 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000519 }
Guido van Rossum82598051997-03-05 00:20:32 +0000520 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000521 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000522 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
523 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000524 }
Guido van Rossum82598051997-03-05 00:20:32 +0000525 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000526 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000527 PySys_SetObject("ps2", v = PyString_FromString("... "));
528 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000529 }
530 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000531 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000532#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000533 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000534#endif
535 if (ret == E_EOF)
536 return 0;
537 /*
538 if (ret == E_NOMEM)
539 return -1;
540 */
541 }
542}
543
544int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000545PyRun_InteractiveOne(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000546{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000547 return PyRun_InteractiveOneFlags(fp, filename, NULL);
548}
549
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000550/* compute parser flags based on compiler flags */
551#if 0 /* future keyword */
552#define PARSER_FLAGS(flags) \
553 (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \
554 PyPARSE_YIELD_IS_KEYWORD : 0)
555#else
556#define PARSER_FLAGS(flags) 0
557#endif
558
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000559int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000560PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000561{
Guido van Rossum82598051997-03-05 00:20:32 +0000562 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000563 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000564 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000565 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000566
Guido van Rossum82598051997-03-05 00:20:32 +0000567 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000568 if (v != NULL) {
569 v = PyObject_Str(v);
570 if (v == NULL)
571 PyErr_Clear();
572 else if (PyString_Check(v))
573 ps1 = PyString_AsString(v);
574 }
Guido van Rossum82598051997-03-05 00:20:32 +0000575 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000576 if (w != NULL) {
577 w = PyObject_Str(w);
578 if (w == NULL)
579 PyErr_Clear();
580 else if (PyString_Check(w))
581 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000582 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000583 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
584 Py_single_input, ps1, ps2, &err,
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000585 PARSER_FLAGS(flags));
Guido van Rossum82598051997-03-05 00:20:32 +0000586 Py_XDECREF(v);
587 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000588 if (n == NULL) {
589 if (err.error == E_EOF) {
590 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000591 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000592 return E_EOF;
593 }
594 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000595 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000596 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000597 }
Guido van Rossum82598051997-03-05 00:20:32 +0000598 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000599 if (m == NULL)
600 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000601 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000602 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000603 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000604 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000605 return -1;
606 }
Guido van Rossum82598051997-03-05 00:20:32 +0000607 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000608 if (Py_FlushLine())
609 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000610 return 0;
611}
612
613int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000614PyRun_SimpleFile(FILE *fp, const char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000615{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000616 return PyRun_SimpleFileEx(fp, filename, 0);
617}
618
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000619/* Check whether a file maybe a pyc file: Look at the extension,
620 the file type, and, if we may close it, at the first few bytes. */
621
622static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000623maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000624{
625 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
626 return 1;
627
628#ifdef macintosh
629 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
Jack Jansen72f3b7a2002-12-13 15:23:10 +0000630 if (PyMac_getfiletype((char *)filename) == 'PYC '
631 || PyMac_getfiletype((char *)filename) == 'APPL')
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000632 return 1;
633#endif /* macintosh */
634
635 /* Only look into the file if we are allowed to close it, since
636 it then should also be seekable. */
637 if (closeit) {
638 /* Read only two bytes of the magic. If the file was opened in
639 text mode, the bytes 3 and 4 of the magic (\r\n) might not
640 be read as they are on disk. */
641 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
642 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000643 /* Mess: In case of -x, the stream is NOT at its start now,
644 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000645 which makes the current stream position formally undefined,
646 and a x-platform nightmare.
647 Unfortunately, we have no direct way to know whether -x
648 was specified. So we use a terrible hack: if the current
649 stream position is not 0, we assume -x was specified, and
650 give up. Bug 132850 on SourceForge spells out the
651 hopelessness of trying anything else (fseek and ftell
652 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000653 */
Tim Peters3e876562001-02-11 04:35:39 +0000654 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000655 if (ftell(fp) == 0) {
656 if (fread(buf, 1, 2, fp) == 2 &&
657 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
658 ispyc = 1;
659 rewind(fp);
660 }
Tim Peters3e876562001-02-11 04:35:39 +0000661 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000662 }
663 return 0;
664}
665
Guido van Rossum0df002c2000-08-27 19:21:52 +0000666int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000667PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000668{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000669 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
670}
671
672int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000673PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000674 PyCompilerFlags *flags)
675{
Guido van Rossum82598051997-03-05 00:20:32 +0000676 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000677 const char *ext;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000678
Guido van Rossum82598051997-03-05 00:20:32 +0000679 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000680 if (m == NULL)
681 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000682 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +0000683 if (PyDict_GetItemString(d, "__file__") == NULL) {
684 PyObject *f = PyString_FromString(filename);
685 if (f == NULL)
686 return -1;
687 if (PyDict_SetItemString(d, "__file__", f) < 0) {
688 Py_DECREF(f);
689 return -1;
690 }
691 Py_DECREF(f);
692 }
Guido van Rossumfdef2711994-09-14 13:31:04 +0000693 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000694 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000695 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000696 if (closeit)
697 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +0000698 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000699 fprintf(stderr, "python: Can't reopen .pyc file\n");
700 return -1;
701 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000702 /* Turn on optimization if a .pyo file is given */
703 if (strcmp(ext, ".pyo") == 0)
704 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000705 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000706 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000707 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
708 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000709 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000710 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000711 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000712 return -1;
713 }
Guido van Rossum82598051997-03-05 00:20:32 +0000714 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000715 if (Py_FlushLine())
716 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000717 return 0;
718}
719
720int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000721PyRun_SimpleString(const char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000722{
Guido van Rossum393661d2001-08-31 17:40:15 +0000723 return PyRun_SimpleStringFlags(command, NULL);
724}
725
726int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000727PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000728{
Guido van Rossum82598051997-03-05 00:20:32 +0000729 PyObject *m, *d, *v;
730 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000731 if (m == NULL)
732 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000733 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +0000734 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000735 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000736 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000737 return -1;
738 }
Guido van Rossum82598051997-03-05 00:20:32 +0000739 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000740 if (Py_FlushLine())
741 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000742 return 0;
743}
744
Barry Warsaw035574d1997-08-29 22:07:17 +0000745static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000746parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
747 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000748{
749 long hold;
750 PyObject *v;
751
752 /* old style errors */
753 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +0000754 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
755 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000756
757 /* new style errors. `err' is an instance */
758
759 if (! (v = PyObject_GetAttrString(err, "msg")))
760 goto finally;
761 *message = v;
762
763 if (!(v = PyObject_GetAttrString(err, "filename")))
764 goto finally;
765 if (v == Py_None)
766 *filename = NULL;
767 else if (! (*filename = PyString_AsString(v)))
768 goto finally;
769
770 Py_DECREF(v);
771 if (!(v = PyObject_GetAttrString(err, "lineno")))
772 goto finally;
773 hold = PyInt_AsLong(v);
774 Py_DECREF(v);
775 v = NULL;
776 if (hold < 0 && PyErr_Occurred())
777 goto finally;
778 *lineno = (int)hold;
779
780 if (!(v = PyObject_GetAttrString(err, "offset")))
781 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000782 if (v == Py_None) {
783 *offset = -1;
784 Py_DECREF(v);
785 v = NULL;
786 } else {
787 hold = PyInt_AsLong(v);
788 Py_DECREF(v);
789 v = NULL;
790 if (hold < 0 && PyErr_Occurred())
791 goto finally;
792 *offset = (int)hold;
793 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000794
795 if (!(v = PyObject_GetAttrString(err, "text")))
796 goto finally;
797 if (v == Py_None)
798 *text = NULL;
799 else if (! (*text = PyString_AsString(v)))
800 goto finally;
801 Py_DECREF(v);
802 return 1;
803
804finally:
805 Py_XDECREF(v);
806 return 0;
807}
808
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000809void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000810PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000811{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000812 PyErr_PrintEx(1);
813}
814
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000815static void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000816print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000817{
818 char *nl;
819 if (offset >= 0) {
820 if (offset > 0 && offset == (int)strlen(text))
821 offset--;
822 for (;;) {
823 nl = strchr(text, '\n');
824 if (nl == NULL || nl-text >= offset)
825 break;
826 offset -= (nl+1-text);
827 text = nl+1;
828 }
829 while (*text == ' ' || *text == '\t') {
830 text++;
831 offset--;
832 }
833 }
834 PyFile_WriteString(" ", f);
835 PyFile_WriteString(text, f);
836 if (*text == '\0' || text[strlen(text)-1] != '\n')
837 PyFile_WriteString("\n", f);
838 if (offset == -1)
839 return;
840 PyFile_WriteString(" ", f);
841 offset--;
842 while (offset > 0) {
843 PyFile_WriteString(" ", f);
844 offset--;
845 }
846 PyFile_WriteString("^\n", f);
847}
848
Guido van Rossum66e8e862001-03-23 17:54:43 +0000849static void
850handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000851{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000852 PyObject *exception, *value, *tb;
853 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000854 if (Py_FlushLine())
855 PyErr_Clear();
856 fflush(stdout);
857 if (value == NULL || value == Py_None)
858 Py_Exit(0);
859 if (PyInstance_Check(value)) {
860 /* The error code should be in the `code' attribute. */
861 PyObject *code = PyObject_GetAttrString(value, "code");
862 if (code) {
863 Py_DECREF(value);
864 value = code;
865 if (value == Py_None)
866 Py_Exit(0);
867 }
868 /* If we failed to dig out the 'code' attribute,
869 just let the else clause below print the error. */
870 }
871 if (PyInt_Check(value))
872 Py_Exit((int)PyInt_AsLong(value));
873 else {
874 PyObject_Print(value, stderr, Py_PRINT_RAW);
875 PySys_WriteStderr("\n");
876 Py_Exit(1);
877 }
878}
879
880void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000881PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000882{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000883 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000884
885 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
886 handle_system_exit();
887 }
Guido van Rossum82598051997-03-05 00:20:32 +0000888 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000889 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000890 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000891 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000892 if (set_sys_last_vars) {
893 PySys_SetObject("last_type", exception);
894 PySys_SetObject("last_value", v);
895 PySys_SetObject("last_traceback", tb);
896 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000897 hook = PySys_GetObject("excepthook");
898 if (hook) {
899 PyObject *args = Py_BuildValue("(OOO)",
900 exception, v ? v : Py_None, tb ? tb : Py_None);
901 PyObject *result = PyEval_CallObject(hook, args);
902 if (result == NULL) {
903 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000904 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
905 handle_system_exit();
906 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000907 PyErr_Fetch(&exception2, &v2, &tb2);
908 PyErr_NormalizeException(&exception2, &v2, &tb2);
909 if (Py_FlushLine())
910 PyErr_Clear();
911 fflush(stdout);
912 PySys_WriteStderr("Error in sys.excepthook:\n");
913 PyErr_Display(exception2, v2, tb2);
914 PySys_WriteStderr("\nOriginal exception was:\n");
915 PyErr_Display(exception, v, tb);
Jeremy Hylton07028582001-12-07 15:35:35 +0000916 Py_XDECREF(exception2);
917 Py_XDECREF(v2);
918 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000919 }
920 Py_XDECREF(result);
921 Py_XDECREF(args);
922 } else {
923 PySys_WriteStderr("sys.excepthook is missing\n");
924 PyErr_Display(exception, v, tb);
925 }
926 Py_XDECREF(exception);
927 Py_XDECREF(v);
928 Py_XDECREF(tb);
929}
930
931void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
932{
933 int err = 0;
934 PyObject *v = value;
935 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000936 if (f == NULL)
937 fprintf(stderr, "lost sys.stderr\n");
938 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000939 if (Py_FlushLine())
940 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000941 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000942 if (tb && tb != Py_None)
943 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000944 if (err == 0 &&
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000945 PyObject_HasAttrString(v, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +0000946 {
Guido van Rossum82598051997-03-05 00:20:32 +0000947 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +0000948 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000949 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000950 if (!parse_syntax_error(v, &message, &filename,
951 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000952 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000953 else {
954 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000955 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000956 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000957 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000958 else
Guido van Rossum82598051997-03-05 00:20:32 +0000959 PyFile_WriteString(filename, f);
960 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000961 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000962 PyFile_WriteString(buf, f);
963 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000964 if (text != NULL)
965 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000966 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000967 /* Can't be bothered to check all those
968 PyFile_WriteString() calls */
969 if (PyErr_Occurred())
970 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000971 }
972 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000973 if (err) {
974 /* Don't do anything else */
975 }
976 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000977 PyClassObject* exc = (PyClassObject*)exception;
978 PyObject* className = exc->cl_name;
979 PyObject* moduleName =
980 PyDict_GetItemString(exc->cl_dict, "__module__");
981
982 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000983 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000984 else {
985 char* modstr = PyString_AsString(moduleName);
986 if (modstr && strcmp(modstr, "exceptions"))
987 {
988 err = PyFile_WriteString(modstr, f);
989 err += PyFile_WriteString(".", f);
990 }
991 }
992 if (err == 0) {
993 if (className == NULL)
994 err = PyFile_WriteString("<unknown>", f);
995 else
996 err = PyFile_WriteObject(className, f,
997 Py_PRINT_RAW);
998 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000999 }
1000 else
1001 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1002 if (err == 0) {
1003 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +00001004 PyObject *s = PyObject_Str(v);
1005 /* only print colon if the str() of the
1006 object is not the empty string
1007 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001008 if (s == NULL)
1009 err = -1;
1010 else if (!PyString_Check(s) ||
1011 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +00001012 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001013 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +00001014 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1015 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001016 }
Guido van Rossum262e1241995-02-07 15:30:45 +00001017 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001018 if (err == 0)
1019 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001020 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001021 /* If an error happened here, don't show it.
1022 XXX This is wrong, but too many callers rely on this behavior. */
1023 if (err != 0)
1024 PyErr_Clear();
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_String(const char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001029{
Guido van Rossum82598051997-03-05 00:20:32 +00001030 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001031 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001032}
1033
Guido van Rossum82598051997-03-05 00:20:32 +00001034PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001035PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001036 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001037{
Tim Peterse8682112000-08-27 20:18:17 +00001038 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +00001039}
1040
1041PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001042PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001043 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +00001044{
1045 node *n = PyParser_SimpleParseFile(fp, filename, start);
1046 if (closeit)
1047 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001048 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001049}
1050
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001051PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001052PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001053 PyCompilerFlags *flags)
1054{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001055 return run_err_node(PyParser_SimpleParseStringFlags(
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001056 str, start, PARSER_FLAGS(flags)),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001057 "<string>", globals, locals, flags);
1058}
1059
1060PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001061PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001062 PyObject *locals, PyCompilerFlags *flags)
1063{
1064 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1065 flags);
1066}
1067
1068PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001069PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001070 PyObject *locals, int closeit, PyCompilerFlags *flags)
1071{
Tim Petersfe2127d2001-07-16 05:37:24 +00001072 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001073 PARSER_FLAGS(flags));
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001074 if (closeit)
1075 fclose(fp);
1076 return run_err_node(n, filename, globals, locals, flags);
1077}
1078
Guido van Rossum82598051997-03-05 00:20:32 +00001079static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001080run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001081 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001082{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001083 if (n == NULL)
1084 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001085 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001086}
1087
Guido van Rossum82598051997-03-05 00:20:32 +00001088static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001089run_node(node *n, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001090 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001091{
Guido van Rossum82598051997-03-05 00:20:32 +00001092 PyCodeObject *co;
1093 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001094 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001095 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001096 if (co == NULL)
1097 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001098 v = PyEval_EvalCode(co, globals, locals);
1099 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001100 return v;
1101}
1102
Guido van Rossum82598051997-03-05 00:20:32 +00001103static PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001104run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001105 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001106{
Guido van Rossum82598051997-03-05 00:20:32 +00001107 PyCodeObject *co;
1108 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001109 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001110 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001111
Guido van Rossum82598051997-03-05 00:20:32 +00001112 magic = PyMarshal_ReadLongFromFile(fp);
1113 if (magic != PyImport_GetMagicNumber()) {
1114 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001115 "Bad magic number in .pyc file");
1116 return NULL;
1117 }
Guido van Rossum82598051997-03-05 00:20:32 +00001118 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001119 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001120 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001121 if (v == NULL || !PyCode_Check(v)) {
1122 Py_XDECREF(v);
1123 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001124 "Bad code object in .pyc file");
1125 return NULL;
1126 }
Guido van Rossum82598051997-03-05 00:20:32 +00001127 co = (PyCodeObject *)v;
1128 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001129 if (v && flags)
1130 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001131 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001132 return v;
1133}
1134
Guido van Rossum82598051997-03-05 00:20:32 +00001135PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001136Py_CompileString(const char *str, const char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001137{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001138 return Py_CompileStringFlags(str, filename, start, NULL);
1139}
1140
1141PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001142Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001143 PyCompilerFlags *flags)
1144{
Guido van Rossum5b722181993-03-30 17:46:03 +00001145 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001146 PyCodeObject *co;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001147
1148 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1149 PARSER_FLAGS(flags));
Guido van Rossuma110aa61994-08-29 12:50:44 +00001150 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001151 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001152 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001153 PyNode_Free(n);
1154 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001155}
1156
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001157struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001158Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001159{
1160 node *n;
1161 struct symtable *st;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001162 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1163 start, 0);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001164 if (n == NULL)
1165 return NULL;
1166 st = PyNode_CompileSymtable(n, filename);
1167 PyNode_Free(n);
1168 return st;
1169}
1170
Guido van Rossuma110aa61994-08-29 12:50:44 +00001171/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001172
Guido van Rossuma110aa61994-08-29 12:50:44 +00001173node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001174PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001175{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001176 node *n;
1177 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001178 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1179 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001180 if (n == NULL)
1181 err_input(&err);
1182 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001183}
1184
Tim Petersfe2127d2001-07-16 05:37:24 +00001185node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001186PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
Tim Petersfe2127d2001-07-16 05:37:24 +00001187{
1188 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1189}
1190
Guido van Rossuma110aa61994-08-29 12:50:44 +00001191/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001192
Guido van Rossuma110aa61994-08-29 12:50:44 +00001193node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001194PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001195{
1196 node *n;
1197 perrdetail err;
1198 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1199 flags);
1200 if (n == NULL)
1201 err_input(&err);
1202 return n;
1203}
1204
1205node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001206PyParser_SimpleParseString(const char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001207{
Tim Petersfe2127d2001-07-16 05:37:24 +00001208 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001209}
1210
Thomas Heller6b17abf2002-07-09 09:23:27 +00001211node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001212PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001213 int start, int flags)
1214{
1215 node *n;
1216 perrdetail err;
1217
1218 n = PyParser_ParseStringFlagsFilename(str, filename,
1219 &_PyParser_Grammar,
1220 start, &err, flags);
1221 if (n == NULL)
1222 err_input(&err);
1223 return n;
1224}
1225
1226node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001227PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001228{
1229 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1230 start, 0);
1231}
1232
Guido van Rossuma110aa61994-08-29 12:50:44 +00001233/* Set the error appropriate to the given input error code (see errcode.h) */
1234
1235static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001236err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001237{
Fred Drake85f36392000-07-11 17:53:00 +00001238 PyObject *v, *w, *errtype;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001239 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001240 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001241 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001242 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001243 err->lineno, err->offset, err->text);
1244 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001245 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001246 err->text = NULL;
1247 }
1248 switch (err->error) {
1249 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001250 errtype = PyExc_IndentationError;
1251 if (err->expected == INDENT)
1252 msg = "expected an indented block";
1253 else if (err->token == INDENT)
1254 msg = "unexpected indent";
1255 else if (err->token == DEDENT)
1256 msg = "unexpected unindent";
1257 else {
1258 errtype = PyExc_SyntaxError;
1259 msg = "invalid syntax";
1260 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001261 break;
1262 case E_TOKEN:
1263 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001264 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001265 case E_EOFS:
1266 msg = "EOF while scanning triple-quoted string";
1267 break;
1268 case E_EOLS:
1269 msg = "EOL while scanning single-quoted string";
1270 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001271 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001272 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001273 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001274 return;
1275 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001276 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001277 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001278 return;
1279 case E_EOF:
1280 msg = "unexpected EOF while parsing";
1281 break;
Fred Drake85f36392000-07-11 17:53:00 +00001282 case E_TABSPACE:
1283 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001284 msg = "inconsistent use of tabs and spaces in indentation";
1285 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001286 case E_OVERFLOW:
1287 msg = "expression too long";
1288 break;
Fred Drake85f36392000-07-11 17:53:00 +00001289 case E_DEDENT:
1290 errtype = PyExc_IndentationError;
1291 msg = "unindent does not match any outer indentation level";
1292 break;
1293 case E_TOODEEP:
1294 errtype = PyExc_IndentationError;
1295 msg = "too many levels of indentation";
1296 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001297 case E_DECODE: { /* XXX */
1298 PyThreadState* tstate = PyThreadState_Get();
1299 PyObject* value = tstate->curexc_value;
1300 if (value != NULL) {
1301 u = PyObject_Repr(value);
1302 if (u != NULL) {
1303 msg = PyString_AsString(u);
1304 break;
1305 }
1306 }
1307 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001308 default:
1309 fprintf(stderr, "error=%d\n", err->error);
1310 msg = "unknown parsing error";
1311 break;
1312 }
Guido van Rossum82598051997-03-05 00:20:32 +00001313 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001314 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001315 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001316 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001317 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001318}
1319
1320/* Print fatal error message and abort */
1321
1322void
Tim Peters7c321a82002-07-09 02:57:01 +00001323Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001324{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001325 fprintf(stderr, "Fatal Python error: %s\n", msg);
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001326#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001327 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001328 OutputDebugString(msg);
1329 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001330#ifdef _DEBUG
1331 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001332#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001333#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001334 abort();
1335}
1336
1337/* Clean up and exit */
1338
Guido van Rossuma110aa61994-08-29 12:50:44 +00001339#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001340#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001341int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001342#endif
1343
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001344#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001345static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001346static int nexitfuncs = 0;
1347
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001348int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001349{
1350 if (nexitfuncs >= NEXITFUNCS)
1351 return -1;
1352 exitfuncs[nexitfuncs++] = func;
1353 return 0;
1354}
1355
Guido van Rossumcc283f51997-08-05 02:22:03 +00001356static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001357call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001358{
Guido van Rossum82598051997-03-05 00:20:32 +00001359 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001360
1361 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001362 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001363 Py_INCREF(exitfunc);
1364 PySys_SetObject("exitfunc", (PyObject *)NULL);
1365 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001366 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001367 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1368 PySys_WriteStderr("Error in sys.exitfunc:\n");
1369 }
Guido van Rossum82598051997-03-05 00:20:32 +00001370 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001371 }
Guido van Rossum82598051997-03-05 00:20:32 +00001372 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001373 }
1374
Guido van Rossum0829c751998-02-28 04:31:39 +00001375 if (Py_FlushLine())
1376 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001377}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001378
Guido van Rossumcc283f51997-08-05 02:22:03 +00001379static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001380call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001381{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001382 while (nexitfuncs > 0)
1383 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001384
1385 fflush(stdout);
1386 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001387}
1388
1389void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001390Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001391{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001392 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001393
Jack Jansen66a89771995-10-27 13:22:14 +00001394#ifdef macintosh
1395 PyMac_Exit(sts);
1396#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001397 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001398#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001399}
1400
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001401static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001402initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001403{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001404#ifdef HAVE_SIGNAL_H
1405#ifdef SIGPIPE
1406 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001407#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001408#ifdef SIGXFZ
1409 signal(SIGXFZ, SIG_IGN);
1410#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001411#ifdef SIGXFSZ
1412 signal(SIGXFSZ, SIG_IGN);
1413#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001414#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001415 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001416}
1417
Guido van Rossuma110aa61994-08-29 12:50:44 +00001418#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001419
1420/* Check for file descriptor connected to interactive device.
1421 Pretend that stdin is always interactive, other files never. */
1422
1423int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001424isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001425{
1426 return fd == fileno(stdin);
1427}
1428
1429#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001430
1431/*
1432 * The file descriptor fd is considered ``interactive'' if either
1433 * a) isatty(fd) is TRUE, or
1434 * b) the -i flag was given, and the filename associated with
1435 * the descriptor is NULL or "<stdin>" or "???".
1436 */
1437int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001438Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001439{
1440 if (isatty((int)fileno(fp)))
1441 return 1;
1442 if (!Py_InteractiveFlag)
1443 return 0;
1444 return (filename == NULL) ||
1445 (strcmp(filename, "<stdin>") == 0) ||
1446 (strcmp(filename, "???") == 0);
1447}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001448
1449
1450#if defined(USE_STACKCHECK)
1451#if defined(WIN32) && defined(_MSC_VER)
1452
1453/* Stack checking for Microsoft C */
1454
1455#include <malloc.h>
1456#include <excpt.h>
1457
Fred Drakee8de31c2000-08-31 05:38:39 +00001458/*
1459 * Return non-zero when we run out of memory on the stack; zero otherwise.
1460 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001461int
Fred Drake399739f2000-08-31 05:52:44 +00001462PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001463{
1464 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001465 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001466 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001467 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001468 return 0;
1469 } __except (EXCEPTION_EXECUTE_HANDLER) {
1470 /* just ignore all errors */
1471 }
1472 return 1;
1473}
1474
1475#endif /* WIN32 && _MSC_VER */
1476
1477/* Alternate implementations can be added here... */
1478
1479#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001480
1481
1482/* Wrappers around sigaction() or signal(). */
1483
1484PyOS_sighandler_t
1485PyOS_getsig(int sig)
1486{
1487#ifdef HAVE_SIGACTION
1488 struct sigaction context;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001489 /* Initialize context.sa_handler to SIG_ERR which makes about as
1490 * much sense as anything else. It should get overwritten if
1491 * sigaction actually succeeds and otherwise we avoid an
1492 * uninitialized memory read.
1493 */
1494 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001495 sigaction(sig, NULL, &context);
1496 return context.sa_handler;
1497#else
1498 PyOS_sighandler_t handler;
1499 handler = signal(sig, SIG_IGN);
1500 signal(sig, handler);
1501 return handler;
1502#endif
1503}
1504
1505PyOS_sighandler_t
1506PyOS_setsig(int sig, PyOS_sighandler_t handler)
1507{
1508#ifdef HAVE_SIGACTION
1509 struct sigaction context;
1510 PyOS_sighandler_t oldhandler;
Barry Warsawafeb2a42001-11-13 23:08:26 +00001511 /* Initialize context.sa_handler to SIG_ERR which makes about as
1512 * much sense as anything else. It should get overwritten if
1513 * sigaction actually succeeds and otherwise we avoid an
1514 * uninitialized memory read.
1515 */
1516 context.sa_handler = SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001517 sigaction(sig, NULL, &context);
1518 oldhandler = context.sa_handler;
1519 context.sa_handler = handler;
1520 sigaction(sig, &context, NULL);
1521 return oldhandler;
1522#else
1523 return signal(sig, handler);
1524#endif
1525}