blob: 5f907978abb0f5ec18d7b7391675203e62bf62b2 [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"
Guido van Rossumff4949e1992-08-05 19:58:53 +000012#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000013#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014
Guido van Rossum80bb9651996-12-05 23:27:02 +000015#ifdef HAVE_UNISTD_H
16#include <unistd.h>
17#endif
18
Guido van Rossuma110aa61994-08-29 12:50:44 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000021#endif
22
Guido van Rossum9b38a141996-09-11 23:12:24 +000023#ifdef MS_WIN32
Guido van Rossuma44823b1995-03-14 15:01:17 +000024#undef BYTE
25#include "windows.h"
26#endif
27
Jack Jansencbf630f2000-07-11 21:59:16 +000028#ifdef macintosh
29#include "macglue.h"
30#endif
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000031extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000032
Guido van Rossum82598051997-03-05 00:20:32 +000033extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000034
Guido van Rossumb73cc041993-11-01 16:28:59 +000035/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000036static void initmain(void);
37static void initsite(void);
38static PyObject *run_err_node(node *n, char *filename,
39 PyObject *globals, PyObject *locals);
40static PyObject *run_node(node *n, char *filename,
41 PyObject *globals, PyObject *locals);
42static PyObject *run_pyc_file(FILE *fp, char *filename,
43 PyObject *globals, PyObject *locals);
44static void err_input(perrdetail *);
45static void initsigs(void);
46static void call_sys_exitfunc(void);
47static void call_ll_exitfuncs(void);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000048
Guido van Rossumbffd6832000-01-20 22:32:56 +000049#ifdef Py_TRACE_REFS
50int _Py_AskYesNo(char *prompt);
51#endif
52
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000053extern void _PyUnicode_Init(void);
54extern void _PyUnicode_Fini(void);
55extern void _PyCodecRegistry_Init(void);
56extern void _PyCodecRegistry_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000057
58
Guido van Rossum82598051997-03-05 00:20:32 +000059int Py_DebugFlag; /* Needed by parser.c */
60int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000061int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000062int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000063int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000064int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000065int Py_UnicodeFlag = 0; /* Needed by compile.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000066
Guido van Rossum25ce5661997-08-02 03:10:38 +000067static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000068
Thomas Wouters7e474022000-07-16 12:04:32 +000069/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000070
71int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000072Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000073{
74 return initialized;
75}
76
Guido van Rossum25ce5661997-08-02 03:10:38 +000077/* Global initializations. Can be undone by Py_Finalize(). Don't
78 call this twice without an intervening Py_Finalize() call. When
79 initializations fail, a fatal error is issued and the function does
80 not return. On return, the first thread and interpreter state have
81 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000082
Guido van Rossum25ce5661997-08-02 03:10:38 +000083 Locking: you must hold the interpreter lock while calling this.
84 (If the lock has not yet been initialized, that's equivalent to
85 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000086
Guido van Rossum25ce5661997-08-02 03:10:38 +000087*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000088
89void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000090Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000091{
Guido van Rossuma027efa1997-05-05 20:56:21 +000092 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +000093 PyThreadState *tstate;
94 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +000095 char *p;
Guido van Rossumad6dfda1997-07-19 19:17:22 +000096
Guido van Rossumdcc0c131997-08-29 22:32:42 +000097 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +000098 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +000099 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000100
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000101 if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
Marc-André Lemburgdc3d6062000-08-25 21:00:46 +0000102 Py_DebugFlag = Py_DebugFlag ? Py_DebugFlag : 1;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000103 if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
Marc-André Lemburgdc3d6062000-08-25 21:00:46 +0000104 Py_VerboseFlag = Py_VerboseFlag ? Py_VerboseFlag : 1;
Guido van Rossum562f5b11998-10-07 14:50:42 +0000105 if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0')
Marc-André Lemburgdc3d6062000-08-25 21:00:46 +0000106 Py_OptimizeFlag = Py_OptimizeFlag ? Py_OptimizeFlag : 1;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000107
Guido van Rossuma027efa1997-05-05 20:56:21 +0000108 interp = PyInterpreterState_New();
109 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000110 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000111
Guido van Rossuma027efa1997-05-05 20:56:21 +0000112 tstate = PyThreadState_New(interp);
113 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000114 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000115 (void) PyThreadState_Swap(tstate);
116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117 interp->modules = PyDict_New();
118 if (interp->modules == NULL)
119 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000120
Guido van Rossumc94044c2000-03-10 23:03:54 +0000121 /* Init codec registry */
122 _PyCodecRegistry_Init();
123
124 /* Init Unicode implementation; relies on the codec registry */
125 _PyUnicode_Init();
126
Barry Warsawf242aa02000-05-25 23:09:49 +0000127 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000128 if (bimod == NULL)
129 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000130 interp->builtins = PyModule_GetDict(bimod);
131 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132
133 sysmod = _PySys_Init();
134 if (sysmod == NULL)
135 Py_FatalError("Py_Initialize: can't initialize sys");
136 interp->sysdict = PyModule_GetDict(sysmod);
137 Py_INCREF(interp->sysdict);
138 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000139 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140 PyDict_SetItemString(interp->sysdict, "modules",
141 interp->modules);
142
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000143 _PyImport_Init();
144
Barry Warsawf242aa02000-05-25 23:09:49 +0000145 /* initialize builtin exceptions */
146 init_exceptions();
147
Barry Warsaw035574d1997-08-29 22:07:17 +0000148 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000149 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000150
Guido van Rossum25ce5661997-08-02 03:10:38 +0000151 initsigs(); /* Signal handling stuff, including initintr() */
152
153 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000154 if (!Py_NoSiteFlag)
155 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000156}
157
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000158#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000159extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000160#endif
161
Guido van Rossum25ce5661997-08-02 03:10:38 +0000162/* Undo the effect of Py_Initialize().
163
164 Beware: if multiple interpreter and/or thread states exist, these
165 are not wiped out; only the current thread and interpreter state
166 are deleted. But since everything else is deleted, those other
167 interpreter and thread states should no longer be used.
168
169 (XXX We should do better, e.g. wipe out all interpreters and
170 threads.)
171
172 Locking: as above.
173
174*/
175
176void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000177Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000178{
179 PyInterpreterState *interp;
180 PyThreadState *tstate;
181
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000182 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000183 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000184
Tim Peters384fd102001-01-21 03:40:37 +0000185 /* The interpreter is still entirely intact at this point, and the
186 * exit funcs may be relying on that. In particular, if some thread
187 * or exit func is still waiting to do an import, the import machinery
188 * expects Py_IsInitialized() to return true. So don't say the
189 * interpreter is uninitialized until after the exit funcs have run.
190 * Note that Threading.py uses an exit func to do a join on all the
191 * threads created thru it, so this also protects pending imports in
192 * the threads created via Threading.
193 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000194 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000195 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000196
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000197 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000198 tstate = PyThreadState_Get();
199 interp = tstate->interp;
200
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000201 /* Disable signal handling */
202 PyOS_FiniInterrupts();
203
Guido van Rossumc94044c2000-03-10 23:03:54 +0000204 /* Cleanup Unicode implementation */
205 _PyUnicode_Fini();
206
207 /* Cleanup Codec registry */
208 _PyCodecRegistry_Fini();
209
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000210 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000211 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000212
Guido van Rossum1707aad1997-12-08 23:43:45 +0000213 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
214 _PyImport_Fini();
215
216 /* Debugging stuff */
217#ifdef COUNT_ALLOCS
218 dump_counts();
219#endif
220
221#ifdef Py_REF_DEBUG
222 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
223#endif
224
225#ifdef Py_TRACE_REFS
Guido van Rossumeca47842000-04-27 23:44:15 +0000226 if (
227#ifdef MS_WINDOWS /* Only ask on Windows if env var set */
228 getenv("PYTHONDUMPREFS") &&
229#endif /* MS_WINDOWS */
230 _Py_AskYesNo("Print left references?")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000231 _Py_PrintReferences(stderr);
232 }
233#endif /* Py_TRACE_REFS */
234
Barry Warsaw035574d1997-08-29 22:07:17 +0000235 /* Now we decref the exception classes. After this point nothing
236 can raise an exception. That's okay, because each Fini() method
237 below has been checked to make sure no exceptions are ever
238 raised.
239 */
Barry Warsawf242aa02000-05-25 23:09:49 +0000240 fini_exceptions();
241
242 /* Delete current thread */
243 PyInterpreterState_Clear(interp);
244 PyThreadState_Swap(NULL);
245 PyInterpreterState_Delete(interp);
246
Guido van Rossumcc283f51997-08-05 02:22:03 +0000247 PyMethod_Fini();
248 PyFrame_Fini();
249 PyCFunction_Fini();
250 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000251 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000252 PyInt_Fini();
253 PyFloat_Fini();
254
255 /* XXX Still allocated:
256 - various static ad-hoc pointers to interned strings
257 - int and float free list blocks
258 - whatever various modules and libraries allocate
259 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000260
261 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000262
263 call_ll_exitfuncs();
264
Guido van Rossumcc283f51997-08-05 02:22:03 +0000265#ifdef Py_TRACE_REFS
Guido van Rossumcc283f51997-08-05 02:22:03 +0000266 _Py_ResetReferences();
267#endif /* Py_TRACE_REFS */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000268}
269
270/* Create and initialize a new interpreter and thread, and return the
271 new thread. This requires that Py_Initialize() has been called
272 first.
273
274 Unsuccessful initialization yields a NULL pointer. Note that *no*
275 exception information is available even in this case -- the
276 exception information is held in the thread, and there is no
277 thread.
278
279 Locking: as above.
280
281*/
282
283PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000284Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000285{
286 PyInterpreterState *interp;
287 PyThreadState *tstate, *save_tstate;
288 PyObject *bimod, *sysmod;
289
290 if (!initialized)
291 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
292
293 interp = PyInterpreterState_New();
294 if (interp == NULL)
295 return NULL;
296
297 tstate = PyThreadState_New(interp);
298 if (tstate == NULL) {
299 PyInterpreterState_Delete(interp);
300 return NULL;
301 }
302
303 save_tstate = PyThreadState_Swap(tstate);
304
305 /* XXX The following is lax in error checking */
306
307 interp->modules = PyDict_New();
308
309 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
310 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000311 interp->builtins = PyModule_GetDict(bimod);
312 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313 }
314 sysmod = _PyImport_FindExtension("sys", "sys");
315 if (bimod != NULL && sysmod != NULL) {
316 interp->sysdict = PyModule_GetDict(sysmod);
317 Py_INCREF(interp->sysdict);
318 PySys_SetPath(Py_GetPath());
319 PyDict_SetItemString(interp->sysdict, "modules",
320 interp->modules);
321 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000322 if (!Py_NoSiteFlag)
323 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000324 }
325
326 if (!PyErr_Occurred())
327 return tstate;
328
329 /* Oops, it didn't work. Undo it all. */
330
331 PyErr_Print();
332 PyThreadState_Clear(tstate);
333 PyThreadState_Swap(save_tstate);
334 PyThreadState_Delete(tstate);
335 PyInterpreterState_Delete(interp);
336
337 return NULL;
338}
339
340/* Delete an interpreter and its last thread. This requires that the
341 given thread state is current, that the thread has no remaining
342 frames, and that it is its interpreter's only remaining thread.
343 It is a fatal error to violate these constraints.
344
345 (Py_Finalize() doesn't have these constraints -- it zaps
346 everything, regardless.)
347
348 Locking: as above.
349
350*/
351
352void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000353Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000354{
355 PyInterpreterState *interp = tstate->interp;
356
357 if (tstate != PyThreadState_Get())
358 Py_FatalError("Py_EndInterpreter: thread is not current");
359 if (tstate->frame != NULL)
360 Py_FatalError("Py_EndInterpreter: thread still has a frame");
361 if (tstate != interp->tstate_head || tstate->next != NULL)
362 Py_FatalError("Py_EndInterpreter: not the last thread");
363
364 PyImport_Cleanup();
365 PyInterpreterState_Clear(interp);
366 PyThreadState_Swap(NULL);
367 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000368}
369
370static char *progname = "python";
371
372void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000373Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000374{
375 if (pn && *pn)
376 progname = pn;
377}
378
379char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000380Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000381{
382 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000383}
384
Guido van Rossuma61691e1998-02-06 22:27:24 +0000385static char *default_home = NULL;
386
387void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000388Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000389{
390 default_home = home;
391}
392
393char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000394Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000395{
396 char *home = default_home;
397 if (home == NULL)
398 home = getenv("PYTHONHOME");
399 return home;
400}
401
Guido van Rossum6135a871995-01-09 17:53:26 +0000402/* Create __main__ module */
403
404static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000405initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000406{
Guido van Rossum82598051997-03-05 00:20:32 +0000407 PyObject *m, *d;
408 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000409 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000410 Py_FatalError("can't create __main__ module");
411 d = PyModule_GetDict(m);
412 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000413 PyObject *bimod = PyImport_ImportModule("__builtin__");
414 if (bimod == NULL ||
415 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000416 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000417 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000418 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000419}
420
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000421/* Import the site module (not into __main__ though) */
422
423static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000424initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000425{
426 PyObject *m, *f;
427 m = PyImport_ImportModule("site");
428 if (m == NULL) {
429 f = PySys_GetObject("stderr");
430 if (Py_VerboseFlag) {
431 PyFile_WriteString(
432 "'import site' failed; traceback:\n", f);
433 PyErr_Print();
434 }
435 else {
436 PyFile_WriteString(
437 "'import site' failed; use -v for traceback\n", f);
438 PyErr_Clear();
439 }
440 }
441 else {
442 Py_DECREF(m);
443 }
444}
445
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000446/* Parse input from a file and execute it */
447
448int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000449PyRun_AnyFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000450{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000451 return PyRun_AnyFileEx(fp, filename, 0);
452}
453
454int
455PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
456{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000457 if (filename == NULL)
458 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000459 if (Py_FdIsInteractive(fp, filename)) {
460 int err = PyRun_InteractiveLoop(fp, filename);
461 if (closeit)
462 fclose(fp);
463 return err;
464 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000465 else
Guido van Rossum0df002c2000-08-27 19:21:52 +0000466 return PyRun_SimpleFileEx(fp, filename, closeit);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000467}
468
469int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000470PyRun_InteractiveLoop(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000471{
Guido van Rossum82598051997-03-05 00:20:32 +0000472 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000473 int ret;
Guido van Rossum82598051997-03-05 00:20:32 +0000474 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000475 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000476 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
477 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000478 }
Guido van Rossum82598051997-03-05 00:20:32 +0000479 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000480 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000481 PySys_SetObject("ps2", v = PyString_FromString("... "));
482 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000483 }
484 for (;;) {
Guido van Rossum82598051997-03-05 00:20:32 +0000485 ret = PyRun_InteractiveOne(fp, filename);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000486#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000487 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000488#endif
489 if (ret == E_EOF)
490 return 0;
491 /*
492 if (ret == E_NOMEM)
493 return -1;
494 */
495 }
496}
497
498int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000499PyRun_InteractiveOne(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000500{
Guido van Rossum82598051997-03-05 00:20:32 +0000501 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000502 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000503 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000504 char *ps1 = "", *ps2 = "";
Guido van Rossum82598051997-03-05 00:20:32 +0000505 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000506 if (v != NULL) {
507 v = PyObject_Str(v);
508 if (v == NULL)
509 PyErr_Clear();
510 else if (PyString_Check(v))
511 ps1 = PyString_AsString(v);
512 }
Guido van Rossum82598051997-03-05 00:20:32 +0000513 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000514 if (w != NULL) {
515 w = PyObject_Str(w);
516 if (w == NULL)
517 PyErr_Clear();
518 else if (PyString_Check(w))
519 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000520 }
Guido van Rossum82598051997-03-05 00:20:32 +0000521 n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar,
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000522 Py_single_input, ps1, ps2, &err);
Guido van Rossum82598051997-03-05 00:20:32 +0000523 Py_XDECREF(v);
524 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000525 if (n == NULL) {
526 if (err.error == E_EOF) {
527 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000528 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000529 return E_EOF;
530 }
531 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000532 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000533 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000534 }
Guido van Rossum82598051997-03-05 00:20:32 +0000535 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000536 if (m == NULL)
537 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000538 d = PyModule_GetDict(m);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000539 v = run_node(n, filename, d, d);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000540 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000541 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000542 return -1;
543 }
Guido van Rossum82598051997-03-05 00:20:32 +0000544 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000545 if (Py_FlushLine())
546 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000547 return 0;
548}
549
550int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000551PyRun_SimpleFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000552{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000553 return PyRun_SimpleFileEx(fp, filename, 0);
554}
555
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000556/* Check whether a file maybe a pyc file: Look at the extension,
557 the file type, and, if we may close it, at the first few bytes. */
558
559static int
560maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
561{
562 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
563 return 1;
564
565#ifdef macintosh
566 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
567 if (PyMac_getfiletype(filename) == 'PYC '
568 || PyMac_getfiletype(filename) == 'APPL')
569 return 1;
570#endif /* macintosh */
571
572 /* Only look into the file if we are allowed to close it, since
573 it then should also be seekable. */
574 if (closeit) {
575 /* Read only two bytes of the magic. If the file was opened in
576 text mode, the bytes 3 and 4 of the magic (\r\n) might not
577 be read as they are on disk. */
578 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
579 unsigned char buf[2];
Tim Petersb8584e02001-01-05 00:54:29 +0000580 if (fread(buf, 1, 2, fp) == 2
581 && ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000582 return 1;
583 fseek(fp, 0, SEEK_SET);
584 }
585 return 0;
586}
587
Guido van Rossum0df002c2000-08-27 19:21:52 +0000588int
589PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
590{
Guido van Rossum82598051997-03-05 00:20:32 +0000591 PyObject *m, *d, *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000592 char *ext;
593
Guido van Rossum82598051997-03-05 00:20:32 +0000594 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000595 if (m == NULL)
596 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000597 d = PyModule_GetDict(m);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000598 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000599 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000600 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000601 if (closeit)
602 fclose(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000603 if( (fp = fopen(filename, "rb")) == NULL ) {
604 fprintf(stderr, "python: Can't reopen .pyc file\n");
605 return -1;
606 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000607 /* Turn on optimization if a .pyo file is given */
608 if (strcmp(ext, ".pyo") == 0)
609 Py_OptimizeFlag = 1;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000610 v = run_pyc_file(fp, filename, d, d);
611 } else {
Guido van Rossum0df002c2000-08-27 19:21:52 +0000612 v = PyRun_FileEx(fp, filename, Py_file_input, d, d, closeit);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000613 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000614 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000615 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000616 return -1;
617 }
Guido van Rossum82598051997-03-05 00:20:32 +0000618 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000619 if (Py_FlushLine())
620 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000621 return 0;
622}
623
624int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000625PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000626{
Guido van Rossum82598051997-03-05 00:20:32 +0000627 PyObject *m, *d, *v;
628 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000629 if (m == NULL)
630 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000631 d = PyModule_GetDict(m);
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000632 v = PyRun_String(command, Py_file_input, d, d);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000633 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000634 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000635 return -1;
636 }
Guido van Rossum82598051997-03-05 00:20:32 +0000637 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000638 if (Py_FlushLine())
639 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000640 return 0;
641}
642
Barry Warsaw035574d1997-08-29 22:07:17 +0000643static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000644parse_syntax_error(PyObject *err, PyObject **message, char **filename,
645 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000646{
647 long hold;
648 PyObject *v;
649
650 /* old style errors */
651 if (PyTuple_Check(err))
652 return PyArg_Parse(err, "(O(ziiz))", message, filename,
653 lineno, offset, text);
654
655 /* new style errors. `err' is an instance */
656
657 if (! (v = PyObject_GetAttrString(err, "msg")))
658 goto finally;
659 *message = v;
660
661 if (!(v = PyObject_GetAttrString(err, "filename")))
662 goto finally;
663 if (v == Py_None)
664 *filename = NULL;
665 else if (! (*filename = PyString_AsString(v)))
666 goto finally;
667
668 Py_DECREF(v);
669 if (!(v = PyObject_GetAttrString(err, "lineno")))
670 goto finally;
671 hold = PyInt_AsLong(v);
672 Py_DECREF(v);
673 v = NULL;
674 if (hold < 0 && PyErr_Occurred())
675 goto finally;
676 *lineno = (int)hold;
677
678 if (!(v = PyObject_GetAttrString(err, "offset")))
679 goto finally;
680 hold = PyInt_AsLong(v);
681 Py_DECREF(v);
682 v = NULL;
683 if (hold < 0 && PyErr_Occurred())
684 goto finally;
685 *offset = (int)hold;
686
687 if (!(v = PyObject_GetAttrString(err, "text")))
688 goto finally;
689 if (v == Py_None)
690 *text = NULL;
691 else if (! (*text = PyString_AsString(v)))
692 goto finally;
693 Py_DECREF(v);
694 return 1;
695
696finally:
697 Py_XDECREF(v);
698 return 0;
699}
700
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000701void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000702PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000703{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000704 PyErr_PrintEx(1);
705}
706
707void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000708PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000709{
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000710 int err = 0;
Guido van Rossum82598051997-03-05 00:20:32 +0000711 PyObject *exception, *v, *tb, *f;
712 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000713 PyErr_NormalizeException(&exception, &v, &tb);
714
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000715 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000716 return;
Barry Warsaw035574d1997-08-29 22:07:17 +0000717
Barry Warsaw36b8f941997-08-26 18:09:48 +0000718 if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
Guido van Rossum0829c751998-02-28 04:31:39 +0000719 if (Py_FlushLine())
720 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000721 fflush(stdout);
Guido van Rossum82598051997-03-05 00:20:32 +0000722 if (v == NULL || v == Py_None)
723 Py_Exit(0);
Barry Warsaw035574d1997-08-29 22:07:17 +0000724 if (PyInstance_Check(v)) {
725 /* we expect the error code to be store in the
726 `code' attribute
727 */
728 PyObject *code = PyObject_GetAttrString(v, "code");
729 if (code) {
730 Py_DECREF(v);
731 v = code;
Guido van Rossumaa9606f1997-10-03 13:53:28 +0000732 if (v == Py_None)
733 Py_Exit(0);
Barry Warsaw035574d1997-08-29 22:07:17 +0000734 }
735 /* if we failed to dig out the "code" attribute,
736 then just let the else clause below print the
737 error
738 */
739 }
Guido van Rossum82598051997-03-05 00:20:32 +0000740 if (PyInt_Check(v))
741 Py_Exit((int)PyInt_AsLong(v));
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000742 else {
Guido van Rossum3165fe61992-09-25 21:59:05 +0000743 /* OK to use real stderr here */
Guido van Rossum82598051997-03-05 00:20:32 +0000744 PyObject_Print(v, stderr, Py_PRINT_RAW);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000745 fprintf(stderr, "\n");
Guido van Rossum82598051997-03-05 00:20:32 +0000746 Py_Exit(1);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000747 }
748 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000749 if (set_sys_last_vars) {
750 PySys_SetObject("last_type", exception);
751 PySys_SetObject("last_value", v);
752 PySys_SetObject("last_traceback", tb);
753 }
Guido van Rossum82598051997-03-05 00:20:32 +0000754 f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000755 if (f == NULL)
756 fprintf(stderr, "lost sys.stderr\n");
757 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000758 if (Py_FlushLine())
759 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000760 fflush(stdout);
Guido van Rossum0829c751998-02-28 04:31:39 +0000761 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000762 if (err == 0 &&
763 PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
764 {
Guido van Rossum82598051997-03-05 00:20:32 +0000765 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000766 char *filename, *text;
767 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000768 if (!parse_syntax_error(v, &message, &filename,
769 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000770 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000771 else {
772 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000773 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000774 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000775 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000776 else
Guido van Rossum82598051997-03-05 00:20:32 +0000777 PyFile_WriteString(filename, f);
778 PyFile_WriteString("\", line ", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000779 sprintf(buf, "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000780 PyFile_WriteString(buf, f);
781 PyFile_WriteString("\n", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000782 if (text != NULL) {
Guido van Rossum798199d1994-09-19 08:08:50 +0000783 char *nl;
784 if (offset > 0 &&
Guido van Rossum478e7181997-05-06 15:24:59 +0000785 offset == (int)strlen(text))
Guido van Rossum798199d1994-09-19 08:08:50 +0000786 offset--;
787 for (;;) {
788 nl = strchr(text, '\n');
789 if (nl == NULL ||
790 nl-text >= offset)
791 break;
792 offset -= (nl+1-text);
793 text = nl+1;
794 }
Guido van Rossuma110aa61994-08-29 12:50:44 +0000795 while (*text == ' ' || *text == '\t') {
796 text++;
797 offset--;
798 }
Guido van Rossum82598051997-03-05 00:20:32 +0000799 PyFile_WriteString(" ", f);
800 PyFile_WriteString(text, f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000801 if (*text == '\0' ||
802 text[strlen(text)-1] != '\n')
Guido van Rossum82598051997-03-05 00:20:32 +0000803 PyFile_WriteString("\n", f);
804 PyFile_WriteString(" ", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000805 offset--;
806 while (offset > 0) {
Guido van Rossum82598051997-03-05 00:20:32 +0000807 PyFile_WriteString(" ", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000808 offset--;
809 }
Guido van Rossum82598051997-03-05 00:20:32 +0000810 PyFile_WriteString("^\n", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000811 }
Guido van Rossum82598051997-03-05 00:20:32 +0000812 Py_INCREF(message);
813 Py_DECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000814 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000815 /* Can't be bothered to check all those
816 PyFile_WriteString() calls */
817 if (PyErr_Occurred())
818 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000819 }
820 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000821 if (err) {
822 /* Don't do anything else */
823 }
824 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000825 PyClassObject* exc = (PyClassObject*)exception;
826 PyObject* className = exc->cl_name;
827 PyObject* moduleName =
828 PyDict_GetItemString(exc->cl_dict, "__module__");
829
830 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000831 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000832 else {
833 char* modstr = PyString_AsString(moduleName);
834 if (modstr && strcmp(modstr, "exceptions"))
835 {
836 err = PyFile_WriteString(modstr, f);
837 err += PyFile_WriteString(".", f);
838 }
839 }
840 if (err == 0) {
841 if (className == NULL)
842 err = PyFile_WriteString("<unknown>", f);
843 else
844 err = PyFile_WriteObject(className, f,
845 Py_PRINT_RAW);
846 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000847 }
848 else
849 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
850 if (err == 0) {
851 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000852 PyObject *s = PyObject_Str(v);
853 /* only print colon if the str() of the
854 object is not the empty string
855 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000856 if (s == NULL)
857 err = -1;
858 else if (!PyString_Check(s) ||
859 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +0000860 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000861 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000862 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
863 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +0000864 }
Guido van Rossum262e1241995-02-07 15:30:45 +0000865 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000866 if (err == 0)
867 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000868 }
Guido van Rossum82598051997-03-05 00:20:32 +0000869 Py_XDECREF(exception);
870 Py_XDECREF(v);
871 Py_XDECREF(tb);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000872 /* If an error happened here, don't show it.
873 XXX This is wrong, but too many callers rely on this behavior. */
874 if (err != 0)
875 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000876}
877
Guido van Rossum82598051997-03-05 00:20:32 +0000878PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000879PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000880{
Guido van Rossum82598051997-03-05 00:20:32 +0000881 return run_err_node(PyParser_SimpleParseString(str, start),
Guido van Rossuma110aa61994-08-29 12:50:44 +0000882 "<string>", globals, locals);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000883}
884
Guido van Rossum82598051997-03-05 00:20:32 +0000885PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000886PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
887 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000888{
Tim Peterse8682112000-08-27 20:18:17 +0000889 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000890}
891
892PyObject *
893PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
894 PyObject *locals, int closeit)
895{
896 node *n = PyParser_SimpleParseFile(fp, filename, start);
897 if (closeit)
898 fclose(fp);
899 return run_err_node(n, filename, globals, locals);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000900}
901
Guido van Rossum82598051997-03-05 00:20:32 +0000902static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000903run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000904{
Guido van Rossuma110aa61994-08-29 12:50:44 +0000905 if (n == NULL)
906 return NULL;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000907 return run_node(n, filename, globals, locals);
908}
909
Guido van Rossum82598051997-03-05 00:20:32 +0000910static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000911run_node(node *n, char *filename, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000912{
Guido van Rossum82598051997-03-05 00:20:32 +0000913 PyCodeObject *co;
914 PyObject *v;
915 co = PyNode_Compile(n, filename);
916 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000917 if (co == NULL)
918 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +0000919 v = PyEval_EvalCode(co, globals, locals);
920 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000921 return v;
922}
923
Guido van Rossum82598051997-03-05 00:20:32 +0000924static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000925run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals)
Guido van Rossumfdef2711994-09-14 13:31:04 +0000926{
Guido van Rossum82598051997-03-05 00:20:32 +0000927 PyCodeObject *co;
928 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000929 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +0000930 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000931
Guido van Rossum82598051997-03-05 00:20:32 +0000932 magic = PyMarshal_ReadLongFromFile(fp);
933 if (magic != PyImport_GetMagicNumber()) {
934 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +0000935 "Bad magic number in .pyc file");
936 return NULL;
937 }
Guido van Rossum82598051997-03-05 00:20:32 +0000938 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +0000939 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000940 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +0000941 if (v == NULL || !PyCode_Check(v)) {
942 Py_XDECREF(v);
943 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +0000944 "Bad code object in .pyc file");
945 return NULL;
946 }
Guido van Rossum82598051997-03-05 00:20:32 +0000947 co = (PyCodeObject *)v;
948 v = PyEval_EvalCode(co, globals, locals);
949 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000950 return v;
951}
952
Guido van Rossum82598051997-03-05 00:20:32 +0000953PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000954Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +0000955{
956 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +0000957 PyCodeObject *co;
958 n = PyParser_SimpleParseString(str, start);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000959 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +0000960 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +0000961 co = PyNode_Compile(n, filename);
962 PyNode_Free(n);
963 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +0000964}
965
Guido van Rossuma110aa61994-08-29 12:50:44 +0000966/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000967
Guido van Rossuma110aa61994-08-29 12:50:44 +0000968node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000969PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000970{
Guido van Rossuma110aa61994-08-29 12:50:44 +0000971 node *n;
972 perrdetail err;
Guido van Rossum82598051997-03-05 00:20:32 +0000973 n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar, start,
Guido van Rossuma110aa61994-08-29 12:50:44 +0000974 (char *)0, (char *)0, &err);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000975 if (n == NULL)
976 err_input(&err);
977 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000978}
979
Guido van Rossuma110aa61994-08-29 12:50:44 +0000980/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000981
Guido van Rossuma110aa61994-08-29 12:50:44 +0000982node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000983PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000984{
Guido van Rossuma110aa61994-08-29 12:50:44 +0000985 node *n;
986 perrdetail err;
Guido van Rossum82598051997-03-05 00:20:32 +0000987 n = PyParser_ParseString(str, &_PyParser_Grammar, start, &err);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000988 if (n == NULL)
989 err_input(&err);
990 return n;
991}
992
993/* Set the error appropriate to the given input error code (see errcode.h) */
994
995static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000996err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +0000997{
Fred Drake85f36392000-07-11 17:53:00 +0000998 PyObject *v, *w, *errtype;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000999 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001000 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001001 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001002 err->lineno, err->offset, err->text);
1003 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001004 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001005 err->text = NULL;
1006 }
1007 switch (err->error) {
1008 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001009 errtype = PyExc_IndentationError;
1010 if (err->expected == INDENT)
1011 msg = "expected an indented block";
1012 else if (err->token == INDENT)
1013 msg = "unexpected indent";
1014 else if (err->token == DEDENT)
1015 msg = "unexpected unindent";
1016 else {
1017 errtype = PyExc_SyntaxError;
1018 msg = "invalid syntax";
1019 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001020 break;
1021 case E_TOKEN:
1022 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001023 break;
1024 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001025 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001026 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001027 return;
1028 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001029 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001030 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001031 return;
1032 case E_EOF:
1033 msg = "unexpected EOF while parsing";
1034 break;
Fred Drake85f36392000-07-11 17:53:00 +00001035 case E_TABSPACE:
1036 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001037 msg = "inconsistent use of tabs and spaces in indentation";
1038 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001039 case E_OVERFLOW:
1040 msg = "expression too long";
1041 break;
Fred Drake85f36392000-07-11 17:53:00 +00001042 case E_DEDENT:
1043 errtype = PyExc_IndentationError;
1044 msg = "unindent does not match any outer indentation level";
1045 break;
1046 case E_TOODEEP:
1047 errtype = PyExc_IndentationError;
1048 msg = "too many levels of indentation";
1049 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001050 default:
1051 fprintf(stderr, "error=%d\n", err->error);
1052 msg = "unknown parsing error";
1053 break;
1054 }
Guido van Rossum82598051997-03-05 00:20:32 +00001055 w = Py_BuildValue("(sO)", msg, v);
Fred Drake85f36392000-07-11 17:53:00 +00001056 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001057 Py_XDECREF(w);
Fred Drake83cb7972000-08-15 15:49:03 +00001058
1059 if (v != NULL) {
1060 PyObject *exc, *tb;
1061
1062 PyErr_Fetch(&errtype, &exc, &tb);
1063 PyErr_NormalizeException(&errtype, &exc, &tb);
1064 if (PyObject_SetAttrString(exc, "filename",
1065 PyTuple_GET_ITEM(v, 0)))
1066 PyErr_Clear();
1067 if (PyObject_SetAttrString(exc, "lineno",
1068 PyTuple_GET_ITEM(v, 1)))
1069 PyErr_Clear();
1070 if (PyObject_SetAttrString(exc, "offset",
1071 PyTuple_GET_ITEM(v, 2)))
1072 PyErr_Clear();
1073 Py_DECREF(v);
1074 PyErr_Restore(errtype, exc, tb);
1075 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001076}
1077
1078/* Print fatal error message and abort */
1079
1080void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001081Py_FatalError(char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001082{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001083 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001084#ifdef macintosh
1085 for (;;);
1086#endif
Guido van Rossum9b38a141996-09-11 23:12:24 +00001087#ifdef MS_WIN32
Guido van Rossum23c94461997-05-22 20:21:30 +00001088 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001089 OutputDebugString(msg);
1090 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001091#ifdef _DEBUG
1092 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001093#endif
Guido van Rossum0ba35361998-08-13 13:33:16 +00001094#endif /* MS_WIN32 */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001095 abort();
1096}
1097
1098/* Clean up and exit */
1099
Guido van Rossuma110aa61994-08-29 12:50:44 +00001100#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001101#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001102int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001103#endif
1104
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001105#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001106static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001107static int nexitfuncs = 0;
1108
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001109int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001110{
1111 if (nexitfuncs >= NEXITFUNCS)
1112 return -1;
1113 exitfuncs[nexitfuncs++] = func;
1114 return 0;
1115}
1116
Guido van Rossumcc283f51997-08-05 02:22:03 +00001117static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001118call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001119{
Guido van Rossum82598051997-03-05 00:20:32 +00001120 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001121
1122 if (exitfunc) {
Guido van Rossumbf02fb21998-04-03 21:12:12 +00001123 PyObject *res, *f;
Guido van Rossum82598051997-03-05 00:20:32 +00001124 Py_INCREF(exitfunc);
1125 PySys_SetObject("exitfunc", (PyObject *)NULL);
Guido van Rossumbf02fb21998-04-03 21:12:12 +00001126 f = PySys_GetObject("stderr");
Guido van Rossum82598051997-03-05 00:20:32 +00001127 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001128 if (res == NULL) {
Guido van Rossumbf02fb21998-04-03 21:12:12 +00001129 if (f)
1130 PyFile_WriteString("Error in sys.exitfunc:\n", f);
Guido van Rossum82598051997-03-05 00:20:32 +00001131 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001132 }
Guido van Rossum82598051997-03-05 00:20:32 +00001133 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001134 }
1135
Guido van Rossum0829c751998-02-28 04:31:39 +00001136 if (Py_FlushLine())
1137 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001138}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001139
Guido van Rossumcc283f51997-08-05 02:22:03 +00001140static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001141call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001142{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001143 while (nexitfuncs > 0)
1144 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001145
1146 fflush(stdout);
1147 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001148}
1149
1150void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001151Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001152{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001153 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001154
Jack Jansen66a89771995-10-27 13:22:14 +00001155#ifdef macintosh
1156 PyMac_Exit(sts);
1157#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001158 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001159#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001160}
1161
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001162static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001163initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001164{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001165#ifdef HAVE_SIGNAL_H
1166#ifdef SIGPIPE
1167 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001168#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001169#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001170 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001171}
1172
Guido van Rossumaae0d321996-05-22 16:35:33 +00001173#ifdef Py_TRACE_REFS
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001174/* Ask a yes/no question */
1175
Guido van Rossum59bff391992-09-03 20:28:00 +00001176int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001177_Py_AskYesNo(char *prompt)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001178{
1179 char buf[256];
1180
1181 printf("%s [ny] ", prompt);
1182 if (fgets(buf, sizeof buf, stdin) == NULL)
1183 return 0;
1184 return buf[0] == 'y' || buf[0] == 'Y';
1185}
1186#endif
1187
Guido van Rossuma110aa61994-08-29 12:50:44 +00001188#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001189
1190/* Check for file descriptor connected to interactive device.
1191 Pretend that stdin is always interactive, other files never. */
1192
1193int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001194isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001195{
1196 return fd == fileno(stdin);
1197}
1198
1199#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001200
1201/*
1202 * The file descriptor fd is considered ``interactive'' if either
1203 * a) isatty(fd) is TRUE, or
1204 * b) the -i flag was given, and the filename associated with
1205 * the descriptor is NULL or "<stdin>" or "???".
1206 */
1207int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001208Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001209{
1210 if (isatty((int)fileno(fp)))
1211 return 1;
1212 if (!Py_InteractiveFlag)
1213 return 0;
1214 return (filename == NULL) ||
1215 (strcmp(filename, "<stdin>") == 0) ||
1216 (strcmp(filename, "???") == 0);
1217}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001218
1219
1220#if defined(USE_STACKCHECK)
1221#if defined(WIN32) && defined(_MSC_VER)
1222
1223/* Stack checking for Microsoft C */
1224
1225#include <malloc.h>
1226#include <excpt.h>
1227
Fred Drakee8de31c2000-08-31 05:38:39 +00001228/*
1229 * Return non-zero when we run out of memory on the stack; zero otherwise.
1230 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001231int
Fred Drake399739f2000-08-31 05:52:44 +00001232PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001233{
1234 __try {
1235 /* _alloca throws a stack overflow exception if there's
1236 not enough space left on the stack */
1237 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1238 return 0;
1239 } __except (EXCEPTION_EXECUTE_HANDLER) {
1240 /* just ignore all errors */
1241 }
1242 return 1;
1243}
1244
1245#endif /* WIN32 && _MSC_VER */
1246
1247/* Alternate implementations can be added here... */
1248
1249#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001250
1251
1252/* Wrappers around sigaction() or signal(). */
1253
1254PyOS_sighandler_t
1255PyOS_getsig(int sig)
1256{
1257#ifdef HAVE_SIGACTION
1258 struct sigaction context;
1259 sigaction(sig, NULL, &context);
1260 return context.sa_handler;
1261#else
1262 PyOS_sighandler_t handler;
1263 handler = signal(sig, SIG_IGN);
1264 signal(sig, handler);
1265 return handler;
1266#endif
1267}
1268
1269PyOS_sighandler_t
1270PyOS_setsig(int sig, PyOS_sighandler_t handler)
1271{
1272#ifdef HAVE_SIGACTION
1273 struct sigaction context;
1274 PyOS_sighandler_t oldhandler;
1275 sigaction(sig, NULL, &context);
1276 oldhandler = context.sa_handler;
1277 context.sa_handler = handler;
1278 sigaction(sig, &context, NULL);
1279 return oldhandler;
1280#else
1281 return signal(sig, handler);
1282#endif
1283}