- Got rid of newmodule.c
[python/dscho.git] / Python / pythonrun.c
blob324bc8950638166ca600b50e05d7f6b3f0acedc6
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_SIGNAL_H
17 #include <signal.h>
18 #endif
20 #ifdef MS_WIN32
21 #undef BYTE
22 #include "windows.h"
23 #endif
25 #ifdef macintosh
26 #include "macglue.h"
27 #endif
28 extern char *Py_GetPath(void);
30 extern grammar _PyParser_Grammar; /* From graminit.c */
32 /* Forward */
33 static void initmain(void);
34 static void initsite(void);
35 static PyObject *run_err_node(node *, char *, PyObject *, PyObject *,
36 PyCompilerFlags *);
37 static PyObject *run_node(node *, char *, PyObject *, PyObject *,
38 PyCompilerFlags *);
39 static PyObject *run_pyc_file(FILE *, char *, PyObject *, PyObject *,
40 PyCompilerFlags *);
41 static void err_input(perrdetail *);
42 static void initsigs(void);
43 static void call_sys_exitfunc(void);
44 static void call_ll_exitfuncs(void);
46 #ifdef Py_TRACE_REFS
47 int _Py_AskYesNo(char *prompt);
48 #endif
50 extern void _PyUnicode_Init(void);
51 extern void _PyUnicode_Fini(void);
52 extern void _PyCodecRegistry_Init(void);
53 extern void _PyCodecRegistry_Fini(void);
55 int Py_DebugFlag; /* Needed by parser.c */
56 int Py_VerboseFlag; /* Needed by import.c */
57 int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
58 int Py_NoSiteFlag; /* Suppress 'import site' */
59 int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
60 int Py_FrozenFlag; /* Needed by getpath.c */
61 int Py_UnicodeFlag = 0; /* Needed by compile.c */
62 int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
63 /* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
64 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
65 true divisions (which they will be in 2.3). */
66 int _Py_QnewFlag = 0;
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 static int
91 add_flag(int flag, const char *envs)
93 int env = atoi(envs);
94 if (flag < env)
95 flag = env;
96 if (flag < 1)
97 flag = 1;
98 return flag;
101 void
102 Py_Initialize(void)
104 PyInterpreterState *interp;
105 PyThreadState *tstate;
106 PyObject *bimod, *sysmod;
107 char *p;
108 extern void _Py_ReadyTypes(void);
110 if (initialized)
111 return;
112 initialized = 1;
114 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
115 Py_DebugFlag = add_flag(Py_DebugFlag, p);
116 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
117 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
118 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
119 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
121 interp = PyInterpreterState_New();
122 if (interp == NULL)
123 Py_FatalError("Py_Initialize: can't make first interpreter");
125 tstate = PyThreadState_New(interp);
126 if (tstate == NULL)
127 Py_FatalError("Py_Initialize: can't make first thread");
128 (void) PyThreadState_Swap(tstate);
130 _Py_ReadyTypes();
132 interp->modules = PyDict_New();
133 if (interp->modules == NULL)
134 Py_FatalError("Py_Initialize: can't make modules dictionary");
136 /* Init codec registry */
137 _PyCodecRegistry_Init();
139 #ifdef Py_USING_UNICODE
140 /* Init Unicode implementation; relies on the codec registry */
141 _PyUnicode_Init();
142 #endif
144 bimod = _PyBuiltin_Init();
145 if (bimod == NULL)
146 Py_FatalError("Py_Initialize: can't initialize __builtin__");
147 interp->builtins = PyModule_GetDict(bimod);
148 Py_INCREF(interp->builtins);
150 sysmod = _PySys_Init();
151 if (sysmod == NULL)
152 Py_FatalError("Py_Initialize: can't initialize sys");
153 interp->sysdict = PyModule_GetDict(sysmod);
154 Py_INCREF(interp->sysdict);
155 _PyImport_FixupExtension("sys", "sys");
156 PySys_SetPath(Py_GetPath());
157 PyDict_SetItemString(interp->sysdict, "modules",
158 interp->modules);
160 _PyImport_Init();
162 /* initialize builtin exceptions */
163 _PyExc_Init();
164 _PyImport_FixupExtension("exceptions", "exceptions");
166 /* phase 2 of builtins */
167 _PyImport_FixupExtension("__builtin__", "__builtin__");
169 initsigs(); /* Signal handling stuff, including initintr() */
171 initmain(); /* Module __main__ */
172 if (!Py_NoSiteFlag)
173 initsite(); /* Module site */
176 #ifdef COUNT_ALLOCS
177 extern void dump_counts(void);
178 #endif
180 /* Undo the effect of Py_Initialize().
182 Beware: if multiple interpreter and/or thread states exist, these
183 are not wiped out; only the current thread and interpreter state
184 are deleted. But since everything else is deleted, those other
185 interpreter and thread states should no longer be used.
187 (XXX We should do better, e.g. wipe out all interpreters and
188 threads.)
190 Locking: as above.
194 void
195 Py_Finalize(void)
197 PyInterpreterState *interp;
198 PyThreadState *tstate;
200 if (!initialized)
201 return;
203 /* The interpreter is still entirely intact at this point, and the
204 * exit funcs may be relying on that. In particular, if some thread
205 * or exit func is still waiting to do an import, the import machinery
206 * expects Py_IsInitialized() to return true. So don't say the
207 * interpreter is uninitialized until after the exit funcs have run.
208 * Note that Threading.py uses an exit func to do a join on all the
209 * threads created thru it, so this also protects pending imports in
210 * the threads created via Threading.
212 call_sys_exitfunc();
213 initialized = 0;
215 /* Get current thread state and interpreter pointer */
216 tstate = PyThreadState_Get();
217 interp = tstate->interp;
219 /* Disable signal handling */
220 PyOS_FiniInterrupts();
222 /* Cleanup Codec registry */
223 _PyCodecRegistry_Fini();
225 /* Destroy all modules */
226 PyImport_Cleanup();
228 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
229 _PyImport_Fini();
231 /* Debugging stuff */
232 #ifdef COUNT_ALLOCS
233 dump_counts();
234 #endif
236 #ifdef Py_REF_DEBUG
237 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
238 #endif
240 #ifdef Py_TRACE_REFS
241 if (Py_GETENV("PYTHONDUMPREFS")) {
242 _Py_PrintReferences(stderr);
244 #endif /* Py_TRACE_REFS */
246 /* Now we decref the exception classes. After this point nothing
247 can raise an exception. That's okay, because each Fini() method
248 below has been checked to make sure no exceptions are ever
249 raised.
251 _PyExc_Fini();
253 /* Delete current thread */
254 PyInterpreterState_Clear(interp);
255 PyThreadState_Swap(NULL);
256 PyInterpreterState_Delete(interp);
258 PyMethod_Fini();
259 PyFrame_Fini();
260 PyCFunction_Fini();
261 PyTuple_Fini();
262 PyString_Fini();
263 PyInt_Fini();
264 PyFloat_Fini();
266 #ifdef Py_USING_UNICODE
267 /* Cleanup Unicode implementation */
268 _PyUnicode_Fini();
269 #endif
271 /* XXX Still allocated:
272 - various static ad-hoc pointers to interned strings
273 - int and float free list blocks
274 - whatever various modules and libraries allocate
277 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
279 #ifdef PYMALLOC_DEBUG
280 if (Py_GETENV("PYTHONMALLOCSTATS"))
281 _PyObject_DebugMallocStats();
282 #endif
284 call_ll_exitfuncs();
286 #ifdef Py_TRACE_REFS
287 _Py_ResetReferences();
288 #endif /* Py_TRACE_REFS */
291 /* Create and initialize a new interpreter and thread, and return the
292 new thread. This requires that Py_Initialize() has been called
293 first.
295 Unsuccessful initialization yields a NULL pointer. Note that *no*
296 exception information is available even in this case -- the
297 exception information is held in the thread, and there is no
298 thread.
300 Locking: as above.
304 PyThreadState *
305 Py_NewInterpreter(void)
307 PyInterpreterState *interp;
308 PyThreadState *tstate, *save_tstate;
309 PyObject *bimod, *sysmod;
311 if (!initialized)
312 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
314 interp = PyInterpreterState_New();
315 if (interp == NULL)
316 return NULL;
318 tstate = PyThreadState_New(interp);
319 if (tstate == NULL) {
320 PyInterpreterState_Delete(interp);
321 return NULL;
324 save_tstate = PyThreadState_Swap(tstate);
326 /* XXX The following is lax in error checking */
328 interp->modules = PyDict_New();
330 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
331 if (bimod != NULL) {
332 interp->builtins = PyModule_GetDict(bimod);
333 Py_INCREF(interp->builtins);
335 sysmod = _PyImport_FindExtension("sys", "sys");
336 if (bimod != NULL && sysmod != NULL) {
337 interp->sysdict = PyModule_GetDict(sysmod);
338 Py_INCREF(interp->sysdict);
339 PySys_SetPath(Py_GetPath());
340 PyDict_SetItemString(interp->sysdict, "modules",
341 interp->modules);
342 initmain();
343 if (!Py_NoSiteFlag)
344 initsite();
347 if (!PyErr_Occurred())
348 return tstate;
350 /* Oops, it didn't work. Undo it all. */
352 PyErr_Print();
353 PyThreadState_Clear(tstate);
354 PyThreadState_Swap(save_tstate);
355 PyThreadState_Delete(tstate);
356 PyInterpreterState_Delete(interp);
358 return NULL;
361 /* Delete an interpreter and its last thread. This requires that the
362 given thread state is current, that the thread has no remaining
363 frames, and that it is its interpreter's only remaining thread.
364 It is a fatal error to violate these constraints.
366 (Py_Finalize() doesn't have these constraints -- it zaps
367 everything, regardless.)
369 Locking: as above.
373 void
374 Py_EndInterpreter(PyThreadState *tstate)
376 PyInterpreterState *interp = tstate->interp;
378 if (tstate != PyThreadState_Get())
379 Py_FatalError("Py_EndInterpreter: thread is not current");
380 if (tstate->frame != NULL)
381 Py_FatalError("Py_EndInterpreter: thread still has a frame");
382 if (tstate != interp->tstate_head || tstate->next != NULL)
383 Py_FatalError("Py_EndInterpreter: not the last thread");
385 PyImport_Cleanup();
386 PyInterpreterState_Clear(interp);
387 PyThreadState_Swap(NULL);
388 PyInterpreterState_Delete(interp);
391 static char *progname = "python";
393 void
394 Py_SetProgramName(char *pn)
396 if (pn && *pn)
397 progname = pn;
400 char *
401 Py_GetProgramName(void)
403 return progname;
406 static char *default_home = NULL;
408 void
409 Py_SetPythonHome(char *home)
411 default_home = home;
414 char *
415 Py_GetPythonHome(void)
417 char *home = default_home;
418 if (home == NULL && !Py_IgnoreEnvironmentFlag)
419 home = Py_GETENV("PYTHONHOME");
420 return home;
423 /* Create __main__ module */
425 static void
426 initmain(void)
428 PyObject *m, *d;
429 m = PyImport_AddModule("__main__");
430 if (m == NULL)
431 Py_FatalError("can't create __main__ module");
432 d = PyModule_GetDict(m);
433 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
434 PyObject *bimod = PyImport_ImportModule("__builtin__");
435 if (bimod == NULL ||
436 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
437 Py_FatalError("can't add __builtins__ to __main__");
438 Py_DECREF(bimod);
442 /* Import the site module (not into __main__ though) */
444 static void
445 initsite(void)
447 PyObject *m, *f;
448 m = PyImport_ImportModule("site");
449 if (m == NULL) {
450 f = PySys_GetObject("stderr");
451 if (Py_VerboseFlag) {
452 PyFile_WriteString(
453 "'import site' failed; traceback:\n", f);
454 PyErr_Print();
456 else {
457 PyFile_WriteString(
458 "'import site' failed; use -v for traceback\n", f);
459 PyErr_Clear();
462 else {
463 Py_DECREF(m);
467 /* Parse input from a file and execute it */
470 PyRun_AnyFile(FILE *fp, char *filename)
472 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
476 PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
478 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
482 PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
484 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
488 PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
489 PyCompilerFlags *flags)
491 if (filename == NULL)
492 filename = "???";
493 if (Py_FdIsInteractive(fp, filename)) {
494 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
495 if (closeit)
496 fclose(fp);
497 return err;
499 else
500 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
504 PyRun_InteractiveLoop(FILE *fp, char *filename)
506 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
510 PyRun_InteractiveLoopFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
512 PyObject *v;
513 int ret;
514 PyCompilerFlags local_flags;
516 if (flags == NULL) {
517 flags = &local_flags;
518 local_flags.cf_flags = 0;
520 v = PySys_GetObject("ps1");
521 if (v == NULL) {
522 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
523 Py_XDECREF(v);
525 v = PySys_GetObject("ps2");
526 if (v == NULL) {
527 PySys_SetObject("ps2", v = PyString_FromString("... "));
528 Py_XDECREF(v);
530 for (;;) {
531 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
532 #ifdef Py_REF_DEBUG
533 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
534 #endif
535 if (ret == E_EOF)
536 return 0;
538 if (ret == E_NOMEM)
539 return -1;
545 PyRun_InteractiveOne(FILE *fp, char *filename)
547 return PyRun_InteractiveOneFlags(fp, filename, NULL);
550 /* compute parser flags based on compiler flags */
551 #if 0 /* future keyword */
552 #define PARSER_FLAGS(flags) \
553 (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \
554 PyPARSE_YIELD_IS_KEYWORD : 0)
555 #else
556 #define PARSER_FLAGS(flags) 0
557 #endif
560 PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
562 PyObject *m, *d, *v, *w;
563 node *n;
564 perrdetail err;
565 char *ps1 = "", *ps2 = "";
567 v = PySys_GetObject("ps1");
568 if (v != NULL) {
569 v = PyObject_Str(v);
570 if (v == NULL)
571 PyErr_Clear();
572 else if (PyString_Check(v))
573 ps1 = PyString_AsString(v);
575 w = PySys_GetObject("ps2");
576 if (w != NULL) {
577 w = PyObject_Str(w);
578 if (w == NULL)
579 PyErr_Clear();
580 else if (PyString_Check(w))
581 ps2 = PyString_AsString(w);
583 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
584 Py_single_input, ps1, ps2, &err,
585 PARSER_FLAGS(flags));
586 Py_XDECREF(v);
587 Py_XDECREF(w);
588 if (n == NULL) {
589 if (err.error == E_EOF) {
590 if (err.text)
591 PyMem_DEL(err.text);
592 return E_EOF;
594 err_input(&err);
595 PyErr_Print();
596 return err.error;
598 m = PyImport_AddModule("__main__");
599 if (m == NULL)
600 return -1;
601 d = PyModule_GetDict(m);
602 v = run_node(n, filename, d, d, flags);
603 if (v == NULL) {
604 PyErr_Print();
605 return -1;
607 Py_DECREF(v);
608 if (Py_FlushLine())
609 PyErr_Clear();
610 return 0;
614 PyRun_SimpleFile(FILE *fp, char *filename)
616 return PyRun_SimpleFileEx(fp, filename, 0);
619 /* Check whether a file maybe a pyc file: Look at the extension,
620 the file type, and, if we may close it, at the first few bytes. */
622 static int
623 maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
625 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
626 return 1;
628 #ifdef macintosh
629 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
630 if (PyMac_getfiletype(filename) == 'PYC '
631 || PyMac_getfiletype(filename) == 'APPL')
632 return 1;
633 #endif /* macintosh */
635 /* Only look into the file if we are allowed to close it, since
636 it then should also be seekable. */
637 if (closeit) {
638 /* Read only two bytes of the magic. If the file was opened in
639 text mode, the bytes 3 and 4 of the magic (\r\n) might not
640 be read as they are on disk. */
641 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
642 unsigned char buf[2];
643 /* Mess: In case of -x, the stream is NOT at its start now,
644 and ungetc() was used to push back the first newline,
645 which makes the current stream position formally undefined,
646 and a x-platform nightmare.
647 Unfortunately, we have no direct way to know whether -x
648 was specified. So we use a terrible hack: if the current
649 stream position is not 0, we assume -x was specified, and
650 give up. Bug 132850 on SourceForge spells out the
651 hopelessness of trying anything else (fseek and ftell
652 don't work predictably x-platform for text-mode files).
654 int ispyc = 0;
655 if (ftell(fp) == 0) {
656 if (fread(buf, 1, 2, fp) == 2 &&
657 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
658 ispyc = 1;
659 rewind(fp);
661 return ispyc;
663 return 0;
667 PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
669 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
673 PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit,
674 PyCompilerFlags *flags)
676 PyObject *m, *d, *v;
677 char *ext;
679 m = PyImport_AddModule("__main__");
680 if (m == NULL)
681 return -1;
682 d = PyModule_GetDict(m);
683 ext = filename + strlen(filename) - 4;
684 if (maybe_pyc_file(fp, filename, ext, closeit)) {
685 /* Try to run a pyc file. First, re-open in binary */
686 if (closeit)
687 fclose(fp);
688 if( (fp = fopen(filename, "rb")) == NULL ) {
689 fprintf(stderr, "python: Can't reopen .pyc file\n");
690 return -1;
692 /* Turn on optimization if a .pyo file is given */
693 if (strcmp(ext, ".pyo") == 0)
694 Py_OptimizeFlag = 1;
695 v = run_pyc_file(fp, filename, d, d, flags);
696 } else {
697 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
698 closeit, flags);
700 if (v == NULL) {
701 PyErr_Print();
702 return -1;
704 Py_DECREF(v);
705 if (Py_FlushLine())
706 PyErr_Clear();
707 return 0;
711 PyRun_SimpleString(char *command)
713 return PyRun_SimpleStringFlags(command, NULL);
717 PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
719 PyObject *m, *d, *v;
720 m = PyImport_AddModule("__main__");
721 if (m == NULL)
722 return -1;
723 d = PyModule_GetDict(m);
724 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
725 if (v == NULL) {
726 PyErr_Print();
727 return -1;
729 Py_DECREF(v);
730 if (Py_FlushLine())
731 PyErr_Clear();
732 return 0;
735 static int
736 parse_syntax_error(PyObject *err, PyObject **message, char **filename,
737 int *lineno, int *offset, char **text)
739 long hold;
740 PyObject *v;
742 /* old style errors */
743 if (PyTuple_Check(err))
744 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
745 lineno, offset, text);
747 /* new style errors. `err' is an instance */
749 if (! (v = PyObject_GetAttrString(err, "msg")))
750 goto finally;
751 *message = v;
753 if (!(v = PyObject_GetAttrString(err, "filename")))
754 goto finally;
755 if (v == Py_None)
756 *filename = NULL;
757 else if (! (*filename = PyString_AsString(v)))
758 goto finally;
760 Py_DECREF(v);
761 if (!(v = PyObject_GetAttrString(err, "lineno")))
762 goto finally;
763 hold = PyInt_AsLong(v);
764 Py_DECREF(v);
765 v = NULL;
766 if (hold < 0 && PyErr_Occurred())
767 goto finally;
768 *lineno = (int)hold;
770 if (!(v = PyObject_GetAttrString(err, "offset")))
771 goto finally;
772 if (v == Py_None) {
773 *offset = -1;
774 Py_DECREF(v);
775 v = NULL;
776 } else {
777 hold = PyInt_AsLong(v);
778 Py_DECREF(v);
779 v = NULL;
780 if (hold < 0 && PyErr_Occurred())
781 goto finally;
782 *offset = (int)hold;
785 if (!(v = PyObject_GetAttrString(err, "text")))
786 goto finally;
787 if (v == Py_None)
788 *text = NULL;
789 else if (! (*text = PyString_AsString(v)))
790 goto finally;
791 Py_DECREF(v);
792 return 1;
794 finally:
795 Py_XDECREF(v);
796 return 0;
799 void
800 PyErr_Print(void)
802 PyErr_PrintEx(1);
805 static void
806 print_error_text(PyObject *f, int offset, char *text)
808 char *nl;
809 if (offset >= 0) {
810 if (offset > 0 && offset == (int)strlen(text))
811 offset--;
812 for (;;) {
813 nl = strchr(text, '\n');
814 if (nl == NULL || nl-text >= offset)
815 break;
816 offset -= (nl+1-text);
817 text = nl+1;
819 while (*text == ' ' || *text == '\t') {
820 text++;
821 offset--;
824 PyFile_WriteString(" ", f);
825 PyFile_WriteString(text, f);
826 if (*text == '\0' || text[strlen(text)-1] != '\n')
827 PyFile_WriteString("\n", f);
828 if (offset == -1)
829 return;
830 PyFile_WriteString(" ", f);
831 offset--;
832 while (offset > 0) {
833 PyFile_WriteString(" ", f);
834 offset--;
836 PyFile_WriteString("^\n", f);
839 static void
840 handle_system_exit(void)
842 PyObject *exception, *value, *tb;
843 PyErr_Fetch(&exception, &value, &tb);
844 if (Py_FlushLine())
845 PyErr_Clear();
846 fflush(stdout);
847 if (value == NULL || value == Py_None)
848 Py_Exit(0);
849 if (PyInstance_Check(value)) {
850 /* The error code should be in the `code' attribute. */
851 PyObject *code = PyObject_GetAttrString(value, "code");
852 if (code) {
853 Py_DECREF(value);
854 value = code;
855 if (value == Py_None)
856 Py_Exit(0);
858 /* If we failed to dig out the 'code' attribute,
859 just let the else clause below print the error. */
861 if (PyInt_Check(value))
862 Py_Exit((int)PyInt_AsLong(value));
863 else {
864 PyObject_Print(value, stderr, Py_PRINT_RAW);
865 PySys_WriteStderr("\n");
866 Py_Exit(1);
870 void
871 PyErr_PrintEx(int set_sys_last_vars)
873 PyObject *exception, *v, *tb, *hook;
875 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
876 handle_system_exit();
878 PyErr_Fetch(&exception, &v, &tb);
879 PyErr_NormalizeException(&exception, &v, &tb);
880 if (exception == NULL)
881 return;
882 if (set_sys_last_vars) {
883 PySys_SetObject("last_type", exception);
884 PySys_SetObject("last_value", v);
885 PySys_SetObject("last_traceback", tb);
887 hook = PySys_GetObject("excepthook");
888 if (hook) {
889 PyObject *args = Py_BuildValue("(OOO)",
890 exception, v ? v : Py_None, tb ? tb : Py_None);
891 PyObject *result = PyEval_CallObject(hook, args);
892 if (result == NULL) {
893 PyObject *exception2, *v2, *tb2;
894 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
895 handle_system_exit();
897 PyErr_Fetch(&exception2, &v2, &tb2);
898 PyErr_NormalizeException(&exception2, &v2, &tb2);
899 if (Py_FlushLine())
900 PyErr_Clear();
901 fflush(stdout);
902 PySys_WriteStderr("Error in sys.excepthook:\n");
903 PyErr_Display(exception2, v2, tb2);
904 PySys_WriteStderr("\nOriginal exception was:\n");
905 PyErr_Display(exception, v, tb);
906 Py_XDECREF(exception2);
907 Py_XDECREF(v2);
908 Py_XDECREF(tb2);
910 Py_XDECREF(result);
911 Py_XDECREF(args);
912 } else {
913 PySys_WriteStderr("sys.excepthook is missing\n");
914 PyErr_Display(exception, v, tb);
916 Py_XDECREF(exception);
917 Py_XDECREF(v);
918 Py_XDECREF(tb);
921 void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
923 int err = 0;
924 PyObject *v = value;
925 PyObject *f = PySys_GetObject("stderr");
926 if (f == NULL)
927 fprintf(stderr, "lost sys.stderr\n");
928 else {
929 if (Py_FlushLine())
930 PyErr_Clear();
931 fflush(stdout);
932 if (tb && tb != Py_None)
933 err = PyTraceBack_Print(tb, f);
934 if (err == 0 &&
935 PyObject_HasAttrString(v, "print_file_and_line"))
937 PyObject *message;
938 char *filename, *text;
939 int lineno, offset;
940 if (!parse_syntax_error(v, &message, &filename,
941 &lineno, &offset, &text))
942 PyErr_Clear();
943 else {
944 char buf[10];
945 PyFile_WriteString(" File \"", f);
946 if (filename == NULL)
947 PyFile_WriteString("<string>", f);
948 else
949 PyFile_WriteString(filename, f);
950 PyFile_WriteString("\", line ", f);
951 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
952 PyFile_WriteString(buf, f);
953 PyFile_WriteString("\n", f);
954 if (text != NULL)
955 print_error_text(f, offset, text);
956 v = message;
957 /* Can't be bothered to check all those
958 PyFile_WriteString() calls */
959 if (PyErr_Occurred())
960 err = -1;
963 if (err) {
964 /* Don't do anything else */
966 else if (PyClass_Check(exception)) {
967 PyClassObject* exc = (PyClassObject*)exception;
968 PyObject* className = exc->cl_name;
969 PyObject* moduleName =
970 PyDict_GetItemString(exc->cl_dict, "__module__");
972 if (moduleName == NULL)
973 err = PyFile_WriteString("<unknown>", f);
974 else {
975 char* modstr = PyString_AsString(moduleName);
976 if (modstr && strcmp(modstr, "exceptions"))
978 err = PyFile_WriteString(modstr, f);
979 err += PyFile_WriteString(".", f);
982 if (err == 0) {
983 if (className == NULL)
984 err = PyFile_WriteString("<unknown>", f);
985 else
986 err = PyFile_WriteObject(className, f,
987 Py_PRINT_RAW);
990 else
991 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
992 if (err == 0) {
993 if (v != NULL && v != Py_None) {
994 PyObject *s = PyObject_Str(v);
995 /* only print colon if the str() of the
996 object is not the empty string
998 if (s == NULL)
999 err = -1;
1000 else if (!PyString_Check(s) ||
1001 PyString_GET_SIZE(s) != 0)
1002 err = PyFile_WriteString(": ", f);
1003 if (err == 0)
1004 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1005 Py_XDECREF(s);
1008 if (err == 0)
1009 err = PyFile_WriteString("\n", f);
1011 /* If an error happened here, don't show it.
1012 XXX This is wrong, but too many callers rely on this behavior. */
1013 if (err != 0)
1014 PyErr_Clear();
1017 PyObject *
1018 PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
1020 return run_err_node(PyParser_SimpleParseString(str, start),
1021 "<string>", globals, locals, NULL);
1024 PyObject *
1025 PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1026 PyObject *locals)
1028 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
1031 PyObject *
1032 PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
1033 PyObject *locals, int closeit)
1035 node *n = PyParser_SimpleParseFile(fp, filename, start);
1036 if (closeit)
1037 fclose(fp);
1038 return run_err_node(n, filename, globals, locals, NULL);
1041 PyObject *
1042 PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1043 PyCompilerFlags *flags)
1045 return run_err_node(PyParser_SimpleParseStringFlags(
1046 str, start, PARSER_FLAGS(flags)),
1047 "<string>", globals, locals, flags);
1050 PyObject *
1051 PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1052 PyObject *locals, PyCompilerFlags *flags)
1054 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1055 flags);
1058 PyObject *
1059 PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1060 PyObject *locals, int closeit, PyCompilerFlags *flags)
1062 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
1063 PARSER_FLAGS(flags));
1064 if (closeit)
1065 fclose(fp);
1066 return run_err_node(n, filename, globals, locals, flags);
1069 static PyObject *
1070 run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1071 PyCompilerFlags *flags)
1073 if (n == NULL)
1074 return NULL;
1075 return run_node(n, filename, globals, locals, flags);
1078 static PyObject *
1079 run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1080 PyCompilerFlags *flags)
1082 PyCodeObject *co;
1083 PyObject *v;
1084 co = PyNode_CompileFlags(n, filename, flags);
1085 PyNode_Free(n);
1086 if (co == NULL)
1087 return NULL;
1088 v = PyEval_EvalCode(co, globals, locals);
1089 Py_DECREF(co);
1090 return v;
1093 static PyObject *
1094 run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1095 PyCompilerFlags *flags)
1097 PyCodeObject *co;
1098 PyObject *v;
1099 long magic;
1100 long PyImport_GetMagicNumber(void);
1102 magic = PyMarshal_ReadLongFromFile(fp);
1103 if (magic != PyImport_GetMagicNumber()) {
1104 PyErr_SetString(PyExc_RuntimeError,
1105 "Bad magic number in .pyc file");
1106 return NULL;
1108 (void) PyMarshal_ReadLongFromFile(fp);
1109 v = PyMarshal_ReadLastObjectFromFile(fp);
1110 fclose(fp);
1111 if (v == NULL || !PyCode_Check(v)) {
1112 Py_XDECREF(v);
1113 PyErr_SetString(PyExc_RuntimeError,
1114 "Bad code object in .pyc file");
1115 return NULL;
1117 co = (PyCodeObject *)v;
1118 v = PyEval_EvalCode(co, globals, locals);
1119 if (v && flags)
1120 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1121 Py_DECREF(co);
1122 return v;
1125 PyObject *
1126 Py_CompileString(char *str, char *filename, int start)
1128 return Py_CompileStringFlags(str, filename, start, NULL);
1131 PyObject *
1132 Py_CompileStringFlags(char *str, char *filename, int start,
1133 PyCompilerFlags *flags)
1135 node *n;
1136 PyCodeObject *co;
1137 n = PyParser_SimpleParseStringFlags(str, start, PARSER_FLAGS(flags));
1138 if (n == NULL)
1139 return NULL;
1140 co = PyNode_CompileFlags(n, filename, flags);
1141 PyNode_Free(n);
1142 return (PyObject *)co;
1145 struct symtable *
1146 Py_SymtableString(char *str, char *filename, int start)
1148 node *n;
1149 struct symtable *st;
1150 n = PyParser_SimpleParseString(str, start);
1151 if (n == NULL)
1152 return NULL;
1153 st = PyNode_CompileSymtable(n, filename);
1154 PyNode_Free(n);
1155 return st;
1158 /* Simplified interface to parsefile -- return node or set exception */
1160 node *
1161 PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
1163 node *n;
1164 perrdetail err;
1165 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1166 (char *)0, (char *)0, &err, flags);
1167 if (n == NULL)
1168 err_input(&err);
1169 return n;
1172 node *
1173 PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1175 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1178 /* Simplified interface to parsestring -- return node or set exception */
1180 node *
1181 PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1183 node *n;
1184 perrdetail err;
1185 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1186 flags);
1187 if (n == NULL)
1188 err_input(&err);
1189 return n;
1192 node *
1193 PyParser_SimpleParseString(char *str, int start)
1195 return PyParser_SimpleParseStringFlags(str, start, 0);
1198 /* Set the error appropriate to the given input error code (see errcode.h) */
1200 static void
1201 err_input(perrdetail *err)
1203 PyObject *v, *w, *errtype;
1204 char *msg = NULL;
1205 errtype = PyExc_SyntaxError;
1206 v = Py_BuildValue("(ziiz)", err->filename,
1207 err->lineno, err->offset, err->text);
1208 if (err->text != NULL) {
1209 PyMem_DEL(err->text);
1210 err->text = NULL;
1212 switch (err->error) {
1213 case E_SYNTAX:
1214 errtype = PyExc_IndentationError;
1215 if (err->expected == INDENT)
1216 msg = "expected an indented block";
1217 else if (err->token == INDENT)
1218 msg = "unexpected indent";
1219 else if (err->token == DEDENT)
1220 msg = "unexpected unindent";
1221 else {
1222 errtype = PyExc_SyntaxError;
1223 msg = "invalid syntax";
1225 break;
1226 case E_TOKEN:
1227 msg = "invalid token";
1228 break;
1229 case E_INTR:
1230 PyErr_SetNone(PyExc_KeyboardInterrupt);
1231 Py_XDECREF(v);
1232 return;
1233 case E_NOMEM:
1234 PyErr_NoMemory();
1235 Py_XDECREF(v);
1236 return;
1237 case E_EOF:
1238 msg = "unexpected EOF while parsing";
1239 break;
1240 case E_TABSPACE:
1241 errtype = PyExc_TabError;
1242 msg = "inconsistent use of tabs and spaces in indentation";
1243 break;
1244 case E_OVERFLOW:
1245 msg = "expression too long";
1246 break;
1247 case E_DEDENT:
1248 errtype = PyExc_IndentationError;
1249 msg = "unindent does not match any outer indentation level";
1250 break;
1251 case E_TOODEEP:
1252 errtype = PyExc_IndentationError;
1253 msg = "too many levels of indentation";
1254 break;
1255 default:
1256 fprintf(stderr, "error=%d\n", err->error);
1257 msg = "unknown parsing error";
1258 break;
1260 w = Py_BuildValue("(sO)", msg, v);
1261 Py_XDECREF(v);
1262 PyErr_SetObject(errtype, w);
1263 Py_XDECREF(w);
1266 /* Print fatal error message and abort */
1268 void
1269 Py_FatalError(char *msg)
1271 fprintf(stderr, "Fatal Python error: %s\n", msg);
1272 #ifdef macintosh
1273 for (;;);
1274 #endif
1275 #ifdef MS_WIN32
1276 OutputDebugString("Fatal Python error: ");
1277 OutputDebugString(msg);
1278 OutputDebugString("\n");
1279 #ifdef _DEBUG
1280 DebugBreak();
1281 #endif
1282 #endif /* MS_WIN32 */
1283 abort();
1286 /* Clean up and exit */
1288 #ifdef WITH_THREAD
1289 #include "pythread.h"
1290 int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
1291 #endif
1293 #define NEXITFUNCS 32
1294 static void (*exitfuncs[NEXITFUNCS])(void);
1295 static int nexitfuncs = 0;
1297 int Py_AtExit(void (*func)(void))
1299 if (nexitfuncs >= NEXITFUNCS)
1300 return -1;
1301 exitfuncs[nexitfuncs++] = func;
1302 return 0;
1305 static void
1306 call_sys_exitfunc(void)
1308 PyObject *exitfunc = PySys_GetObject("exitfunc");
1310 if (exitfunc) {
1311 PyObject *res;
1312 Py_INCREF(exitfunc);
1313 PySys_SetObject("exitfunc", (PyObject *)NULL);
1314 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1315 if (res == NULL) {
1316 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1317 PySys_WriteStderr("Error in sys.exitfunc:\n");
1319 PyErr_Print();
1321 Py_DECREF(exitfunc);
1324 if (Py_FlushLine())
1325 PyErr_Clear();
1328 static void
1329 call_ll_exitfuncs(void)
1331 while (nexitfuncs > 0)
1332 (*exitfuncs[--nexitfuncs])();
1334 fflush(stdout);
1335 fflush(stderr);
1338 void
1339 Py_Exit(int sts)
1341 Py_Finalize();
1343 #ifdef macintosh
1344 PyMac_Exit(sts);
1345 #else
1346 exit(sts);
1347 #endif
1350 static void
1351 initsigs(void)
1353 #ifdef HAVE_SIGNAL_H
1354 #ifdef SIGPIPE
1355 signal(SIGPIPE, SIG_IGN);
1356 #endif
1357 #ifdef SIGXFZ
1358 signal(SIGXFZ, SIG_IGN);
1359 #endif
1360 #ifdef SIGXFSZ
1361 signal(SIGXFSZ, SIG_IGN);
1362 #endif
1363 #endif /* HAVE_SIGNAL_H */
1364 PyOS_InitInterrupts(); /* May imply initsignal() */
1367 #ifdef Py_TRACE_REFS
1368 /* Ask a yes/no question */
1371 _Py_AskYesNo(char *prompt)
1373 char buf[256];
1375 fprintf(stderr, "%s [ny] ", prompt);
1376 if (fgets(buf, sizeof buf, stdin) == NULL)
1377 return 0;
1378 return buf[0] == 'y' || buf[0] == 'Y';
1380 #endif
1382 #ifdef MPW
1384 /* Check for file descriptor connected to interactive device.
1385 Pretend that stdin is always interactive, other files never. */
1388 isatty(int fd)
1390 return fd == fileno(stdin);
1393 #endif
1396 * The file descriptor fd is considered ``interactive'' if either
1397 * a) isatty(fd) is TRUE, or
1398 * b) the -i flag was given, and the filename associated with
1399 * the descriptor is NULL or "<stdin>" or "???".
1402 Py_FdIsInteractive(FILE *fp, char *filename)
1404 if (isatty((int)fileno(fp)))
1405 return 1;
1406 if (!Py_InteractiveFlag)
1407 return 0;
1408 return (filename == NULL) ||
1409 (strcmp(filename, "<stdin>") == 0) ||
1410 (strcmp(filename, "???") == 0);
1414 #if defined(USE_STACKCHECK)
1415 #if defined(WIN32) && defined(_MSC_VER)
1417 /* Stack checking for Microsoft C */
1419 #include <malloc.h>
1420 #include <excpt.h>
1423 * Return non-zero when we run out of memory on the stack; zero otherwise.
1426 PyOS_CheckStack(void)
1428 __try {
1429 /* _alloca throws a stack overflow exception if there's
1430 not enough space left on the stack */
1431 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1432 return 0;
1433 } __except (EXCEPTION_EXECUTE_HANDLER) {
1434 /* just ignore all errors */
1436 return 1;
1439 #endif /* WIN32 && _MSC_VER */
1441 /* Alternate implementations can be added here... */
1443 #endif /* USE_STACKCHECK */
1446 /* Wrappers around sigaction() or signal(). */
1448 PyOS_sighandler_t
1449 PyOS_getsig(int sig)
1451 #ifdef HAVE_SIGACTION
1452 struct sigaction context;
1453 /* Initialize context.sa_handler to SIG_ERR which makes about as
1454 * much sense as anything else. It should get overwritten if
1455 * sigaction actually succeeds and otherwise we avoid an
1456 * uninitialized memory read.
1458 context.sa_handler = SIG_ERR;
1459 sigaction(sig, NULL, &context);
1460 return context.sa_handler;
1461 #else
1462 PyOS_sighandler_t handler;
1463 handler = signal(sig, SIG_IGN);
1464 signal(sig, handler);
1465 return handler;
1466 #endif
1469 PyOS_sighandler_t
1470 PyOS_setsig(int sig, PyOS_sighandler_t handler)
1472 #ifdef HAVE_SIGACTION
1473 struct sigaction context;
1474 PyOS_sighandler_t oldhandler;
1475 /* Initialize context.sa_handler to SIG_ERR which makes about as
1476 * much sense as anything else. It should get overwritten if
1477 * sigaction actually succeeds and otherwise we avoid an
1478 * uninitialized memory read.
1480 context.sa_handler = SIG_ERR;
1481 sigaction(sig, NULL, &context);
1482 oldhandler = context.sa_handler;
1483 context.sa_handler = handler;
1484 sigaction(sig, &context, NULL);
1485 return oldhandler;
1486 #else
1487 return signal(sig, handler);
1488 #endif