Use full package paths in imports.
[python/dscho.git] / Python / pythonrun.c
blobb1fde29bd285bee530a92b24997cd32270df434b
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_WINDOWS
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);
45 extern void _PyUnicode_Init(void);
46 extern void _PyUnicode_Fini(void);
47 extern void _PyCodecRegistry_Init(void);
48 extern void _PyCodecRegistry_Fini(void);
50 int Py_DebugFlag; /* Needed by parser.c */
51 int Py_VerboseFlag; /* Needed by import.c */
52 int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
53 int Py_NoSiteFlag; /* Suppress 'import site' */
54 int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
55 int Py_FrozenFlag; /* Needed by getpath.c */
56 int Py_UnicodeFlag = 0; /* Needed by compile.c */
57 int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
58 /* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
59 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
60 true divisions (which they will be in 2.3). */
61 int _Py_QnewFlag = 0;
63 static int initialized = 0;
65 /* API to access the initialized flag -- useful for esoteric use */
67 int
68 Py_IsInitialized(void)
70 return initialized;
73 /* Global initializations. Can be undone by Py_Finalize(). Don't
74 call this twice without an intervening Py_Finalize() call. When
75 initializations fail, a fatal error is issued and the function does
76 not return. On return, the first thread and interpreter state have
77 been created.
79 Locking: you must hold the interpreter lock while calling this.
80 (If the lock has not yet been initialized, that's equivalent to
81 having the lock, but you cannot use multiple threads.)
85 static int
86 add_flag(int flag, const char *envs)
88 int env = atoi(envs);
89 if (flag < env)
90 flag = env;
91 if (flag < 1)
92 flag = 1;
93 return flag;
96 void
97 Py_Initialize(void)
99 PyInterpreterState *interp;
100 PyThreadState *tstate;
101 PyObject *bimod, *sysmod;
102 char *p;
103 extern void _Py_ReadyTypes(void);
105 if (initialized)
106 return;
107 initialized = 1;
109 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
110 Py_DebugFlag = add_flag(Py_DebugFlag, p);
111 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
112 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
113 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
114 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
116 interp = PyInterpreterState_New();
117 if (interp == NULL)
118 Py_FatalError("Py_Initialize: can't make first interpreter");
120 tstate = PyThreadState_New(interp);
121 if (tstate == NULL)
122 Py_FatalError("Py_Initialize: can't make first thread");
123 (void) PyThreadState_Swap(tstate);
125 _Py_ReadyTypes();
127 interp->modules = PyDict_New();
128 if (interp->modules == NULL)
129 Py_FatalError("Py_Initialize: can't make modules dictionary");
131 /* Init codec registry */
132 _PyCodecRegistry_Init();
134 #ifdef Py_USING_UNICODE
135 /* Init Unicode implementation; relies on the codec registry */
136 _PyUnicode_Init();
137 #endif
139 bimod = _PyBuiltin_Init();
140 if (bimod == NULL)
141 Py_FatalError("Py_Initialize: can't initialize __builtin__");
142 interp->builtins = PyModule_GetDict(bimod);
143 Py_INCREF(interp->builtins);
145 sysmod = _PySys_Init();
146 if (sysmod == NULL)
147 Py_FatalError("Py_Initialize: can't initialize sys");
148 interp->sysdict = PyModule_GetDict(sysmod);
149 Py_INCREF(interp->sysdict);
150 _PyImport_FixupExtension("sys", "sys");
151 PySys_SetPath(Py_GetPath());
152 PyDict_SetItemString(interp->sysdict, "modules",
153 interp->modules);
155 _PyImport_Init();
157 /* initialize builtin exceptions */
158 _PyExc_Init();
159 _PyImport_FixupExtension("exceptions", "exceptions");
161 /* phase 2 of builtins */
162 _PyImport_FixupExtension("__builtin__", "__builtin__");
164 initsigs(); /* Signal handling stuff, including initintr() */
166 initmain(); /* Module __main__ */
167 if (!Py_NoSiteFlag)
168 initsite(); /* Module site */
171 #ifdef COUNT_ALLOCS
172 extern void dump_counts(void);
173 #endif
175 /* Undo the effect of Py_Initialize().
177 Beware: if multiple interpreter and/or thread states exist, these
178 are not wiped out; only the current thread and interpreter state
179 are deleted. But since everything else is deleted, those other
180 interpreter and thread states should no longer be used.
182 (XXX We should do better, e.g. wipe out all interpreters and
183 threads.)
185 Locking: as above.
189 void
190 Py_Finalize(void)
192 PyInterpreterState *interp;
193 PyThreadState *tstate;
195 if (!initialized)
196 return;
198 /* The interpreter is still entirely intact at this point, and the
199 * exit funcs may be relying on that. In particular, if some thread
200 * or exit func is still waiting to do an import, the import machinery
201 * expects Py_IsInitialized() to return true. So don't say the
202 * interpreter is uninitialized until after the exit funcs have run.
203 * Note that Threading.py uses an exit func to do a join on all the
204 * threads created thru it, so this also protects pending imports in
205 * the threads created via Threading.
207 call_sys_exitfunc();
208 initialized = 0;
210 /* Get current thread state and interpreter pointer */
211 tstate = PyThreadState_Get();
212 interp = tstate->interp;
214 /* Disable signal handling */
215 PyOS_FiniInterrupts();
217 /* Cleanup Codec registry */
218 _PyCodecRegistry_Fini();
220 /* Destroy all modules */
221 PyImport_Cleanup();
223 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
224 _PyImport_Fini();
226 /* Debugging stuff */
227 #ifdef COUNT_ALLOCS
228 dump_counts();
229 #endif
231 #ifdef Py_REF_DEBUG
232 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
233 #endif
235 #ifdef Py_TRACE_REFS
236 if (Py_GETENV("PYTHONDUMPREFS")) {
237 _Py_PrintReferences(stderr);
239 #endif /* Py_TRACE_REFS */
241 /* Now we decref the exception classes. After this point nothing
242 can raise an exception. That's okay, because each Fini() method
243 below has been checked to make sure no exceptions are ever
244 raised.
246 _PyExc_Fini();
248 /* Delete current thread */
249 PyInterpreterState_Clear(interp);
250 PyThreadState_Swap(NULL);
251 PyInterpreterState_Delete(interp);
253 PyMethod_Fini();
254 PyFrame_Fini();
255 PyCFunction_Fini();
256 PyTuple_Fini();
257 PyString_Fini();
258 PyInt_Fini();
259 PyFloat_Fini();
261 #ifdef Py_USING_UNICODE
262 /* Cleanup Unicode implementation */
263 _PyUnicode_Fini();
264 #endif
266 /* XXX Still allocated:
267 - various static ad-hoc pointers to interned strings
268 - int and float free list blocks
269 - whatever various modules and libraries allocate
272 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
274 #ifdef PYMALLOC_DEBUG
275 if (Py_GETENV("PYTHONMALLOCSTATS"))
276 _PyObject_DebugMallocStats();
277 #endif
279 call_ll_exitfuncs();
281 #ifdef Py_TRACE_REFS
282 _Py_ResetReferences();
283 #endif /* Py_TRACE_REFS */
286 /* Create and initialize a new interpreter and thread, and return the
287 new thread. This requires that Py_Initialize() has been called
288 first.
290 Unsuccessful initialization yields a NULL pointer. Note that *no*
291 exception information is available even in this case -- the
292 exception information is held in the thread, and there is no
293 thread.
295 Locking: as above.
299 PyThreadState *
300 Py_NewInterpreter(void)
302 PyInterpreterState *interp;
303 PyThreadState *tstate, *save_tstate;
304 PyObject *bimod, *sysmod;
306 if (!initialized)
307 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
309 interp = PyInterpreterState_New();
310 if (interp == NULL)
311 return NULL;
313 tstate = PyThreadState_New(interp);
314 if (tstate == NULL) {
315 PyInterpreterState_Delete(interp);
316 return NULL;
319 save_tstate = PyThreadState_Swap(tstate);
321 /* XXX The following is lax in error checking */
323 interp->modules = PyDict_New();
325 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
326 if (bimod != NULL) {
327 interp->builtins = PyModule_GetDict(bimod);
328 Py_INCREF(interp->builtins);
330 sysmod = _PyImport_FindExtension("sys", "sys");
331 if (bimod != NULL && sysmod != NULL) {
332 interp->sysdict = PyModule_GetDict(sysmod);
333 Py_INCREF(interp->sysdict);
334 PySys_SetPath(Py_GetPath());
335 PyDict_SetItemString(interp->sysdict, "modules",
336 interp->modules);
337 initmain();
338 if (!Py_NoSiteFlag)
339 initsite();
342 if (!PyErr_Occurred())
343 return tstate;
345 /* Oops, it didn't work. Undo it all. */
347 PyErr_Print();
348 PyThreadState_Clear(tstate);
349 PyThreadState_Swap(save_tstate);
350 PyThreadState_Delete(tstate);
351 PyInterpreterState_Delete(interp);
353 return NULL;
356 /* Delete an interpreter and its last thread. This requires that the
357 given thread state is current, that the thread has no remaining
358 frames, and that it is its interpreter's only remaining thread.
359 It is a fatal error to violate these constraints.
361 (Py_Finalize() doesn't have these constraints -- it zaps
362 everything, regardless.)
364 Locking: as above.
368 void
369 Py_EndInterpreter(PyThreadState *tstate)
371 PyInterpreterState *interp = tstate->interp;
373 if (tstate != PyThreadState_Get())
374 Py_FatalError("Py_EndInterpreter: thread is not current");
375 if (tstate->frame != NULL)
376 Py_FatalError("Py_EndInterpreter: thread still has a frame");
377 if (tstate != interp->tstate_head || tstate->next != NULL)
378 Py_FatalError("Py_EndInterpreter: not the last thread");
380 PyImport_Cleanup();
381 PyInterpreterState_Clear(interp);
382 PyThreadState_Swap(NULL);
383 PyInterpreterState_Delete(interp);
386 static char *progname = "python";
388 void
389 Py_SetProgramName(char *pn)
391 if (pn && *pn)
392 progname = pn;
395 char *
396 Py_GetProgramName(void)
398 return progname;
401 static char *default_home = NULL;
403 void
404 Py_SetPythonHome(char *home)
406 default_home = home;
409 char *
410 Py_GetPythonHome(void)
412 char *home = default_home;
413 if (home == NULL && !Py_IgnoreEnvironmentFlag)
414 home = Py_GETENV("PYTHONHOME");
415 return home;
418 /* Create __main__ module */
420 static void
421 initmain(void)
423 PyObject *m, *d;
424 m = PyImport_AddModule("__main__");
425 if (m == NULL)
426 Py_FatalError("can't create __main__ module");
427 d = PyModule_GetDict(m);
428 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
429 PyObject *bimod = PyImport_ImportModule("__builtin__");
430 if (bimod == NULL ||
431 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
432 Py_FatalError("can't add __builtins__ to __main__");
433 Py_DECREF(bimod);
437 /* Import the site module (not into __main__ though) */
439 static void
440 initsite(void)
442 PyObject *m, *f;
443 m = PyImport_ImportModule("site");
444 if (m == NULL) {
445 f = PySys_GetObject("stderr");
446 if (Py_VerboseFlag) {
447 PyFile_WriteString(
448 "'import site' failed; traceback:\n", f);
449 PyErr_Print();
451 else {
452 PyFile_WriteString(
453 "'import site' failed; use -v for traceback\n", f);
454 PyErr_Clear();
457 else {
458 Py_DECREF(m);
462 /* Parse input from a file and execute it */
465 PyRun_AnyFile(FILE *fp, char *filename)
467 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
471 PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
473 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
477 PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
479 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
483 PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
484 PyCompilerFlags *flags)
486 if (filename == NULL)
487 filename = "???";
488 if (Py_FdIsInteractive(fp, filename)) {
489 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
490 if (closeit)
491 fclose(fp);
492 return err;
494 else
495 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
499 PyRun_InteractiveLoop(FILE *fp, char *filename)
501 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
505 PyRun_InteractiveLoopFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
507 PyObject *v;
508 int ret;
509 PyCompilerFlags local_flags;
511 if (flags == NULL) {
512 flags = &local_flags;
513 local_flags.cf_flags = 0;
515 v = PySys_GetObject("ps1");
516 if (v == NULL) {
517 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
518 Py_XDECREF(v);
520 v = PySys_GetObject("ps2");
521 if (v == NULL) {
522 PySys_SetObject("ps2", v = PyString_FromString("... "));
523 Py_XDECREF(v);
525 for (;;) {
526 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
527 #ifdef Py_REF_DEBUG
528 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
529 #endif
530 if (ret == E_EOF)
531 return 0;
533 if (ret == E_NOMEM)
534 return -1;
540 PyRun_InteractiveOne(FILE *fp, char *filename)
542 return PyRun_InteractiveOneFlags(fp, filename, NULL);
545 /* compute parser flags based on compiler flags */
546 #if 0 /* future keyword */
547 #define PARSER_FLAGS(flags) \
548 (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \
549 PyPARSE_YIELD_IS_KEYWORD : 0)
550 #else
551 #define PARSER_FLAGS(flags) 0
552 #endif
555 PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
557 PyObject *m, *d, *v, *w;
558 node *n;
559 perrdetail err;
560 char *ps1 = "", *ps2 = "";
562 v = PySys_GetObject("ps1");
563 if (v != NULL) {
564 v = PyObject_Str(v);
565 if (v == NULL)
566 PyErr_Clear();
567 else if (PyString_Check(v))
568 ps1 = PyString_AsString(v);
570 w = PySys_GetObject("ps2");
571 if (w != NULL) {
572 w = PyObject_Str(w);
573 if (w == NULL)
574 PyErr_Clear();
575 else if (PyString_Check(w))
576 ps2 = PyString_AsString(w);
578 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
579 Py_single_input, ps1, ps2, &err,
580 PARSER_FLAGS(flags));
581 Py_XDECREF(v);
582 Py_XDECREF(w);
583 if (n == NULL) {
584 if (err.error == E_EOF) {
585 if (err.text)
586 PyMem_DEL(err.text);
587 return E_EOF;
589 err_input(&err);
590 PyErr_Print();
591 return err.error;
593 m = PyImport_AddModule("__main__");
594 if (m == NULL)
595 return -1;
596 d = PyModule_GetDict(m);
597 v = run_node(n, filename, d, d, flags);
598 if (v == NULL) {
599 PyErr_Print();
600 return -1;
602 Py_DECREF(v);
603 if (Py_FlushLine())
604 PyErr_Clear();
605 return 0;
609 PyRun_SimpleFile(FILE *fp, char *filename)
611 return PyRun_SimpleFileEx(fp, filename, 0);
614 /* Check whether a file maybe a pyc file: Look at the extension,
615 the file type, and, if we may close it, at the first few bytes. */
617 static int
618 maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
620 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
621 return 1;
623 #ifdef macintosh
624 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
625 if (PyMac_getfiletype(filename) == 'PYC '
626 || PyMac_getfiletype(filename) == 'APPL')
627 return 1;
628 #endif /* macintosh */
630 /* Only look into the file if we are allowed to close it, since
631 it then should also be seekable. */
632 if (closeit) {
633 /* Read only two bytes of the magic. If the file was opened in
634 text mode, the bytes 3 and 4 of the magic (\r\n) might not
635 be read as they are on disk. */
636 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
637 unsigned char buf[2];
638 /* Mess: In case of -x, the stream is NOT at its start now,
639 and ungetc() was used to push back the first newline,
640 which makes the current stream position formally undefined,
641 and a x-platform nightmare.
642 Unfortunately, we have no direct way to know whether -x
643 was specified. So we use a terrible hack: if the current
644 stream position is not 0, we assume -x was specified, and
645 give up. Bug 132850 on SourceForge spells out the
646 hopelessness of trying anything else (fseek and ftell
647 don't work predictably x-platform for text-mode files).
649 int ispyc = 0;
650 if (ftell(fp) == 0) {
651 if (fread(buf, 1, 2, fp) == 2 &&
652 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
653 ispyc = 1;
654 rewind(fp);
656 return ispyc;
658 return 0;
662 PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
664 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
668 PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit,
669 PyCompilerFlags *flags)
671 PyObject *m, *d, *v;
672 char *ext;
674 m = PyImport_AddModule("__main__");
675 if (m == NULL)
676 return -1;
677 d = PyModule_GetDict(m);
678 ext = filename + strlen(filename) - 4;
679 if (maybe_pyc_file(fp, filename, ext, closeit)) {
680 /* Try to run a pyc file. First, re-open in binary */
681 if (closeit)
682 fclose(fp);
683 if( (fp = fopen(filename, "rb")) == NULL ) {
684 fprintf(stderr, "python: Can't reopen .pyc file\n");
685 return -1;
687 /* Turn on optimization if a .pyo file is given */
688 if (strcmp(ext, ".pyo") == 0)
689 Py_OptimizeFlag = 1;
690 v = run_pyc_file(fp, filename, d, d, flags);
691 } else {
692 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
693 closeit, flags);
695 if (v == NULL) {
696 PyErr_Print();
697 return -1;
699 Py_DECREF(v);
700 if (Py_FlushLine())
701 PyErr_Clear();
702 return 0;
706 PyRun_SimpleString(char *command)
708 return PyRun_SimpleStringFlags(command, NULL);
712 PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags)
714 PyObject *m, *d, *v;
715 m = PyImport_AddModule("__main__");
716 if (m == NULL)
717 return -1;
718 d = PyModule_GetDict(m);
719 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
720 if (v == NULL) {
721 PyErr_Print();
722 return -1;
724 Py_DECREF(v);
725 if (Py_FlushLine())
726 PyErr_Clear();
727 return 0;
730 static int
731 parse_syntax_error(PyObject *err, PyObject **message, char **filename,
732 int *lineno, int *offset, char **text)
734 long hold;
735 PyObject *v;
737 /* old style errors */
738 if (PyTuple_Check(err))
739 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
740 lineno, offset, text);
742 /* new style errors. `err' is an instance */
744 if (! (v = PyObject_GetAttrString(err, "msg")))
745 goto finally;
746 *message = v;
748 if (!(v = PyObject_GetAttrString(err, "filename")))
749 goto finally;
750 if (v == Py_None)
751 *filename = NULL;
752 else if (! (*filename = PyString_AsString(v)))
753 goto finally;
755 Py_DECREF(v);
756 if (!(v = PyObject_GetAttrString(err, "lineno")))
757 goto finally;
758 hold = PyInt_AsLong(v);
759 Py_DECREF(v);
760 v = NULL;
761 if (hold < 0 && PyErr_Occurred())
762 goto finally;
763 *lineno = (int)hold;
765 if (!(v = PyObject_GetAttrString(err, "offset")))
766 goto finally;
767 if (v == Py_None) {
768 *offset = -1;
769 Py_DECREF(v);
770 v = NULL;
771 } else {
772 hold = PyInt_AsLong(v);
773 Py_DECREF(v);
774 v = NULL;
775 if (hold < 0 && PyErr_Occurred())
776 goto finally;
777 *offset = (int)hold;
780 if (!(v = PyObject_GetAttrString(err, "text")))
781 goto finally;
782 if (v == Py_None)
783 *text = NULL;
784 else if (! (*text = PyString_AsString(v)))
785 goto finally;
786 Py_DECREF(v);
787 return 1;
789 finally:
790 Py_XDECREF(v);
791 return 0;
794 void
795 PyErr_Print(void)
797 PyErr_PrintEx(1);
800 static void
801 print_error_text(PyObject *f, int offset, char *text)
803 char *nl;
804 if (offset >= 0) {
805 if (offset > 0 && offset == (int)strlen(text))
806 offset--;
807 for (;;) {
808 nl = strchr(text, '\n');
809 if (nl == NULL || nl-text >= offset)
810 break;
811 offset -= (nl+1-text);
812 text = nl+1;
814 while (*text == ' ' || *text == '\t') {
815 text++;
816 offset--;
819 PyFile_WriteString(" ", f);
820 PyFile_WriteString(text, f);
821 if (*text == '\0' || text[strlen(text)-1] != '\n')
822 PyFile_WriteString("\n", f);
823 if (offset == -1)
824 return;
825 PyFile_WriteString(" ", f);
826 offset--;
827 while (offset > 0) {
828 PyFile_WriteString(" ", f);
829 offset--;
831 PyFile_WriteString("^\n", f);
834 static void
835 handle_system_exit(void)
837 PyObject *exception, *value, *tb;
838 PyErr_Fetch(&exception, &value, &tb);
839 if (Py_FlushLine())
840 PyErr_Clear();
841 fflush(stdout);
842 if (value == NULL || value == Py_None)
843 Py_Exit(0);
844 if (PyInstance_Check(value)) {
845 /* The error code should be in the `code' attribute. */
846 PyObject *code = PyObject_GetAttrString(value, "code");
847 if (code) {
848 Py_DECREF(value);
849 value = code;
850 if (value == Py_None)
851 Py_Exit(0);
853 /* If we failed to dig out the 'code' attribute,
854 just let the else clause below print the error. */
856 if (PyInt_Check(value))
857 Py_Exit((int)PyInt_AsLong(value));
858 else {
859 PyObject_Print(value, stderr, Py_PRINT_RAW);
860 PySys_WriteStderr("\n");
861 Py_Exit(1);
865 void
866 PyErr_PrintEx(int set_sys_last_vars)
868 PyObject *exception, *v, *tb, *hook;
870 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
871 handle_system_exit();
873 PyErr_Fetch(&exception, &v, &tb);
874 PyErr_NormalizeException(&exception, &v, &tb);
875 if (exception == NULL)
876 return;
877 if (set_sys_last_vars) {
878 PySys_SetObject("last_type", exception);
879 PySys_SetObject("last_value", v);
880 PySys_SetObject("last_traceback", tb);
882 hook = PySys_GetObject("excepthook");
883 if (hook) {
884 PyObject *args = Py_BuildValue("(OOO)",
885 exception, v ? v : Py_None, tb ? tb : Py_None);
886 PyObject *result = PyEval_CallObject(hook, args);
887 if (result == NULL) {
888 PyObject *exception2, *v2, *tb2;
889 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
890 handle_system_exit();
892 PyErr_Fetch(&exception2, &v2, &tb2);
893 PyErr_NormalizeException(&exception2, &v2, &tb2);
894 if (Py_FlushLine())
895 PyErr_Clear();
896 fflush(stdout);
897 PySys_WriteStderr("Error in sys.excepthook:\n");
898 PyErr_Display(exception2, v2, tb2);
899 PySys_WriteStderr("\nOriginal exception was:\n");
900 PyErr_Display(exception, v, tb);
901 Py_XDECREF(exception2);
902 Py_XDECREF(v2);
903 Py_XDECREF(tb2);
905 Py_XDECREF(result);
906 Py_XDECREF(args);
907 } else {
908 PySys_WriteStderr("sys.excepthook is missing\n");
909 PyErr_Display(exception, v, tb);
911 Py_XDECREF(exception);
912 Py_XDECREF(v);
913 Py_XDECREF(tb);
916 void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
918 int err = 0;
919 PyObject *v = value;
920 PyObject *f = PySys_GetObject("stderr");
921 if (f == NULL)
922 fprintf(stderr, "lost sys.stderr\n");
923 else {
924 if (Py_FlushLine())
925 PyErr_Clear();
926 fflush(stdout);
927 if (tb && tb != Py_None)
928 err = PyTraceBack_Print(tb, f);
929 if (err == 0 &&
930 PyObject_HasAttrString(v, "print_file_and_line"))
932 PyObject *message;
933 char *filename, *text;
934 int lineno, offset;
935 if (!parse_syntax_error(v, &message, &filename,
936 &lineno, &offset, &text))
937 PyErr_Clear();
938 else {
939 char buf[10];
940 PyFile_WriteString(" File \"", f);
941 if (filename == NULL)
942 PyFile_WriteString("<string>", f);
943 else
944 PyFile_WriteString(filename, f);
945 PyFile_WriteString("\", line ", f);
946 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
947 PyFile_WriteString(buf, f);
948 PyFile_WriteString("\n", f);
949 if (text != NULL)
950 print_error_text(f, offset, text);
951 v = message;
952 /* Can't be bothered to check all those
953 PyFile_WriteString() calls */
954 if (PyErr_Occurred())
955 err = -1;
958 if (err) {
959 /* Don't do anything else */
961 else if (PyClass_Check(exception)) {
962 PyClassObject* exc = (PyClassObject*)exception;
963 PyObject* className = exc->cl_name;
964 PyObject* moduleName =
965 PyDict_GetItemString(exc->cl_dict, "__module__");
967 if (moduleName == NULL)
968 err = PyFile_WriteString("<unknown>", f);
969 else {
970 char* modstr = PyString_AsString(moduleName);
971 if (modstr && strcmp(modstr, "exceptions"))
973 err = PyFile_WriteString(modstr, f);
974 err += PyFile_WriteString(".", f);
977 if (err == 0) {
978 if (className == NULL)
979 err = PyFile_WriteString("<unknown>", f);
980 else
981 err = PyFile_WriteObject(className, f,
982 Py_PRINT_RAW);
985 else
986 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
987 if (err == 0) {
988 if (v != NULL && v != Py_None) {
989 PyObject *s = PyObject_Str(v);
990 /* only print colon if the str() of the
991 object is not the empty string
993 if (s == NULL)
994 err = -1;
995 else if (!PyString_Check(s) ||
996 PyString_GET_SIZE(s) != 0)
997 err = PyFile_WriteString(": ", f);
998 if (err == 0)
999 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1000 Py_XDECREF(s);
1003 if (err == 0)
1004 err = PyFile_WriteString("\n", f);
1006 /* If an error happened here, don't show it.
1007 XXX This is wrong, but too many callers rely on this behavior. */
1008 if (err != 0)
1009 PyErr_Clear();
1012 PyObject *
1013 PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
1015 return run_err_node(PyParser_SimpleParseString(str, start),
1016 "<string>", globals, locals, NULL);
1019 PyObject *
1020 PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
1021 PyObject *locals)
1023 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
1026 PyObject *
1027 PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
1028 PyObject *locals, int closeit)
1030 node *n = PyParser_SimpleParseFile(fp, filename, start);
1031 if (closeit)
1032 fclose(fp);
1033 return run_err_node(n, filename, globals, locals, NULL);
1036 PyObject *
1037 PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1038 PyCompilerFlags *flags)
1040 return run_err_node(PyParser_SimpleParseStringFlags(
1041 str, start, PARSER_FLAGS(flags)),
1042 "<string>", globals, locals, flags);
1045 PyObject *
1046 PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1047 PyObject *locals, PyCompilerFlags *flags)
1049 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1050 flags);
1053 PyObject *
1054 PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1055 PyObject *locals, int closeit, PyCompilerFlags *flags)
1057 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
1058 PARSER_FLAGS(flags));
1059 if (closeit)
1060 fclose(fp);
1061 return run_err_node(n, filename, globals, locals, flags);
1064 static PyObject *
1065 run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1066 PyCompilerFlags *flags)
1068 if (n == NULL)
1069 return NULL;
1070 return run_node(n, filename, globals, locals, flags);
1073 static PyObject *
1074 run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1075 PyCompilerFlags *flags)
1077 PyCodeObject *co;
1078 PyObject *v;
1079 co = PyNode_CompileFlags(n, filename, flags);
1080 PyNode_Free(n);
1081 if (co == NULL)
1082 return NULL;
1083 v = PyEval_EvalCode(co, globals, locals);
1084 Py_DECREF(co);
1085 return v;
1088 static PyObject *
1089 run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1090 PyCompilerFlags *flags)
1092 PyCodeObject *co;
1093 PyObject *v;
1094 long magic;
1095 long PyImport_GetMagicNumber(void);
1097 magic = PyMarshal_ReadLongFromFile(fp);
1098 if (magic != PyImport_GetMagicNumber()) {
1099 PyErr_SetString(PyExc_RuntimeError,
1100 "Bad magic number in .pyc file");
1101 return NULL;
1103 (void) PyMarshal_ReadLongFromFile(fp);
1104 v = PyMarshal_ReadLastObjectFromFile(fp);
1105 fclose(fp);
1106 if (v == NULL || !PyCode_Check(v)) {
1107 Py_XDECREF(v);
1108 PyErr_SetString(PyExc_RuntimeError,
1109 "Bad code object in .pyc file");
1110 return NULL;
1112 co = (PyCodeObject *)v;
1113 v = PyEval_EvalCode(co, globals, locals);
1114 if (v && flags)
1115 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1116 Py_DECREF(co);
1117 return v;
1120 PyObject *
1121 Py_CompileString(char *str, char *filename, int start)
1123 return Py_CompileStringFlags(str, filename, start, NULL);
1126 PyObject *
1127 Py_CompileStringFlags(char *str, char *filename, int start,
1128 PyCompilerFlags *flags)
1130 node *n;
1131 PyCodeObject *co;
1133 n = PyParser_SimpleParseStringFlagsFilename(str, filename, start,
1134 PARSER_FLAGS(flags));
1135 if (n == NULL)
1136 return NULL;
1137 co = PyNode_CompileFlags(n, filename, flags);
1138 PyNode_Free(n);
1139 return (PyObject *)co;
1142 struct symtable *
1143 Py_SymtableString(char *str, char *filename, int start)
1145 node *n;
1146 struct symtable *st;
1147 n = PyParser_SimpleParseStringFlagsFilename(str, filename,
1148 start, 0);
1149 if (n == NULL)
1150 return NULL;
1151 st = PyNode_CompileSymtable(n, filename);
1152 PyNode_Free(n);
1153 return st;
1156 /* Simplified interface to parsefile -- return node or set exception */
1158 node *
1159 PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
1161 node *n;
1162 perrdetail err;
1163 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1164 (char *)0, (char *)0, &err, flags);
1165 if (n == NULL)
1166 err_input(&err);
1167 return n;
1170 node *
1171 PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1173 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1176 /* Simplified interface to parsestring -- return node or set exception */
1178 node *
1179 PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1181 node *n;
1182 perrdetail err;
1183 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1184 flags);
1185 if (n == NULL)
1186 err_input(&err);
1187 return n;
1190 node *
1191 PyParser_SimpleParseString(char *str, int start)
1193 return PyParser_SimpleParseStringFlags(str, start, 0);
1196 node *
1197 PyParser_SimpleParseStringFlagsFilename(char *str, char *filename,
1198 int start, int flags)
1200 node *n;
1201 perrdetail err;
1203 n = PyParser_ParseStringFlagsFilename(str, filename,
1204 &_PyParser_Grammar,
1205 start, &err, flags);
1206 if (n == NULL)
1207 err_input(&err);
1208 return n;
1211 node *
1212 PyParser_SimpleParseStringFilename(char *str, char *filename, int start)
1214 return PyParser_SimpleParseStringFlagsFilename(str, filename,
1215 start, 0);
1218 /* Set the error appropriate to the given input error code (see errcode.h) */
1220 static void
1221 err_input(perrdetail *err)
1223 PyObject *v, *w, *errtype;
1224 char *msg = NULL;
1225 errtype = PyExc_SyntaxError;
1226 v = Py_BuildValue("(ziiz)", err->filename,
1227 err->lineno, err->offset, err->text);
1228 if (err->text != NULL) {
1229 PyMem_DEL(err->text);
1230 err->text = NULL;
1232 switch (err->error) {
1233 case E_SYNTAX:
1234 errtype = PyExc_IndentationError;
1235 if (err->expected == INDENT)
1236 msg = "expected an indented block";
1237 else if (err->token == INDENT)
1238 msg = "unexpected indent";
1239 else if (err->token == DEDENT)
1240 msg = "unexpected unindent";
1241 else {
1242 errtype = PyExc_SyntaxError;
1243 msg = "invalid syntax";
1245 break;
1246 case E_TOKEN:
1247 msg = "invalid token";
1248 break;
1249 case E_INTR:
1250 PyErr_SetNone(PyExc_KeyboardInterrupt);
1251 Py_XDECREF(v);
1252 return;
1253 case E_NOMEM:
1254 PyErr_NoMemory();
1255 Py_XDECREF(v);
1256 return;
1257 case E_EOF:
1258 msg = "unexpected EOF while parsing";
1259 break;
1260 case E_TABSPACE:
1261 errtype = PyExc_TabError;
1262 msg = "inconsistent use of tabs and spaces in indentation";
1263 break;
1264 case E_OVERFLOW:
1265 msg = "expression too long";
1266 break;
1267 case E_DEDENT:
1268 errtype = PyExc_IndentationError;
1269 msg = "unindent does not match any outer indentation level";
1270 break;
1271 case E_TOODEEP:
1272 errtype = PyExc_IndentationError;
1273 msg = "too many levels of indentation";
1274 break;
1275 default:
1276 fprintf(stderr, "error=%d\n", err->error);
1277 msg = "unknown parsing error";
1278 break;
1280 w = Py_BuildValue("(sO)", msg, v);
1281 Py_XDECREF(v);
1282 PyErr_SetObject(errtype, w);
1283 Py_XDECREF(w);
1286 /* Print fatal error message and abort */
1288 void
1289 Py_FatalError(const char *msg)
1291 fprintf(stderr, "Fatal Python error: %s\n", msg);
1292 #ifdef macintosh
1293 for (;;);
1294 #endif
1295 #ifdef MS_WINDOWS
1296 OutputDebugString("Fatal Python error: ");
1297 OutputDebugString(msg);
1298 OutputDebugString("\n");
1299 #ifdef _DEBUG
1300 DebugBreak();
1301 #endif
1302 #endif /* MS_WINDOWS */
1303 abort();
1306 /* Clean up and exit */
1308 #ifdef WITH_THREAD
1309 #include "pythread.h"
1310 int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
1311 #endif
1313 #define NEXITFUNCS 32
1314 static void (*exitfuncs[NEXITFUNCS])(void);
1315 static int nexitfuncs = 0;
1317 int Py_AtExit(void (*func)(void))
1319 if (nexitfuncs >= NEXITFUNCS)
1320 return -1;
1321 exitfuncs[nexitfuncs++] = func;
1322 return 0;
1325 static void
1326 call_sys_exitfunc(void)
1328 PyObject *exitfunc = PySys_GetObject("exitfunc");
1330 if (exitfunc) {
1331 PyObject *res;
1332 Py_INCREF(exitfunc);
1333 PySys_SetObject("exitfunc", (PyObject *)NULL);
1334 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1335 if (res == NULL) {
1336 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1337 PySys_WriteStderr("Error in sys.exitfunc:\n");
1339 PyErr_Print();
1341 Py_DECREF(exitfunc);
1344 if (Py_FlushLine())
1345 PyErr_Clear();
1348 static void
1349 call_ll_exitfuncs(void)
1351 while (nexitfuncs > 0)
1352 (*exitfuncs[--nexitfuncs])();
1354 fflush(stdout);
1355 fflush(stderr);
1358 void
1359 Py_Exit(int sts)
1361 Py_Finalize();
1363 #ifdef macintosh
1364 PyMac_Exit(sts);
1365 #else
1366 exit(sts);
1367 #endif
1370 static void
1371 initsigs(void)
1373 #ifdef HAVE_SIGNAL_H
1374 #ifdef SIGPIPE
1375 signal(SIGPIPE, SIG_IGN);
1376 #endif
1377 #ifdef SIGXFZ
1378 signal(SIGXFZ, SIG_IGN);
1379 #endif
1380 #ifdef SIGXFSZ
1381 signal(SIGXFSZ, SIG_IGN);
1382 #endif
1383 #endif /* HAVE_SIGNAL_H */
1384 PyOS_InitInterrupts(); /* May imply initsignal() */
1387 #ifdef MPW
1389 /* Check for file descriptor connected to interactive device.
1390 Pretend that stdin is always interactive, other files never. */
1393 isatty(int fd)
1395 return fd == fileno(stdin);
1398 #endif
1401 * The file descriptor fd is considered ``interactive'' if either
1402 * a) isatty(fd) is TRUE, or
1403 * b) the -i flag was given, and the filename associated with
1404 * the descriptor is NULL or "<stdin>" or "???".
1407 Py_FdIsInteractive(FILE *fp, char *filename)
1409 if (isatty((int)fileno(fp)))
1410 return 1;
1411 if (!Py_InteractiveFlag)
1412 return 0;
1413 return (filename == NULL) ||
1414 (strcmp(filename, "<stdin>") == 0) ||
1415 (strcmp(filename, "???") == 0);
1419 #if defined(USE_STACKCHECK)
1420 #if defined(WIN32) && defined(_MSC_VER)
1422 /* Stack checking for Microsoft C */
1424 #include <malloc.h>
1425 #include <excpt.h>
1428 * Return non-zero when we run out of memory on the stack; zero otherwise.
1431 PyOS_CheckStack(void)
1433 __try {
1434 /* _alloca throws a stack overflow exception if there's
1435 not enough space left on the stack */
1436 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1437 return 0;
1438 } __except (EXCEPTION_EXECUTE_HANDLER) {
1439 /* just ignore all errors */
1441 return 1;
1444 #endif /* WIN32 && _MSC_VER */
1446 /* Alternate implementations can be added here... */
1448 #endif /* USE_STACKCHECK */
1451 /* Wrappers around sigaction() or signal(). */
1453 PyOS_sighandler_t
1454 PyOS_getsig(int sig)
1456 #ifdef HAVE_SIGACTION
1457 struct sigaction context;
1458 /* Initialize context.sa_handler to SIG_ERR which makes about as
1459 * much sense as anything else. It should get overwritten if
1460 * sigaction actually succeeds and otherwise we avoid an
1461 * uninitialized memory read.
1463 context.sa_handler = SIG_ERR;
1464 sigaction(sig, NULL, &context);
1465 return context.sa_handler;
1466 #else
1467 PyOS_sighandler_t handler;
1468 handler = signal(sig, SIG_IGN);
1469 signal(sig, handler);
1470 return handler;
1471 #endif
1474 PyOS_sighandler_t
1475 PyOS_setsig(int sig, PyOS_sighandler_t handler)
1477 #ifdef HAVE_SIGACTION
1478 struct sigaction context;
1479 PyOS_sighandler_t oldhandler;
1480 /* Initialize context.sa_handler to SIG_ERR which makes about as
1481 * much sense as anything else. It should get overwritten if
1482 * sigaction actually succeeds and otherwise we avoid an
1483 * uninitialized memory read.
1485 context.sa_handler = SIG_ERR;
1486 sigaction(sig, NULL, &context);
1487 oldhandler = context.sa_handler;
1488 context.sa_handler = handler;
1489 sigaction(sig, &context, NULL);
1490 return oldhandler;
1491 #else
1492 return signal(sig, handler);
1493 #endif