This commit was manufactured by cvs2svn to create tag 'r22a4-fork'.
[python/dscho.git] / Python / pythonrun.c
blob8dd9c14c3b402852661b98ff2454263dc9253f0b
2 /* Python interpreter top-level routines, including init/exit */
4 #include "Python.h"
6 #include "grammar.h"
7 #include "node.h"
8 #include "token.h"
9 #include "parsetok.h"
10 #include "errcode.h"
11 #include "compile.h"
12 #include "symtable.h"
13 #include "eval.h"
14 #include "marshal.h"
16 #ifdef HAVE_UNISTD_H
17 #include <unistd.h>
18 #endif
20 #ifdef HAVE_SIGNAL_H
21 #include <signal.h>
22 #endif
24 #ifdef MS_WIN32
25 #undef BYTE
26 #include "windows.h"
27 #endif
29 #ifdef macintosh
30 #include "macglue.h"
31 #endif
32 extern char *Py_GetPath(void);
34 extern grammar _PyParser_Grammar; /* From graminit.c */
36 /* Forward */
37 static void initmain(void);
38 static void initsite(void);
39 static PyObject *run_err_node(node *, char *, PyObject *, PyObject *,
40 PyCompilerFlags *);
41 static PyObject *run_node(node *, char *, PyObject *, PyObject *,
42 PyCompilerFlags *);
43 static PyObject *run_pyc_file(FILE *, char *, PyObject *, PyObject *,
44 PyCompilerFlags *);
45 static void err_input(perrdetail *);
46 static void initsigs(void);
47 static void call_sys_exitfunc(void);
48 static void call_ll_exitfuncs(void);
50 #ifdef Py_TRACE_REFS
51 int _Py_AskYesNo(char *prompt);
52 #endif
54 extern void _PyUnicode_Init(void);
55 extern void _PyUnicode_Fini(void);
56 extern void _PyCodecRegistry_Init(void);
57 extern void _PyCodecRegistry_Fini(void);
59 int Py_DebugFlag; /* Needed by parser.c */
60 int Py_VerboseFlag; /* Needed by import.c */
61 int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
62 int Py_NoSiteFlag; /* Suppress 'import site' */
63 int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
64 int Py_FrozenFlag; /* Needed by getpath.c */
65 int Py_UnicodeFlag = 0; /* Needed by compile.c */
66 int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
68 static int initialized = 0;
70 /* API to access the initialized flag -- useful for esoteric use */
72 int
73 Py_IsInitialized(void)
75 return initialized;
78 /* 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.
84 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.)
90 void
91 Py_Initialize(void)
93 PyInterpreterState *interp;
94 PyThreadState *tstate;
95 PyObject *bimod, *sysmod;
96 char *p;
97 extern void _Py_ReadyTypes(void);
99 if (initialized)
100 return;
101 initialized = 1;
103 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
104 Py_DebugFlag = Py_DebugFlag ? Py_DebugFlag : 1;
105 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
106 Py_VerboseFlag = Py_VerboseFlag ? Py_VerboseFlag : 1;
107 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
108 Py_OptimizeFlag = Py_OptimizeFlag ? Py_OptimizeFlag : 1;
110 interp = PyInterpreterState_New();
111 if (interp == NULL)
112 Py_FatalError("Py_Initialize: can't make first interpreter");
114 tstate = PyThreadState_New(interp);
115 if (tstate == NULL)
116 Py_FatalError("Py_Initialize: can't make first thread");
117 (void) PyThreadState_Swap(tstate);
119 _Py_ReadyTypes();
121 interp->modules = PyDict_New();
122 if (interp->modules == NULL)
123 Py_FatalError("Py_Initialize: can't make modules dictionary");
125 /* Init codec registry */
126 _PyCodecRegistry_Init();
128 #ifdef Py_USING_UNICODE
129 /* Init Unicode implementation; relies on the codec registry */
130 _PyUnicode_Init();
131 #endif
133 bimod = _PyBuiltin_Init();
134 if (bimod == NULL)
135 Py_FatalError("Py_Initialize: can't initialize __builtin__");
136 interp->builtins = PyModule_GetDict(bimod);
137 Py_INCREF(interp->builtins);
139 sysmod = _PySys_Init();
140 if (sysmod == NULL)
141 Py_FatalError("Py_Initialize: can't initialize sys");
142 interp->sysdict = PyModule_GetDict(sysmod);
143 Py_INCREF(interp->sysdict);
144 _PyImport_FixupExtension("sys", "sys");
145 PySys_SetPath(Py_GetPath());
146 PyDict_SetItemString(interp->sysdict, "modules",
147 interp->modules);
149 _PyImport_Init();
151 /* initialize builtin exceptions */
152 _PyExc_Init();
153 _PyImport_FixupExtension("exceptions", "exceptions");
155 /* phase 2 of builtins */
156 _PyImport_FixupExtension("__builtin__", "__builtin__");
158 initsigs(); /* Signal handling stuff, including initintr() */
160 initmain(); /* Module __main__ */
161 if (!Py_NoSiteFlag)
162 initsite(); /* Module site */
165 #ifdef COUNT_ALLOCS
166 extern void dump_counts(void);
167 #endif
169 /* Undo the effect of Py_Initialize().
171 Beware: if multiple interpreter and/or thread states exist, these
172 are not wiped out; only the current thread and interpreter state
173 are deleted. But since everything else is deleted, those other
174 interpreter and thread states should no longer be used.
176 (XXX We should do better, e.g. wipe out all interpreters and
177 threads.)
179 Locking: as above.
183 void
184 Py_Finalize(void)
186 PyInterpreterState *interp;
187 PyThreadState *tstate;
189 if (!initialized)
190 return;
192 /* The interpreter is still entirely intact at this point, and the
193 * exit funcs may be relying on that. In particular, if some thread
194 * or exit func is still waiting to do an import, the import machinery
195 * expects Py_IsInitialized() to return true. So don't say the
196 * interpreter is uninitialized until after the exit funcs have run.
197 * Note that Threading.py uses an exit func to do a join on all the
198 * threads created thru it, so this also protects pending imports in
199 * the threads created via Threading.
201 call_sys_exitfunc();
202 initialized = 0;
204 /* Get current thread state and interpreter pointer */
205 tstate = PyThreadState_Get();
206 interp = tstate->interp;
208 /* Disable signal handling */
209 PyOS_FiniInterrupts();
211 #ifdef Py_USING_UNICODE
212 /* Cleanup Unicode implementation */
213 _PyUnicode_Fini();
214 #endif
216 /* Cleanup Codec registry */
217 _PyCodecRegistry_Fini();
219 /* Destroy all modules */
220 PyImport_Cleanup();
222 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
223 _PyImport_Fini();
225 /* Debugging stuff */
226 #ifdef COUNT_ALLOCS
227 dump_counts();
228 #endif
230 #ifdef Py_REF_DEBUG
231 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
232 #endif
234 #ifdef Py_TRACE_REFS
235 if (Py_GETENV("PYTHONDUMPREFS")) {
236 _Py_PrintReferences(stderr);
238 #endif /* Py_TRACE_REFS */
240 /* Now we decref the exception classes. After this point nothing
241 can raise an exception. That's okay, because each Fini() method
242 below has been checked to make sure no exceptions are ever
243 raised.
245 _PyExc_Fini();
247 /* Delete current thread */
248 PyInterpreterState_Clear(interp);
249 PyThreadState_Swap(NULL);
250 PyInterpreterState_Delete(interp);
252 PyMethod_Fini();
253 PyFrame_Fini();
254 PyCFunction_Fini();
255 PyTuple_Fini();
256 PyString_Fini();
257 PyInt_Fini();
258 PyFloat_Fini();
260 /* XXX Still allocated:
261 - various static ad-hoc pointers to interned strings
262 - int and float free list blocks
263 - whatever various modules and libraries allocate
266 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
268 call_ll_exitfuncs();
270 #ifdef Py_TRACE_REFS
271 _Py_ResetReferences();
272 #endif /* Py_TRACE_REFS */
275 /* Create and initialize a new interpreter and thread, and return the
276 new thread. This requires that Py_Initialize() has been called
277 first.
279 Unsuccessful initialization yields a NULL pointer. Note that *no*
280 exception information is available even in this case -- the
281 exception information is held in the thread, and there is no
282 thread.
284 Locking: as above.
288 PyThreadState *
289 Py_NewInterpreter(void)
291 PyInterpreterState *interp;
292 PyThreadState *tstate, *save_tstate;
293 PyObject *bimod, *sysmod;
295 if (!initialized)
296 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
298 interp = PyInterpreterState_New();
299 if (interp == NULL)
300 return NULL;
302 tstate = PyThreadState_New(interp);
303 if (tstate == NULL) {
304 PyInterpreterState_Delete(interp);
305 return NULL;
308 save_tstate = PyThreadState_Swap(tstate);
310 /* XXX The following is lax in error checking */
312 interp->modules = PyDict_New();
314 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
315 if (bimod != NULL) {
316 interp->builtins = PyModule_GetDict(bimod);
317 Py_INCREF(interp->builtins);
319 sysmod = _PyImport_FindExtension("sys", "sys");
320 if (bimod != NULL && sysmod != NULL) {
321 interp->sysdict = PyModule_GetDict(sysmod);
322 Py_INCREF(interp->sysdict);
323 PySys_SetPath(Py_GetPath());
324 PyDict_SetItemString(interp->sysdict, "modules",
325 interp->modules);
326 initmain();
327 if (!Py_NoSiteFlag)
328 initsite();
331 if (!PyErr_Occurred())
332 return tstate;
334 /* Oops, it didn't work. Undo it all. */
336 PyErr_Print();
337 PyThreadState_Clear(tstate);
338 PyThreadState_Swap(save_tstate);
339 PyThreadState_Delete(tstate);
340 PyInterpreterState_Delete(interp);
342 return NULL;
345 /* Delete an interpreter and its last thread. This requires that the
346 given thread state is current, that the thread has no remaining
347 frames, and that it is its interpreter's only remaining thread.
348 It is a fatal error to violate these constraints.
350 (Py_Finalize() doesn't have these constraints -- it zaps
351 everything, regardless.)
353 Locking: as above.
357 void
358 Py_EndInterpreter(PyThreadState *tstate)
360 PyInterpreterState *interp = tstate->interp;
362 if (tstate != PyThreadState_Get())
363 Py_FatalError("Py_EndInterpreter: thread is not current");
364 if (tstate->frame != NULL)
365 Py_FatalError("Py_EndInterpreter: thread still has a frame");
366 if (tstate != interp->tstate_head || tstate->next != NULL)
367 Py_FatalError("Py_EndInterpreter: not the last thread");
369 PyImport_Cleanup();
370 PyInterpreterState_Clear(interp);
371 PyThreadState_Swap(NULL);
372 PyInterpreterState_Delete(interp);
375 static char *progname = "python";
377 void
378 Py_SetProgramName(char *pn)
380 if (pn && *pn)
381 progname = pn;
384 char *
385 Py_GetProgramName(void)
387 return progname;
390 static char *default_home = NULL;
392 void
393 Py_SetPythonHome(char *home)
395 default_home = home;
398 char *
399 Py_GetPythonHome(void)
401 char *home = default_home;
402 if (home == NULL && !Py_IgnoreEnvironmentFlag)
403 home = Py_GETENV("PYTHONHOME");
404 return home;
407 /* Create __main__ module */
409 static void
410 initmain(void)
412 PyObject *m, *d;
413 m = PyImport_AddModule("__main__");
414 if (m == NULL)
415 Py_FatalError("can't create __main__ module");
416 d = PyModule_GetDict(m);
417 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
418 PyObject *bimod = PyImport_ImportModule("__builtin__");
419 if (bimod == NULL ||
420 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
421 Py_FatalError("can't add __builtins__ to __main__");
422 Py_DECREF(bimod);
426 /* Import the site module (not into __main__ though) */
428 static void
429 initsite(void)
431 PyObject *m, *f;
432 m = PyImport_ImportModule("site");
433 if (m == NULL) {
434 f = PySys_GetObject("stderr");
435 if (Py_VerboseFlag) {
436 PyFile_WriteString(
437 "'import site' failed; traceback:\n", f);
438 PyErr_Print();
440 else {
441 PyFile_WriteString(
442 "'import site' failed; use -v for traceback\n", f);
443 PyErr_Clear();
446 else {
447 Py_DECREF(m);
451 /* Parse input from a file and execute it */
454 PyRun_AnyFile(FILE *fp, char *filename)
456 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
460 PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
462 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
466 PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
468 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
472 PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
473 PyCompilerFlags *flags)
475 if (filename == NULL)
476 filename = "???";
477 if (Py_FdIsInteractive(fp, filename)) {
478 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
479 if (closeit)
480 fclose(fp);
481 return err;
483 else
484 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
488 PyRun_InteractiveLoop(FILE *fp, char *filename)
490 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
494 PyRun_InteractiveLoopFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
496 PyObject *v;
497 int ret;
498 PyCompilerFlags local_flags;
500 if (flags == NULL) {
501 flags = &local_flags;
502 local_flags.cf_flags = 0;
504 v = PySys_GetObject("ps1");
505 if (v == NULL) {
506 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
507 Py_XDECREF(v);
509 v = PySys_GetObject("ps2");
510 if (v == NULL) {
511 PySys_SetObject("ps2", v = PyString_FromString("... "));
512 Py_XDECREF(v);
514 for (;;) {
515 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
516 #ifdef Py_REF_DEBUG
517 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
518 #endif
519 if (ret == E_EOF)
520 return 0;
522 if (ret == E_NOMEM)
523 return -1;
529 PyRun_InteractiveOne(FILE *fp, char *filename)
531 return PyRun_InteractiveOneFlags(fp, filename, NULL);
535 PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
537 PyObject *m, *d, *v, *w;
538 node *n;
539 perrdetail err;
540 char *ps1 = "", *ps2 = "";
542 v = PySys_GetObject("ps1");
543 if (v != NULL) {
544 v = PyObject_Str(v);
545 if (v == NULL)
546 PyErr_Clear();
547 else if (PyString_Check(v))
548 ps1 = PyString_AsString(v);
550 w = PySys_GetObject("ps2");
551 if (w != NULL) {
552 w = PyObject_Str(w);
553 if (w == NULL)
554 PyErr_Clear();
555 else if (PyString_Check(w))
556 ps2 = PyString_AsString(w);
558 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
559 Py_single_input, ps1, ps2, &err,
560 (flags &&
561 flags->cf_flags & CO_GENERATOR_ALLOWED) ?
562 PyPARSE_YIELD_IS_KEYWORD : 0);
563 Py_XDECREF(v);
564 Py_XDECREF(w);
565 if (n == NULL) {
566 if (err.error == E_EOF) {
567 if (err.text)
568 PyMem_DEL(err.text);
569 return E_EOF;
571 err_input(&err);
572 PyErr_Print();
573 return err.error;
575 m = PyImport_AddModule("__main__");
576 if (m == NULL)
577 return -1;
578 d = PyModule_GetDict(m);
579 v = run_node(n, filename, d, d, flags);
580 if (v == NULL) {
581 PyErr_Print();
582 return -1;
584 Py_DECREF(v);
585 if (Py_FlushLine())
586 PyErr_Clear();
587 return 0;
591 PyRun_SimpleFile(FILE *fp, char *filename)
593 return PyRun_SimpleFileEx(fp, filename, 0);
596 /* Check whether a file maybe a pyc file: Look at the extension,
597 the file type, and, if we may close it, at the first few bytes. */
599 static int
600 maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
602 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
603 return 1;
605 #ifdef macintosh
606 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
607 if (PyMac_getfiletype(filename) == 'PYC '
608 || PyMac_getfiletype(filename) == 'APPL')
609 return 1;
610 #endif /* macintosh */
612 /* Only look into the file if we are allowed to close it, since
613 it then should also be seekable. */
614 if (closeit) {
615 /* Read only two bytes of the magic. If the file was opened in
616 text mode, the bytes 3 and 4 of the magic (\r\n) might not
617 be read as they are on disk. */
618 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
619 unsigned char buf[2];
620 /* Mess: In case of -x, the stream is NOT at its start now,
621 and ungetc() was used to push back the first newline,
622 which makes the current stream position formally undefined,
623 and a x-platform nightmare.
624 Unfortunately, we have no direct way to know whether -x
625 was specified. So we use a terrible hack: if the current
626 stream position is not 0, we assume -x was specified, and
627 give up. Bug 132850 on SourceForge spells out the
628 hopelessness of trying anything else (fseek and ftell
629 don't work predictably x-platform for text-mode files).
631 int ispyc = 0;
632 if (ftell(fp) == 0) {
633 if (fread(buf, 1, 2, fp) == 2 &&
634 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
635 ispyc = 1;
636 rewind(fp);
638 return ispyc;
640 return 0;
644 PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
646 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
650 PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit,
651 PyCompilerFlags *flags)
653 PyObject *m, *d, *v;
654 char *ext;
656 m = PyImport_AddModule("__main__");
657 if (m == NULL)
658 return -1;
659 d = PyModule_GetDict(m);
660 ext = filename + strlen(filename) - 4;
661 if (maybe_pyc_file(fp, filename, ext, closeit)) {
662 /* Try to run a pyc file. First, re-open in binary */
663 if (closeit)
664 fclose(fp);
665 if( (fp = fopen(filename, "rb")) == NULL ) {
666 fprintf(stderr, "python: Can't reopen .pyc file\n");
667 return -1;
669 /* Turn on optimization if a .pyo file is given */
670 if (strcmp(ext, ".pyo") == 0)
671 Py_OptimizeFlag = 1;
672 v = run_pyc_file(fp, filename, d, d, flags);
673 } else {
674 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
675 closeit, flags);
677 if (v == NULL) {
678 PyErr_Print();
679 return -1;
681 Py_DECREF(v);
682 if (Py_FlushLine())
683 PyErr_Clear();
684 return 0;
688 PyRun_SimpleString(char *command)
690 return PyRun_SimpleStringFlags(command, NULL);
694 PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
696 PyObject *m, *d, *v;
697 m = PyImport_AddModule("__main__");
698 if (m == NULL)
699 return -1;
700 d = PyModule_GetDict(m);
701 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
702 if (v == NULL) {
703 PyErr_Print();
704 return -1;
706 Py_DECREF(v);
707 if (Py_FlushLine())
708 PyErr_Clear();
709 return 0;
712 static int
713 parse_syntax_error(PyObject *err, PyObject **message, char **filename,
714 int *lineno, int *offset, char **text)
716 long hold;
717 PyObject *v;
719 /* old style errors */
720 if (PyTuple_Check(err))
721 return PyArg_Parse(err, "(O(ziiz))", message, filename,
722 lineno, offset, text);
724 /* new style errors. `err' is an instance */
726 if (! (v = PyObject_GetAttrString(err, "msg")))
727 goto finally;
728 *message = v;
730 if (!(v = PyObject_GetAttrString(err, "filename")))
731 goto finally;
732 if (v == Py_None)
733 *filename = NULL;
734 else if (! (*filename = PyString_AsString(v)))
735 goto finally;
737 Py_DECREF(v);
738 if (!(v = PyObject_GetAttrString(err, "lineno")))
739 goto finally;
740 hold = PyInt_AsLong(v);
741 Py_DECREF(v);
742 v = NULL;
743 if (hold < 0 && PyErr_Occurred())
744 goto finally;
745 *lineno = (int)hold;
747 if (!(v = PyObject_GetAttrString(err, "offset")))
748 goto finally;
749 if (v == Py_None) {
750 *offset = -1;
751 Py_DECREF(v);
752 v = NULL;
753 } else {
754 hold = PyInt_AsLong(v);
755 Py_DECREF(v);
756 v = NULL;
757 if (hold < 0 && PyErr_Occurred())
758 goto finally;
759 *offset = (int)hold;
762 if (!(v = PyObject_GetAttrString(err, "text")))
763 goto finally;
764 if (v == Py_None)
765 *text = NULL;
766 else if (! (*text = PyString_AsString(v)))
767 goto finally;
768 Py_DECREF(v);
769 return 1;
771 finally:
772 Py_XDECREF(v);
773 return 0;
776 void
777 PyErr_Print(void)
779 PyErr_PrintEx(1);
782 static void
783 print_error_text(PyObject *f, int offset, char *text)
785 char *nl;
786 if (offset >= 0) {
787 if (offset > 0 && offset == (int)strlen(text))
788 offset--;
789 for (;;) {
790 nl = strchr(text, '\n');
791 if (nl == NULL || nl-text >= offset)
792 break;
793 offset -= (nl+1-text);
794 text = nl+1;
796 while (*text == ' ' || *text == '\t') {
797 text++;
798 offset--;
801 PyFile_WriteString(" ", f);
802 PyFile_WriteString(text, f);
803 if (*text == '\0' || text[strlen(text)-1] != '\n')
804 PyFile_WriteString("\n", f);
805 if (offset == -1)
806 return;
807 PyFile_WriteString(" ", f);
808 offset--;
809 while (offset > 0) {
810 PyFile_WriteString(" ", f);
811 offset--;
813 PyFile_WriteString("^\n", f);
816 static void
817 handle_system_exit(void)
819 PyObject *exception, *value, *tb;
820 PyErr_Fetch(&exception, &value, &tb);
821 if (Py_FlushLine())
822 PyErr_Clear();
823 fflush(stdout);
824 if (value == NULL || value == Py_None)
825 Py_Exit(0);
826 if (PyInstance_Check(value)) {
827 /* The error code should be in the `code' attribute. */
828 PyObject *code = PyObject_GetAttrString(value, "code");
829 if (code) {
830 Py_DECREF(value);
831 value = code;
832 if (value == Py_None)
833 Py_Exit(0);
835 /* If we failed to dig out the 'code' attribute,
836 just let the else clause below print the error. */
838 if (PyInt_Check(value))
839 Py_Exit((int)PyInt_AsLong(value));
840 else {
841 PyObject_Print(value, stderr, Py_PRINT_RAW);
842 PySys_WriteStderr("\n");
843 Py_Exit(1);
847 void
848 PyErr_PrintEx(int set_sys_last_vars)
850 PyObject *exception, *v, *tb, *hook;
852 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
853 handle_system_exit();
855 PyErr_Fetch(&exception, &v, &tb);
856 PyErr_NormalizeException(&exception, &v, &tb);
857 if (exception == NULL)
858 return;
859 if (set_sys_last_vars) {
860 PySys_SetObject("last_type", exception);
861 PySys_SetObject("last_value", v);
862 PySys_SetObject("last_traceback", tb);
864 hook = PySys_GetObject("excepthook");
865 if (hook) {
866 PyObject *args = Py_BuildValue("(OOO)",
867 exception, v ? v : Py_None, tb ? tb : Py_None);
868 PyObject *result = PyEval_CallObject(hook, args);
869 if (result == NULL) {
870 PyObject *exception2, *v2, *tb2;
871 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
872 handle_system_exit();
874 PyErr_Fetch(&exception2, &v2, &tb2);
875 PyErr_NormalizeException(&exception2, &v2, &tb2);
876 if (Py_FlushLine())
877 PyErr_Clear();
878 fflush(stdout);
879 PySys_WriteStderr("Error in sys.excepthook:\n");
880 PyErr_Display(exception2, v2, tb2);
881 PySys_WriteStderr("\nOriginal exception was:\n");
882 PyErr_Display(exception, v, tb);
884 Py_XDECREF(result);
885 Py_XDECREF(args);
886 } else {
887 PySys_WriteStderr("sys.excepthook is missing\n");
888 PyErr_Display(exception, v, tb);
890 Py_XDECREF(exception);
891 Py_XDECREF(v);
892 Py_XDECREF(tb);
895 void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
897 int err = 0;
898 PyObject *v = value;
899 PyObject *f = PySys_GetObject("stderr");
900 if (f == NULL)
901 fprintf(stderr, "lost sys.stderr\n");
902 else {
903 if (Py_FlushLine())
904 PyErr_Clear();
905 fflush(stdout);
906 if (tb && tb != Py_None)
907 err = PyTraceBack_Print(tb, f);
908 if (err == 0 &&
909 PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
911 PyObject *message;
912 char *filename, *text;
913 int lineno, offset;
914 if (!parse_syntax_error(v, &message, &filename,
915 &lineno, &offset, &text))
916 PyErr_Clear();
917 else {
918 char buf[10];
919 PyFile_WriteString(" File \"", f);
920 if (filename == NULL)
921 PyFile_WriteString("<string>", f);
922 else
923 PyFile_WriteString(filename, f);
924 PyFile_WriteString("\", line ", f);
925 sprintf(buf, "%d", lineno);
926 PyFile_WriteString(buf, f);
927 PyFile_WriteString("\n", f);
928 if (text != NULL)
929 print_error_text(f, offset, text);
930 v = message;
931 /* Can't be bothered to check all those
932 PyFile_WriteString() calls */
933 if (PyErr_Occurred())
934 err = -1;
937 if (err) {
938 /* Don't do anything else */
940 else if (PyClass_Check(exception)) {
941 PyClassObject* exc = (PyClassObject*)exception;
942 PyObject* className = exc->cl_name;
943 PyObject* moduleName =
944 PyDict_GetItemString(exc->cl_dict, "__module__");
946 if (moduleName == NULL)
947 err = PyFile_WriteString("<unknown>", f);
948 else {
949 char* modstr = PyString_AsString(moduleName);
950 if (modstr && strcmp(modstr, "exceptions"))
952 err = PyFile_WriteString(modstr, f);
953 err += PyFile_WriteString(".", f);
956 if (err == 0) {
957 if (className == NULL)
958 err = PyFile_WriteString("<unknown>", f);
959 else
960 err = PyFile_WriteObject(className, f,
961 Py_PRINT_RAW);
964 else
965 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
966 if (err == 0) {
967 if (v != NULL && v != Py_None) {
968 PyObject *s = PyObject_Str(v);
969 /* only print colon if the str() of the
970 object is not the empty string
972 if (s == NULL)
973 err = -1;
974 else if (!PyString_Check(s) ||
975 PyString_GET_SIZE(s) != 0)
976 err = PyFile_WriteString(": ", f);
977 if (err == 0)
978 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
979 Py_XDECREF(s);
982 if (err == 0)
983 err = PyFile_WriteString("\n", f);
985 /* If an error happened here, don't show it.
986 XXX This is wrong, but too many callers rely on this behavior. */
987 if (err != 0)
988 PyErr_Clear();
991 PyObject *
992 PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
994 return run_err_node(PyParser_SimpleParseString(str, start),
995 "<string>", globals, locals, NULL);
998 PyObject *
999 PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1000 PyObject *locals)
1002 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
1005 PyObject *
1006 PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
1007 PyObject *locals, int closeit)
1009 node *n = PyParser_SimpleParseFile(fp, filename, start);
1010 if (closeit)
1011 fclose(fp);
1012 return run_err_node(n, filename, globals, locals, NULL);
1015 PyObject *
1016 PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1017 PyCompilerFlags *flags)
1019 return run_err_node(PyParser_SimpleParseStringFlags(
1020 str, start,
1021 (flags && flags->cf_flags & CO_GENERATOR_ALLOWED) ?
1022 PyPARSE_YIELD_IS_KEYWORD : 0),
1023 "<string>", globals, locals, flags);
1026 PyObject *
1027 PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1028 PyObject *locals, PyCompilerFlags *flags)
1030 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1031 flags);
1034 PyObject *
1035 PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1036 PyObject *locals, int closeit, PyCompilerFlags *flags)
1038 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
1039 (flags && flags->cf_flags & CO_GENERATOR_ALLOWED) ?
1040 PyPARSE_YIELD_IS_KEYWORD : 0);
1041 if (closeit)
1042 fclose(fp);
1043 return run_err_node(n, filename, globals, locals, flags);
1046 static PyObject *
1047 run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1048 PyCompilerFlags *flags)
1050 if (n == NULL)
1051 return NULL;
1052 return run_node(n, filename, globals, locals, flags);
1055 static PyObject *
1056 run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1057 PyCompilerFlags *flags)
1059 PyCodeObject *co;
1060 PyObject *v;
1061 co = PyNode_CompileFlags(n, filename, flags);
1062 PyNode_Free(n);
1063 if (co == NULL)
1064 return NULL;
1065 v = PyEval_EvalCode(co, globals, locals);
1066 Py_DECREF(co);
1067 return v;
1070 static PyObject *
1071 run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1072 PyCompilerFlags *flags)
1074 PyCodeObject *co;
1075 PyObject *v;
1076 long magic;
1077 long PyImport_GetMagicNumber(void);
1079 magic = PyMarshal_ReadLongFromFile(fp);
1080 if (magic != PyImport_GetMagicNumber()) {
1081 PyErr_SetString(PyExc_RuntimeError,
1082 "Bad magic number in .pyc file");
1083 return NULL;
1085 (void) PyMarshal_ReadLongFromFile(fp);
1086 v = PyMarshal_ReadLastObjectFromFile(fp);
1087 fclose(fp);
1088 if (v == NULL || !PyCode_Check(v)) {
1089 Py_XDECREF(v);
1090 PyErr_SetString(PyExc_RuntimeError,
1091 "Bad code object in .pyc file");
1092 return NULL;
1094 co = (PyCodeObject *)v;
1095 v = PyEval_EvalCode(co, globals, locals);
1096 if (v && flags)
1097 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1098 Py_DECREF(co);
1099 return v;
1102 PyObject *
1103 Py_CompileString(char *str, char *filename, int start)
1105 return Py_CompileStringFlags(str, filename, start, NULL);
1108 PyObject *
1109 Py_CompileStringFlags(char *str, char *filename, int start,
1110 PyCompilerFlags *flags)
1112 node *n;
1113 PyCodeObject *co;
1114 n = PyParser_SimpleParseStringFlags(str, start,
1115 (flags && flags->cf_flags & CO_GENERATOR_ALLOWED) ?
1116 PyPARSE_YIELD_IS_KEYWORD : 0);
1117 if (n == NULL)
1118 return NULL;
1119 co = PyNode_CompileFlags(n, filename, flags);
1120 PyNode_Free(n);
1121 return (PyObject *)co;
1124 struct symtable *
1125 Py_SymtableString(char *str, char *filename, int start)
1127 node *n;
1128 struct symtable *st;
1129 n = PyParser_SimpleParseString(str, start);
1130 if (n == NULL)
1131 return NULL;
1132 st = PyNode_CompileSymtable(n, filename);
1133 PyNode_Free(n);
1134 return st;
1137 /* Simplified interface to parsefile -- return node or set exception */
1139 node *
1140 PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
1142 node *n;
1143 perrdetail err;
1144 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1145 (char *)0, (char *)0, &err, flags);
1146 if (n == NULL)
1147 err_input(&err);
1148 return n;
1151 node *
1152 PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1154 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1157 /* Simplified interface to parsestring -- return node or set exception */
1159 node *
1160 PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1162 node *n;
1163 perrdetail err;
1164 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1165 flags);
1166 if (n == NULL)
1167 err_input(&err);
1168 return n;
1171 node *
1172 PyParser_SimpleParseString(char *str, int start)
1174 return PyParser_SimpleParseStringFlags(str, start, 0);
1177 /* Set the error appropriate to the given input error code (see errcode.h) */
1179 static void
1180 err_input(perrdetail *err)
1182 PyObject *v, *w, *errtype;
1183 char *msg = NULL;
1184 errtype = PyExc_SyntaxError;
1185 v = Py_BuildValue("(ziiz)", err->filename,
1186 err->lineno, err->offset, err->text);
1187 if (err->text != NULL) {
1188 PyMem_DEL(err->text);
1189 err->text = NULL;
1191 switch (err->error) {
1192 case E_SYNTAX:
1193 errtype = PyExc_IndentationError;
1194 if (err->expected == INDENT)
1195 msg = "expected an indented block";
1196 else if (err->token == INDENT)
1197 msg = "unexpected indent";
1198 else if (err->token == DEDENT)
1199 msg = "unexpected unindent";
1200 else {
1201 errtype = PyExc_SyntaxError;
1202 msg = "invalid syntax";
1204 break;
1205 case E_TOKEN:
1206 msg = "invalid token";
1207 break;
1208 case E_INTR:
1209 PyErr_SetNone(PyExc_KeyboardInterrupt);
1210 Py_XDECREF(v);
1211 return;
1212 case E_NOMEM:
1213 PyErr_NoMemory();
1214 Py_XDECREF(v);
1215 return;
1216 case E_EOF:
1217 msg = "unexpected EOF while parsing";
1218 break;
1219 case E_TABSPACE:
1220 errtype = PyExc_TabError;
1221 msg = "inconsistent use of tabs and spaces in indentation";
1222 break;
1223 case E_OVERFLOW:
1224 msg = "expression too long";
1225 break;
1226 case E_DEDENT:
1227 errtype = PyExc_IndentationError;
1228 msg = "unindent does not match any outer indentation level";
1229 break;
1230 case E_TOODEEP:
1231 errtype = PyExc_IndentationError;
1232 msg = "too many levels of indentation";
1233 break;
1234 default:
1235 fprintf(stderr, "error=%d\n", err->error);
1236 msg = "unknown parsing error";
1237 break;
1239 w = Py_BuildValue("(sO)", msg, v);
1240 Py_XDECREF(v);
1241 PyErr_SetObject(errtype, w);
1242 Py_XDECREF(w);
1245 /* Print fatal error message and abort */
1247 void
1248 Py_FatalError(char *msg)
1250 fprintf(stderr, "Fatal Python error: %s\n", msg);
1251 #ifdef macintosh
1252 for (;;);
1253 #endif
1254 #ifdef MS_WIN32
1255 OutputDebugString("Fatal Python error: ");
1256 OutputDebugString(msg);
1257 OutputDebugString("\n");
1258 #ifdef _DEBUG
1259 DebugBreak();
1260 #endif
1261 #endif /* MS_WIN32 */
1262 abort();
1265 /* Clean up and exit */
1267 #ifdef WITH_THREAD
1268 #include "pythread.h"
1269 int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
1270 #endif
1272 #define NEXITFUNCS 32
1273 static void (*exitfuncs[NEXITFUNCS])(void);
1274 static int nexitfuncs = 0;
1276 int Py_AtExit(void (*func)(void))
1278 if (nexitfuncs >= NEXITFUNCS)
1279 return -1;
1280 exitfuncs[nexitfuncs++] = func;
1281 return 0;
1284 static void
1285 call_sys_exitfunc(void)
1287 PyObject *exitfunc = PySys_GetObject("exitfunc");
1289 if (exitfunc) {
1290 PyObject *res;
1291 Py_INCREF(exitfunc);
1292 PySys_SetObject("exitfunc", (PyObject *)NULL);
1293 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1294 if (res == NULL) {
1295 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1296 PySys_WriteStderr("Error in sys.exitfunc:\n");
1298 PyErr_Print();
1300 Py_DECREF(exitfunc);
1303 if (Py_FlushLine())
1304 PyErr_Clear();
1307 static void
1308 call_ll_exitfuncs(void)
1310 while (nexitfuncs > 0)
1311 (*exitfuncs[--nexitfuncs])();
1313 fflush(stdout);
1314 fflush(stderr);
1317 void
1318 Py_Exit(int sts)
1320 Py_Finalize();
1322 #ifdef macintosh
1323 PyMac_Exit(sts);
1324 #else
1325 exit(sts);
1326 #endif
1329 static void
1330 initsigs(void)
1332 #ifdef HAVE_SIGNAL_H
1333 #ifdef SIGPIPE
1334 signal(SIGPIPE, SIG_IGN);
1335 #endif
1336 #ifdef SIGXFZ
1337 signal(SIGXFZ, SIG_IGN);
1338 #endif
1339 #endif /* HAVE_SIGNAL_H */
1340 PyOS_InitInterrupts(); /* May imply initsignal() */
1343 #ifdef Py_TRACE_REFS
1344 /* Ask a yes/no question */
1347 _Py_AskYesNo(char *prompt)
1349 char buf[256];
1351 fprintf(stderr, "%s [ny] ", prompt);
1352 if (fgets(buf, sizeof buf, stdin) == NULL)
1353 return 0;
1354 return buf[0] == 'y' || buf[0] == 'Y';
1356 #endif
1358 #ifdef MPW
1360 /* Check for file descriptor connected to interactive device.
1361 Pretend that stdin is always interactive, other files never. */
1364 isatty(int fd)
1366 return fd == fileno(stdin);
1369 #endif
1372 * The file descriptor fd is considered ``interactive'' if either
1373 * a) isatty(fd) is TRUE, or
1374 * b) the -i flag was given, and the filename associated with
1375 * the descriptor is NULL or "<stdin>" or "???".
1378 Py_FdIsInteractive(FILE *fp, char *filename)
1380 if (isatty((int)fileno(fp)))
1381 return 1;
1382 if (!Py_InteractiveFlag)
1383 return 0;
1384 return (filename == NULL) ||
1385 (strcmp(filename, "<stdin>") == 0) ||
1386 (strcmp(filename, "???") == 0);
1390 #if defined(USE_STACKCHECK)
1391 #if defined(WIN32) && defined(_MSC_VER)
1393 /* Stack checking for Microsoft C */
1395 #include <malloc.h>
1396 #include <excpt.h>
1399 * Return non-zero when we run out of memory on the stack; zero otherwise.
1402 PyOS_CheckStack(void)
1404 __try {
1405 /* _alloca throws a stack overflow exception if there's
1406 not enough space left on the stack */
1407 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1408 return 0;
1409 } __except (EXCEPTION_EXECUTE_HANDLER) {
1410 /* just ignore all errors */
1412 return 1;
1415 #endif /* WIN32 && _MSC_VER */
1417 /* Alternate implementations can be added here... */
1419 #endif /* USE_STACKCHECK */
1422 /* Wrappers around sigaction() or signal(). */
1424 PyOS_sighandler_t
1425 PyOS_getsig(int sig)
1427 #ifdef HAVE_SIGACTION
1428 struct sigaction context;
1429 sigaction(sig, NULL, &context);
1430 return context.sa_handler;
1431 #else
1432 PyOS_sighandler_t handler;
1433 handler = signal(sig, SIG_IGN);
1434 signal(sig, handler);
1435 return handler;
1436 #endif
1439 PyOS_sighandler_t
1440 PyOS_setsig(int sig, PyOS_sighandler_t handler)
1442 #ifdef HAVE_SIGACTION
1443 struct sigaction context;
1444 PyOS_sighandler_t oldhandler;
1445 sigaction(sig, NULL, &context);
1446 oldhandler = context.sa_handler;
1447 context.sa_handler = handler;
1448 sigaction(sig, &context, NULL);
1449 return oldhandler;
1450 #else
1451 return signal(sig, handler);
1452 #endif