blob: 40611b6c5ee19d3c8608a16d2e59a4e0946058c5 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
6#include "grammar.h"
7#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +00008#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00009#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010#include "errcode.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000012#include "symtable.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000013#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000014#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000015
Guido van Rossum80bb9651996-12-05 23:27:02 +000016#ifdef HAVE_UNISTD_H
17#include <unistd.h>
18#endif
19
Guido van Rossuma110aa61994-08-29 12:50:44 +000020#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000021#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022#endif
23
Guido van Rossum9b38a141996-09-11 23:12:24 +000024#ifdef MS_WIN32
Guido van Rossuma44823b1995-03-14 15:01:17 +000025#undef BYTE
26#include "windows.h"
27#endif
28
Jack Jansencbf630f2000-07-11 21:59:16 +000029#ifdef macintosh
30#include "macglue.h"
31#endif
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000032extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000033
Guido van Rossum82598051997-03-05 00:20:32 +000034extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000035
Guido van Rossumb73cc041993-11-01 16:28:59 +000036/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000037static void initmain(void);
38static void initsite(void);
39static PyObject *run_err_node(node *n, char *filename,
40 PyObject *globals, PyObject *locals);
41static PyObject *run_node(node *n, char *filename,
42 PyObject *globals, PyObject *locals);
43static PyObject *run_pyc_file(FILE *fp, char *filename,
44 PyObject *globals, PyObject *locals);
45static void err_input(perrdetail *);
46static void initsigs(void);
47static void call_sys_exitfunc(void);
48static void call_ll_exitfuncs(void);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000049
Guido van Rossumbffd6832000-01-20 22:32:56 +000050#ifdef Py_TRACE_REFS
51int _Py_AskYesNo(char *prompt);
52#endif
53
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000054extern void _PyUnicode_Init(void);
55extern void _PyUnicode_Fini(void);
56extern void _PyCodecRegistry_Init(void);
57extern void _PyCodecRegistry_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000058
59
Guido van Rossum82598051997-03-05 00:20:32 +000060int Py_DebugFlag; /* Needed by parser.c */
61int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000062int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000063int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000064int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000065int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000066int Py_UnicodeFlag = 0; /* Needed by compile.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000067
Guido van Rossum25ce5661997-08-02 03:10:38 +000068static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000069
Thomas Wouters7e474022000-07-16 12:04:32 +000070/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000071
72int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000073Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000074{
75 return initialized;
76}
77
Guido van Rossum25ce5661997-08-02 03:10:38 +000078/* Global initializations. Can be undone by Py_Finalize(). Don't
79 call this twice without an intervening Py_Finalize() call. When
80 initializations fail, a fatal error is issued and the function does
81 not return. On return, the first thread and interpreter state have
82 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000083
Guido van Rossum25ce5661997-08-02 03:10:38 +000084 Locking: you must hold the interpreter lock while calling this.
85 (If the lock has not yet been initialized, that's equivalent to
86 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000087
Guido van Rossum25ce5661997-08-02 03:10:38 +000088*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000089
90void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000091Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000092{
Guido van Rossuma027efa1997-05-05 20:56:21 +000093 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +000094 PyThreadState *tstate;
95 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +000096 char *p;
Guido van Rossumad6dfda1997-07-19 19:17:22 +000097
Guido van Rossumdcc0c131997-08-29 22:32:42 +000098 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +000099 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000100 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000101
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000102 if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
Marc-André Lemburgdc3d6062000-08-25 21:00:46 +0000103 Py_DebugFlag = Py_DebugFlag ? Py_DebugFlag : 1;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000104 if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
Marc-André Lemburgdc3d6062000-08-25 21:00:46 +0000105 Py_VerboseFlag = Py_VerboseFlag ? Py_VerboseFlag : 1;
Guido van Rossum562f5b11998-10-07 14:50:42 +0000106 if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0')
Marc-André Lemburgdc3d6062000-08-25 21:00:46 +0000107 Py_OptimizeFlag = Py_OptimizeFlag ? Py_OptimizeFlag : 1;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000108
Guido van Rossuma027efa1997-05-05 20:56:21 +0000109 interp = PyInterpreterState_New();
110 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000111 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000112
Guido van Rossuma027efa1997-05-05 20:56:21 +0000113 tstate = PyThreadState_New(interp);
114 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000115 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000116 (void) PyThreadState_Swap(tstate);
117
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118 interp->modules = PyDict_New();
119 if (interp->modules == NULL)
120 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000121
Guido van Rossumc94044c2000-03-10 23:03:54 +0000122 /* Init codec registry */
123 _PyCodecRegistry_Init();
124
125 /* Init Unicode implementation; relies on the codec registry */
126 _PyUnicode_Init();
127
Barry Warsawf242aa02000-05-25 23:09:49 +0000128 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000129 if (bimod == NULL)
130 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000131 interp->builtins = PyModule_GetDict(bimod);
132 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133
134 sysmod = _PySys_Init();
135 if (sysmod == NULL)
136 Py_FatalError("Py_Initialize: can't initialize sys");
137 interp->sysdict = PyModule_GetDict(sysmod);
138 Py_INCREF(interp->sysdict);
139 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000140 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000141 PyDict_SetItemString(interp->sysdict, "modules",
142 interp->modules);
143
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000144 _PyImport_Init();
145
Barry Warsawf242aa02000-05-25 23:09:49 +0000146 /* initialize builtin exceptions */
147 init_exceptions();
148
Barry Warsaw035574d1997-08-29 22:07:17 +0000149 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000150 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000151
Guido van Rossum25ce5661997-08-02 03:10:38 +0000152 initsigs(); /* Signal handling stuff, including initintr() */
153
154 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000155 if (!Py_NoSiteFlag)
156 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000157}
158
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000159#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000160extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000161#endif
162
Guido van Rossum25ce5661997-08-02 03:10:38 +0000163/* Undo the effect of Py_Initialize().
164
165 Beware: if multiple interpreter and/or thread states exist, these
166 are not wiped out; only the current thread and interpreter state
167 are deleted. But since everything else is deleted, those other
168 interpreter and thread states should no longer be used.
169
170 (XXX We should do better, e.g. wipe out all interpreters and
171 threads.)
172
173 Locking: as above.
174
175*/
176
177void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000178Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000179{
180 PyInterpreterState *interp;
181 PyThreadState *tstate;
182
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000183 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000184 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000185
Tim Peters384fd102001-01-21 03:40:37 +0000186 /* The interpreter is still entirely intact at this point, and the
187 * exit funcs may be relying on that. In particular, if some thread
188 * or exit func is still waiting to do an import, the import machinery
189 * expects Py_IsInitialized() to return true. So don't say the
190 * interpreter is uninitialized until after the exit funcs have run.
191 * Note that Threading.py uses an exit func to do a join on all the
192 * threads created thru it, so this also protects pending imports in
193 * the threads created via Threading.
194 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000195 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000196 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000197
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000198 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199 tstate = PyThreadState_Get();
200 interp = tstate->interp;
201
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000202 /* Disable signal handling */
203 PyOS_FiniInterrupts();
204
Guido van Rossumc94044c2000-03-10 23:03:54 +0000205 /* Cleanup Unicode implementation */
206 _PyUnicode_Fini();
207
208 /* Cleanup Codec registry */
209 _PyCodecRegistry_Fini();
210
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000211 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000212 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000213
Guido van Rossum1707aad1997-12-08 23:43:45 +0000214 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
215 _PyImport_Fini();
216
217 /* Debugging stuff */
218#ifdef COUNT_ALLOCS
219 dump_counts();
220#endif
221
222#ifdef Py_REF_DEBUG
223 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
224#endif
225
226#ifdef Py_TRACE_REFS
Guido van Rossumeca47842000-04-27 23:44:15 +0000227 if (
228#ifdef MS_WINDOWS /* Only ask on Windows if env var set */
229 getenv("PYTHONDUMPREFS") &&
230#endif /* MS_WINDOWS */
231 _Py_AskYesNo("Print left references?")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000232 _Py_PrintReferences(stderr);
233 }
234#endif /* Py_TRACE_REFS */
235
Barry Warsaw035574d1997-08-29 22:07:17 +0000236 /* Now we decref the exception classes. After this point nothing
237 can raise an exception. That's okay, because each Fini() method
238 below has been checked to make sure no exceptions are ever
239 raised.
240 */
Barry Warsawf242aa02000-05-25 23:09:49 +0000241 fini_exceptions();
242
243 /* Delete current thread */
244 PyInterpreterState_Clear(interp);
245 PyThreadState_Swap(NULL);
246 PyInterpreterState_Delete(interp);
247
Guido van Rossumcc283f51997-08-05 02:22:03 +0000248 PyMethod_Fini();
249 PyFrame_Fini();
250 PyCFunction_Fini();
251 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000252 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000253 PyInt_Fini();
254 PyFloat_Fini();
255
256 /* XXX Still allocated:
257 - various static ad-hoc pointers to interned strings
258 - int and float free list blocks
259 - whatever various modules and libraries allocate
260 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000261
262 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000263
264 call_ll_exitfuncs();
265
Guido van Rossumcc283f51997-08-05 02:22:03 +0000266#ifdef Py_TRACE_REFS
Guido van Rossumcc283f51997-08-05 02:22:03 +0000267 _Py_ResetReferences();
268#endif /* Py_TRACE_REFS */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000269}
270
271/* Create and initialize a new interpreter and thread, and return the
272 new thread. This requires that Py_Initialize() has been called
273 first.
274
275 Unsuccessful initialization yields a NULL pointer. Note that *no*
276 exception information is available even in this case -- the
277 exception information is held in the thread, and there is no
278 thread.
279
280 Locking: as above.
281
282*/
283
284PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000285Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000286{
287 PyInterpreterState *interp;
288 PyThreadState *tstate, *save_tstate;
289 PyObject *bimod, *sysmod;
290
291 if (!initialized)
292 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
293
294 interp = PyInterpreterState_New();
295 if (interp == NULL)
296 return NULL;
297
298 tstate = PyThreadState_New(interp);
299 if (tstate == NULL) {
300 PyInterpreterState_Delete(interp);
301 return NULL;
302 }
303
304 save_tstate = PyThreadState_Swap(tstate);
305
306 /* XXX The following is lax in error checking */
307
308 interp->modules = PyDict_New();
309
310 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
311 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000312 interp->builtins = PyModule_GetDict(bimod);
313 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000314 }
315 sysmod = _PyImport_FindExtension("sys", "sys");
316 if (bimod != NULL && sysmod != NULL) {
317 interp->sysdict = PyModule_GetDict(sysmod);
318 Py_INCREF(interp->sysdict);
319 PySys_SetPath(Py_GetPath());
320 PyDict_SetItemString(interp->sysdict, "modules",
321 interp->modules);
322 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000323 if (!Py_NoSiteFlag)
324 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000325 }
326
327 if (!PyErr_Occurred())
328 return tstate;
329
330 /* Oops, it didn't work. Undo it all. */
331
332 PyErr_Print();
333 PyThreadState_Clear(tstate);
334 PyThreadState_Swap(save_tstate);
335 PyThreadState_Delete(tstate);
336 PyInterpreterState_Delete(interp);
337
338 return NULL;
339}
340
341/* Delete an interpreter and its last thread. This requires that the
342 given thread state is current, that the thread has no remaining
343 frames, and that it is its interpreter's only remaining thread.
344 It is a fatal error to violate these constraints.
345
346 (Py_Finalize() doesn't have these constraints -- it zaps
347 everything, regardless.)
348
349 Locking: as above.
350
351*/
352
353void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000354Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000355{
356 PyInterpreterState *interp = tstate->interp;
357
358 if (tstate != PyThreadState_Get())
359 Py_FatalError("Py_EndInterpreter: thread is not current");
360 if (tstate->frame != NULL)
361 Py_FatalError("Py_EndInterpreter: thread still has a frame");
362 if (tstate != interp->tstate_head || tstate->next != NULL)
363 Py_FatalError("Py_EndInterpreter: not the last thread");
364
365 PyImport_Cleanup();
366 PyInterpreterState_Clear(interp);
367 PyThreadState_Swap(NULL);
368 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000369}
370
371static char *progname = "python";
372
373void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000374Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000375{
376 if (pn && *pn)
377 progname = pn;
378}
379
380char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000381Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000382{
383 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000384}
385
Guido van Rossuma61691e1998-02-06 22:27:24 +0000386static char *default_home = NULL;
387
388void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000389Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000390{
391 default_home = home;
392}
393
394char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000395Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000396{
397 char *home = default_home;
398 if (home == NULL)
399 home = getenv("PYTHONHOME");
400 return home;
401}
402
Guido van Rossum6135a871995-01-09 17:53:26 +0000403/* Create __main__ module */
404
405static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000406initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000407{
Guido van Rossum82598051997-03-05 00:20:32 +0000408 PyObject *m, *d;
409 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000410 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000411 Py_FatalError("can't create __main__ module");
412 d = PyModule_GetDict(m);
413 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000414 PyObject *bimod = PyImport_ImportModule("__builtin__");
415 if (bimod == NULL ||
416 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000417 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000418 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000419 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000420}
421
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000422/* Import the site module (not into __main__ though) */
423
424static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000425initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000426{
427 PyObject *m, *f;
428 m = PyImport_ImportModule("site");
429 if (m == NULL) {
430 f = PySys_GetObject("stderr");
431 if (Py_VerboseFlag) {
432 PyFile_WriteString(
433 "'import site' failed; traceback:\n", f);
434 PyErr_Print();
435 }
436 else {
437 PyFile_WriteString(
438 "'import site' failed; use -v for traceback\n", f);
439 PyErr_Clear();
440 }
441 }
442 else {
443 Py_DECREF(m);
444 }
445}
446
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000447/* Parse input from a file and execute it */
448
449int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000450PyRun_AnyFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000451{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000452 return PyRun_AnyFileEx(fp, filename, 0);
453}
454
455int
456PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
457{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000458 if (filename == NULL)
459 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000460 if (Py_FdIsInteractive(fp, filename)) {
461 int err = PyRun_InteractiveLoop(fp, filename);
462 if (closeit)
463 fclose(fp);
464 return err;
465 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000466 else
Guido van Rossum0df002c2000-08-27 19:21:52 +0000467 return PyRun_SimpleFileEx(fp, filename, closeit);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000468}
469
470int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000471PyRun_InteractiveLoop(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000472{
Guido van Rossum82598051997-03-05 00:20:32 +0000473 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000474 int ret;
Guido van Rossum82598051997-03-05 00:20:32 +0000475 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000476 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000477 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
478 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000479 }
Guido van Rossum82598051997-03-05 00:20:32 +0000480 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000481 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000482 PySys_SetObject("ps2", v = PyString_FromString("... "));
483 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000484 }
485 for (;;) {
Guido van Rossum82598051997-03-05 00:20:32 +0000486 ret = PyRun_InteractiveOne(fp, filename);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000487#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000488 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000489#endif
490 if (ret == E_EOF)
491 return 0;
492 /*
493 if (ret == E_NOMEM)
494 return -1;
495 */
496 }
497}
498
499int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000500PyRun_InteractiveOne(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000501{
Guido van Rossum82598051997-03-05 00:20:32 +0000502 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000503 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000504 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000505 char *ps1 = "", *ps2 = "";
Guido van Rossum82598051997-03-05 00:20:32 +0000506 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000507 if (v != NULL) {
508 v = PyObject_Str(v);
509 if (v == NULL)
510 PyErr_Clear();
511 else if (PyString_Check(v))
512 ps1 = PyString_AsString(v);
513 }
Guido van Rossum82598051997-03-05 00:20:32 +0000514 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000515 if (w != NULL) {
516 w = PyObject_Str(w);
517 if (w == NULL)
518 PyErr_Clear();
519 else if (PyString_Check(w))
520 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000521 }
Guido van Rossum82598051997-03-05 00:20:32 +0000522 n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar,
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000523 Py_single_input, ps1, ps2, &err);
Guido van Rossum82598051997-03-05 00:20:32 +0000524 Py_XDECREF(v);
525 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000526 if (n == NULL) {
527 if (err.error == E_EOF) {
528 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000529 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000530 return E_EOF;
531 }
532 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000533 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000534 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000535 }
Guido van Rossum82598051997-03-05 00:20:32 +0000536 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000537 if (m == NULL)
538 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000539 d = PyModule_GetDict(m);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000540 v = run_node(n, filename, d, d);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000541 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000542 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000543 return -1;
544 }
Guido van Rossum82598051997-03-05 00:20:32 +0000545 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000546 if (Py_FlushLine())
547 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000548 return 0;
549}
550
551int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000552PyRun_SimpleFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000553{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000554 return PyRun_SimpleFileEx(fp, filename, 0);
555}
556
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000557/* Check whether a file maybe a pyc file: Look at the extension,
558 the file type, and, if we may close it, at the first few bytes. */
559
560static int
561maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
562{
563 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
564 return 1;
565
566#ifdef macintosh
567 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
568 if (PyMac_getfiletype(filename) == 'PYC '
569 || PyMac_getfiletype(filename) == 'APPL')
570 return 1;
571#endif /* macintosh */
572
573 /* Only look into the file if we are allowed to close it, since
574 it then should also be seekable. */
575 if (closeit) {
576 /* Read only two bytes of the magic. If the file was opened in
577 text mode, the bytes 3 and 4 of the magic (\r\n) might not
578 be read as they are on disk. */
579 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
580 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000581 /* Mess: In case of -x, the stream is NOT at its start now,
582 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000583 which makes the current stream position formally undefined,
584 and a x-platform nightmare.
585 Unfortunately, we have no direct way to know whether -x
586 was specified. So we use a terrible hack: if the current
587 stream position is not 0, we assume -x was specified, and
588 give up. Bug 132850 on SourceForge spells out the
589 hopelessness of trying anything else (fseek and ftell
590 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000591 */
Tim Peters3e876562001-02-11 04:35:39 +0000592 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000593 if (ftell(fp) == 0) {
594 if (fread(buf, 1, 2, fp) == 2 &&
595 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
596 ispyc = 1;
597 rewind(fp);
598 }
Tim Peters3e876562001-02-11 04:35:39 +0000599 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000600 }
601 return 0;
602}
603
Guido van Rossum0df002c2000-08-27 19:21:52 +0000604int
605PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
606{
Guido van Rossum82598051997-03-05 00:20:32 +0000607 PyObject *m, *d, *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000608 char *ext;
609
Guido van Rossum82598051997-03-05 00:20:32 +0000610 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000611 if (m == NULL)
612 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000613 d = PyModule_GetDict(m);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000614 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000615 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000616 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000617 if (closeit)
618 fclose(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000619 if( (fp = fopen(filename, "rb")) == NULL ) {
620 fprintf(stderr, "python: Can't reopen .pyc file\n");
621 return -1;
622 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000623 /* Turn on optimization if a .pyo file is given */
624 if (strcmp(ext, ".pyo") == 0)
625 Py_OptimizeFlag = 1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000626 v = run_pyc_file(fp, filename, d, d);
627 } else {
Guido van Rossum0df002c2000-08-27 19:21:52 +0000628 v = PyRun_FileEx(fp, filename, Py_file_input, d, d, closeit);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000629 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000630 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000631 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000632 return -1;
633 }
Guido van Rossum82598051997-03-05 00:20:32 +0000634 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000635 if (Py_FlushLine())
636 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000637 return 0;
638}
639
640int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000641PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000642{
Guido van Rossum82598051997-03-05 00:20:32 +0000643 PyObject *m, *d, *v;
644 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000645 if (m == NULL)
646 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000647 d = PyModule_GetDict(m);
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000648 v = PyRun_String(command, Py_file_input, d, d);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000649 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000650 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000651 return -1;
652 }
Guido van Rossum82598051997-03-05 00:20:32 +0000653 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000654 if (Py_FlushLine())
655 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000656 return 0;
657}
658
Barry Warsaw035574d1997-08-29 22:07:17 +0000659static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000660parse_syntax_error(PyObject *err, PyObject **message, char **filename,
661 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000662{
663 long hold;
664 PyObject *v;
665
666 /* old style errors */
667 if (PyTuple_Check(err))
668 return PyArg_Parse(err, "(O(ziiz))", message, filename,
669 lineno, offset, text);
670
671 /* new style errors. `err' is an instance */
672
673 if (! (v = PyObject_GetAttrString(err, "msg")))
674 goto finally;
675 *message = v;
676
677 if (!(v = PyObject_GetAttrString(err, "filename")))
678 goto finally;
679 if (v == Py_None)
680 *filename = NULL;
681 else if (! (*filename = PyString_AsString(v)))
682 goto finally;
683
684 Py_DECREF(v);
685 if (!(v = PyObject_GetAttrString(err, "lineno")))
686 goto finally;
687 hold = PyInt_AsLong(v);
688 Py_DECREF(v);
689 v = NULL;
690 if (hold < 0 && PyErr_Occurred())
691 goto finally;
692 *lineno = (int)hold;
693
694 if (!(v = PyObject_GetAttrString(err, "offset")))
695 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000696 if (v == Py_None) {
697 *offset = -1;
698 Py_DECREF(v);
699 v = NULL;
700 } else {
701 hold = PyInt_AsLong(v);
702 Py_DECREF(v);
703 v = NULL;
704 if (hold < 0 && PyErr_Occurred())
705 goto finally;
706 *offset = (int)hold;
707 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000708
709 if (!(v = PyObject_GetAttrString(err, "text")))
710 goto finally;
711 if (v == Py_None)
712 *text = NULL;
713 else if (! (*text = PyString_AsString(v)))
714 goto finally;
715 Py_DECREF(v);
716 return 1;
717
718finally:
719 Py_XDECREF(v);
720 return 0;
721}
722
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000723void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000724PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000725{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000726 PyErr_PrintEx(1);
727}
728
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000729static void
730print_error_text(PyObject *f, int offset, char *text)
731{
732 char *nl;
733 if (offset >= 0) {
734 if (offset > 0 && offset == (int)strlen(text))
735 offset--;
736 for (;;) {
737 nl = strchr(text, '\n');
738 if (nl == NULL || nl-text >= offset)
739 break;
740 offset -= (nl+1-text);
741 text = nl+1;
742 }
743 while (*text == ' ' || *text == '\t') {
744 text++;
745 offset--;
746 }
747 }
748 PyFile_WriteString(" ", f);
749 PyFile_WriteString(text, f);
750 if (*text == '\0' || text[strlen(text)-1] != '\n')
751 PyFile_WriteString("\n", f);
752 if (offset == -1)
753 return;
754 PyFile_WriteString(" ", f);
755 offset--;
756 while (offset > 0) {
757 PyFile_WriteString(" ", f);
758 offset--;
759 }
760 PyFile_WriteString("^\n", f);
761}
762
Guido van Rossuma61691e1998-02-06 22:27:24 +0000763void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000764PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000765{
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000766 int err = 0;
Guido van Rossum82598051997-03-05 00:20:32 +0000767 PyObject *exception, *v, *tb, *f;
768 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000769 PyErr_NormalizeException(&exception, &v, &tb);
770
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000771 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000772 return;
Barry Warsaw035574d1997-08-29 22:07:17 +0000773
Barry Warsaw36b8f941997-08-26 18:09:48 +0000774 if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
Guido van Rossum0829c751998-02-28 04:31:39 +0000775 if (Py_FlushLine())
776 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000777 fflush(stdout);
Guido van Rossum82598051997-03-05 00:20:32 +0000778 if (v == NULL || v == Py_None)
779 Py_Exit(0);
Barry Warsaw035574d1997-08-29 22:07:17 +0000780 if (PyInstance_Check(v)) {
781 /* we expect the error code to be store in the
782 `code' attribute
783 */
784 PyObject *code = PyObject_GetAttrString(v, "code");
785 if (code) {
786 Py_DECREF(v);
787 v = code;
Guido van Rossumaa9606f1997-10-03 13:53:28 +0000788 if (v == Py_None)
789 Py_Exit(0);
Barry Warsaw035574d1997-08-29 22:07:17 +0000790 }
791 /* if we failed to dig out the "code" attribute,
792 then just let the else clause below print the
793 error
794 */
795 }
Guido van Rossum82598051997-03-05 00:20:32 +0000796 if (PyInt_Check(v))
797 Py_Exit((int)PyInt_AsLong(v));
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000798 else {
Guido van Rossum3165fe61992-09-25 21:59:05 +0000799 /* OK to use real stderr here */
Guido van Rossum82598051997-03-05 00:20:32 +0000800 PyObject_Print(v, stderr, Py_PRINT_RAW);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000801 fprintf(stderr, "\n");
Guido van Rossum82598051997-03-05 00:20:32 +0000802 Py_Exit(1);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000803 }
804 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000805 if (set_sys_last_vars) {
806 PySys_SetObject("last_type", exception);
807 PySys_SetObject("last_value", v);
808 PySys_SetObject("last_traceback", tb);
809 }
Guido van Rossum82598051997-03-05 00:20:32 +0000810 f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000811 if (f == NULL)
812 fprintf(stderr, "lost sys.stderr\n");
813 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000814 if (Py_FlushLine())
815 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000816 fflush(stdout);
Guido van Rossum0829c751998-02-28 04:31:39 +0000817 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000818 if (err == 0 &&
819 PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
820 {
Guido van Rossum82598051997-03-05 00:20:32 +0000821 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000822 char *filename, *text;
823 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000824 if (!parse_syntax_error(v, &message, &filename,
825 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000826 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000827 else {
828 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000829 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000830 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000831 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000832 else
Guido van Rossum82598051997-03-05 00:20:32 +0000833 PyFile_WriteString(filename, f);
834 PyFile_WriteString("\", line ", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000835 sprintf(buf, "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000836 PyFile_WriteString(buf, f);
837 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000838 if (text != NULL)
839 print_error_text(f, offset, text);
Guido van Rossum82598051997-03-05 00:20:32 +0000840 Py_INCREF(message);
841 Py_DECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000842 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000843 /* Can't be bothered to check all those
844 PyFile_WriteString() calls */
845 if (PyErr_Occurred())
846 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000847 }
848 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000849 if (err) {
850 /* Don't do anything else */
851 }
852 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000853 PyClassObject* exc = (PyClassObject*)exception;
854 PyObject* className = exc->cl_name;
855 PyObject* moduleName =
856 PyDict_GetItemString(exc->cl_dict, "__module__");
857
858 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000859 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000860 else {
861 char* modstr = PyString_AsString(moduleName);
862 if (modstr && strcmp(modstr, "exceptions"))
863 {
864 err = PyFile_WriteString(modstr, f);
865 err += PyFile_WriteString(".", f);
866 }
867 }
868 if (err == 0) {
869 if (className == NULL)
870 err = PyFile_WriteString("<unknown>", f);
871 else
872 err = PyFile_WriteObject(className, f,
873 Py_PRINT_RAW);
874 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000875 }
876 else
877 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
878 if (err == 0) {
879 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000880 PyObject *s = PyObject_Str(v);
881 /* only print colon if the str() of the
882 object is not the empty string
883 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000884 if (s == NULL)
885 err = -1;
886 else if (!PyString_Check(s) ||
887 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +0000888 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000889 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000890 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
891 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +0000892 }
Guido van Rossum262e1241995-02-07 15:30:45 +0000893 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000894 if (err == 0)
895 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000896 }
Guido van Rossum82598051997-03-05 00:20:32 +0000897 Py_XDECREF(exception);
898 Py_XDECREF(v);
899 Py_XDECREF(tb);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000900 /* If an error happened here, don't show it.
901 XXX This is wrong, but too many callers rely on this behavior. */
902 if (err != 0)
903 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000904}
905
Guido van Rossum82598051997-03-05 00:20:32 +0000906PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000907PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000908{
Guido van Rossum82598051997-03-05 00:20:32 +0000909 return run_err_node(PyParser_SimpleParseString(str, start),
Guido van Rossuma110aa61994-08-29 12:50:44 +0000910 "<string>", globals, locals);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000911}
912
Guido van Rossum82598051997-03-05 00:20:32 +0000913PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000914PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
915 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000916{
Tim Peterse8682112000-08-27 20:18:17 +0000917 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000918}
919
920PyObject *
921PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
922 PyObject *locals, int closeit)
923{
924 node *n = PyParser_SimpleParseFile(fp, filename, start);
925 if (closeit)
926 fclose(fp);
927 return run_err_node(n, filename, globals, locals);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000928}
929
Guido van Rossum82598051997-03-05 00:20:32 +0000930static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000931run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000932{
Guido van Rossuma110aa61994-08-29 12:50:44 +0000933 if (n == NULL)
934 return NULL;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000935 return run_node(n, filename, globals, locals);
936}
937
Guido van Rossum82598051997-03-05 00:20:32 +0000938static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000939run_node(node *n, char *filename, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000940{
Guido van Rossum82598051997-03-05 00:20:32 +0000941 PyCodeObject *co;
942 PyObject *v;
943 co = PyNode_Compile(n, filename);
944 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000945 if (co == NULL)
946 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +0000947 v = PyEval_EvalCode(co, globals, locals);
948 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000949 return v;
950}
951
Guido van Rossum82598051997-03-05 00:20:32 +0000952static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000953run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals)
Guido van Rossumfdef2711994-09-14 13:31:04 +0000954{
Guido van Rossum82598051997-03-05 00:20:32 +0000955 PyCodeObject *co;
956 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000957 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +0000958 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000959
Guido van Rossum82598051997-03-05 00:20:32 +0000960 magic = PyMarshal_ReadLongFromFile(fp);
961 if (magic != PyImport_GetMagicNumber()) {
962 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +0000963 "Bad magic number in .pyc file");
964 return NULL;
965 }
Guido van Rossum82598051997-03-05 00:20:32 +0000966 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +0000967 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000968 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +0000969 if (v == NULL || !PyCode_Check(v)) {
970 Py_XDECREF(v);
971 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +0000972 "Bad code object in .pyc file");
973 return NULL;
974 }
Guido van Rossum82598051997-03-05 00:20:32 +0000975 co = (PyCodeObject *)v;
976 v = PyEval_EvalCode(co, globals, locals);
977 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000978 return v;
979}
980
Guido van Rossum82598051997-03-05 00:20:32 +0000981PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000982Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +0000983{
984 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +0000985 PyCodeObject *co;
986 n = PyParser_SimpleParseString(str, start);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000987 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +0000988 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +0000989 co = PyNode_Compile(n, filename);
990 PyNode_Free(n);
991 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +0000992}
993
Jeremy Hylton4b38da62001-02-02 18:19:15 +0000994struct symtable *
995Py_SymtableString(char *str, char *filename, int start)
996{
997 node *n;
998 struct symtable *st;
999 n = PyParser_SimpleParseString(str, start);
1000 if (n == NULL)
1001 return NULL;
1002 st = PyNode_CompileSymtable(n, filename);
1003 PyNode_Free(n);
1004 return st;
1005}
1006
Guido van Rossuma110aa61994-08-29 12:50:44 +00001007/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001008
Guido van Rossuma110aa61994-08-29 12:50:44 +00001009node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001010PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001011{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001012 node *n;
1013 perrdetail err;
Guido van Rossum82598051997-03-05 00:20:32 +00001014 n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar, start,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001015 (char *)0, (char *)0, &err);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001016 if (n == NULL)
1017 err_input(&err);
1018 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001019}
1020
Guido van Rossuma110aa61994-08-29 12:50:44 +00001021/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001022
Guido van Rossuma110aa61994-08-29 12:50:44 +00001023node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001024PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001025{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001026 node *n;
1027 perrdetail err;
Guido van Rossum82598051997-03-05 00:20:32 +00001028 n = PyParser_ParseString(str, &_PyParser_Grammar, start, &err);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001029 if (n == NULL)
1030 err_input(&err);
1031 return n;
1032}
1033
1034/* Set the error appropriate to the given input error code (see errcode.h) */
1035
1036static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001037err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001038{
Fred Drake85f36392000-07-11 17:53:00 +00001039 PyObject *v, *w, *errtype;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001040 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001041 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001042 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001043 err->lineno, err->offset, err->text);
1044 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001045 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001046 err->text = NULL;
1047 }
1048 switch (err->error) {
1049 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001050 errtype = PyExc_IndentationError;
1051 if (err->expected == INDENT)
1052 msg = "expected an indented block";
1053 else if (err->token == INDENT)
1054 msg = "unexpected indent";
1055 else if (err->token == DEDENT)
1056 msg = "unexpected unindent";
1057 else {
1058 errtype = PyExc_SyntaxError;
1059 msg = "invalid syntax";
1060 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001061 break;
1062 case E_TOKEN:
1063 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001064 break;
1065 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001066 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001067 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001068 return;
1069 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001070 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001071 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001072 return;
1073 case E_EOF:
1074 msg = "unexpected EOF while parsing";
1075 break;
Fred Drake85f36392000-07-11 17:53:00 +00001076 case E_TABSPACE:
1077 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001078 msg = "inconsistent use of tabs and spaces in indentation";
1079 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001080 case E_OVERFLOW:
1081 msg = "expression too long";
1082 break;
Fred Drake85f36392000-07-11 17:53:00 +00001083 case E_DEDENT:
1084 errtype = PyExc_IndentationError;
1085 msg = "unindent does not match any outer indentation level";
1086 break;
1087 case E_TOODEEP:
1088 errtype = PyExc_IndentationError;
1089 msg = "too many levels of indentation";
1090 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001091 default:
1092 fprintf(stderr, "error=%d\n", err->error);
1093 msg = "unknown parsing error";
1094 break;
1095 }
Guido van Rossum82598051997-03-05 00:20:32 +00001096 w = Py_BuildValue("(sO)", msg, v);
Fred Drake85f36392000-07-11 17:53:00 +00001097 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001098 Py_XDECREF(w);
Fred Drake83cb7972000-08-15 15:49:03 +00001099
1100 if (v != NULL) {
1101 PyObject *exc, *tb;
1102
1103 PyErr_Fetch(&errtype, &exc, &tb);
1104 PyErr_NormalizeException(&errtype, &exc, &tb);
1105 if (PyObject_SetAttrString(exc, "filename",
1106 PyTuple_GET_ITEM(v, 0)))
1107 PyErr_Clear();
1108 if (PyObject_SetAttrString(exc, "lineno",
1109 PyTuple_GET_ITEM(v, 1)))
1110 PyErr_Clear();
1111 if (PyObject_SetAttrString(exc, "offset",
1112 PyTuple_GET_ITEM(v, 2)))
1113 PyErr_Clear();
1114 Py_DECREF(v);
1115 PyErr_Restore(errtype, exc, tb);
1116 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001117}
1118
1119/* Print fatal error message and abort */
1120
1121void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001122Py_FatalError(char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001123{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001124 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001125#ifdef macintosh
1126 for (;;);
1127#endif
Guido van Rossum9b38a141996-09-11 23:12:24 +00001128#ifdef MS_WIN32
Guido van Rossum23c94461997-05-22 20:21:30 +00001129 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001130 OutputDebugString(msg);
1131 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001132#ifdef _DEBUG
1133 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001134#endif
Guido van Rossum0ba35361998-08-13 13:33:16 +00001135#endif /* MS_WIN32 */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001136 abort();
1137}
1138
1139/* Clean up and exit */
1140
Guido van Rossuma110aa61994-08-29 12:50:44 +00001141#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001142#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001143int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001144#endif
1145
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001146#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001147static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001148static int nexitfuncs = 0;
1149
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001150int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001151{
1152 if (nexitfuncs >= NEXITFUNCS)
1153 return -1;
1154 exitfuncs[nexitfuncs++] = func;
1155 return 0;
1156}
1157
Guido van Rossumcc283f51997-08-05 02:22:03 +00001158static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001159call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001160{
Guido van Rossum82598051997-03-05 00:20:32 +00001161 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001162
1163 if (exitfunc) {
Guido van Rossumbf02fb21998-04-03 21:12:12 +00001164 PyObject *res, *f;
Guido van Rossum82598051997-03-05 00:20:32 +00001165 Py_INCREF(exitfunc);
1166 PySys_SetObject("exitfunc", (PyObject *)NULL);
Guido van Rossumbf02fb21998-04-03 21:12:12 +00001167 f = PySys_GetObject("stderr");
Guido van Rossum82598051997-03-05 00:20:32 +00001168 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001169 if (res == NULL) {
Guido van Rossumbf02fb21998-04-03 21:12:12 +00001170 if (f)
1171 PyFile_WriteString("Error in sys.exitfunc:\n", f);
Guido van Rossum82598051997-03-05 00:20:32 +00001172 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001173 }
Guido van Rossum82598051997-03-05 00:20:32 +00001174 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001175 }
1176
Guido van Rossum0829c751998-02-28 04:31:39 +00001177 if (Py_FlushLine())
1178 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001179}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001180
Guido van Rossumcc283f51997-08-05 02:22:03 +00001181static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001182call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001183{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001184 while (nexitfuncs > 0)
1185 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001186
1187 fflush(stdout);
1188 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001189}
1190
1191void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001192Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001193{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001194 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001195
Jack Jansen66a89771995-10-27 13:22:14 +00001196#ifdef macintosh
1197 PyMac_Exit(sts);
1198#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001199 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001200#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001201}
1202
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001203static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001204initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001205{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001206#ifdef HAVE_SIGNAL_H
1207#ifdef SIGPIPE
1208 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001209#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001210#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001211 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001212}
1213
Guido van Rossumaae0d321996-05-22 16:35:33 +00001214#ifdef Py_TRACE_REFS
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001215/* Ask a yes/no question */
1216
Guido van Rossum59bff391992-09-03 20:28:00 +00001217int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001218_Py_AskYesNo(char *prompt)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001219{
1220 char buf[256];
1221
1222 printf("%s [ny] ", prompt);
1223 if (fgets(buf, sizeof buf, stdin) == NULL)
1224 return 0;
1225 return buf[0] == 'y' || buf[0] == 'Y';
1226}
1227#endif
1228
Guido van Rossuma110aa61994-08-29 12:50:44 +00001229#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001230
1231/* Check for file descriptor connected to interactive device.
1232 Pretend that stdin is always interactive, other files never. */
1233
1234int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001235isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001236{
1237 return fd == fileno(stdin);
1238}
1239
1240#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001241
1242/*
1243 * The file descriptor fd is considered ``interactive'' if either
1244 * a) isatty(fd) is TRUE, or
1245 * b) the -i flag was given, and the filename associated with
1246 * the descriptor is NULL or "<stdin>" or "???".
1247 */
1248int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001249Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001250{
1251 if (isatty((int)fileno(fp)))
1252 return 1;
1253 if (!Py_InteractiveFlag)
1254 return 0;
1255 return (filename == NULL) ||
1256 (strcmp(filename, "<stdin>") == 0) ||
1257 (strcmp(filename, "???") == 0);
1258}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001259
1260
1261#if defined(USE_STACKCHECK)
1262#if defined(WIN32) && defined(_MSC_VER)
1263
1264/* Stack checking for Microsoft C */
1265
1266#include <malloc.h>
1267#include <excpt.h>
1268
Fred Drakee8de31c2000-08-31 05:38:39 +00001269/*
1270 * Return non-zero when we run out of memory on the stack; zero otherwise.
1271 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001272int
Fred Drake399739f2000-08-31 05:52:44 +00001273PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001274{
1275 __try {
1276 /* _alloca throws a stack overflow exception if there's
1277 not enough space left on the stack */
1278 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1279 return 0;
1280 } __except (EXCEPTION_EXECUTE_HANDLER) {
1281 /* just ignore all errors */
1282 }
1283 return 1;
1284}
1285
1286#endif /* WIN32 && _MSC_VER */
1287
1288/* Alternate implementations can be added here... */
1289
1290#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001291
1292
1293/* Wrappers around sigaction() or signal(). */
1294
1295PyOS_sighandler_t
1296PyOS_getsig(int sig)
1297{
1298#ifdef HAVE_SIGACTION
1299 struct sigaction context;
1300 sigaction(sig, NULL, &context);
1301 return context.sa_handler;
1302#else
1303 PyOS_sighandler_t handler;
1304 handler = signal(sig, SIG_IGN);
1305 signal(sig, handler);
1306 return handler;
1307#endif
1308}
1309
1310PyOS_sighandler_t
1311PyOS_setsig(int sig, PyOS_sighandler_t handler)
1312{
1313#ifdef HAVE_SIGACTION
1314 struct sigaction context;
1315 PyOS_sighandler_t oldhandler;
1316 sigaction(sig, NULL, &context);
1317 oldhandler = context.sa_handler;
1318 context.sa_handler = handler;
1319 sigaction(sig, &context, NULL);
1320 return oldhandler;
1321#else
1322 return signal(sig, handler);
1323#endif
1324}