Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Python/pythonrun.c

    r2 r388  
    4141#define PRINT_TOTAL_REFS()
    4242#else /* Py_REF_DEBUG */
    43 #define PRINT_TOTAL_REFS() fprintf(stderr,                              \
    44                                    "[%" PY_FORMAT_SIZE_T "d refs]\n",   \
    45                                    _Py_GetRefTotal())
     43#define PRINT_TOTAL_REFS() fprintf(stderr,                              \
     44                   "[%" PY_FORMAT_SIZE_T "d refs]\n",                   \
     45                   _Py_GetRefTotal())
    4646#endif
    4747
     
    5858static void initsite(void);
    5959static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
    60                           PyCompilerFlags *, PyArena *);
     60                          PyCompilerFlags *, PyArena *);
    6161static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
    62                               PyCompilerFlags *);
     62                              PyCompilerFlags *);
    6363static void err_input(perrdetail *);
    6464static void initsigs(void);
     
    7777int Py_VerboseFlag; /* Needed by import.c */
    7878int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
    79 int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
     79int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
    8080int Py_NoSiteFlag; /* Suppress 'import site' */
    8181int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
     
    9090int _Py_QnewFlag = 0;
    9191int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
     92int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
     93
     94
     95/* Hack to force loading of object files */
     96int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
     97    PyOS_mystrnicmp; /* Python/pystrcmp.o */
    9298
    9399/* PyModule_GetWarningsModule is no longer necessary as of 2.6
     
    96102PyModule_GetWarningsModule(void)
    97103{
    98         return PyImport_ImportModule("warnings");
     104    return PyImport_ImportModule("warnings");
    99105}
    100106
     
    106112Py_IsInitialized(void)
    107113{
    108         return initialized;
     114    return initialized;
    109115}
    110116
     
    124130add_flag(int flag, const char *envs)
    125131{
    126         int env = atoi(envs);
    127         if (flag < env)
    128                 flag = env;
    129         if (flag < 1)
    130                 flag = 1;
    131         return flag;
     132    int env = atoi(envs);
     133    if (flag < env)
     134        flag = env;
     135    if (flag < 1)
     136        flag = 1;
     137    return flag;
    132138}
    133139
     
    135141Py_InitializeEx(int install_sigs)
    136142{
    137         PyInterpreterState *interp;
    138         PyThreadState *tstate;
    139         PyObject *bimod, *sysmod;
    140         char *p;
    141         char *icodeset = NULL; /* On Windows, input codeset may theoretically
    142                                   differ from output codeset. */
    143         char *codeset = NULL;
    144         char *errors = NULL;
    145         int free_codeset = 0;
    146         int overridden = 0;
    147         PyObject *sys_stream, *sys_isatty;
     143    PyInterpreterState *interp;
     144    PyThreadState *tstate;
     145    PyObject *bimod, *sysmod;
     146    char *p;
     147    char *icodeset = NULL; /* On Windows, input codeset may theoretically
     148                              differ from output codeset. */
     149    char *codeset = NULL;
     150    char *errors = NULL;
     151    int free_codeset = 0;
     152    int overridden = 0;
     153    PyObject *sys_stream, *sys_isatty;
    148154#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
    149         char *saved_locale, *loc_codeset;
     155    char *saved_locale, *loc_codeset;
    150156#endif
    151157#ifdef MS_WINDOWS
    152         char ibuf[128];
    153         char buf[128];
    154 #endif
    155         extern void _Py_ReadyTypes(void);
    156 
    157         if (initialized)
    158                 return;
    159         initialized = 1;
    160 
    161         if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
    162                 Py_DebugFlag = add_flag(Py_DebugFlag, p);
    163         if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
    164                 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
    165         if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
    166                 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
    167         if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
    168                 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
    169 
    170         interp = PyInterpreterState_New();
    171         if (interp == NULL)
    172                 Py_FatalError("Py_Initialize: can't make first interpreter");
    173 
    174         tstate = PyThreadState_New(interp);
    175         if (tstate == NULL)
    176                 Py_FatalError("Py_Initialize: can't make first thread");
    177         (void) PyThreadState_Swap(tstate);
    178 
    179         _Py_ReadyTypes();
    180 
    181         if (!_PyFrame_Init())
    182                 Py_FatalError("Py_Initialize: can't init frames");
    183 
    184         if (!_PyInt_Init())
    185                 Py_FatalError("Py_Initialize: can't init ints");
    186 
    187         if (!PyByteArray_Init())
    188                 Py_FatalError("Py_Initialize: can't init bytearray");
    189 
    190         _PyFloat_Init();
    191 
    192         interp->modules = PyDict_New();
    193         if (interp->modules == NULL)
    194                 Py_FatalError("Py_Initialize: can't make modules dictionary");
    195         interp->modules_reloading = PyDict_New();
    196         if (interp->modules_reloading == NULL)
    197                 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
     158    char ibuf[128];
     159    char buf[128];
     160#endif
     161    extern void _Py_ReadyTypes(void);
     162
     163    if (initialized)
     164        return;
     165    initialized = 1;
     166
     167    if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
     168        Py_DebugFlag = add_flag(Py_DebugFlag, p);
     169    if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
     170        Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
     171    if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
     172        Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
     173    if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
     174        Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
     175    /* The variable is only tested for existence here; _PyRandom_Init will
     176       check its value further. */
     177    if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
     178        Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
     179
     180    _PyRandom_Init();
     181
     182    interp = PyInterpreterState_New();
     183    if (interp == NULL)
     184        Py_FatalError("Py_Initialize: can't make first interpreter");
     185
     186    tstate = PyThreadState_New(interp);
     187    if (tstate == NULL)
     188        Py_FatalError("Py_Initialize: can't make first thread");
     189    (void) PyThreadState_Swap(tstate);
     190
     191    _Py_ReadyTypes();
     192
     193    if (!_PyFrame_Init())
     194        Py_FatalError("Py_Initialize: can't init frames");
     195
     196    if (!_PyInt_Init())
     197        Py_FatalError("Py_Initialize: can't init ints");
     198
     199    if (!_PyLong_Init())
     200        Py_FatalError("Py_Initialize: can't init longs");
     201
     202    if (!PyByteArray_Init())
     203        Py_FatalError("Py_Initialize: can't init bytearray");
     204
     205    _PyFloat_Init();
     206
     207    interp->modules = PyDict_New();
     208    if (interp->modules == NULL)
     209        Py_FatalError("Py_Initialize: can't make modules dictionary");
     210    interp->modules_reloading = PyDict_New();
     211    if (interp->modules_reloading == NULL)
     212        Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
    198213
    199214#ifdef Py_USING_UNICODE
    200         /* Init Unicode implementation; relies on the codec registry */
    201         _PyUnicode_Init();
    202 #endif
    203 
    204         bimod = _PyBuiltin_Init();
    205         if (bimod == NULL)
    206                 Py_FatalError("Py_Initialize: can't initialize __builtin__");
    207         interp->builtins = PyModule_GetDict(bimod);
    208         if (interp->builtins == NULL)
    209                 Py_FatalError("Py_Initialize: can't initialize builtins dict");
    210         Py_INCREF(interp->builtins);
    211 
    212         sysmod = _PySys_Init();
    213         if (sysmod == NULL)
    214                 Py_FatalError("Py_Initialize: can't initialize sys");
    215         interp->sysdict = PyModule_GetDict(sysmod);
    216         if (interp->sysdict == NULL)
    217                 Py_FatalError("Py_Initialize: can't initialize sys dict");
    218         Py_INCREF(interp->sysdict);
    219         _PyImport_FixupExtension("sys", "sys");
    220         PySys_SetPath(Py_GetPath());
    221         PyDict_SetItemString(interp->sysdict, "modules",
    222                              interp->modules);
    223 
    224         _PyImport_Init();
    225 
    226         /* initialize builtin exceptions */
    227         _PyExc_Init();
    228         _PyImport_FixupExtension("exceptions", "exceptions");
    229 
    230         /* phase 2 of builtins */
    231         _PyImport_FixupExtension("__builtin__", "__builtin__");
    232 
    233         _PyImportHooks_Init();
    234 
    235         if (install_sigs)
    236                 initsigs(); /* Signal handling stuff, including initintr() */
    237                
    238         /* Initialize warnings. */
    239         _PyWarnings_Init();
    240         if (PySys_HasWarnOptions()) {
    241                 PyObject *warnings_module = PyImport_ImportModule("warnings");
    242                 if (!warnings_module)
    243                         PyErr_Clear();
    244                 Py_XDECREF(warnings_module);
    245         }
    246 
    247         initmain(); /* Module __main__ */
    248         if (!Py_NoSiteFlag)
    249                 initsite(); /* Module site */
    250 
    251         /* auto-thread-state API, if available */
     215    /* Init Unicode implementation; relies on the codec registry */
     216    _PyUnicode_Init();
     217#endif
     218
     219    bimod = _PyBuiltin_Init();
     220    if (bimod == NULL)
     221        Py_FatalError("Py_Initialize: can't initialize __builtin__");
     222    interp->builtins = PyModule_GetDict(bimod);
     223    if (interp->builtins == NULL)
     224        Py_FatalError("Py_Initialize: can't initialize builtins dict");
     225    Py_INCREF(interp->builtins);
     226
     227    sysmod = _PySys_Init();
     228    if (sysmod == NULL)
     229        Py_FatalError("Py_Initialize: can't initialize sys");
     230    interp->sysdict = PyModule_GetDict(sysmod);
     231    if (interp->sysdict == NULL)
     232        Py_FatalError("Py_Initialize: can't initialize sys dict");
     233    Py_INCREF(interp->sysdict);
     234    _PyImport_FixupExtension("sys", "sys");
     235    PySys_SetPath(Py_GetPath());
     236    PyDict_SetItemString(interp->sysdict, "modules",
     237                         interp->modules);
     238
     239    _PyImport_Init();
     240
     241    /* initialize builtin exceptions */
     242    _PyExc_Init();
     243    _PyImport_FixupExtension("exceptions", "exceptions");
     244
     245    /* phase 2 of builtins */
     246    _PyImport_FixupExtension("__builtin__", "__builtin__");
     247
     248    _PyImportHooks_Init();
     249
     250    if (install_sigs)
     251        initsigs(); /* Signal handling stuff, including initintr() */
     252
     253    /* Initialize warnings. */
     254    _PyWarnings_Init();
     255    if (PySys_HasWarnOptions()) {
     256        PyObject *warnings_module = PyImport_ImportModule("warnings");
     257        if (!warnings_module)
     258            PyErr_Clear();
     259        Py_XDECREF(warnings_module);
     260    }
     261
     262    initmain(); /* Module __main__ */
     263
     264    /* auto-thread-state API, if available */
    252265#ifdef WITH_THREAD
    253         _PyGILState_Init(interp, tstate);
     266    _PyGILState_Init(interp, tstate);
    254267#endif /* WITH_THREAD */
    255268
    256         if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
    257                 p = icodeset = codeset = strdup(p);
    258                 free_codeset = 1;
    259                 errors = strchr(p, ':');
    260                 if (errors) {
    261                         *errors = '\0';
    262                         errors++;
    263                 }
    264                 overridden = 1;
    265         }
     269    if (!Py_NoSiteFlag)
     270        initsite(); /* Module site */
     271
     272    if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
     273        p = icodeset = codeset = strdup(p);
     274        free_codeset = 1;
     275        errors = strchr(p, ':');
     276        if (errors) {
     277            *errors = '\0';
     278            errors++;
     279        }
     280        overridden = 1;
     281    }
    266282
    267283#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
    268         /* On Unix, set the file system encoding according to the
    269            user's preference, if the CODESET names a well-known
    270            Python codec, and Py_FileSystemDefaultEncoding isn't
    271            initialized by other means. Also set the encoding of
    272            stdin and stdout if these are terminals, unless overridden.  */
    273 
    274         if (!overridden || !Py_FileSystemDefaultEncoding) {
    275                 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
    276                 setlocale(LC_CTYPE, "");
    277                 loc_codeset = nl_langinfo(CODESET);
    278                 if (loc_codeset && *loc_codeset) {
    279                         PyObject *enc = PyCodec_Encoder(loc_codeset);
    280                         if (enc) {
    281                                 loc_codeset = strdup(loc_codeset);
    282                                 Py_DECREF(enc);
    283                         } else {
    284                                 loc_codeset = NULL;
    285                                 PyErr_Clear();
    286                         }
    287                 } else
    288                         loc_codeset = NULL;
    289                 setlocale(LC_CTYPE, saved_locale);
    290                 free(saved_locale);
    291 
    292                 if (!overridden) {
    293                         codeset = icodeset = loc_codeset;
    294                         free_codeset = 1;
    295                 }
    296 
    297                 /* Initialize Py_FileSystemDefaultEncoding from
    298                    locale even if PYTHONIOENCODING is set. */
    299                 if (!Py_FileSystemDefaultEncoding) {
    300                         Py_FileSystemDefaultEncoding = loc_codeset;
    301                         if (!overridden)
    302                                 free_codeset = 0;
    303                 }
    304         }
     284    /* On Unix, set the file system encoding according to the
     285       user's preference, if the CODESET names a well-known
     286       Python codec, and Py_FileSystemDefaultEncoding isn't
     287       initialized by other means. Also set the encoding of
     288       stdin and stdout if these are terminals, unless overridden.  */
     289
     290    if (!overridden || !Py_FileSystemDefaultEncoding) {
     291        saved_locale = strdup(setlocale(LC_CTYPE, NULL));
     292        setlocale(LC_CTYPE, "");
     293        loc_codeset = nl_langinfo(CODESET);
     294        if (loc_codeset && *loc_codeset) {
     295            PyObject *enc = PyCodec_Encoder(loc_codeset);
     296            if (enc) {
     297                loc_codeset = strdup(loc_codeset);
     298                Py_DECREF(enc);
     299            } else {
     300                if (PyErr_ExceptionMatches(PyExc_LookupError)) {
     301                    PyErr_Clear();
     302                    loc_codeset = NULL;
     303                } else {
     304                    PyErr_Print();
     305                    exit(1);
     306                }
     307            }
     308        } else
     309            loc_codeset = NULL;
     310        setlocale(LC_CTYPE, saved_locale);
     311        free(saved_locale);
     312
     313        if (!overridden) {
     314            codeset = icodeset = loc_codeset;
     315            free_codeset = 1;
     316        }
     317
     318        /* Initialize Py_FileSystemDefaultEncoding from
     319           locale even if PYTHONIOENCODING is set. */
     320        if (!Py_FileSystemDefaultEncoding) {
     321            Py_FileSystemDefaultEncoding = loc_codeset;
     322            if (!overridden)
     323                free_codeset = 0;
     324        }
     325    }
    305326#endif
    306327
    307328#ifdef MS_WINDOWS
    308         if (!overridden) {
    309                 icodeset = ibuf;
    310                 codeset = buf;
    311                 sprintf(ibuf, "cp%d", GetConsoleCP());
    312                 sprintf(buf, "cp%d", GetConsoleOutputCP());
    313         }
    314 #endif
    315 
    316         if (codeset) {
    317                 sys_stream = PySys_GetObject("stdin");
    318                 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
    319                 if (!sys_isatty)
    320                         PyErr_Clear();
    321                 if ((overridden ||
    322                      (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
    323                    PyFile_Check(sys_stream)) {
    324                         if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
    325                                 Py_FatalError("Cannot set codeset of stdin");
    326                 }
    327                 Py_XDECREF(sys_isatty);
    328 
    329                 sys_stream = PySys_GetObject("stdout");
    330                 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
    331                 if (!sys_isatty)
    332                         PyErr_Clear();
    333                 if ((overridden ||
    334                      (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
    335                    PyFile_Check(sys_stream)) {
    336                         if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
    337                                 Py_FatalError("Cannot set codeset of stdout");
    338                 }
    339                 Py_XDECREF(sys_isatty);
    340 
    341                 sys_stream = PySys_GetObject("stderr");
    342                 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
    343                 if (!sys_isatty)
    344                         PyErr_Clear();
    345                 if((overridden ||
    346                     (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
    347                    PyFile_Check(sys_stream)) {
    348                         if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
    349                                 Py_FatalError("Cannot set codeset of stderr");
    350                 }
    351                 Py_XDECREF(sys_isatty);
    352 
    353                 if (free_codeset)
    354                         free(codeset);
    355         }
     329    if (!overridden) {
     330        icodeset = ibuf;
     331        codeset = buf;
     332        sprintf(ibuf, "cp%d", GetConsoleCP());
     333        sprintf(buf, "cp%d", GetConsoleOutputCP());
     334    }
     335#endif
     336
     337    if (codeset) {
     338        sys_stream = PySys_GetObject("stdin");
     339        sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
     340        if (!sys_isatty)
     341            PyErr_Clear();
     342        if ((overridden ||
     343             (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
     344           PyFile_Check(sys_stream)) {
     345            if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
     346                Py_FatalError("Cannot set codeset of stdin");
     347        }
     348        Py_XDECREF(sys_isatty);
     349
     350        sys_stream = PySys_GetObject("stdout");
     351        sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
     352        if (!sys_isatty)
     353            PyErr_Clear();
     354        if ((overridden ||
     355             (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
     356           PyFile_Check(sys_stream)) {
     357            if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
     358                Py_FatalError("Cannot set codeset of stdout");
     359        }
     360        Py_XDECREF(sys_isatty);
     361
     362        sys_stream = PySys_GetObject("stderr");
     363        sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
     364        if (!sys_isatty)
     365            PyErr_Clear();
     366        if((overridden ||
     367            (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
     368           PyFile_Check(sys_stream)) {
     369            if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
     370                Py_FatalError("Cannot set codeset of stderr");
     371        }
     372        Py_XDECREF(sys_isatty);
     373
     374        if (free_codeset)
     375            free(codeset);
     376    }
    356377}
    357378
     
    359380Py_Initialize(void)
    360381{
    361         Py_InitializeEx(1);
     382    Py_InitializeEx(1);
    362383}
    363384
     
    384405Py_Finalize(void)
    385406{
    386         PyInterpreterState *interp;
    387         PyThreadState *tstate;
    388 
    389         if (!initialized)
    390                 return;
    391 
    392         wait_for_thread_shutdown();
    393 
    394         /* The interpreter is still entirely intact at this point, and the
    395         * exit funcs may be relying on that.  In particular, if some thread
    396         * or exit func is still waiting to do an import, the import machinery
    397         * expects Py_IsInitialized() to return true.  So don't say the
    398         * interpreter is uninitialized until after the exit funcs have run.
    399         * Note that Threading.py uses an exit func to do a join on all the
    400         * threads created thru it, so this also protects pending imports in
    401         * the threads created via Threading.
    402         */
    403         call_sys_exitfunc();
    404         initialized = 0;
    405 
    406         /* Get current thread state and interpreter pointer */
    407         tstate = PyThreadState_GET();
    408         interp = tstate->interp;
    409 
    410         /* Disable signal handling */
    411         PyOS_FiniInterrupts();
    412 
    413         /* Clear type lookup cache */
    414         PyType_ClearCache();
    415 
    416         /* Collect garbage.  This may call finalizers; it's nice to call these
    417         * before all modules are destroyed.
    418         * XXX If a __del__ or weakref callback is triggered here, and tries to
    419         * XXX import a module, bad things can happen, because Python no
    420         * XXX longer believes it's initialized.
    421         * XXX     Fatal Python error: Interpreter not initialized (version mismatch?)
    422         * XXX is easy to provoke that way.  I've also seen, e.g.,
    423         * XXX     Exception exceptions.ImportError: 'No module named sha'
    424         * XXX         in <function callback at 0x008F5718> ignored
    425         * XXX but I'm unclear on exactly how that one happens.  In any case,
    426         * XXX I haven't seen a real-life report of either of these.
    427         */
    428         PyGC_Collect();
     407    PyInterpreterState *interp;
     408    PyThreadState *tstate;
     409
     410    if (!initialized)
     411        return;
     412
     413    wait_for_thread_shutdown();
     414
     415    /* The interpreter is still entirely intact at this point, and the
     416    * exit funcs may be relying on that.  In particular, if some thread
     417    * or exit func is still waiting to do an import, the import machinery
     418    * expects Py_IsInitialized() to return true.  So don't say the
     419    * interpreter is uninitialized until after the exit funcs have run.
     420    * Note that Threading.py uses an exit func to do a join on all the
     421    * threads created thru it, so this also protects pending imports in
     422    * the threads created via Threading.
     423    */
     424    call_sys_exitfunc();
     425    initialized = 0;
     426
     427    /* Get current thread state and interpreter pointer */
     428    tstate = PyThreadState_GET();
     429    interp = tstate->interp;
     430
     431    /* Disable signal handling */
     432    PyOS_FiniInterrupts();
     433
     434    /* Clear type lookup cache */
     435    PyType_ClearCache();
     436
     437    /* Collect garbage.  This may call finalizers; it's nice to call these
     438    * before all modules are destroyed.
     439    * XXX If a __del__ or weakref callback is triggered here, and tries to
     440    * XXX import a module, bad things can happen, because Python no
     441    * XXX longer believes it's initialized.
     442    * XXX     Fatal Python error: Interpreter not initialized (version mismatch?)
     443    * XXX is easy to provoke that way.  I've also seen, e.g.,
     444    * XXX     Exception exceptions.ImportError: 'No module named sha'
     445    * XXX         in <function callback at 0x008F5718> ignored
     446    * XXX but I'm unclear on exactly how that one happens.  In any case,
     447    * XXX I haven't seen a real-life report of either of these.
     448    */
     449    PyGC_Collect();
    429450#ifdef COUNT_ALLOCS
    430         /* With COUNT_ALLOCS, it helps to run GC multiple times:
    431            each collection might release some types from the type
    432            list, so they become garbage. */
    433         while (PyGC_Collect() > 0)
    434                 /* nothing */;
    435 #endif
    436 
    437         /* Destroy all modules */
    438         PyImport_Cleanup();
    439 
    440         /* Collect final garbage.  This disposes of cycles created by
    441         * new-style class definitions, for example.
    442         * XXX This is disabled because it caused too many problems.  If
    443         * XXX a __del__ or weakref callback triggers here, Python code has
    444         * XXX a hard time running, because even the sys module has been
    445         * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
    446         * XXX One symptom is a sequence of information-free messages
    447         * XXX coming from threads (if a __del__ or callback is invoked,
    448         * XXX other threads can execute too, and any exception they encounter
    449         * XXX triggers a comedy of errors as subsystem after subsystem
    450         * XXX fails to find what it *expects* to find in sys to help report
    451         * XXX the exception and consequent unexpected failures).  I've also
    452         * XXX seen segfaults then, after adding print statements to the
    453         * XXX Python code getting called.
    454         */
     451    /* With COUNT_ALLOCS, it helps to run GC multiple times:
     452       each collection might release some types from the type
     453       list, so they become garbage. */
     454    while (PyGC_Collect() > 0)
     455        /* nothing */;
     456#endif
     457
     458    /* Destroy all modules */
     459    PyImport_Cleanup();
     460
     461    /* Collect final garbage.  This disposes of cycles created by
     462    * new-style class definitions, for example.
     463    * XXX This is disabled because it caused too many problems.  If
     464    * XXX a __del__ or weakref callback triggers here, Python code has
     465    * XXX a hard time running, because even the sys module has been
     466    * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
     467    * XXX One symptom is a sequence of information-free messages
     468    * XXX coming from threads (if a __del__ or callback is invoked,
     469    * XXX other threads can execute too, and any exception they encounter
     470    * XXX triggers a comedy of errors as subsystem after subsystem
     471    * XXX fails to find what it *expects* to find in sys to help report
     472    * XXX the exception and consequent unexpected failures).  I've also
     473    * XXX seen segfaults then, after adding print statements to the
     474    * XXX Python code getting called.
     475    */
    455476#if 0
    456         PyGC_Collect();
    457 #endif
    458 
    459         /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
    460         _PyImport_Fini();
    461 
    462         /* Debugging stuff */
     477    PyGC_Collect();
     478#endif
     479
     480    /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
     481    _PyImport_Fini();
     482
     483    /* Debugging stuff */
    463484#ifdef COUNT_ALLOCS
    464         dump_counts(stdout);
    465 #endif
    466 
    467         PRINT_TOTAL_REFS();
     485    dump_counts(stdout);
     486#endif
     487
     488    PRINT_TOTAL_REFS();
    468489
    469490#ifdef Py_TRACE_REFS
    470         /* Display all objects still alive -- this can invoke arbitrary
    471         * __repr__ overrides, so requires a mostly-intact interpreter.
    472         * Alas, a lot of stuff may still be alive now that will be cleaned
    473         * up later.
    474         */
    475         if (Py_GETENV("PYTHONDUMPREFS"))
    476                 _Py_PrintReferences(stderr);
     491    /* Display all objects still alive -- this can invoke arbitrary
     492    * __repr__ overrides, so requires a mostly-intact interpreter.
     493    * Alas, a lot of stuff may still be alive now that will be cleaned
     494    * up later.
     495    */
     496    if (Py_GETENV("PYTHONDUMPREFS"))
     497        _Py_PrintReferences(stderr);
    477498#endif /* Py_TRACE_REFS */
    478499
    479         /* Clear interpreter state */
    480         PyInterpreterState_Clear(interp);
    481 
    482         /* Now we decref the exception classes.  After this point nothing
    483            can raise an exception.  That's okay, because each Fini() method
    484            below has been checked to make sure no exceptions are ever
    485            raised.
    486         */
    487 
    488         _PyExc_Fini();
    489 
    490         /* Cleanup auto-thread-state */
     500    /* Clear interpreter state */
     501    PyInterpreterState_Clear(interp);
     502
     503    /* Now we decref the exception classes.  After this point nothing
     504       can raise an exception.  That's okay, because each Fini() method
     505       below has been checked to make sure no exceptions are ever
     506       raised.
     507    */
     508
     509    _PyExc_Fini();
     510
     511    /* Cleanup auto-thread-state */
    491512#ifdef WITH_THREAD
    492         _PyGILState_Fini();
     513    _PyGILState_Fini();
    493514#endif /* WITH_THREAD */
    494515
    495         /* Delete current thread */
    496         PyThreadState_Swap(NULL);
    497         PyInterpreterState_Delete(interp);
    498 
    499         /* Sundry finalizers */
    500         PyMethod_Fini();
    501         PyFrame_Fini();
    502         PyCFunction_Fini();
    503         PyTuple_Fini();
    504         PyList_Fini();
    505         PySet_Fini();
    506         PyString_Fini();
    507         PyByteArray_Fini();
    508         PyInt_Fini();
    509         PyFloat_Fini();
    510         PyDict_Fini();
     516    /* Delete current thread */
     517    PyThreadState_Swap(NULL);
     518    PyInterpreterState_Delete(interp);
     519
     520    /* Sundry finalizers */
     521    PyMethod_Fini();
     522    PyFrame_Fini();
     523    PyCFunction_Fini();
     524    PyTuple_Fini();
     525    PyList_Fini();
     526    PySet_Fini();
     527    PyString_Fini();
     528    PyByteArray_Fini();
     529    PyInt_Fini();
     530    PyFloat_Fini();
     531    PyDict_Fini();
    511532
    512533#ifdef Py_USING_UNICODE
    513         /* Cleanup Unicode implementation */
    514         _PyUnicode_Fini();
    515 #endif
    516 
    517         /* XXX Still allocated:
    518            - various static ad-hoc pointers to interned strings
    519            - int and float free list blocks
    520            - whatever various modules and libraries allocate
    521         */
    522 
    523         PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
     534    /* Cleanup Unicode implementation */
     535    _PyUnicode_Fini();
     536#endif
     537
     538    /* XXX Still allocated:
     539       - various static ad-hoc pointers to interned strings
     540       - int and float free list blocks
     541       - whatever various modules and libraries allocate
     542    */
     543
     544    PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
    524545
    525546#ifdef Py_TRACE_REFS
    526         /* Display addresses (& refcnts) of all objects still alive.
    527         * An address can be used to find the repr of the object, printed
    528         * above by _Py_PrintReferences.
    529         */
    530         if (Py_GETENV("PYTHONDUMPREFS"))
    531                 _Py_PrintReferenceAddresses(stderr);
     547    /* Display addresses (& refcnts) of all objects still alive.
     548    * An address can be used to find the repr of the object, printed
     549    * above by _Py_PrintReferences.
     550    */
     551    if (Py_GETENV("PYTHONDUMPREFS"))
     552        _Py_PrintReferenceAddresses(stderr);
    532553#endif /* Py_TRACE_REFS */
    533554#ifdef PYMALLOC_DEBUG
    534         if (Py_GETENV("PYTHONMALLOCSTATS"))
    535                 _PyObject_DebugMallocStats();
    536 #endif
    537 
    538         call_ll_exitfuncs();
     555    if (Py_GETENV("PYTHONMALLOCSTATS"))
     556        _PyObject_DebugMallocStats();
     557#endif
     558
     559    call_ll_exitfuncs();
    539560}
    540561
     
    555576Py_NewInterpreter(void)
    556577{
    557         PyInterpreterState *interp;
    558         PyThreadState *tstate, *save_tstate;
    559         PyObject *bimod, *sysmod;
    560 
    561         if (!initialized)
    562                 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
    563 
    564         interp = PyInterpreterState_New();
    565         if (interp == NULL)
    566                 return NULL;
    567 
    568         tstate = PyThreadState_New(interp);
    569         if (tstate == NULL) {
    570                 PyInterpreterState_Delete(interp);
    571                 return NULL;
    572         }
    573 
    574         save_tstate = PyThreadState_Swap(tstate);
    575 
    576         /* XXX The following is lax in error checking */
    577 
    578         interp->modules = PyDict_New();
    579         interp->modules_reloading = PyDict_New();
    580 
    581         bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
    582         if (bimod != NULL) {
    583                 interp->builtins = PyModule_GetDict(bimod);
    584                 if (interp->builtins == NULL)
    585                         goto handle_error;
    586                 Py_INCREF(interp->builtins);
    587         }
    588         sysmod = _PyImport_FindExtension("sys", "sys");
    589         if (bimod != NULL && sysmod != NULL) {
    590                 interp->sysdict = PyModule_GetDict(sysmod);
    591                 if (interp->sysdict == NULL)
    592                         goto handle_error;
    593                 Py_INCREF(interp->sysdict);
    594                 PySys_SetPath(Py_GetPath());
    595                 PyDict_SetItemString(interp->sysdict, "modules",
    596                                      interp->modules);
    597                 _PyImportHooks_Init();
    598                 initmain();
    599                 if (!Py_NoSiteFlag)
    600                         initsite();
    601         }
    602 
    603         if (!PyErr_Occurred())
    604                 return tstate;
     578    PyInterpreterState *interp;
     579    PyThreadState *tstate, *save_tstate;
     580    PyObject *bimod, *sysmod;
     581
     582    if (!initialized)
     583        Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
     584
     585    interp = PyInterpreterState_New();
     586    if (interp == NULL)
     587        return NULL;
     588
     589    tstate = PyThreadState_New(interp);
     590    if (tstate == NULL) {
     591        PyInterpreterState_Delete(interp);
     592        return NULL;
     593    }
     594
     595    save_tstate = PyThreadState_Swap(tstate);
     596
     597    /* XXX The following is lax in error checking */
     598
     599    interp->modules = PyDict_New();
     600    interp->modules_reloading = PyDict_New();
     601
     602    bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
     603    if (bimod != NULL) {
     604        interp->builtins = PyModule_GetDict(bimod);
     605        if (interp->builtins == NULL)
     606            goto handle_error;
     607        Py_INCREF(interp->builtins);
     608    }
     609    sysmod = _PyImport_FindExtension("sys", "sys");
     610    if (bimod != NULL && sysmod != NULL) {
     611        interp->sysdict = PyModule_GetDict(sysmod);
     612        if (interp->sysdict == NULL)
     613            goto handle_error;
     614        Py_INCREF(interp->sysdict);
     615        PySys_SetPath(Py_GetPath());
     616        PyDict_SetItemString(interp->sysdict, "modules",
     617                             interp->modules);
     618        _PyImportHooks_Init();
     619        initmain();
     620        if (!Py_NoSiteFlag)
     621            initsite();
     622    }
     623
     624    if (!PyErr_Occurred())
     625        return tstate;
    605626
    606627handle_error:
    607         /* Oops, it didn't work.  Undo it all. */
    608 
    609         PyErr_Print();
    610         PyThreadState_Clear(tstate);
    611         PyThreadState_Swap(save_tstate);
    612         PyThreadState_Delete(tstate);
    613         PyInterpreterState_Delete(interp);
    614 
    615         return NULL;
     628    /* Oops, it didn't work.  Undo it all. */
     629
     630    PyErr_Print();
     631    PyThreadState_Clear(tstate);
     632    PyThreadState_Swap(save_tstate);
     633    PyThreadState_Delete(tstate);
     634    PyInterpreterState_Delete(interp);
     635
     636    return NULL;
    616637}
    617638
     
    631652Py_EndInterpreter(PyThreadState *tstate)
    632653{
    633         PyInterpreterState *interp = tstate->interp;
    634 
    635         if (tstate != PyThreadState_GET())
    636                 Py_FatalError("Py_EndInterpreter: thread is not current");
    637         if (tstate->frame != NULL)
    638                 Py_FatalError("Py_EndInterpreter: thread still has a frame");
    639         if (tstate != interp->tstate_head || tstate->next != NULL)
    640                 Py_FatalError("Py_EndInterpreter: not the last thread");
    641 
    642         PyImport_Cleanup();
    643         PyInterpreterState_Clear(interp);
    644         PyThreadState_Swap(NULL);
    645         PyInterpreterState_Delete(interp);
     654    PyInterpreterState *interp = tstate->interp;
     655
     656    if (tstate != PyThreadState_GET())
     657        Py_FatalError("Py_EndInterpreter: thread is not current");
     658    if (tstate->frame != NULL)
     659        Py_FatalError("Py_EndInterpreter: thread still has a frame");
     660    if (tstate != interp->tstate_head || tstate->next != NULL)
     661        Py_FatalError("Py_EndInterpreter: not the last thread");
     662
     663    PyImport_Cleanup();
     664    PyInterpreterState_Clear(interp);
     665    PyThreadState_Swap(NULL);
     666    PyInterpreterState_Delete(interp);
    646667}
    647668
     
    651672Py_SetProgramName(char *pn)
    652673{
    653         if (pn && *pn)
    654                 progname = pn;
     674    if (pn && *pn)
     675        progname = pn;
    655676}
    656677
     
    658679Py_GetProgramName(void)
    659680{
    660         return progname;
     681    return progname;
    661682}
    662683
     
    666687Py_SetPythonHome(char *home)
    667688{
    668         default_home = home;
     689    default_home = home;
    669690}
    670691
     
    672693Py_GetPythonHome(void)
    673694{
    674         char *home = default_home;
    675         if (home == NULL && !Py_IgnoreEnvironmentFlag)
    676                 home = Py_GETENV("PYTHONHOME");
    677         return home;
     695    char *home = default_home;
     696    if (home == NULL && !Py_IgnoreEnvironmentFlag)
     697        home = Py_GETENV("PYTHONHOME");
     698    return home;
    678699}
    679700
     
    683704initmain(void)
    684705{
    685         PyObject *m, *d;
    686         m = PyImport_AddModule("__main__");
    687         if (m == NULL)
    688                 Py_FatalError("can't create __main__ module");
    689         d = PyModule_GetDict(m);
    690         if (PyDict_GetItemString(d, "__builtins__") == NULL) {
    691                 PyObject *bimod = PyImport_ImportModule("__builtin__");
    692                 if (bimod == NULL ||
    693                     PyDict_SetItemString(d, "__builtins__", bimod) != 0)
    694                         Py_FatalError("can't add __builtins__ to __main__");
    695                 Py_DECREF(bimod);
    696         }
     706    PyObject *m, *d;
     707    m = PyImport_AddModule("__main__");
     708    if (m == NULL)
     709        Py_FatalError("can't create __main__ module");
     710    d = PyModule_GetDict(m);
     711    if (PyDict_GetItemString(d, "__builtins__") == NULL) {
     712        PyObject *bimod = PyImport_ImportModule("__builtin__");
     713        if (bimod == NULL ||
     714            PyDict_SetItemString(d, "__builtins__", bimod) != 0)
     715            Py_FatalError("can't add __builtins__ to __main__");
     716        Py_XDECREF(bimod);
     717    }
    697718}
    698719
     
    702723initsite(void)
    703724{
    704         PyObject *m, *f;
    705         m = PyImport_ImportModule("site");
    706         if (m == NULL) {
    707                 f = PySys_GetObject("stderr");
    708                 if (Py_VerboseFlag) {
    709                         PyFile_WriteString(
    710                                 "'import site' failed; traceback:\n", f);
    711                         PyErr_Print();
    712                 }
    713                 else {
    714                         PyFile_WriteString(
    715                           "'import site' failed; use -v for traceback\n", f);
    716                         PyErr_Clear();
    717                 }
    718         }
    719         else {
    720                 Py_DECREF(m);
    721         }
     725    PyObject *m;
     726    m = PyImport_ImportModule("site");
     727    if (m == NULL) {
     728        PyErr_Print();
     729        Py_Finalize();
     730        exit(1);
     731    }
     732    else {
     733        Py_DECREF(m);
     734    }
    722735}
    723736
     
    726739int
    727740PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
    728                      PyCompilerFlags *flags)
    729 {
    730         if (filename == NULL)
    731                 filename = "???";
    732         if (Py_FdIsInteractive(fp, filename)) {
    733                 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
    734                 if (closeit)
    735                         fclose(fp);
    736                 return err;
    737         }
    738         else
    739                 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
     741                     PyCompilerFlags *flags)
     742{
     743    if (filename == NULL)
     744        filename = "???";
     745    if (Py_FdIsInteractive(fp, filename)) {
     746        int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
     747        if (closeit)
     748            fclose(fp);
     749        return err;
     750    }
     751    else
     752        return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
    740753}
    741754
     
    743756PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
    744757{
    745         PyObject *v;
    746         int ret;
    747         PyCompilerFlags local_flags;
    748 
    749         if (flags == NULL) {
    750                 flags = &local_flags;
    751                 local_flags.cf_flags = 0;
    752         }
    753         v = PySys_GetObject("ps1");
    754         if (v == NULL) {
    755                 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
    756                 Py_XDECREF(v);
    757         }
    758         v = PySys_GetObject("ps2");
    759         if (v == NULL) {
    760                 PySys_SetObject("ps2", v = PyString_FromString("... "));
    761                 Py_XDECREF(v);
    762         }
    763         for (;;) {
    764                 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
    765                 PRINT_TOTAL_REFS();
    766                 if (ret == E_EOF)
    767                         return 0;
    768                 /*
    769                 if (ret == E_NOMEM)
    770                         return -1;
    771                 */
    772         }
     758    PyObject *v;
     759    int ret;
     760    PyCompilerFlags local_flags;
     761
     762    if (flags == NULL) {
     763        flags = &local_flags;
     764        local_flags.cf_flags = 0;
     765    }
     766    v = PySys_GetObject("ps1");
     767    if (v == NULL) {
     768        PySys_SetObject("ps1", v = PyString_FromString(">>> "));
     769        Py_XDECREF(v);
     770    }
     771    v = PySys_GetObject("ps2");
     772    if (v == NULL) {
     773        PySys_SetObject("ps2", v = PyString_FromString("... "));
     774        Py_XDECREF(v);
     775    }
     776    for (;;) {
     777        ret = PyRun_InteractiveOneFlags(fp, filename, flags);
     778        PRINT_TOTAL_REFS();
     779        if (ret == E_EOF)
     780            return 0;
     781        /*
     782        if (ret == E_NOMEM)
     783            return -1;
     784        */
     785    }
    773786}
    774787
     
    776789/* compute parser flags based on compiler flags */
    777790#define PARSER_FLAGS(flags) \
    778         ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
    779                       PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
     791    ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
     792                  PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
    780793#endif
    781794#if 1
    782795/* Keep an example of flags with future keyword support. */
    783796#define PARSER_FLAGS(flags) \
    784         ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
    785                       PyPARSE_DONT_IMPLY_DEDENT : 0) \
    786                     | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
    787                        PyPARSE_PRINT_IS_FUNCTION : 0) \
    788                     | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
    789                        PyPARSE_UNICODE_LITERALS : 0) \
    790                     ) : 0)
     797    ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
     798                  PyPARSE_DONT_IMPLY_DEDENT : 0) \
     799                | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
     800                   PyPARSE_PRINT_IS_FUNCTION : 0) \
     801                | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
     802                   PyPARSE_UNICODE_LITERALS : 0) \
     803                ) : 0)
    791804#endif
    792805
     
    794807PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
    795808{
    796         PyObject *m, *d, *v, *w;
    797         mod_ty mod;
    798         PyArena *arena;
    799         char *ps1 = "", *ps2 = "";
    800         int errcode = 0;
    801 
    802         v = PySys_GetObject("ps1");
    803         if (v != NULL) {
    804                 v = PyObject_Str(v);
    805                 if (v == NULL)
    806                         PyErr_Clear();
    807                 else if (PyString_Check(v))
    808                         ps1 = PyString_AsString(v);
    809         }
    810         w = PySys_GetObject("ps2");
    811         if (w != NULL) {
    812                 w = PyObject_Str(w);
    813                 if (w == NULL)
    814                         PyErr_Clear();
    815                 else if (PyString_Check(w))
    816                         ps2 = PyString_AsString(w);
    817         }
    818         arena = PyArena_New();
    819         if (arena == NULL) {
    820                 Py_XDECREF(v);
    821                 Py_XDECREF(w);
    822                 return -1;
    823         }
    824         mod = PyParser_ASTFromFile(fp, filename,
    825                                    Py_single_input, ps1, ps2,
    826                                    flags, &errcode, arena);
    827         Py_XDECREF(v);
    828         Py_XDECREF(w);
    829         if (mod == NULL) {
    830                 PyArena_Free(arena);
    831                 if (errcode == E_EOF) {
    832                         PyErr_Clear();
    833                         return E_EOF;
    834                 }
    835                 PyErr_Print();
    836                 return -1;
    837         }
    838         m = PyImport_AddModule("__main__");
    839         if (m == NULL) {
    840                 PyArena_Free(arena);
    841                 return -1;
    842         }
    843         d = PyModule_GetDict(m);
    844         v = run_mod(mod, filename, d, d, flags, arena);
    845         PyArena_Free(arena);
    846         if (v == NULL) {
    847                 PyErr_Print();
    848                 return -1;
    849         }
    850         Py_DECREF(v);
    851         if (Py_FlushLine())
    852                 PyErr_Clear();
    853         return 0;
     809    PyObject *m, *d, *v, *w;
     810    mod_ty mod;
     811    PyArena *arena;
     812    char *ps1 = "", *ps2 = "";
     813    int errcode = 0;
     814
     815    v = PySys_GetObject("ps1");
     816    if (v != NULL) {
     817        v = PyObject_Str(v);
     818        if (v == NULL)
     819            PyErr_Clear();
     820        else if (PyString_Check(v))
     821            ps1 = PyString_AsString(v);
     822    }
     823    w = PySys_GetObject("ps2");
     824    if (w != NULL) {
     825        w = PyObject_Str(w);
     826        if (w == NULL)
     827            PyErr_Clear();
     828        else if (PyString_Check(w))
     829            ps2 = PyString_AsString(w);
     830    }
     831    arena = PyArena_New();
     832    if (arena == NULL) {
     833        Py_XDECREF(v);
     834        Py_XDECREF(w);
     835        return -1;
     836    }
     837    mod = PyParser_ASTFromFile(fp, filename,
     838                               Py_single_input, ps1, ps2,
     839                               flags, &errcode, arena);
     840    Py_XDECREF(v);
     841    Py_XDECREF(w);
     842    if (mod == NULL) {
     843        PyArena_Free(arena);
     844        if (errcode == E_EOF) {
     845            PyErr_Clear();
     846            return E_EOF;
     847        }
     848        PyErr_Print();
     849        return -1;
     850    }
     851    m = PyImport_AddModule("__main__");
     852    if (m == NULL) {
     853        PyArena_Free(arena);
     854        return -1;
     855    }
     856    d = PyModule_GetDict(m);
     857    v = run_mod(mod, filename, d, d, flags, arena);
     858    PyArena_Free(arena);
     859    if (v == NULL) {
     860        PyErr_Print();
     861        return -1;
     862    }
     863    Py_DECREF(v);
     864    if (Py_FlushLine())
     865        PyErr_Clear();
     866    return 0;
    854867}
    855868
     
    860873maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
    861874{
    862         if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
    863                 return 1;
    864 
    865         /* Only look into the file if we are allowed to close it, since
    866            it then should also be seekable. */
    867         if (closeit) {
    868                 /* Read only two bytes of the magic. If the file was opened in
    869                    text mode, the bytes 3 and 4 of the magic (\r\n) might not
    870                    be read as they are on disk. */
    871                 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
    872                 unsigned char buf[2];
    873                 /* Mess:  In case of -x, the stream is NOT at its start now,
    874                    and ungetc() was used to push back the first newline,
    875                    which makes the current stream position formally undefined,
    876                    and a x-platform nightmare.
    877                    Unfortunately, we have no direct way to know whether -x
    878                    was specified.  So we use a terrible hack:  if the current
    879                    stream position is not 0, we assume -x was specified, and
    880                    give up.  Bug 132850 on SourceForge spells out the
    881                    hopelessness of trying anything else (fseek and ftell
    882                    don't work predictably x-platform for text-mode files).
    883                 */
    884                 int ispyc = 0;
    885                 if (ftell(fp) == 0) {
    886                         if (fread(buf, 1, 2, fp) == 2 &&
    887                             ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
    888                                 ispyc = 1;
    889                         rewind(fp);
    890                 }
    891                 return ispyc;
    892         }
    893         return 0;
     875    if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
     876        return 1;
     877
     878    /* Only look into the file if we are allowed to close it, since
     879       it then should also be seekable. */
     880    if (closeit) {
     881        /* Read only two bytes of the magic. If the file was opened in
     882           text mode, the bytes 3 and 4 of the magic (\r\n) might not
     883           be read as they are on disk. */
     884        unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
     885        unsigned char buf[2];
     886        /* Mess:  In case of -x, the stream is NOT at its start now,
     887           and ungetc() was used to push back the first newline,
     888           which makes the current stream position formally undefined,
     889           and a x-platform nightmare.
     890           Unfortunately, we have no direct way to know whether -x
     891           was specified.  So we use a terrible hack:  if the current
     892           stream position is not 0, we assume -x was specified, and
     893           give up.  Bug 132850 on SourceForge spells out the
     894           hopelessness of trying anything else (fseek and ftell
     895           don't work predictably x-platform for text-mode files).
     896        */
     897        int ispyc = 0;
     898        if (ftell(fp) == 0) {
     899            if (fread(buf, 1, 2, fp) == 2 &&
     900                ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
     901                ispyc = 1;
     902            rewind(fp);
     903        }
     904        return ispyc;
     905    }
     906    return 0;
    894907}
    895908
    896909int
    897910PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
    898                         PyCompilerFlags *flags)
    899 {
    900         PyObject *m, *d, *v;
    901         const char *ext;
    902         int set_file_name = 0, ret, len;
    903 
    904         m = PyImport_AddModule("__main__");
    905         if (m == NULL)
    906                 return -1;
    907         d = PyModule_GetDict(m);
    908         if (PyDict_GetItemString(d, "__file__") == NULL) {
    909                 PyObject *f = PyString_FromString(filename);
    910                 if (f == NULL)
    911                         return -1;
    912                 if (PyDict_SetItemString(d, "__file__", f) < 0) {
    913                         Py_DECREF(f);
    914                         return -1;
    915                 }
    916                 set_file_name = 1;
    917                 Py_DECREF(f);
    918         }
    919         len = strlen(filename);
    920         ext = filename + len - (len > 4 ? 4 : 0);
    921         if (maybe_pyc_file(fp, filename, ext, closeit)) {
    922                 /* Try to run a pyc file. First, re-open in binary */
    923                 if (closeit)
    924                         fclose(fp);
    925                 if ((fp = fopen(filename, "rb")) == NULL) {
    926                         fprintf(stderr, "python: Can't reopen .pyc file\n");
    927                         ret = -1;
    928                         goto done;
    929                 }
    930                 /* Turn on optimization if a .pyo file is given */
    931                 if (strcmp(ext, ".pyo") == 0)
    932                         Py_OptimizeFlag = 1;
    933                 v = run_pyc_file(fp, filename, d, d, flags);
    934         } else {
    935                 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
    936                                       closeit, flags);
    937         }
    938         if (v == NULL) {
    939                 PyErr_Print();
    940                 ret = -1;
    941                 goto done;
    942         }
    943         Py_DECREF(v);
    944         if (Py_FlushLine())
    945                 PyErr_Clear();
    946         ret = 0;
     911                        PyCompilerFlags *flags)
     912{
     913    PyObject *m, *d, *v;
     914    const char *ext;
     915    int set_file_name = 0, len, ret = -1;
     916
     917    m = PyImport_AddModule("__main__");
     918    if (m == NULL)
     919        return -1;
     920    Py_INCREF(m);
     921    d = PyModule_GetDict(m);
     922    if (PyDict_GetItemString(d, "__file__") == NULL) {
     923        PyObject *f = PyString_FromString(filename);
     924        if (f == NULL)
     925            goto done;
     926        if (PyDict_SetItemString(d, "__file__", f) < 0) {
     927            Py_DECREF(f);
     928            goto done;
     929        }
     930        set_file_name = 1;
     931        Py_DECREF(f);
     932    }
     933    len = strlen(filename);
     934    ext = filename + len - (len > 4 ? 4 : 0);
     935    if (maybe_pyc_file(fp, filename, ext, closeit)) {
     936        /* Try to run a pyc file. First, re-open in binary */
     937        if (closeit)
     938            fclose(fp);
     939        if ((fp = fopen(filename, "rb")) == NULL) {
     940            fprintf(stderr, "python: Can't reopen .pyc file\n");
     941            goto done;
     942        }
     943        /* Turn on optimization if a .pyo file is given */
     944        if (strcmp(ext, ".pyo") == 0)
     945            Py_OptimizeFlag = 1;
     946        v = run_pyc_file(fp, filename, d, d, flags);
     947    } else {
     948        v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
     949                              closeit, flags);
     950    }
     951    if (v == NULL) {
     952        PyErr_Print();
     953        goto done;
     954    }
     955    Py_DECREF(v);
     956    if (Py_FlushLine())
     957        PyErr_Clear();
     958    ret = 0;
    947959  done:
    948         if (set_file_name && PyDict_DelItemString(d, "__file__"))
    949                 PyErr_Clear();
    950         return ret;
     960    if (set_file_name && PyDict_DelItemString(d, "__file__"))
     961        PyErr_Clear();
     962    Py_DECREF(m);
     963    return ret;
    951964}
    952965
     
    954967PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
    955968{
    956         PyObject *m, *d, *v;
    957         m = PyImport_AddModule("__main__");
    958         if (m == NULL)
    959                 return -1;
    960         d = PyModule_GetDict(m);
    961         v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
    962         if (v == NULL) {
    963                 PyErr_Print();
    964                 return -1;
    965         }
    966         Py_DECREF(v);
    967         if (Py_FlushLine())
    968                 PyErr_Clear();
    969         return 0;
     969    PyObject *m, *d, *v;
     970    m = PyImport_AddModule("__main__");
     971    if (m == NULL)
     972        return -1;
     973    d = PyModule_GetDict(m);
     974    v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
     975    if (v == NULL) {
     976        PyErr_Print();
     977        return -1;
     978    }
     979    Py_DECREF(v);
     980    if (Py_FlushLine())
     981        PyErr_Clear();
     982    return 0;
    970983}
    971984
    972985static int
    973986parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
    974                    int *lineno, int *offset, const char **text)
    975 {
    976         long hold;
    977         PyObject *v;
    978 
    979         /* old style errors */
    980         if (PyTuple_Check(err))
    981                 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
    982                                         lineno, offset, text);
    983 
    984         /* new style errors.  `err' is an instance */
    985 
    986         if (! (v = PyObject_GetAttrString(err, "msg")))
    987                 goto finally;
    988         *message = v;
    989 
    990         if (!(v = PyObject_GetAttrString(err, "filename")))
    991                 goto finally;
    992         if (v == Py_None)
    993                 *filename = NULL;
    994         else if (! (*filename = PyString_AsString(v)))
    995                 goto finally;
    996 
    997         Py_DECREF(v);
    998         if (!(v = PyObject_GetAttrString(err, "lineno")))
    999                 goto finally;
    1000         hold = PyInt_AsLong(v);
    1001         Py_DECREF(v);
    1002         v = NULL;
    1003         if (hold < 0 && PyErr_Occurred())
    1004                 goto finally;
    1005         *lineno = (int)hold;
    1006 
    1007         if (!(v = PyObject_GetAttrString(err, "offset")))
    1008                 goto finally;
    1009         if (v == Py_None) {
    1010                 *offset = -1;
    1011                 Py_DECREF(v);
    1012                 v = NULL;
    1013         } else {
    1014                 hold = PyInt_AsLong(v);
    1015                 Py_DECREF(v);
    1016                 v = NULL;
    1017                 if (hold < 0 && PyErr_Occurred())
    1018                         goto finally;
    1019                 *offset = (int)hold;
    1020         }
    1021 
    1022         if (!(v = PyObject_GetAttrString(err, "text")))
    1023                 goto finally;
    1024         if (v == Py_None)
    1025                 *text = NULL;
    1026         else if (! (*text = PyString_AsString(v)))
    1027                 goto finally;
    1028         Py_DECREF(v);
    1029         return 1;
     987                   int *lineno, int *offset, const char **text)
     988{
     989    long hold;
     990    PyObject *v;
     991
     992    /* old style errors */
     993    if (PyTuple_Check(err))
     994        return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
     995                                lineno, offset, text);
     996
     997    *message = NULL;
     998
     999    /* new style errors.  `err' is an instance */
     1000    *message = PyObject_GetAttrString(err, "msg");
     1001    if (!*message)
     1002        goto finally;
     1003
     1004    v = PyObject_GetAttrString(err, "filename");
     1005    if (!v)
     1006        goto finally;
     1007    if (v == Py_None) {
     1008        Py_DECREF(v);
     1009        *filename = NULL;
     1010    }
     1011    else {
     1012        *filename = PyString_AsString(v);
     1013        Py_DECREF(v);
     1014        if (!*filename)
     1015            goto finally;
     1016    }
     1017
     1018    v = PyObject_GetAttrString(err, "lineno");
     1019    if (!v)
     1020        goto finally;
     1021    hold = PyInt_AsLong(v);
     1022    Py_DECREF(v);
     1023    if (hold < 0 && PyErr_Occurred())
     1024        goto finally;
     1025    *lineno = (int)hold;
     1026
     1027    v = PyObject_GetAttrString(err, "offset");
     1028    if (!v)
     1029        goto finally;
     1030    if (v == Py_None) {
     1031        *offset = -1;
     1032        Py_DECREF(v);
     1033    } else {
     1034        hold = PyInt_AsLong(v);
     1035        Py_DECREF(v);
     1036        if (hold < 0 && PyErr_Occurred())
     1037            goto finally;
     1038        *offset = (int)hold;
     1039    }
     1040
     1041    v = PyObject_GetAttrString(err, "text");
     1042    if (!v)
     1043        goto finally;
     1044    if (v == Py_None) {
     1045        Py_DECREF(v);
     1046        *text = NULL;
     1047    }
     1048    else {
     1049        *text = PyString_AsString(v);
     1050        Py_DECREF(v);
     1051        if (!*text)
     1052            goto finally;
     1053    }
     1054    return 1;
    10301055
    10311056finally:
    1032         Py_XDECREF(v);
    1033         return 0;
     1057    Py_XDECREF(*message);
     1058    return 0;
    10341059}
    10351060
     
    10371062PyErr_Print(void)
    10381063{
    1039         PyErr_PrintEx(1);
     1064    PyErr_PrintEx(1);
    10401065}
    10411066
     
    10431068print_error_text(PyObject *f, int offset, const char *text)
    10441069{
    1045         char *nl;
    1046         if (offset >= 0) {
    1047                 if (offset > 0 && offset == (int)strlen(text))
    1048                         offset--;
    1049                 for (;;) {
    1050                         nl = strchr(text, '\n');
    1051                         if (nl == NULL || nl-text >= offset)
    1052                                 break;
    1053                         offset -= (int)(nl+1-text);
    1054                         text = nl+1;
    1055                 }
    1056                 while (*text == ' ' || *text == '\t') {
    1057                         text++;
    1058                         offset--;
    1059                 }
    1060         }
    1061         PyFile_WriteString("    ", f);
    1062         PyFile_WriteString(text, f);
    1063         if (*text == '\0' || text[strlen(text)-1] != '\n')
    1064                 PyFile_WriteString("\n", f);
    1065         if (offset == -1)
    1066                 return;
    1067         PyFile_WriteString("    ", f);
    1068         offset--;
    1069         while (offset > 0) {
    1070                 PyFile_WriteString(" ", f);
    1071                 offset--;
    1072         }
    1073         PyFile_WriteString("^\n", f);
     1070    char *nl;
     1071    if (offset >= 0) {
     1072        if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
     1073            offset--;
     1074        for (;;) {
     1075            nl = strchr(text, '\n');
     1076            if (nl == NULL || nl-text >= offset)
     1077                break;
     1078            offset -= (int)(nl+1-text);
     1079            text = nl+1;
     1080        }
     1081        while (*text == ' ' || *text == '\t') {
     1082            text++;
     1083            offset--;
     1084        }
     1085    }
     1086    PyFile_WriteString("    ", f);
     1087    PyFile_WriteString(text, f);
     1088    if (*text == '\0' || text[strlen(text)-1] != '\n')
     1089        PyFile_WriteString("\n", f);
     1090    if (offset == -1)
     1091        return;
     1092    PyFile_WriteString("    ", f);
     1093    offset--;
     1094    while (offset > 0) {
     1095        PyFile_WriteString(" ", f);
     1096        offset--;
     1097    }
     1098    PyFile_WriteString("^\n", f);
    10741099}
    10751100
     
    10771102handle_system_exit(void)
    10781103{
    1079         PyObject *exception, *value, *tb;
    1080         int exitcode = 0;
    1081 
    1082         if (Py_InspectFlag)
    1083                 /* Don't exit if -i flag was given. This flag is set to 0
    1084                  * when entering interactive mode for inspecting. */
    1085                 return;
    1086 
    1087         PyErr_Fetch(&exception, &value, &tb);
    1088         if (Py_FlushLine())
    1089                 PyErr_Clear();
    1090         fflush(stdout);
    1091         if (value == NULL || value == Py_None)
    1092                 goto done;
    1093         if (PyExceptionInstance_Check(value)) {
    1094                 /* The error code should be in the `code' attribute. */
    1095                 PyObject *code = PyObject_GetAttrString(value, "code");
    1096                 if (code) {
    1097                         Py_DECREF(value);
    1098                         value = code;
    1099                         if (value == Py_None)
    1100                                 goto done;
    1101                 }
    1102                 /* If we failed to dig out the 'code' attribute,
    1103                    just let the else clause below print the error. */
    1104         }
    1105         if (PyInt_Check(value))
    1106                 exitcode = (int)PyInt_AsLong(value);
    1107         else {
    1108                 PyObject_Print(value, stderr, Py_PRINT_RAW);
    1109                 PySys_WriteStderr("\n");
    1110                 exitcode = 1;
    1111         }
     1104    PyObject *exception, *value, *tb;
     1105    int exitcode = 0;
     1106
     1107    if (Py_InspectFlag)
     1108        /* Don't exit if -i flag was given. This flag is set to 0
     1109         * when entering interactive mode for inspecting. */
     1110        return;
     1111
     1112    PyErr_Fetch(&exception, &value, &tb);
     1113    if (Py_FlushLine())
     1114        PyErr_Clear();
     1115    fflush(stdout);
     1116    if (value == NULL || value == Py_None)
     1117        goto done;
     1118    if (PyExceptionInstance_Check(value)) {
     1119        /* The error code should be in the `code' attribute. */
     1120        PyObject *code = PyObject_GetAttrString(value, "code");
     1121        if (code) {
     1122            Py_DECREF(value);
     1123            value = code;
     1124            if (value == Py_None)
     1125                goto done;
     1126        }
     1127        /* If we failed to dig out the 'code' attribute,
     1128           just let the else clause below print the error. */
     1129    }
     1130    if (PyInt_Check(value))
     1131        exitcode = (int)PyInt_AsLong(value);
     1132    else {
     1133        PyObject *sys_stderr = PySys_GetObject("stderr");
     1134        if (sys_stderr != NULL && sys_stderr != Py_None) {
     1135            PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
     1136        } else {
     1137            PyObject_Print(value, stderr, Py_PRINT_RAW);
     1138            fflush(stderr);
     1139        }
     1140        PySys_WriteStderr("\n");
     1141        exitcode = 1;
     1142    }
    11121143 done:
    1113         /* Restore and clear the exception info, in order to properly decref
    1114          * the exception, value, and traceback. If we just exit instead,
    1115         * these leak, which confuses PYTHONDUMPREFS output, and may prevent
    1116         * some finalizers from running.
    1117         */
    1118         PyErr_Restore(exception, value, tb);
    1119         PyErr_Clear();
    1120         Py_Exit(exitcode);
    1121         /* NOTREACHED */
     1144    /* Restore and clear the exception info, in order to properly decref
     1145     * the exception, value, and traceback.      If we just exit instead,
     1146    * these leak, which confuses PYTHONDUMPREFS output, and may prevent
     1147    * some finalizers from running.
     1148    */
     1149    PyErr_Restore(exception, value, tb);
     1150    PyErr_Clear();
     1151    Py_Exit(exitcode);
     1152    /* NOTREACHED */
    11221153}
    11231154
     
    11251156PyErr_PrintEx(int set_sys_last_vars)
    11261157{
    1127         PyObject *exception, *v, *tb, *hook;
    1128 
    1129         if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
    1130                 handle_system_exit();
    1131         }
    1132         PyErr_Fetch(&exception, &v, &tb);
    1133         if (exception == NULL)
    1134                 return;
    1135         PyErr_NormalizeException(&exception, &v, &tb);
    1136         if (exception == NULL)
    1137                 return;
    1138         /* Now we know v != NULL too */
    1139         if (set_sys_last_vars) {
    1140                 PySys_SetObject("last_type", exception);
    1141                 PySys_SetObject("last_value", v);
    1142                 PySys_SetObject("last_traceback", tb);
    1143         }
    1144         hook = PySys_GetObject("excepthook");
    1145         if (hook) {
    1146                 PyObject *args = PyTuple_Pack(3,
    1147                     exception, v, tb ? tb : Py_None);
    1148                 PyObject *result = PyEval_CallObject(hook, args);
    1149                 if (result == NULL) {
    1150                         PyObject *exception2, *v2, *tb2;
    1151                         if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
    1152                                 handle_system_exit();
    1153                         }
    1154                         PyErr_Fetch(&exception2, &v2, &tb2);
    1155                         PyErr_NormalizeException(&exception2, &v2, &tb2);
    1156                         /* It should not be possible for exception2 or v2
    1157                            to be NULL. However PyErr_Display() can't
    1158                            tolerate NULLs, so just be safe. */
    1159                         if (exception2 == NULL) {
    1160                                 exception2 = Py_None;
    1161                                 Py_INCREF(exception2);
    1162                         }
    1163                         if (v2 == NULL) {
    1164                                 v2 = Py_None;
    1165                                 Py_INCREF(v2);
    1166                         }
    1167                         if (Py_FlushLine())
    1168                                 PyErr_Clear();
    1169                         fflush(stdout);
    1170                         PySys_WriteStderr("Error in sys.excepthook:\n");
    1171                         PyErr_Display(exception2, v2, tb2);
    1172                         PySys_WriteStderr("\nOriginal exception was:\n");
    1173                         PyErr_Display(exception, v, tb);
    1174                         Py_DECREF(exception2);
    1175                         Py_DECREF(v2);
    1176                         Py_XDECREF(tb2);
    1177                 }
    1178                 Py_XDECREF(result);
    1179                 Py_XDECREF(args);
    1180         } else {
    1181                 PySys_WriteStderr("sys.excepthook is missing\n");
    1182                 PyErr_Display(exception, v, tb);
    1183         }
    1184         Py_XDECREF(exception);
    1185         Py_XDECREF(v);
    1186         Py_XDECREF(tb);
     1158    PyObject *exception, *v, *tb, *hook;
     1159
     1160    if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
     1161        handle_system_exit();
     1162    }
     1163    PyErr_Fetch(&exception, &v, &tb);
     1164    if (exception == NULL)
     1165        return;
     1166    PyErr_NormalizeException(&exception, &v, &tb);
     1167    if (exception == NULL)
     1168        return;
     1169    /* Now we know v != NULL too */
     1170    if (set_sys_last_vars) {
     1171        PySys_SetObject("last_type", exception);
     1172        PySys_SetObject("last_value", v);
     1173        PySys_SetObject("last_traceback", tb);
     1174    }
     1175    hook = PySys_GetObject("excepthook");
     1176    if (hook && hook != Py_None) {
     1177        PyObject *args = PyTuple_Pack(3,
     1178            exception, v, tb ? tb : Py_None);
     1179        PyObject *result = PyEval_CallObject(hook, args);
     1180        if (result == NULL) {
     1181            PyObject *exception2, *v2, *tb2;
     1182            if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
     1183                handle_system_exit();
     1184            }
     1185            PyErr_Fetch(&exception2, &v2, &tb2);
     1186            PyErr_NormalizeException(&exception2, &v2, &tb2);
     1187            /* It should not be possible for exception2 or v2
     1188               to be NULL. However PyErr_Display() can't
     1189               tolerate NULLs, so just be safe. */
     1190            if (exception2 == NULL) {
     1191                exception2 = Py_None;
     1192                Py_INCREF(exception2);
     1193            }
     1194            if (v2 == NULL) {
     1195                v2 = Py_None;
     1196                Py_INCREF(v2);
     1197            }
     1198            if (Py_FlushLine())
     1199                PyErr_Clear();
     1200            fflush(stdout);
     1201            PySys_WriteStderr("Error in sys.excepthook:\n");
     1202            PyErr_Display(exception2, v2, tb2);
     1203            PySys_WriteStderr("\nOriginal exception was:\n");
     1204            PyErr_Display(exception, v, tb);
     1205            Py_DECREF(exception2);
     1206            Py_DECREF(v2);
     1207            Py_XDECREF(tb2);
     1208        }
     1209        Py_XDECREF(result);
     1210        Py_XDECREF(args);
     1211    } else {
     1212        PySys_WriteStderr("sys.excepthook is missing\n");
     1213        PyErr_Display(exception, v, tb);
     1214    }
     1215    Py_XDECREF(exception);
     1216    Py_XDECREF(v);
     1217    Py_XDECREF(tb);
    11871218}
    11881219
     
    11901221PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
    11911222{
    1192         int err = 0;
    1193         PyObject *f = PySys_GetObject("stderr");
    1194         Py_INCREF(value);
    1195         if (f == NULL)
    1196                 fprintf(stderr, "lost sys.stderr\n");
    1197         else {
    1198                 if (Py_FlushLine())
    1199                         PyErr_Clear();
    1200                 fflush(stdout);
    1201                 if (tb && tb != Py_None)
    1202                         err = PyTraceBack_Print(tb, f);
    1203                 if (err == 0 &&
    1204                     PyObject_HasAttrString(value, "print_file_and_line"))
    1205                 {
    1206                         PyObject *message;
    1207                         const char *filename, *text;
    1208                         int lineno, offset;
    1209                         if (!parse_syntax_error(value, &message, &filename,
    1210                                                 &lineno, &offset, &text))
    1211                                 PyErr_Clear();
    1212                         else {
    1213                                 char buf[10];
    1214                                 PyFile_WriteString("  File \"", f);
    1215                                 if (filename == NULL)
    1216                                         PyFile_WriteString("<string>", f);
    1217                                 else
    1218                                         PyFile_WriteString(filename, f);
    1219                                 PyFile_WriteString("\", line ", f);
    1220                                 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
    1221                                 PyFile_WriteString(buf, f);
    1222                                 PyFile_WriteString("\n", f);
    1223                                 if (text != NULL)
    1224                                         print_error_text(f, offset, text);
    1225                                 Py_DECREF(value);
    1226                                 value = message;
    1227                                 /* Can't be bothered to check all those
    1228                                    PyFile_WriteString() calls */
    1229                                 if (PyErr_Occurred())
    1230                                         err = -1;
    1231                         }
    1232                 }
    1233                 if (err) {
    1234                         /* Don't do anything else */
    1235                 }
    1236                 else if (PyExceptionClass_Check(exception)) {
    1237                         PyObject* moduleName;
    1238                         char* className = PyExceptionClass_Name(exception);
    1239                         if (className != NULL) {
    1240                                 char *dot = strrchr(className, '.');
    1241                                 if (dot != NULL)
    1242                                         className = dot+1;
    1243                         }
    1244 
    1245                         moduleName = PyObject_GetAttrString(exception, "__module__");
    1246                         if (moduleName == NULL)
    1247                                 err = PyFile_WriteString("<unknown>", f);
    1248                         else {
    1249                                 char* modstr = PyString_AsString(moduleName);
    1250                                 if (modstr && strcmp(modstr, "exceptions"))
    1251                                 {
    1252                                         err = PyFile_WriteString(modstr, f);
    1253                                         err += PyFile_WriteString(".", f);
    1254                                 }
    1255                                 Py_DECREF(moduleName);
    1256                         }
    1257                         if (err == 0) {
    1258                                 if (className == NULL)
    1259                                       err = PyFile_WriteString("<unknown>", f);
    1260                                 else
    1261                                       err = PyFile_WriteString(className, f);
    1262                         }
    1263                 }
    1264                 else
    1265                         err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
    1266                 if (err == 0 && (value != Py_None)) {
    1267                         PyObject *s = PyObject_Str(value);
    1268                         /* only print colon if the str() of the
    1269                            object is not the empty string
    1270                         */
    1271                         if (s == NULL)
    1272                                 err = -1;
    1273                         else if (!PyString_Check(s) ||
    1274                                 PyString_GET_SIZE(s) != 0)
    1275                                 err = PyFile_WriteString(": ", f);
    1276                         if (err == 0)
    1277                           err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
    1278                         Py_XDECREF(s);
    1279                 }
    1280                 /* try to write a newline in any case */
    1281                 err += PyFile_WriteString("\n", f);
    1282         }
    1283         Py_DECREF(value);
    1284         /* If an error happened here, don't show it.
    1285            XXX This is wrong, but too many callers rely on this behavior. */
    1286         if (err != 0)
    1287                 PyErr_Clear();
     1223    int err = 0;
     1224    PyObject *f = PySys_GetObject("stderr");
     1225    Py_INCREF(value);
     1226    if (f == NULL || f == Py_None)
     1227        fprintf(stderr, "lost sys.stderr\n");
     1228    else {
     1229        if (Py_FlushLine())
     1230            PyErr_Clear();
     1231        fflush(stdout);
     1232        if (tb && tb != Py_None)
     1233            err = PyTraceBack_Print(tb, f);
     1234        if (err == 0 &&
     1235            PyObject_HasAttrString(value, "print_file_and_line"))
     1236        {
     1237            PyObject *message;
     1238            const char *filename, *text;
     1239            int lineno, offset;
     1240            if (!parse_syntax_error(value, &message, &filename,
     1241                                    &lineno, &offset, &text))
     1242                PyErr_Clear();
     1243            else {
     1244                char buf[10];
     1245                PyFile_WriteString("  File \"", f);
     1246                if (filename == NULL)
     1247                    PyFile_WriteString("<string>", f);
     1248                else
     1249                    PyFile_WriteString(filename, f);
     1250                PyFile_WriteString("\", line ", f);
     1251                PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
     1252                PyFile_WriteString(buf, f);
     1253                PyFile_WriteString("\n", f);
     1254                if (text != NULL)
     1255                    print_error_text(f, offset, text);
     1256                Py_DECREF(value);
     1257                value = message;
     1258                /* Can't be bothered to check all those
     1259                   PyFile_WriteString() calls */
     1260                if (PyErr_Occurred())
     1261                    err = -1;
     1262            }
     1263        }
     1264        if (err) {
     1265            /* Don't do anything else */
     1266        }
     1267        else if (PyExceptionClass_Check(exception)) {
     1268            PyObject* moduleName;
     1269            char* className = PyExceptionClass_Name(exception);
     1270            if (className != NULL) {
     1271                char *dot = strrchr(className, '.');
     1272                if (dot != NULL)
     1273                    className = dot+1;
     1274            }
     1275
     1276            moduleName = PyObject_GetAttrString(exception, "__module__");
     1277            if (moduleName == NULL)
     1278                err = PyFile_WriteString("<unknown>", f);
     1279            else {
     1280                char* modstr = PyString_AsString(moduleName);
     1281                if (modstr && strcmp(modstr, "exceptions"))
     1282                {
     1283                    err = PyFile_WriteString(modstr, f);
     1284                    err += PyFile_WriteString(".", f);
     1285                }
     1286                Py_DECREF(moduleName);
     1287            }
     1288            if (err == 0) {
     1289                if (className == NULL)
     1290                      err = PyFile_WriteString("<unknown>", f);
     1291                else
     1292                      err = PyFile_WriteString(className, f);
     1293            }
     1294        }
     1295        else
     1296            err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
     1297        if (err == 0 && (value != Py_None)) {
     1298            PyObject *s = PyObject_Str(value);
     1299            /* only print colon if the str() of the
     1300               object is not the empty string
     1301            */
     1302            if (s == NULL)
     1303                err = -1;
     1304            else if (!PyString_Check(s) ||
     1305                    PyString_GET_SIZE(s) != 0)
     1306                err = PyFile_WriteString(": ", f);
     1307            if (err == 0)
     1308              err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
     1309            Py_XDECREF(s);
     1310        }
     1311        /* try to write a newline in any case */
     1312        err += PyFile_WriteString("\n", f);
     1313    }
     1314    Py_DECREF(value);
     1315    /* If an error happened here, don't show it.
     1316       XXX This is wrong, but too many callers rely on this behavior. */
     1317    if (err != 0)
     1318        PyErr_Clear();
    12881319}
    12891320
    12901321PyObject *
    12911322PyRun_StringFlags(const char *str, int start, PyObject *globals,
    1292                   PyObject *locals, PyCompilerFlags *flags)
    1293 {
    1294         PyObject *ret = NULL;
    1295         mod_ty mod;
    1296         PyArena *arena = PyArena_New();
    1297         if (arena == NULL)
    1298                 return NULL;
    1299        
    1300         mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
    1301         if (mod != NULL)
    1302                 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
    1303         PyArena_Free(arena);
    1304         return ret;
     1323                  PyObject *locals, PyCompilerFlags *flags)
     1324{
     1325    PyObject *ret = NULL;
     1326    mod_ty mod;
     1327    PyArena *arena = PyArena_New();
     1328    if (arena == NULL)
     1329        return NULL;
     1330
     1331    mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
     1332    if (mod != NULL)
     1333        ret = run_mod(mod, "<string>", globals, locals, flags, arena);
     1334    PyArena_Free(arena);
     1335    return ret;
    13051336}
    13061337
    13071338PyObject *
    13081339PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
    1309                   PyObject *locals, int closeit, PyCompilerFlags *flags)
    1310 {
    1311         PyObject *ret;
    1312         mod_ty mod;
    1313         PyArena *arena = PyArena_New();
    1314         if (arena == NULL)
    1315                 return NULL;
    1316        
    1317         mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
    1318                                    flags, NULL, arena);
    1319         if (closeit)
    1320                 fclose(fp);
    1321         if (mod == NULL) {
    1322                 PyArena_Free(arena);
    1323                 return NULL;
    1324         }
    1325         ret = run_mod(mod, filename, globals, locals, flags, arena);
    1326         PyArena_Free(arena);
    1327         return ret;
     1340                  PyObject *locals, int closeit, PyCompilerFlags *flags)
     1341{
     1342    PyObject *ret;
     1343    mod_ty mod;
     1344    PyArena *arena = PyArena_New();
     1345    if (arena == NULL)
     1346        return NULL;
     1347
     1348    mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
     1349                               flags, NULL, arena);
     1350    if (closeit)
     1351        fclose(fp);
     1352    if (mod == NULL) {
     1353        PyArena_Free(arena);
     1354        return NULL;
     1355    }
     1356    ret = run_mod(mod, filename, globals, locals, flags, arena);
     1357    PyArena_Free(arena);
     1358    return ret;
    13281359}
    13291360
    13301361static PyObject *
    13311362run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
    1332         PyCompilerFlags *flags, PyArena *arena)
    1333 {
    1334         PyCodeObject *co;
    1335         PyObject *v;
    1336         co = PyAST_Compile(mod, filename, flags, arena);
    1337         if (co == NULL)
    1338                 return NULL;
    1339         v = PyEval_EvalCode(co, globals, locals);
    1340         Py_DECREF(co);
    1341         return v;
     1363        PyCompilerFlags *flags, PyArena *arena)
     1364{
     1365    PyCodeObject *co;
     1366    PyObject *v;
     1367    co = PyAST_Compile(mod, filename, flags, arena);
     1368    if (co == NULL)
     1369        return NULL;
     1370    v = PyEval_EvalCode(co, globals, locals);
     1371    Py_DECREF(co);
     1372    return v;
    13421373}
    13431374
    13441375static PyObject *
    13451376run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
    1346              PyObject *locals, PyCompilerFlags *flags)
    1347 {
    1348         PyCodeObject *co;
    1349         PyObject *v;
    1350         long magic;
    1351         long PyImport_GetMagicNumber(void);
    1352 
    1353         magic = PyMarshal_ReadLongFromFile(fp);
    1354         if (magic != PyImport_GetMagicNumber()) {
    1355                 PyErr_SetString(PyExc_RuntimeError,
    1356                            "Bad magic number in .pyc file");
    1357                 return NULL;
    1358         }
    1359         (void) PyMarshal_ReadLongFromFile(fp);
    1360         v = PyMarshal_ReadLastObjectFromFile(fp);
    1361         fclose(fp);
    1362         if (v == NULL || !PyCode_Check(v)) {
    1363                 Py_XDECREF(v);
    1364                 PyErr_SetString(PyExc_RuntimeError,
    1365                            "Bad code object in .pyc file");
    1366                 return NULL;
    1367         }
    1368         co = (PyCodeObject *)v;
    1369         v = PyEval_EvalCode(co, globals, locals);
    1370         if (v && flags)
    1371                 flags->cf_flags |= (co->co_flags & PyCF_MASK);
    1372         Py_DECREF(co);
    1373         return v;
     1377             PyObject *locals, PyCompilerFlags *flags)
     1378{
     1379    PyCodeObject *co;
     1380    PyObject *v;
     1381    long magic;
     1382    long PyImport_GetMagicNumber(void);
     1383
     1384    magic = PyMarshal_ReadLongFromFile(fp);
     1385    if (magic != PyImport_GetMagicNumber()) {
     1386        PyErr_SetString(PyExc_RuntimeError,
     1387                   "Bad magic number in .pyc file");
     1388        return NULL;
     1389    }
     1390    (void) PyMarshal_ReadLongFromFile(fp);
     1391    v = PyMarshal_ReadLastObjectFromFile(fp);
     1392    fclose(fp);
     1393    if (v == NULL || !PyCode_Check(v)) {
     1394        Py_XDECREF(v);
     1395        PyErr_SetString(PyExc_RuntimeError,
     1396                   "Bad code object in .pyc file");
     1397        return NULL;
     1398    }
     1399    co = (PyCodeObject *)v;
     1400    v = PyEval_EvalCode(co, globals, locals);
     1401    if (v && flags)
     1402        flags->cf_flags |= (co->co_flags & PyCF_MASK);
     1403    Py_DECREF(co);
     1404    return v;
    13741405}
    13751406
    13761407PyObject *
    13771408Py_CompileStringFlags(const char *str, const char *filename, int start,
    1378                       PyCompilerFlags *flags)
    1379 {
    1380         PyCodeObject *co;
    1381         mod_ty mod;
    1382         PyArena *arena = PyArena_New();
    1383         if (arena == NULL)
    1384                 return NULL;
    1385 
    1386         mod = PyParser_ASTFromString(str, filename, start, flags, arena);
    1387         if (mod == NULL) {
    1388                 PyArena_Free(arena);
    1389                 return NULL;
    1390         }
    1391         if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
    1392                 PyObject *result = PyAST_mod2obj(mod);
    1393                 PyArena_Free(arena);
    1394                 return result;
    1395         }
    1396         co = PyAST_Compile(mod, filename, flags, arena);
    1397         PyArena_Free(arena);
    1398         return (PyObject *)co;
     1409                      PyCompilerFlags *flags)
     1410{
     1411    PyCodeObject *co;
     1412    mod_ty mod;
     1413    PyArena *arena = PyArena_New();
     1414    if (arena == NULL)
     1415        return NULL;
     1416
     1417    mod = PyParser_ASTFromString(str, filename, start, flags, arena);
     1418    if (mod == NULL) {
     1419        PyArena_Free(arena);
     1420        return NULL;
     1421    }
     1422    if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
     1423        PyObject *result = PyAST_mod2obj(mod);
     1424        PyArena_Free(arena);
     1425        return result;
     1426    }
     1427    co = PyAST_Compile(mod, filename, flags, arena);
     1428    PyArena_Free(arena);
     1429    return (PyObject *)co;
    13991430}
    14001431
     
    14021433Py_SymtableString(const char *str, const char *filename, int start)
    14031434{
    1404         struct symtable *st;
    1405         mod_ty mod;
    1406         PyCompilerFlags flags;
    1407         PyArena *arena = PyArena_New();
    1408         if (arena == NULL)
    1409                 return NULL;
    1410 
    1411         flags.cf_flags = 0;
    1412 
    1413         mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
    1414         if (mod == NULL) {
    1415                 PyArena_Free(arena);
    1416                 return NULL;
    1417         }
    1418         st = PySymtable_Build(mod, filename, 0);
    1419         PyArena_Free(arena);
    1420         return st;
     1435    struct symtable *st;
     1436    mod_ty mod;
     1437    PyCompilerFlags flags;
     1438    PyArena *arena = PyArena_New();
     1439    if (arena == NULL)
     1440        return NULL;
     1441
     1442    flags.cf_flags = 0;
     1443
     1444    mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
     1445    if (mod == NULL) {
     1446        PyArena_Free(arena);
     1447        return NULL;
     1448    }
     1449    st = PySymtable_Build(mod, filename, 0);
     1450    PyArena_Free(arena);
     1451    return st;
    14211452}
    14221453
     
    14241455mod_ty
    14251456PyParser_ASTFromString(const char *s, const char *filename, int start,
    1426                        PyCompilerFlags *flags, PyArena *arena)
    1427 {
    1428         mod_ty mod;
    1429         PyCompilerFlags localflags;
    1430         perrdetail err;
    1431         int iflags = PARSER_FLAGS(flags);
    1432 
    1433         node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
    1434                                         &_PyParser_Grammar, start, &err,
    1435                                         &iflags);
    1436         if (flags == NULL) {
    1437                 localflags.cf_flags = 0;
    1438                 flags = &localflags;
    1439         }
    1440         if (n) {
    1441                 flags->cf_flags |= iflags & PyCF_MASK;
    1442                 mod = PyAST_FromNode(n, flags, filename, arena);
    1443                 PyNode_Free(n);
    1444                 return mod;
    1445         }
    1446         else {
    1447                 err_input(&err);
    1448                 return NULL;
    1449         }
     1457                       PyCompilerFlags *flags, PyArena *arena)
     1458{
     1459    mod_ty mod;
     1460    PyCompilerFlags localflags;
     1461    perrdetail err;
     1462    int iflags = PARSER_FLAGS(flags);
     1463
     1464    node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
     1465                                    &_PyParser_Grammar, start, &err,
     1466                                    &iflags);
     1467    if (flags == NULL) {
     1468        localflags.cf_flags = 0;
     1469        flags = &localflags;
     1470    }
     1471    if (n) {
     1472        flags->cf_flags |= iflags & PyCF_MASK;
     1473        mod = PyAST_FromNode(n, flags, filename, arena);
     1474        PyNode_Free(n);
     1475        return mod;
     1476    }
     1477    else {
     1478        err_input(&err);
     1479        return NULL;
     1480    }
    14501481}
    14511482
    14521483mod_ty
    14531484PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
    1454                      char *ps2, PyCompilerFlags *flags, int *errcode,
    1455                      PyArena *arena)
    1456 {
    1457         mod_ty mod;
    1458         PyCompilerFlags localflags;
    1459         perrdetail err;
    1460         int iflags = PARSER_FLAGS(flags);
    1461 
    1462         node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
    1463                                 start, ps1, ps2, &err, &iflags);
    1464         if (flags == NULL) {
    1465                 localflags.cf_flags = 0;
    1466                 flags = &localflags;
    1467         }
    1468         if (n) {
    1469                 flags->cf_flags |= iflags & PyCF_MASK;
    1470                 mod = PyAST_FromNode(n, flags, filename, arena);
    1471                 PyNode_Free(n);
    1472                 return mod;
    1473         }
    1474         else {
    1475                 err_input(&err);
    1476                 if (errcode)
    1477                         *errcode = err.error;
    1478                 return NULL;
    1479         }
     1485                     char *ps2, PyCompilerFlags *flags, int *errcode,
     1486                     PyArena *arena)
     1487{
     1488    mod_ty mod;
     1489    PyCompilerFlags localflags;
     1490    perrdetail err;
     1491    int iflags = PARSER_FLAGS(flags);
     1492
     1493    node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
     1494                            start, ps1, ps2, &err, &iflags);
     1495    if (flags == NULL) {
     1496        localflags.cf_flags = 0;
     1497        flags = &localflags;
     1498    }
     1499    if (n) {
     1500        flags->cf_flags |= iflags & PyCF_MASK;
     1501        mod = PyAST_FromNode(n, flags, filename, arena);
     1502        PyNode_Free(n);
     1503        return mod;
     1504    }
     1505    else {
     1506        err_input(&err);
     1507        if (errcode)
     1508            *errcode = err.error;
     1509        return NULL;
     1510    }
    14801511}
    14811512
     
    14851516PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
    14861517{
    1487         perrdetail err;
    1488         node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
    1489                                           start, NULL, NULL, &err, flags);
    1490         if (n == NULL)
    1491                 err_input(&err);
    1492 
    1493         return n;
     1518    perrdetail err;
     1519    node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
     1520                                      start, NULL, NULL, &err, flags);
     1521    if (n == NULL)
     1522        err_input(&err);
     1523
     1524    return n;
    14941525}
    14951526
     
    14991530PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
    15001531{
    1501         perrdetail err;
    1502         node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
    1503                                             start, &err, flags);
    1504         if (n == NULL)
    1505                 err_input(&err);
    1506         return n;
     1532    perrdetail err;
     1533    node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
     1534                                        start, &err, flags);
     1535    if (n == NULL)
     1536        err_input(&err);
     1537    return n;
    15071538}
    15081539
    15091540node *
    15101541PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
    1511                                         int start, int flags)
    1512 {
    1513         perrdetail err;
    1514         node *n = PyParser_ParseStringFlagsFilename(str, filename,
    1515                                 &_PyParser_Grammar, start, &err, flags);
    1516         if (n == NULL)
    1517                 err_input(&err);
    1518         return n;
     1542                                        int start, int flags)
     1543{
     1544    perrdetail err;
     1545    node *n = PyParser_ParseStringFlagsFilename(str, filename,
     1546                            &_PyParser_Grammar, start, &err, flags);
     1547    if (n == NULL)
     1548        err_input(&err);
     1549    return n;
    15191550}
    15201551
     
    15221553PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
    15231554{
    1524         return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
     1555    return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
    15251556}
    15261557
     
    15311562PyParser_SetError(perrdetail *err)
    15321563{
    1533         err_input(err);
     1564    err_input(err);
    15341565}
    15351566
     
    15391570err_input(perrdetail *err)
    15401571{
    1541         PyObject *v, *w, *errtype;
    1542         PyObject* u = NULL;
    1543         char *msg = NULL;
    1544         errtype = PyExc_SyntaxError;
    1545         switch (err->error) {
    1546         case E_SYNTAX:
    1547                 errtype = PyExc_IndentationError;
    1548                 if (err->expected == INDENT)
    1549                         msg = "expected an indented block";
    1550                 else if (err->token == INDENT)
    1551                         msg = "unexpected indent";
    1552                 else if (err->token == DEDENT)
    1553                         msg = "unexpected unindent";
    1554                 else {
    1555                         errtype = PyExc_SyntaxError;
    1556                         msg = "invalid syntax";
    1557                 }
    1558                 break;
    1559         case E_TOKEN:
    1560                 msg = "invalid token";
    1561                 break;
    1562         case E_EOFS:
    1563                 msg = "EOF while scanning triple-quoted string literal";
    1564                 break;
    1565         case E_EOLS:
    1566                 msg = "EOL while scanning string literal";
    1567                 break;
    1568         case E_INTR:
    1569                 if (!PyErr_Occurred())
    1570                         PyErr_SetNone(PyExc_KeyboardInterrupt);
    1571                 goto cleanup;
    1572         case E_NOMEM:
    1573                 PyErr_NoMemory();
    1574                 goto cleanup;
    1575         case E_EOF:
    1576                 msg = "unexpected EOF while parsing";
    1577                 break;
    1578         case E_TABSPACE:
    1579                 errtype = PyExc_TabError;
    1580                 msg = "inconsistent use of tabs and spaces in indentation";
    1581                 break;
    1582         case E_OVERFLOW:
    1583                 msg = "expression too long";
    1584                 break;
    1585         case E_DEDENT:
    1586                 errtype = PyExc_IndentationError;
    1587                 msg = "unindent does not match any outer indentation level";
    1588                 break;
    1589         case E_TOODEEP:
    1590                 errtype = PyExc_IndentationError;
    1591                 msg = "too many levels of indentation";
    1592                 break;
    1593         case E_DECODE: {
    1594                 PyObject *type, *value, *tb;
    1595                 PyErr_Fetch(&type, &value, &tb);
    1596                 if (value != NULL) {
    1597                         u = PyObject_Str(value);
    1598                         if (u != NULL) {
    1599                                 msg = PyString_AsString(u);
    1600                         }
    1601                 }
    1602                 if (msg == NULL)
    1603                         msg = "unknown decode error";
    1604                 Py_XDECREF(type);
    1605                 Py_XDECREF(value);
    1606                 Py_XDECREF(tb);
    1607                 break;
    1608         }
    1609         case E_LINECONT:
    1610                 msg = "unexpected character after line continuation character";
    1611                 break;
    1612         default:
    1613                 fprintf(stderr, "error=%d\n", err->error);
    1614                 msg = "unknown parsing error";
    1615                 break;
    1616         }
    1617         v = Py_BuildValue("(ziiz)", err->filename,
    1618                           err->lineno, err->offset, err->text);
    1619         w = NULL;
    1620         if (v != NULL)
    1621                 w = Py_BuildValue("(sO)", msg, v);
    1622         Py_XDECREF(u);
    1623         Py_XDECREF(v);
    1624         PyErr_SetObject(errtype, w);
    1625         Py_XDECREF(w);
     1572    PyObject *v, *w, *errtype;
     1573    PyObject* u = NULL;
     1574    char *msg = NULL;
     1575    errtype = PyExc_SyntaxError;
     1576    switch (err->error) {
     1577    case E_ERROR:
     1578        return;
     1579    case E_SYNTAX:
     1580        errtype = PyExc_IndentationError;
     1581        if (err->expected == INDENT)
     1582            msg = "expected an indented block";
     1583        else if (err->token == INDENT)
     1584            msg = "unexpected indent";
     1585        else if (err->token == DEDENT)
     1586            msg = "unexpected unindent";
     1587        else {
     1588            errtype = PyExc_SyntaxError;
     1589            msg = "invalid syntax";
     1590        }
     1591        break;
     1592    case E_TOKEN:
     1593        msg = "invalid token";
     1594        break;
     1595    case E_EOFS:
     1596        msg = "EOF while scanning triple-quoted string literal";
     1597        break;
     1598    case E_EOLS:
     1599        msg = "EOL while scanning string literal";
     1600        break;
     1601    case E_INTR:
     1602        if (!PyErr_Occurred())
     1603            PyErr_SetNone(PyExc_KeyboardInterrupt);
     1604        goto cleanup;
     1605    case E_NOMEM:
     1606        PyErr_NoMemory();
     1607        goto cleanup;
     1608    case E_EOF:
     1609        msg = "unexpected EOF while parsing";
     1610        break;
     1611    case E_TABSPACE:
     1612        errtype = PyExc_TabError;
     1613        msg = "inconsistent use of tabs and spaces in indentation";
     1614        break;
     1615    case E_OVERFLOW:
     1616        msg = "expression too long";
     1617        break;
     1618    case E_DEDENT:
     1619        errtype = PyExc_IndentationError;
     1620        msg = "unindent does not match any outer indentation level";
     1621        break;
     1622    case E_TOODEEP:
     1623        errtype = PyExc_IndentationError;
     1624        msg = "too many levels of indentation";
     1625        break;
     1626    case E_DECODE: {
     1627        PyObject *type, *value, *tb;
     1628        PyErr_Fetch(&type, &value, &tb);
     1629        if (value != NULL) {
     1630            u = PyObject_Str(value);
     1631            if (u != NULL) {
     1632                msg = PyString_AsString(u);
     1633            }
     1634        }
     1635        if (msg == NULL)
     1636            msg = "unknown decode error";
     1637        Py_XDECREF(type);
     1638        Py_XDECREF(value);
     1639        Py_XDECREF(tb);
     1640        break;
     1641    }
     1642    case E_LINECONT:
     1643        msg = "unexpected character after line continuation character";
     1644        break;
     1645    default:
     1646        fprintf(stderr, "error=%d\n", err->error);
     1647        msg = "unknown parsing error";
     1648        break;
     1649    }
     1650    v = Py_BuildValue("(ziiz)", err->filename,
     1651                      err->lineno, err->offset, err->text);
     1652    w = NULL;
     1653    if (v != NULL)
     1654        w = Py_BuildValue("(sO)", msg, v);
     1655    Py_XDECREF(u);
     1656    Py_XDECREF(v);
     1657    PyErr_SetObject(errtype, w);
     1658    Py_XDECREF(w);
    16261659cleanup:
    1627         if (err->text != NULL) {
    1628                 PyObject_FREE(err->text);
    1629                 err->text = NULL;
    1630         }
     1660    if (err->text != NULL) {
     1661        PyObject_FREE(err->text);
     1662        err->text = NULL;
     1663    }
    16311664}
    16321665
     
    16361669Py_FatalError(const char *msg)
    16371670{
    1638         fprintf(stderr, "Fatal Python error: %s\n", msg);
    1639         fflush(stderr); /* it helps in Windows debug build */
     1671    fprintf(stderr, "Fatal Python error: %s\n", msg);
     1672    fflush(stderr); /* it helps in Windows debug build */
    16401673
    16411674#ifdef MS_WINDOWS
    1642         {
    1643                 size_t len = strlen(msg);
    1644                 WCHAR* buffer;
    1645                 size_t i;
    1646 
    1647                 /* Convert the message to wchar_t. This uses a simple one-to-one
    1648                 conversion, assuming that the this error message actually uses ASCII
    1649                 only. If this ceases to be true, we will have to convert. */
    1650                 buffer = alloca( (len+1) * (sizeof *buffer));
    1651                 for( i=0; i<=len; ++i)
    1652                         buffer[i] = msg[i];
    1653                 OutputDebugStringW(L"Fatal Python error: ");
    1654                 OutputDebugStringW(buffer);
    1655                 OutputDebugStringW(L"\n");
    1656         }
     1675    {
     1676        size_t len = strlen(msg);
     1677        WCHAR* buffer;
     1678        size_t i;
     1679
     1680        /* Convert the message to wchar_t. This uses a simple one-to-one
     1681        conversion, assuming that the this error message actually uses ASCII
     1682        only. If this ceases to be true, we will have to convert. */
     1683        buffer = alloca( (len+1) * (sizeof *buffer));
     1684        for( i=0; i<=len; ++i)
     1685            buffer[i] = msg[i];
     1686        OutputDebugStringW(L"Fatal Python error: ");
     1687        OutputDebugStringW(buffer);
     1688        OutputDebugStringW(L"\n");
     1689    }
    16571690#ifdef _DEBUG
    1658         DebugBreak();
     1691    DebugBreak();
    16591692#endif
    16601693#endif /* MS_WINDOWS */
    1661         abort();
     1694    abort();
    16621695}
    16631696
     
    16761709{
    16771710#ifdef WITH_THREAD
    1678         PyObject *result;
    1679         PyThreadState *tstate = PyThreadState_GET();
    1680         PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
    1681                                                       "threading");
    1682         if (threading == NULL) {
    1683                 /* threading not imported */
    1684                 PyErr_Clear();
    1685                 return;
    1686         }
    1687         result = PyObject_CallMethod(threading, "_shutdown", "");
    1688         if (result == NULL)
    1689                 PyErr_WriteUnraisable(threading);
    1690         else
    1691                 Py_DECREF(result);
    1692         Py_DECREF(threading);
     1711    PyObject *result;
     1712    PyThreadState *tstate = PyThreadState_GET();
     1713    PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
     1714                                                  "threading");
     1715    if (threading == NULL) {
     1716        /* threading not imported */
     1717        PyErr_Clear();
     1718        return;
     1719    }
     1720    result = PyObject_CallMethod(threading, "_shutdown", "");
     1721    if (result == NULL)
     1722        PyErr_WriteUnraisable(threading);
     1723    else
     1724        Py_DECREF(result);
     1725    Py_DECREF(threading);
    16931726#endif
    16941727}
     
    17001733int Py_AtExit(void (*func)(void))
    17011734{
    1702         if (nexitfuncs >= NEXITFUNCS)
    1703                 return -1;
    1704         exitfuncs[nexitfuncs++] = func;
    1705         return 0;
     1735    if (nexitfuncs >= NEXITFUNCS)
     1736        return -1;
     1737    exitfuncs[nexitfuncs++] = func;
     1738    return 0;
    17061739}
    17071740
     
    17091742call_sys_exitfunc(void)
    17101743{
    1711         PyObject *exitfunc = PySys_GetObject("exitfunc");
    1712 
    1713         if (exitfunc) {
    1714                 PyObject *res;
    1715                 Py_INCREF(exitfunc);
    1716                 PySys_SetObject("exitfunc", (PyObject *)NULL);
    1717                 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
    1718                 if (res == NULL) {
    1719                         if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
    1720                                 PySys_WriteStderr("Error in sys.exitfunc:\n");
    1721                         }
    1722                         PyErr_Print();
    1723                 }
    1724                 Py_DECREF(exitfunc);
    1725         }
    1726 
    1727         if (Py_FlushLine())
    1728                 PyErr_Clear();
     1744    PyObject *exitfunc = PySys_GetObject("exitfunc");
     1745
     1746    if (exitfunc) {
     1747        PyObject *res;
     1748        Py_INCREF(exitfunc);
     1749        PySys_SetObject("exitfunc", (PyObject *)NULL);
     1750        res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
     1751        if (res == NULL) {
     1752            if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
     1753                PySys_WriteStderr("Error in sys.exitfunc:\n");
     1754            }
     1755            PyErr_Print();
     1756        }
     1757        Py_DECREF(exitfunc);
     1758    }
     1759
     1760    if (Py_FlushLine())
     1761        PyErr_Clear();
    17291762}
    17301763
     
    17321765call_ll_exitfuncs(void)
    17331766{
    1734         while (nexitfuncs > 0)
    1735                 (*exitfuncs[--nexitfuncs])();
    1736 
    1737         fflush(stdout);
    1738         fflush(stderr);
     1767    while (nexitfuncs > 0)
     1768        (*exitfuncs[--nexitfuncs])();
     1769
     1770    fflush(stdout);
     1771    fflush(stderr);
    17391772}
    17401773
     
    17421775Py_Exit(int sts)
    17431776{
    1744         Py_Finalize();
    1745 
    1746         exit(sts);
     1777    Py_Finalize();
     1778
     1779    exit(sts);
    17471780}
    17481781
     
    17511784{
    17521785#ifdef SIGPIPE
    1753         PyOS_setsig(SIGPIPE, SIG_IGN);
     1786    PyOS_setsig(SIGPIPE, SIG_IGN);
    17541787#endif
    17551788#ifdef SIGXFZ
    1756         PyOS_setsig(SIGXFZ, SIG_IGN);
     1789    PyOS_setsig(SIGXFZ, SIG_IGN);
    17571790#endif
    17581791#ifdef SIGXFSZ
    1759         PyOS_setsig(SIGXFSZ, SIG_IGN);
    1760 #endif
    1761         PyOS_InitInterrupts(); /* May imply initsignal() */
     1792    PyOS_setsig(SIGXFSZ, SIG_IGN);
     1793#endif
     1794    PyOS_InitInterrupts(); /* May imply initsignal() */
    17621795}
    17631796
     
    17721805Py_FdIsInteractive(FILE *fp, const char *filename)
    17731806{
    1774         if (isatty((int)fileno(fp)))
    1775                 return 1;
    1776         if (!Py_InteractiveFlag)
    1777                 return 0;
    1778         return (filename == NULL) ||
    1779                (strcmp(filename, "<stdin>") == 0) ||
    1780                (strcmp(filename, "???") == 0);
     1807    if (isatty((int)fileno(fp)))
     1808        return 1;
     1809    if (!Py_InteractiveFlag)
     1810        return 0;
     1811    return (filename == NULL) ||
     1812           (strcmp(filename, "<stdin>") == 0) ||
     1813           (strcmp(filename, "???") == 0);
    17811814}
    17821815
     
    17961829PyOS_CheckStack(void)
    17971830{
    1798         __try {
    1799                 /* alloca throws a stack overflow exception if there's
    1800                    not enough space left on the stack */
    1801                 alloca(PYOS_STACK_MARGIN * sizeof(void*));
    1802                 return 0;
    1803         } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
    1804                         EXCEPTION_EXECUTE_HANDLER :
    1805                         EXCEPTION_CONTINUE_SEARCH) {
    1806                 int errcode = _resetstkoflw();
    1807                 if (errcode == 0)
    1808                 {
    1809                         Py_FatalError("Could not reset the stack!");
    1810                 }
    1811         }
    1812         return 1;
     1831    __try {
     1832        /* alloca throws a stack overflow exception if there's
     1833           not enough space left on the stack */
     1834        alloca(PYOS_STACK_MARGIN * sizeof(void*));
     1835        return 0;
     1836    } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
     1837                    EXCEPTION_EXECUTE_HANDLER :
     1838            EXCEPTION_CONTINUE_SEARCH) {
     1839        int errcode = _resetstkoflw();
     1840        if (errcode == 0)
     1841        {
     1842            Py_FatalError("Could not reset the stack!");
     1843        }
     1844    }
     1845    return 1;
    18131846}
    18141847
     
    18261859{
    18271860#ifdef HAVE_SIGACTION
    1828         struct sigaction context;
    1829         if (sigaction(sig, NULL, &context) == -1)
    1830                 return SIG_ERR;
    1831         return context.sa_handler;
     1861    struct sigaction context;
     1862    if (sigaction(sig, NULL, &context) == -1)
     1863        return SIG_ERR;
     1864    return context.sa_handler;
    18321865#else
    1833         PyOS_sighandler_t handler;
     1866    PyOS_sighandler_t handler;
    18341867/* Special signal handling for the secure CRT in Visual Studio 2005 */
    18351868#if defined(_MSC_VER) && _MSC_VER >= 1400
    1836         switch (sig) {
    1837         /* Only these signals are valid */
    1838         case SIGINT:
    1839         case SIGILL:
    1840         case SIGFPE:
    1841         case SIGSEGV:
    1842         case SIGTERM:
    1843         case SIGBREAK:
    1844         case SIGABRT:
    1845                 break;
    1846         /* Don't call signal() with other values or it will assert */
    1847         default:
    1848                 return SIG_ERR;
    1849         }
     1869    switch (sig) {
     1870    /* Only these signals are valid */
     1871    case SIGINT:
     1872    case SIGILL:
     1873    case SIGFPE:
     1874    case SIGSEGV:
     1875    case SIGTERM:
     1876    case SIGBREAK:
     1877    case SIGABRT:
     1878        break;
     1879    /* Don't call signal() with other values or it will assert */
     1880    default:
     1881        return SIG_ERR;
     1882    }
    18501883#endif /* _MSC_VER && _MSC_VER >= 1400 */
    1851         handler = signal(sig, SIG_IGN);
    1852         if (handler != SIG_ERR)
    1853                 signal(sig, handler);
    1854         return handler;
     1884    handler = signal(sig, SIG_IGN);
     1885    if (handler != SIG_ERR)
     1886        signal(sig, handler);
     1887    return handler;
    18551888#endif
    18561889}
     
    18601893{
    18611894#ifdef HAVE_SIGACTION
    1862         struct sigaction context, ocontext;
    1863         context.sa_handler = handler;
    1864         sigemptyset(&context.sa_mask);
    1865         context.sa_flags = 0;
    1866         if (sigaction(sig, &context, &ocontext) == -1)
    1867                 return SIG_ERR;
    1868         return ocontext.sa_handler;
     1895    /* Some code in Modules/signalmodule.c depends on sigaction() being
     1896     * used here if HAVE_SIGACTION is defined.  Fix that if this code
     1897     * changes to invalidate that assumption.
     1898     */
     1899    struct sigaction context, ocontext;
     1900    context.sa_handler = handler;
     1901    sigemptyset(&context.sa_mask);
     1902    context.sa_flags = 0;
     1903    if (sigaction(sig, &context, &ocontext) == -1)
     1904        return SIG_ERR;
     1905    return ocontext.sa_handler;
    18691906#else
    1870         PyOS_sighandler_t oldhandler;
    1871         oldhandler = signal(sig, handler);
     1907    PyOS_sighandler_t oldhandler;
     1908    oldhandler = signal(sig, handler);
    18721909#ifdef HAVE_SIGINTERRUPT
    1873         siginterrupt(sig, 1);
    1874 #endif
    1875         return oldhandler;
     1910    siginterrupt(sig, 1);
     1911#endif
     1912    return oldhandler;
    18761913#endif
    18771914}
     
    18831920PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
    18841921{
    1885         return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
     1922    return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
    18861923}
    18871924
     
    18901927PyParser_SimpleParseString(const char *str, int start)
    18911928{
    1892         return PyParser_SimpleParseStringFlags(str, start, 0);
     1929    return PyParser_SimpleParseStringFlags(str, start, 0);
    18931930}
    18941931
     
    18971934PyRun_AnyFile(FILE *fp, const char *name)
    18981935{
    1899         return PyRun_AnyFileExFlags(fp, name, 0, NULL);
     1936    return PyRun_AnyFileExFlags(fp, name, 0, NULL);
    19001937}
    19011938
     
    19041941PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
    19051942{
    1906         return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
     1943    return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
    19071944}
    19081945
     
    19111948PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
    19121949{
    1913         return PyRun_AnyFileExFlags(fp, name, 0, flags);
     1950    return PyRun_AnyFileExFlags(fp, name, 0, flags);
    19141951}
    19151952
     
    19181955PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
    19191956{
    1920         return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
     1957    return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
    19211958}
    19221959
     
    19251962PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
    19261963{
    1927         return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
     1964    return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
    19281965}
    19291966
     
    19311968PyAPI_FUNC(PyObject *)
    19321969PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
    1933                 PyCompilerFlags *flags)
    1934 {
    1935         return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
     1970                PyCompilerFlags *flags)
     1971{
     1972    return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
    19361973}
    19371974
     
    19401977PyRun_SimpleFile(FILE *f, const char *p)
    19411978{
    1942         return PyRun_SimpleFileExFlags(f, p, 0, NULL);
     1979    return PyRun_SimpleFileExFlags(f, p, 0, NULL);
    19431980}
    19441981
     
    19471984PyRun_SimpleFileEx(FILE *f, const char *p, int c)
    19481985{
    1949         return PyRun_SimpleFileExFlags(f, p, c, NULL);
     1986    return PyRun_SimpleFileExFlags(f, p, c, NULL);
    19501987}
    19511988
     
    19551992PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
    19561993{
    1957         return PyRun_StringFlags(str, s, g, l, NULL);
     1994    return PyRun_StringFlags(str, s, g, l, NULL);
    19581995}
    19591996
     
    19621999PyRun_SimpleString(const char *s)
    19632000{
    1964         return PyRun_SimpleStringFlags(s, NULL);
     2001    return PyRun_SimpleStringFlags(s, NULL);
    19652002}
    19662003
     
    19692006Py_CompileString(const char *str, const char *p, int s)
    19702007{
    1971         return Py_CompileStringFlags(str, p, s, NULL);
     2008    return Py_CompileStringFlags(str, p, s, NULL);
    19722009}
    19732010
     
    19762013PyRun_InteractiveOne(FILE *f, const char *p)
    19772014{
    1978         return PyRun_InteractiveOneFlags(f, p, NULL);
     2015    return PyRun_InteractiveOneFlags(f, p, NULL);
    19792016}
    19802017
     
    19832020PyRun_InteractiveLoop(FILE *f, const char *p)
    19842021{
    1985         return PyRun_InteractiveLoopFlags(f, p, NULL);
     2022    return PyRun_InteractiveLoopFlags(f, p, NULL);
    19862023}
    19872024
Note: See TracChangeset for help on using the changeset viewer.