home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Python / pythonrun.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  27.3 KB  |  1,256 lines

  1.  
  2. /* Python interpreter top-level routines, including init/exit */
  3.  
  4. #include "Python.h"
  5.  
  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 "eval.h"
  13. #include "marshal.h"
  14.  
  15. #ifdef HAVE_UNISTD_H
  16. #include <unistd.h>
  17. #endif
  18.  
  19. #ifdef HAVE_SIGNAL_H
  20. #include <signal.h>
  21. #endif
  22.  
  23. #ifdef MS_WIN32
  24. #undef BYTE
  25. #include "windows.h"
  26. #endif
  27.  
  28. #ifdef macintosh
  29. #include "macglue.h"
  30. #endif
  31. extern char *Py_GetPath(void);
  32.  
  33. extern grammar _PyParser_Grammar; /* From graminit.c */
  34.  
  35. /* Forward */
  36. static void initmain(void);
  37. static void initsite(void);
  38. static PyObject *run_err_node(node *n, char *filename,
  39.                   PyObject *globals, PyObject *locals);
  40. static PyObject *run_node(node *n, char *filename,
  41.               PyObject *globals, PyObject *locals);
  42. static PyObject *run_pyc_file(FILE *fp, char *filename,
  43.                   PyObject *globals, PyObject *locals);
  44. static void err_input(perrdetail *);
  45. static void initsigs(void);
  46. static void call_sys_exitfunc(void);
  47. static void call_ll_exitfuncs(void);
  48.  
  49. #ifdef Py_TRACE_REFS
  50. int _Py_AskYesNo(char *prompt);
  51. #endif
  52.  
  53. extern void _PyUnicode_Init(void);
  54. extern void _PyUnicode_Fini(void);
  55. extern void _PyCodecRegistry_Init(void);
  56. extern void _PyCodecRegistry_Fini(void);
  57.  
  58.  
  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.  
  67. static int initialized = 0;
  68.  
  69. /* API to access the initialized flag -- useful for esoteric use */
  70.  
  71. int
  72. Py_IsInitialized(void)
  73. {
  74.     return initialized;
  75. }
  76.  
  77. /* Global initializations.  Can be undone by Py_Finalize().  Don't
  78.    call this twice without an intervening Py_Finalize() call.  When
  79.    initializations fail, a fatal error is issued and the function does
  80.    not return.  On return, the first thread and interpreter state have
  81.    been created.
  82.  
  83.    Locking: you must hold the interpreter lock while calling this.
  84.    (If the lock has not yet been initialized, that's equivalent to
  85.    having the lock, but you cannot use multiple threads.)
  86.  
  87. */
  88.  
  89. void
  90. Py_Initialize(void)
  91. {
  92.     PyInterpreterState *interp;
  93.     PyThreadState *tstate;
  94.     PyObject *bimod, *sysmod;
  95.     char *p;
  96.  
  97.     if (initialized)
  98.         return;
  99.     initialized = 1;
  100.     
  101.     if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
  102.         Py_DebugFlag = Py_DebugFlag ? Py_DebugFlag : 1;
  103.     if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
  104.         Py_VerboseFlag = Py_VerboseFlag ? Py_VerboseFlag : 1;
  105.     if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0')
  106.         Py_OptimizeFlag = Py_OptimizeFlag ? Py_OptimizeFlag : 1;
  107.  
  108.     interp = PyInterpreterState_New();
  109.     if (interp == NULL)
  110.         Py_FatalError("Py_Initialize: can't make first interpreter");
  111.  
  112.     tstate = PyThreadState_New(interp);
  113.     if (tstate == NULL)
  114.         Py_FatalError("Py_Initialize: can't make first thread");
  115.     (void) PyThreadState_Swap(tstate);
  116.  
  117.     interp->modules = PyDict_New();
  118.     if (interp->modules == NULL)
  119.         Py_FatalError("Py_Initialize: can't make modules dictionary");
  120.  
  121.     /* Init codec registry */
  122.     _PyCodecRegistry_Init();
  123.  
  124.     /* Init Unicode implementation; relies on the codec registry */
  125.     _PyUnicode_Init();
  126.  
  127.     _PyCompareState_Key = PyString_InternFromString("cmp_state");
  128.  
  129.     bimod = _PyBuiltin_Init();
  130.     if (bimod == NULL)
  131.         Py_FatalError("Py_Initialize: can't initialize __builtin__");
  132.     interp->builtins = PyModule_GetDict(bimod);
  133.     Py_INCREF(interp->builtins);
  134.  
  135.     sysmod = _PySys_Init();
  136.     if (sysmod == NULL)
  137.         Py_FatalError("Py_Initialize: can't initialize sys");
  138.     interp->sysdict = PyModule_GetDict(sysmod);
  139.     Py_INCREF(interp->sysdict);
  140.     _PyImport_FixupExtension("sys", "sys");
  141.     PySys_SetPath(Py_GetPath());
  142.     PyDict_SetItemString(interp->sysdict, "modules",
  143.                  interp->modules);
  144.  
  145.     _PyImport_Init();
  146.  
  147.     /* initialize builtin exceptions */
  148.     init_exceptions();
  149.  
  150.     /* phase 2 of builtins */
  151.     _PyImport_FixupExtension("__builtin__", "__builtin__");
  152.  
  153.     initsigs(); /* Signal handling stuff, including initintr() */
  154.  
  155.     initmain(); /* Module __main__ */
  156.     if (!Py_NoSiteFlag)
  157.         initsite(); /* Module site */
  158. }
  159.  
  160. #ifdef COUNT_ALLOCS
  161. extern void dump_counts(void);
  162. #endif
  163.  
  164. /* Undo the effect of Py_Initialize().
  165.  
  166.    Beware: if multiple interpreter and/or thread states exist, these
  167.    are not wiped out; only the current thread and interpreter state
  168.    are deleted.  But since everything else is deleted, those other
  169.    interpreter and thread states should no longer be used.
  170.  
  171.    (XXX We should do better, e.g. wipe out all interpreters and
  172.    threads.)
  173.  
  174.    Locking: as above.
  175.  
  176. */
  177.  
  178. void
  179. Py_Finalize(void)
  180. {
  181.     PyInterpreterState *interp;
  182.     PyThreadState *tstate;
  183.  
  184.     if (!initialized)
  185.         return;
  186.     initialized = 0;
  187.  
  188.     call_sys_exitfunc();
  189.  
  190.     /* Get current thread state and interpreter pointer */
  191.     tstate = PyThreadState_Get();
  192.     interp = tstate->interp;
  193.  
  194.     /* Disable signal handling */
  195.     PyOS_FiniInterrupts();
  196.  
  197.     /* Cleanup Unicode implementation */
  198.     _PyUnicode_Fini();
  199.  
  200.     /* Cleanup Codec registry */
  201.     _PyCodecRegistry_Fini();
  202.  
  203.     /* Destroy all modules */
  204.     PyImport_Cleanup();
  205.  
  206.     /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
  207.     _PyImport_Fini();
  208.  
  209.     /* Debugging stuff */
  210. #ifdef COUNT_ALLOCS
  211.     dump_counts();
  212. #endif
  213.  
  214. #ifdef Py_REF_DEBUG
  215.     fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  216. #endif
  217.  
  218. #ifdef Py_TRACE_REFS
  219.     if (
  220. #ifdef MS_WINDOWS /* Only ask on Windows if env var set */
  221.         getenv("PYTHONDUMPREFS") &&
  222. #endif /* MS_WINDOWS */
  223.         _Py_AskYesNo("Print left references?")) {
  224.         _Py_PrintReferences(stderr);
  225.     }
  226. #endif /* Py_TRACE_REFS */
  227.  
  228.     /* Now we decref the exception classes.  After this point nothing
  229.        can raise an exception.  That's okay, because each Fini() method
  230.        below has been checked to make sure no exceptions are ever
  231.        raised.
  232.     */
  233.     fini_exceptions();
  234.  
  235.     /* Delete current thread */
  236.     PyInterpreterState_Clear(interp);
  237.     PyThreadState_Swap(NULL);
  238.     PyInterpreterState_Delete(interp);
  239.  
  240.     PyMethod_Fini();
  241.     PyFrame_Fini();
  242.     PyCFunction_Fini();
  243.     PyTuple_Fini();
  244.     PyString_Fini();
  245.     PyInt_Fini();
  246.     PyFloat_Fini();
  247.  
  248.     /* XXX Still allocated:
  249.        - various static ad-hoc pointers to interned strings
  250.        - int and float free list blocks
  251.        - whatever various modules and libraries allocate
  252.     */
  253.  
  254.     PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
  255.  
  256.     call_ll_exitfuncs();
  257.  
  258. #ifdef Py_TRACE_REFS
  259.     _Py_ResetReferences();
  260. #endif /* Py_TRACE_REFS */
  261. }
  262.  
  263. /* Create and initialize a new interpreter and thread, and return the
  264.    new thread.  This requires that Py_Initialize() has been called
  265.    first.
  266.  
  267.    Unsuccessful initialization yields a NULL pointer.  Note that *no*
  268.    exception information is available even in this case -- the
  269.    exception information is held in the thread, and there is no
  270.    thread.
  271.  
  272.    Locking: as above.
  273.  
  274. */
  275.  
  276. PyThreadState *
  277. Py_NewInterpreter(void)
  278. {
  279.     PyInterpreterState *interp;
  280.     PyThreadState *tstate, *save_tstate;
  281.     PyObject *bimod, *sysmod;
  282.  
  283.     if (!initialized)
  284.         Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
  285.  
  286.     interp = PyInterpreterState_New();
  287.     if (interp == NULL)
  288.         return NULL;
  289.  
  290.     tstate = PyThreadState_New(interp);
  291.     if (tstate == NULL) {
  292.         PyInterpreterState_Delete(interp);
  293.         return NULL;
  294.     }
  295.  
  296.     save_tstate = PyThreadState_Swap(tstate);
  297.  
  298.     /* XXX The following is lax in error checking */
  299.  
  300.     interp->modules = PyDict_New();
  301.  
  302.     bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
  303.     if (bimod != NULL) {
  304.         interp->builtins = PyModule_GetDict(bimod);
  305.         Py_INCREF(interp->builtins);
  306.     }
  307.     sysmod = _PyImport_FindExtension("sys", "sys");
  308.     if (bimod != NULL && sysmod != NULL) {
  309.         interp->sysdict = PyModule_GetDict(sysmod);
  310.         Py_INCREF(interp->sysdict);
  311.         PySys_SetPath(Py_GetPath());
  312.         PyDict_SetItemString(interp->sysdict, "modules",
  313.                      interp->modules);
  314.         initmain();
  315.         if (!Py_NoSiteFlag)
  316.             initsite();
  317.     }
  318.  
  319.     if (!PyErr_Occurred())
  320.         return tstate;
  321.  
  322.     /* Oops, it didn't work.  Undo it all. */
  323.  
  324.     PyErr_Print();
  325.     PyThreadState_Clear(tstate);
  326.     PyThreadState_Swap(save_tstate);
  327.     PyThreadState_Delete(tstate);
  328.     PyInterpreterState_Delete(interp);
  329.  
  330.     return NULL;
  331. }
  332.  
  333. /* Delete an interpreter and its last thread.  This requires that the
  334.    given thread state is current, that the thread has no remaining
  335.    frames, and that it is its interpreter's only remaining thread.
  336.    It is a fatal error to violate these constraints.
  337.  
  338.    (Py_Finalize() doesn't have these constraints -- it zaps
  339.    everything, regardless.)
  340.  
  341.    Locking: as above.
  342.  
  343. */
  344.  
  345. void
  346. Py_EndInterpreter(PyThreadState *tstate)
  347. {
  348.     PyInterpreterState *interp = tstate->interp;
  349.  
  350.     if (tstate != PyThreadState_Get())
  351.         Py_FatalError("Py_EndInterpreter: thread is not current");
  352.     if (tstate->frame != NULL)
  353.         Py_FatalError("Py_EndInterpreter: thread still has a frame");
  354.     if (tstate != interp->tstate_head || tstate->next != NULL)
  355.         Py_FatalError("Py_EndInterpreter: not the last thread");
  356.  
  357.     PyImport_Cleanup();
  358.     PyInterpreterState_Clear(interp);
  359.     PyThreadState_Swap(NULL);
  360.     PyInterpreterState_Delete(interp);
  361. }
  362.  
  363. static char *progname = "python";
  364.  
  365. void
  366. Py_SetProgramName(char *pn)
  367. {
  368.     if (pn && *pn)
  369.         progname = pn;
  370. }
  371.  
  372. char *
  373. Py_GetProgramName(void)
  374. {
  375.     return progname;
  376. }
  377.  
  378. static char *default_home = NULL;
  379.  
  380. void
  381. Py_SetPythonHome(char *home)
  382. {
  383.     default_home = home;
  384. }
  385.  
  386. char *
  387. Py_GetPythonHome(void)
  388. {
  389.     char *home = default_home;
  390.     if (home == NULL)
  391.         home = getenv("PYTHONHOME");
  392.     return home;
  393. }
  394.  
  395. /* Create __main__ module */
  396.  
  397. static void
  398. initmain(void)
  399. {
  400.     PyObject *m, *d;
  401.     m = PyImport_AddModule("__main__");
  402.     if (m == NULL)
  403.         Py_FatalError("can't create __main__ module");
  404.     d = PyModule_GetDict(m);
  405.     if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  406.         PyObject *bimod = PyImport_ImportModule("__builtin__");
  407.         if (bimod == NULL ||
  408.             PyDict_SetItemString(d, "__builtins__", bimod) != 0)
  409.             Py_FatalError("can't add __builtins__ to __main__");
  410.         Py_DECREF(bimod);
  411.     }
  412. }
  413.  
  414. /* Import the site module (not into __main__ though) */
  415.  
  416. static void
  417. initsite(void)
  418. {
  419.     PyObject *m, *f;
  420.     m = PyImport_ImportModule("site");
  421.     if (m == NULL) {
  422.         f = PySys_GetObject("stderr");
  423.         if (Py_VerboseFlag) {
  424.             PyFile_WriteString(
  425.                 "'import site' failed; traceback:\n", f);
  426.             PyErr_Print();
  427.         }
  428.         else {
  429.             PyFile_WriteString(
  430.               "'import site' failed; use -v for traceback\n", f);
  431.             PyErr_Clear();
  432.         }
  433.     }
  434.     else {
  435.         Py_DECREF(m);
  436.     }
  437. }
  438.  
  439. /* Parse input from a file and execute it */
  440.  
  441. int
  442. PyRun_AnyFile(FILE *fp, char *filename)
  443. {
  444.     return PyRun_AnyFileEx(fp, filename, 0);
  445. }
  446.  
  447. int
  448. PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
  449. {
  450.     if (filename == NULL)
  451.         filename = "???";
  452.     if (Py_FdIsInteractive(fp, filename)) {
  453.         int err = PyRun_InteractiveLoop(fp, filename);
  454.         if (closeit)
  455.             fclose(fp);
  456.         return err;
  457.     }
  458.     else
  459.         return PyRun_SimpleFileEx(fp, filename, closeit);
  460. }
  461.  
  462. int
  463. PyRun_InteractiveLoop(FILE *fp, char *filename)
  464. {
  465.     PyObject *v;
  466.     int ret;
  467.     v = PySys_GetObject("ps1");
  468.     if (v == NULL) {
  469.         PySys_SetObject("ps1", v = PyString_FromString(">>> "));
  470.         Py_XDECREF(v);
  471.     }
  472.     v = PySys_GetObject("ps2");
  473.     if (v == NULL) {
  474.         PySys_SetObject("ps2", v = PyString_FromString("... "));
  475.         Py_XDECREF(v);
  476.     }
  477.     for (;;) {
  478.         ret = PyRun_InteractiveOne(fp, filename);
  479. #ifdef Py_REF_DEBUG
  480.         fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  481. #endif
  482.         if (ret == E_EOF)
  483.             return 0;
  484.         /*
  485.         if (ret == E_NOMEM)
  486.             return -1;
  487.         */
  488.     }
  489. }
  490.  
  491. int
  492. PyRun_InteractiveOne(FILE *fp, char *filename)
  493. {
  494.     PyObject *m, *d, *v, *w;
  495.     node *n;
  496.     perrdetail err;
  497.     char *ps1 = "", *ps2 = "";
  498.     v = PySys_GetObject("ps1");
  499.     if (v != NULL) {
  500.         v = PyObject_Str(v);
  501.         if (v == NULL)
  502.             PyErr_Clear();
  503.         else if (PyString_Check(v))
  504.             ps1 = PyString_AsString(v);
  505.     }
  506.     w = PySys_GetObject("ps2");
  507.     if (w != NULL) {
  508.         w = PyObject_Str(w);
  509.         if (w == NULL)
  510.             PyErr_Clear();
  511.         else if (PyString_Check(w))
  512.             ps2 = PyString_AsString(w);
  513.     }
  514.     n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar,
  515.                    Py_single_input, ps1, ps2, &err);
  516.     Py_XDECREF(v);
  517.     Py_XDECREF(w);
  518.     if (n == NULL) {
  519.         if (err.error == E_EOF) {
  520.             if (err.text)
  521.                 PyMem_DEL(err.text);
  522.             return E_EOF;
  523.         }
  524.         err_input(&err);
  525.         PyErr_Print();
  526.         return err.error;
  527.     }
  528.     m = PyImport_AddModule("__main__");
  529.     if (m == NULL)
  530.         return -1;
  531.     d = PyModule_GetDict(m);
  532.     v = run_node(n, filename, d, d);
  533.     if (v == NULL) {
  534.         PyErr_Print();
  535.         return -1;
  536.     }
  537.     Py_DECREF(v);
  538.     if (Py_FlushLine())
  539.         PyErr_Clear();
  540.     return 0;
  541. }
  542.  
  543. int
  544. PyRun_SimpleFile(FILE *fp, char *filename)
  545. {
  546.     return PyRun_SimpleFileEx(fp, filename, 0);
  547. }
  548.  
  549. int
  550. PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
  551. {
  552.     PyObject *m, *d, *v;
  553.     char *ext;
  554.  
  555.     m = PyImport_AddModule("__main__");
  556.     if (m == NULL)
  557.         return -1;
  558.     d = PyModule_GetDict(m);
  559.     ext = filename + strlen(filename) - 4;
  560. #ifdef _AMIGA
  561.     /* on Amiga, filenames are case insensitive */
  562.     if (stricmp(ext, ".pyc") == 0 || stricmp(ext, ".pyo") == 0
  563. #else
  564.     if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0
  565. #endif /* _AMIGA */
  566. #ifdef macintosh
  567.     /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
  568.         || PyMac_getfiletype(filename) == 'PYC '
  569.         || PyMac_getfiletype(filename) == 'APPL'
  570. #endif /* macintosh */
  571.         ) {
  572.         /* Try to run a pyc file. First, re-open in binary */
  573.         if (closeit)
  574.             fclose(fp);
  575.         if( (fp = fopen(filename, "rb")) == NULL ) {
  576.             fprintf(stderr, "python: Can't reopen .pyc file\n");
  577.             return -1;
  578.         }
  579.         /* Turn on optimization if a .pyo file is given */
  580.         if (strcmp(ext, ".pyo") == 0)
  581.             Py_OptimizeFlag = 1;
  582.         v = run_pyc_file(fp, filename, d, d);
  583.     } else {
  584.         v = PyRun_FileEx(fp, filename, Py_file_input, d, d, closeit);
  585.     }
  586.     if (v == NULL) {
  587.         PyErr_Print();
  588.         return -1;
  589.     }
  590.     Py_DECREF(v);
  591.     if (Py_FlushLine())
  592.         PyErr_Clear();
  593.     return 0;
  594. }
  595.  
  596. int
  597. PyRun_SimpleString(char *command)
  598. {
  599.     PyObject *m, *d, *v;
  600.     m = PyImport_AddModule("__main__");
  601.     if (m == NULL)
  602.         return -1;
  603.     d = PyModule_GetDict(m);
  604.     v = PyRun_String(command, Py_file_input, d, d);
  605.     if (v == NULL) {
  606.         PyErr_Print();
  607.         return -1;
  608.     }
  609.     Py_DECREF(v);
  610.     if (Py_FlushLine())
  611.         PyErr_Clear();
  612.     return 0;
  613. }
  614.  
  615. static int
  616. parse_syntax_error(PyObject *err, PyObject **message, char **filename,
  617.            int *lineno, int *offset, char **text)
  618. {
  619.     long hold;
  620.     PyObject *v;
  621.  
  622.     /* old style errors */
  623.     if (PyTuple_Check(err))
  624.         return PyArg_Parse(err, "(O(ziiz))", message, filename,
  625.                    lineno, offset, text);
  626.  
  627.     /* new style errors.  `err' is an instance */
  628.  
  629.     if (! (v = PyObject_GetAttrString(err, "msg")))
  630.         goto finally;
  631.     *message = v;
  632.  
  633.     if (!(v = PyObject_GetAttrString(err, "filename")))
  634.         goto finally;
  635.     if (v == Py_None)
  636.         *filename = NULL;
  637.     else if (! (*filename = PyString_AsString(v)))
  638.         goto finally;
  639.  
  640.     Py_DECREF(v);
  641.     if (!(v = PyObject_GetAttrString(err, "lineno")))
  642.         goto finally;
  643.     hold = PyInt_AsLong(v);
  644.     Py_DECREF(v);
  645.     v = NULL;
  646.     if (hold < 0 && PyErr_Occurred())
  647.         goto finally;
  648.     *lineno = (int)hold;
  649.  
  650.     if (!(v = PyObject_GetAttrString(err, "offset")))
  651.         goto finally;
  652.     hold = PyInt_AsLong(v);
  653.     Py_DECREF(v);
  654.     v = NULL;
  655.     if (hold < 0 && PyErr_Occurred())
  656.         goto finally;
  657.     *offset = (int)hold;
  658.  
  659.     if (!(v = PyObject_GetAttrString(err, "text")))
  660.         goto finally;
  661.     if (v == Py_None)
  662.         *text = NULL;
  663.     else if (! (*text = PyString_AsString(v)))
  664.         goto finally;
  665.     Py_DECREF(v);
  666.     return 1;
  667.  
  668. finally:
  669.     Py_XDECREF(v);
  670.     return 0;
  671. }
  672.  
  673. void
  674. PyErr_Print(void)
  675. {
  676.     PyErr_PrintEx(1);
  677. }
  678.  
  679. void
  680. PyErr_PrintEx(int set_sys_last_vars)
  681. {
  682.     int err = 0;
  683.     PyObject *exception, *v, *tb, *f;
  684.     PyErr_Fetch(&exception, &v, &tb);
  685.     PyErr_NormalizeException(&exception, &v, &tb);
  686.  
  687.     if (exception == NULL)
  688.         return;
  689.  
  690.     if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
  691.         if (Py_FlushLine())
  692.             PyErr_Clear();
  693.         fflush(stdout);
  694.         if (v == NULL || v == Py_None)
  695.             Py_Exit(0);
  696.         if (PyInstance_Check(v)) {
  697.             /* we expect the error code to be store in the
  698.                `code' attribute
  699.             */
  700.             PyObject *code = PyObject_GetAttrString(v, "code");
  701.             if (code) {
  702.                 Py_DECREF(v);
  703.                 v = code;
  704.                 if (v == Py_None)
  705.                     Py_Exit(0);
  706.             }
  707.             /* if we failed to dig out the "code" attribute,
  708.                then just let the else clause below print the
  709.                error
  710.             */
  711.         }
  712.         if (PyInt_Check(v))
  713.             Py_Exit((int)PyInt_AsLong(v));
  714.         else {
  715.             /* OK to use real stderr here */
  716.             PyObject_Print(v, stderr, Py_PRINT_RAW);
  717.             fprintf(stderr, "\n");
  718.             Py_Exit(1);
  719.         }
  720.     }
  721.     if (set_sys_last_vars) {
  722.         PySys_SetObject("last_type", exception);
  723.         PySys_SetObject("last_value", v);
  724.         PySys_SetObject("last_traceback", tb);
  725.     }
  726.     f = PySys_GetObject("stderr");
  727.     if (f == NULL)
  728.         fprintf(stderr, "lost sys.stderr\n");
  729.     else {
  730.         if (Py_FlushLine())
  731.             PyErr_Clear();
  732.         fflush(stdout);
  733.         err = PyTraceBack_Print(tb, f);
  734.         if (err == 0 &&
  735.             PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
  736.         {
  737.             PyObject *message;
  738.             char *filename, *text;
  739.             int lineno, offset;
  740.             if (!parse_syntax_error(v, &message, &filename,
  741.                         &lineno, &offset, &text))
  742.                 PyErr_Clear();
  743.             else {
  744.                 char buf[10];
  745.                 PyFile_WriteString("  File \"", f);
  746.                 if (filename == NULL)
  747.                     PyFile_WriteString("<string>", f);
  748.                 else
  749.                     PyFile_WriteString(filename, f);
  750.                 PyFile_WriteString("\", line ", f);
  751.                 sprintf(buf, "%d", lineno);
  752.                 PyFile_WriteString(buf, f);
  753.                 PyFile_WriteString("\n", f);
  754.                 if (text != NULL) {
  755.                     char *nl;
  756.                     if (offset > 0 &&
  757.                         offset == (int)strlen(text))
  758.                         offset--;
  759.                     for (;;) {
  760.                         nl = strchr(text, '\n');
  761.                         if (nl == NULL ||
  762.                             nl-text >= offset)
  763.                             break;
  764.                         offset -= (nl+1-text);
  765.                         text = nl+1;
  766.                     }
  767.                     while (*text == ' ' || *text == '\t') {
  768.                         text++;
  769.                         offset--;
  770.                     }
  771.                     PyFile_WriteString("    ", f);
  772.                     PyFile_WriteString(text, f);
  773.                     if (*text == '\0' ||
  774.                         text[strlen(text)-1] != '\n')
  775.                         PyFile_WriteString("\n", f);
  776.                     PyFile_WriteString("    ", f);
  777.                     offset--;
  778.                     while (offset > 0) {
  779.                         PyFile_WriteString(" ", f);
  780.                         offset--;
  781.                     }
  782.                     PyFile_WriteString("^\n", f);
  783.                 }
  784.                 Py_INCREF(message);
  785.                 Py_DECREF(v);
  786.                 v = message;
  787.                 /* Can't be bothered to check all those
  788.                    PyFile_WriteString() calls */
  789.                 if (PyErr_Occurred())
  790.                     err = -1;
  791.             }
  792.         }
  793.         if (err) {
  794.             /* Don't do anything else */
  795.         }
  796.         else if (PyClass_Check(exception)) {
  797.             PyClassObject* exc = (PyClassObject*)exception;
  798.             PyObject* className = exc->cl_name;
  799.             PyObject* moduleName =
  800.                   PyDict_GetItemString(exc->cl_dict, "__module__");
  801.  
  802.             if (moduleName == NULL)
  803.                 err = PyFile_WriteString("<unknown>", f);
  804.             else {
  805.                 char* modstr = PyString_AsString(moduleName);
  806.                 if (modstr && strcmp(modstr, "exceptions")) 
  807.                 {
  808.                     err = PyFile_WriteString(modstr, f);
  809.                     err += PyFile_WriteString(".", f);
  810.                 }
  811.             }
  812.             if (err == 0) {
  813.                 if (className == NULL)
  814.                       err = PyFile_WriteString("<unknown>", f);
  815.                 else
  816.                       err = PyFile_WriteObject(className, f,
  817.                                    Py_PRINT_RAW);
  818.             }
  819.         }
  820.         else
  821.             err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
  822.         if (err == 0) {
  823.             if (v != NULL && v != Py_None) {
  824.                 PyObject *s = PyObject_Str(v);
  825.                 /* only print colon if the str() of the
  826.                    object is not the empty string
  827.                 */
  828.                 if (s == NULL)
  829.                     err = -1;
  830.                 else if (!PyString_Check(s) ||
  831.                      PyString_GET_SIZE(s) != 0)
  832.                     err = PyFile_WriteString(": ", f);
  833.                 if (err == 0)
  834.                   err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
  835.                 Py_XDECREF(s);
  836.             }
  837.         }
  838.         if (err == 0)
  839.             err = PyFile_WriteString("\n", f);
  840.     }
  841.     Py_XDECREF(exception);
  842.     Py_XDECREF(v);
  843.     Py_XDECREF(tb);
  844.     /* If an error happened here, don't show it.
  845.        XXX This is wrong, but too many callers rely on this behavior. */
  846.     if (err != 0)
  847.         PyErr_Clear();
  848. }
  849.  
  850. PyObject *
  851. PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
  852. {
  853.     return run_err_node(PyParser_SimpleParseString(str, start),
  854.                 "<string>", globals, locals);
  855. }
  856.  
  857. PyObject *
  858. PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
  859.        PyObject *locals)
  860. {
  861.     return PyRun_FileEx(fp, filename, start, globals, locals, 0);
  862. }
  863.  
  864. PyObject *
  865. PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
  866.        PyObject *locals, int closeit)
  867. {
  868.     node *n = PyParser_SimpleParseFile(fp, filename, start);
  869.     if (closeit)
  870.         fclose(fp);
  871.     return run_err_node(n, filename, globals, locals);
  872. }
  873.  
  874. static PyObject *
  875. run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals)
  876. {
  877.     if (n == NULL)
  878.         return  NULL;
  879.     return run_node(n, filename, globals, locals);
  880. }
  881.  
  882. static PyObject *
  883. run_node(node *n, char *filename, PyObject *globals, PyObject *locals)
  884. {
  885.     PyCodeObject *co;
  886.     PyObject *v;
  887.     co = PyNode_Compile(n, filename);
  888.     PyNode_Free(n);
  889.     if (co == NULL)
  890.         return NULL;
  891.     v = PyEval_EvalCode(co, globals, locals);
  892.     Py_DECREF(co);
  893.     return v;
  894. }
  895.  
  896. static PyObject *
  897. run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals)
  898. {
  899.     PyCodeObject *co;
  900.     PyObject *v;
  901.     long magic;
  902.     long PyImport_GetMagicNumber(void);
  903.  
  904.     magic = PyMarshal_ReadLongFromFile(fp);
  905.     if (magic != PyImport_GetMagicNumber()) {
  906.         PyErr_SetString(PyExc_RuntimeError,
  907.                "Bad magic number in .pyc file");
  908.         return NULL;
  909.     }
  910.     (void) PyMarshal_ReadLongFromFile(fp);
  911.     v = PyMarshal_ReadObjectFromFile(fp);
  912.     fclose(fp);
  913.     if (v == NULL || !PyCode_Check(v)) {
  914.         Py_XDECREF(v);
  915.         PyErr_SetString(PyExc_RuntimeError,
  916.                "Bad code object in .pyc file");
  917.         return NULL;
  918.     }
  919.     co = (PyCodeObject *)v;
  920.     v = PyEval_EvalCode(co, globals, locals);
  921.     Py_DECREF(co);
  922.     return v;
  923. }
  924.  
  925. PyObject *
  926. Py_CompileString(char *str, char *filename, int start)
  927. {
  928.     node *n;
  929.     PyCodeObject *co;
  930.     n = PyParser_SimpleParseString(str, start);
  931.     if (n == NULL)
  932.         return NULL;
  933.     co = PyNode_Compile(n, filename);
  934.     PyNode_Free(n);
  935.     return (PyObject *)co;
  936. }
  937.  
  938. /* Simplified interface to parsefile -- return node or set exception */
  939.  
  940. node *
  941. PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
  942. {
  943.     node *n;
  944.     perrdetail err;
  945.     n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar, start,
  946.                 (char *)0, (char *)0, &err);
  947.     if (n == NULL)
  948.         err_input(&err);
  949.     return n;
  950. }
  951.  
  952. /* Simplified interface to parsestring -- return node or set exception */
  953.  
  954. node *
  955. PyParser_SimpleParseString(char *str, int start)
  956. {
  957.     node *n;
  958.     perrdetail err;
  959.     n = PyParser_ParseString(str, &_PyParser_Grammar, start, &err);
  960.     if (n == NULL)
  961.         err_input(&err);
  962.     return n;
  963. }
  964.  
  965. /* Set the error appropriate to the given input error code (see errcode.h) */
  966.  
  967. static void
  968. err_input(perrdetail *err)
  969. {
  970.     PyObject *v, *w, *errtype;
  971.     char *msg = NULL;
  972.     errtype = PyExc_SyntaxError;
  973.     v = Py_BuildValue("(ziiz)", err->filename,
  974.                 err->lineno, err->offset, err->text);
  975.     if (err->text != NULL) {
  976.         PyMem_DEL(err->text);
  977.         err->text = NULL;
  978.     }
  979.     switch (err->error) {
  980.     case E_SYNTAX:
  981.         errtype = PyExc_IndentationError;
  982.         if (err->expected == INDENT)
  983.             msg = "expected an indented block";
  984.         else if (err->token == INDENT)
  985.             msg = "unexpected indent";
  986.         else if (err->token == DEDENT)
  987.             msg = "unexpected unindent";
  988.         else {
  989.             errtype = PyExc_SyntaxError;
  990.             msg = "invalid syntax";
  991.         }
  992.         break;
  993.     case E_TOKEN:
  994.         msg = "invalid token";
  995.         break;
  996.     case E_INTR:
  997.         PyErr_SetNone(PyExc_KeyboardInterrupt);
  998.         Py_XDECREF(v);
  999.         return;
  1000.     case E_NOMEM:
  1001.         PyErr_NoMemory();
  1002.         Py_XDECREF(v);
  1003.         return;
  1004.     case E_EOF:
  1005.         msg = "unexpected EOF while parsing";
  1006.         break;
  1007.     case E_TABSPACE:
  1008.         errtype = PyExc_TabError;
  1009.         msg = "inconsistent use of tabs and spaces in indentation";
  1010.         break;
  1011.     case E_OVERFLOW:
  1012.         msg = "expression too long";
  1013.         break;
  1014.     case E_DEDENT:
  1015.         errtype = PyExc_IndentationError;
  1016.         msg = "unindent does not match any outer indentation level";
  1017.         break;
  1018.     case E_TOODEEP:
  1019.         errtype = PyExc_IndentationError;
  1020.         msg = "too many levels of indentation";
  1021.         break;
  1022.     default:
  1023.         fprintf(stderr, "error=%d\n", err->error);
  1024.         msg = "unknown parsing error";
  1025.         break;
  1026.     }
  1027.     w = Py_BuildValue("(sO)", msg, v);
  1028.     PyErr_SetObject(errtype, w);
  1029.     Py_XDECREF(w);
  1030.  
  1031.     if (v != NULL) {
  1032.         PyObject *exc, *tb;
  1033.  
  1034.         PyErr_Fetch(&errtype, &exc, &tb);
  1035.         PyErr_NormalizeException(&errtype, &exc, &tb);
  1036.         if (PyObject_SetAttrString(exc, "filename",
  1037.                        PyTuple_GET_ITEM(v, 0)))
  1038.             PyErr_Clear();
  1039.         if (PyObject_SetAttrString(exc, "lineno",
  1040.                        PyTuple_GET_ITEM(v, 1)))
  1041.             PyErr_Clear();
  1042.         if (PyObject_SetAttrString(exc, "offset",
  1043.                        PyTuple_GET_ITEM(v, 2)))
  1044.             PyErr_Clear();
  1045.         Py_DECREF(v);
  1046.         PyErr_Restore(errtype, exc, tb);
  1047.     }
  1048. }
  1049.  
  1050. /* Print fatal error message and abort */
  1051.  
  1052. void
  1053. Py_FatalError(char *msg)
  1054. {
  1055.     fprintf(stderr, "Fatal Python error: %s\n", msg);
  1056. #ifdef macintosh
  1057.     for (;;);
  1058. #endif
  1059. #ifdef MS_WIN32
  1060.     OutputDebugString("Fatal Python error: ");
  1061.     OutputDebugString(msg);
  1062.     OutputDebugString("\n");
  1063. #ifdef _DEBUG
  1064.     DebugBreak();
  1065. #endif
  1066. #endif /* MS_WIN32 */
  1067.     abort();
  1068. }
  1069.  
  1070. /* Clean up and exit */
  1071.  
  1072. #ifdef WITH_THREAD
  1073. #include "pythread.h"
  1074. int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
  1075. #endif
  1076.  
  1077. #define NEXITFUNCS 32
  1078. static void (*exitfuncs[NEXITFUNCS])(void);
  1079. static int nexitfuncs = 0;
  1080.  
  1081. int Py_AtExit(void (*func)(void))
  1082. {
  1083.     if (nexitfuncs >= NEXITFUNCS)
  1084.         return -1;
  1085.     exitfuncs[nexitfuncs++] = func;
  1086.     return 0;
  1087. }
  1088.  
  1089. static void
  1090. call_sys_exitfunc(void)
  1091. {
  1092.     PyObject *exitfunc = PySys_GetObject("exitfunc");
  1093.  
  1094.     if (exitfunc) {
  1095.         PyObject *res, *f;
  1096.         Py_INCREF(exitfunc);
  1097.         PySys_SetObject("exitfunc", (PyObject *)NULL);
  1098.         f = PySys_GetObject("stderr");
  1099.         res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
  1100.         if (res == NULL) {
  1101.             if (f)
  1102.                 PyFile_WriteString("Error in sys.exitfunc:\n", f);
  1103.             PyErr_Print();
  1104.         }
  1105.         Py_DECREF(exitfunc);
  1106.     }
  1107.  
  1108.     if (Py_FlushLine())
  1109.         PyErr_Clear();
  1110. }
  1111.  
  1112. static void
  1113. call_ll_exitfuncs(void)
  1114. {
  1115.     while (nexitfuncs > 0)
  1116.         (*exitfuncs[--nexitfuncs])();
  1117.  
  1118.     fflush(stdout);
  1119.     fflush(stderr);
  1120. }
  1121.  
  1122. void
  1123. Py_Exit(int sts)
  1124. {
  1125.     Py_Finalize();
  1126.  
  1127. #ifdef macintosh
  1128.     PyMac_Exit(sts);
  1129. #else
  1130.     exit(sts);
  1131. #endif
  1132. }
  1133.  
  1134. static void
  1135. initsigs(void)
  1136. {
  1137. #ifdef HAVE_SIGNAL_H
  1138. #ifdef SIGPIPE
  1139.     signal(SIGPIPE, SIG_IGN);
  1140. #endif
  1141. #endif /* HAVE_SIGNAL_H */
  1142.     PyOS_InitInterrupts(); /* May imply initsignal() */
  1143. }
  1144.  
  1145. #ifdef Py_TRACE_REFS
  1146. /* Ask a yes/no question */
  1147.  
  1148. int
  1149. _Py_AskYesNo(char *prompt)
  1150. {
  1151.     char buf[256];
  1152.     
  1153.     printf("%s [ny] ", prompt);
  1154.     if (fgets(buf, sizeof buf, stdin) == NULL)
  1155.         return 0;
  1156.     return buf[0] == 'y' || buf[0] == 'Y';
  1157. }
  1158. #endif
  1159.  
  1160. #ifdef MPW
  1161.  
  1162. /* Check for file descriptor connected to interactive device.
  1163.    Pretend that stdin is always interactive, other files never. */
  1164.  
  1165. int
  1166. isatty(int fd)
  1167. {
  1168.     return fd == fileno(stdin);
  1169. }
  1170.  
  1171. #endif
  1172.  
  1173. /*
  1174.  * The file descriptor fd is considered ``interactive'' if either
  1175.  *   a) isatty(fd) is TRUE, or
  1176.  *   b) the -i flag was given, and the filename associated with
  1177.  *      the descriptor is NULL or "<stdin>" or "???".
  1178.  */
  1179. int
  1180. Py_FdIsInteractive(FILE *fp, char *filename)
  1181. {
  1182.     if (isatty((int)fileno(fp)))
  1183.         return 1;
  1184.     if (!Py_InteractiveFlag)
  1185.         return 0;
  1186.     return (filename == NULL) ||
  1187.            (strcmp(filename, "<stdin>") == 0) ||
  1188.            (strcmp(filename, "???") == 0);
  1189. }
  1190.  
  1191.  
  1192. #if defined(USE_STACKCHECK) 
  1193. #if defined(WIN32) && defined(_MSC_VER)
  1194.  
  1195. /* Stack checking for Microsoft C */
  1196.  
  1197. #include <malloc.h>
  1198. #include <excpt.h>
  1199.  
  1200. /*
  1201.  * Return non-zero when we run out of memory on the stack; zero otherwise.
  1202.  */
  1203. int
  1204. PyOS_CheckStack(void)
  1205. {
  1206.     __try {
  1207.         /* _alloca throws a stack overflow exception if there's
  1208.            not enough space left on the stack */
  1209.         _alloca(PYOS_STACK_MARGIN * sizeof(void*));
  1210.         return 0;
  1211.     } __except (EXCEPTION_EXECUTE_HANDLER) {
  1212.         /* just ignore all errors */
  1213.     }
  1214.     return 1;
  1215. }
  1216.  
  1217. #endif /* WIN32 && _MSC_VER */
  1218.  
  1219. /* Alternate implementations can be added here... */
  1220.  
  1221. #endif /* USE_STACKCHECK */
  1222.  
  1223.  
  1224. /* Wrappers around sigaction() or signal(). */
  1225.  
  1226. PyOS_sighandler_t
  1227. PyOS_getsig(int sig)
  1228. {
  1229. #ifdef HAVE_SIGACTION
  1230.     struct sigaction context;
  1231.     sigaction(sig, NULL, &context);
  1232.     return context.sa_handler;
  1233. #else
  1234.     PyOS_sighandler_t handler;
  1235.     handler = signal(sig, SIG_IGN);
  1236.     signal(sig, handler);
  1237.     return handler;
  1238. #endif
  1239. }
  1240.  
  1241. PyOS_sighandler_t
  1242. PyOS_setsig(int sig, PyOS_sighandler_t handler)
  1243. {
  1244. #ifdef HAVE_SIGACTION
  1245.     struct sigaction context;
  1246.     PyOS_sighandler_t oldhandler;
  1247.     sigaction(sig, NULL, &context);
  1248.     oldhandler = context.sa_handler;
  1249.     context.sa_handler = handler;
  1250.     sigaction(sig, &context, NULL);
  1251.     return oldhandler;
  1252. #else
  1253.     return signal(sig, handler);
  1254. #endif
  1255. }
  1256.