Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Python/errors.c

    r2 r391  
    2525PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
    2626{
    27         PyThreadState *tstate = PyThreadState_GET();
    28         PyObject *oldtype, *oldvalue, *oldtraceback;
    29 
    30         if (traceback != NULL && !PyTraceBack_Check(traceback)) {
    31                 /* XXX Should never happen -- fatal error instead? */
    32                 /* Well, it could be None. */
    33                 Py_DECREF(traceback);
    34                 traceback = NULL;
    35         }
    36 
    37         /* Save these in locals to safeguard against recursive
    38            invocation through Py_XDECREF */
    39         oldtype = tstate->curexc_type;
    40         oldvalue = tstate->curexc_value;
    41         oldtraceback = tstate->curexc_traceback;
    42 
    43         tstate->curexc_type = type;
    44         tstate->curexc_value = value;
    45         tstate->curexc_traceback = traceback;
    46 
    47         Py_XDECREF(oldtype);
    48         Py_XDECREF(oldvalue);
    49         Py_XDECREF(oldtraceback);
     27    PyThreadState *tstate = PyThreadState_GET();
     28    PyObject *oldtype, *oldvalue, *oldtraceback;
     29
     30    if (traceback != NULL && !PyTraceBack_Check(traceback)) {
     31        /* XXX Should never happen -- fatal error instead? */
     32        /* Well, it could be None. */
     33        Py_DECREF(traceback);
     34        traceback = NULL;
     35    }
     36
     37    /* Save these in locals to safeguard against recursive
     38       invocation through Py_XDECREF */
     39    oldtype = tstate->curexc_type;
     40    oldvalue = tstate->curexc_value;
     41    oldtraceback = tstate->curexc_traceback;
     42
     43    tstate->curexc_type = type;
     44    tstate->curexc_value = value;
     45    tstate->curexc_traceback = traceback;
     46
     47    Py_XDECREF(oldtype);
     48    Py_XDECREF(oldvalue);
     49    Py_XDECREF(oldtraceback);
    5050}
    5151
     
    5353PyErr_SetObject(PyObject *exception, PyObject *value)
    5454{
    55         Py_XINCREF(exception);
    56         Py_XINCREF(value);
    57         PyErr_Restore(exception, value, (PyObject *)NULL);
     55    Py_XINCREF(exception);
     56    Py_XINCREF(value);
     57    PyErr_Restore(exception, value, (PyObject *)NULL);
    5858}
    5959
     
    6161PyErr_SetNone(PyObject *exception)
    6262{
    63         PyErr_SetObject(exception, (PyObject *)NULL);
     63    PyErr_SetObject(exception, (PyObject *)NULL);
    6464}
    6565
     
    6767PyErr_SetString(PyObject *exception, const char *string)
    6868{
    69         PyObject *value = PyString_FromString(string);
    70         PyErr_SetObject(exception, value);
    71         Py_XDECREF(value);
     69    PyObject *value = PyString_FromString(string);
     70    PyErr_SetObject(exception, value);
     71    Py_XDECREF(value);
    7272}
    7373
     
    7676PyErr_Occurred(void)
    7777{
    78         PyThreadState *tstate = PyThreadState_GET();
    79 
    80         return tstate->curexc_type;
     78    PyThreadState *tstate = PyThreadState_GET();
     79
     80    return tstate->curexc_type;
    8181}
    8282
     
    8585PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
    8686{
    87         if (err == NULL || exc == NULL) {
    88                 /* maybe caused by "import exceptions" that failed early on */
    89                 return 0;
    90         }
    91         if (PyTuple_Check(exc)) {
    92                 Py_ssize_t i, n;
    93                 n = PyTuple_Size(exc);
    94                 for (i = 0; i < n; i++) {
    95                         /* Test recursively */
    96                      if (PyErr_GivenExceptionMatches(
    97                              err, PyTuple_GET_ITEM(exc, i)))
    98                      {
    99                              return 1;
    100                      }
    101                 }
    102                 return 0;
    103         }
    104         /* err might be an instance, so check its class. */
    105         if (PyExceptionInstance_Check(err))
    106                 err = PyExceptionInstance_Class(err);
    107 
    108         if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
    109                 int res = 0;
    110                 PyObject *exception, *value, *tb;
    111                 PyErr_Fetch(&exception, &value, &tb);
    112                 res = PyObject_IsSubclass(err, exc);
    113                 /* This function must not fail, so print the error here */
    114                 if (res == -1) {
    115                         PyErr_WriteUnraisable(err);
    116                         res = 0;
    117                 }
    118                 PyErr_Restore(exception, value, tb);
    119                 return res;
    120         }
    121 
    122         return err == exc;
     87    if (err == NULL || exc == NULL) {
     88        /* maybe caused by "import exceptions" that failed early on */
     89        return 0;
     90    }
     91    if (PyTuple_Check(exc)) {
     92        Py_ssize_t i, n;
     93        n = PyTuple_Size(exc);
     94        for (i = 0; i < n; i++) {
     95            /* Test recursively */
     96             if (PyErr_GivenExceptionMatches(
     97                 err, PyTuple_GET_ITEM(exc, i)))
     98             {
     99                 return 1;
     100             }
     101        }
     102        return 0;
     103    }
     104    /* err might be an instance, so check its class. */
     105    if (PyExceptionInstance_Check(err))
     106        err = PyExceptionInstance_Class(err);
     107
     108    if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
     109        int res = 0, reclimit;
     110        PyObject *exception, *value, *tb;
     111        PyErr_Fetch(&exception, &value, &tb);
     112        /* Temporarily bump the recursion limit, so that in the most
     113           common case PyObject_IsSubclass will not raise a recursion
     114           error we have to ignore anyway.  Don't do it when the limit
     115           is already insanely high, to avoid overflow */
     116        reclimit = Py_GetRecursionLimit();
     117        if (reclimit < (1 << 30))
     118            Py_SetRecursionLimit(reclimit + 5);
     119        res = PyObject_IsSubclass(err, exc);
     120        Py_SetRecursionLimit(reclimit);
     121        /* This function must not fail, so print the error here */
     122        if (res == -1) {
     123            PyErr_WriteUnraisable(err);
     124            res = 0;
     125        }
     126        PyErr_Restore(exception, value, tb);
     127        return res;
     128    }
     129
     130    return err == exc;
    123131}
    124132
     
    127135PyErr_ExceptionMatches(PyObject *exc)
    128136{
    129         return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
     137    return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
    130138}
    131139
     
    137145PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
    138146{
    139         PyObject *type = *exc;
    140         PyObject *value = *val;
    141         PyObject *inclass = NULL;
    142         PyObject *initial_tb = NULL;
    143         PyThreadState *tstate = NULL;
    144 
    145         if (type == NULL) {
    146                 /* There was no exception, so nothing to do. */
    147                 return;
    148         }
    149 
    150         /* If PyErr_SetNone() was used, the value will have been actually
    151            set to NULL.
    152         */
    153         if (!value) {
    154                 value = Py_None;
    155                 Py_INCREF(value);
    156         }
    157 
    158         if (PyExceptionInstance_Check(value))
    159                 inclass = PyExceptionInstance_Class(value);
    160 
    161         /* Normalize the exception so that if the type is a class, the
    162            value will be an instance.
    163         */
    164         if (PyExceptionClass_Check(type)) {
    165                 /* if the value was not an instance, or is not an instance
    166                    whose class is (or is derived from) type, then use the
    167                    value as an argument to instantiation of the type
    168                    class.
    169                 */
    170                 if (!inclass || !PyObject_IsSubclass(inclass, type)) {
    171                         PyObject *args, *res;
    172 
    173                         if (value == Py_None)
    174                                 args = PyTuple_New(0);
    175                         else if (PyTuple_Check(value)) {
    176                                 Py_INCREF(value);
    177                                 args = value;
    178                         }
    179                         else
    180                                 args = PyTuple_Pack(1, value);
    181 
    182                         if (args == NULL)
    183                                 goto finally;
    184                         res = PyEval_CallObject(type, args);
    185                         Py_DECREF(args);
    186                         if (res == NULL)
    187                                 goto finally;
    188                         Py_DECREF(value);
    189                         value = res;
    190                 }
    191                 /* if the class of the instance doesn't exactly match the
    192                    class of the type, believe the instance
    193                 */
    194                 else if (inclass != type) {
    195                         Py_DECREF(type);
    196                         type = inclass;
    197                         Py_INCREF(type);
    198                 }
    199         }
    200         *exc = type;
    201         *val = value;
    202         return;
     147    PyObject *type = *exc;
     148    PyObject *value = *val;
     149    PyObject *inclass = NULL;
     150    PyObject *initial_tb = NULL;
     151    PyThreadState *tstate = NULL;
     152
     153    if (type == NULL) {
     154        /* There was no exception, so nothing to do. */
     155        return;
     156    }
     157
     158    /* If PyErr_SetNone() was used, the value will have been actually
     159       set to NULL.
     160    */
     161    if (!value) {
     162        value = Py_None;
     163        Py_INCREF(value);
     164    }
     165
     166    if (PyExceptionInstance_Check(value))
     167        inclass = PyExceptionInstance_Class(value);
     168
     169    /* Normalize the exception so that if the type is a class, the
     170       value will be an instance.
     171    */
     172    if (PyExceptionClass_Check(type)) {
     173        /* if the value was not an instance, or is not an instance
     174           whose class is (or is derived from) type, then use the
     175           value as an argument to instantiation of the type
     176           class.
     177        */
     178        if (!inclass || !PyObject_IsSubclass(inclass, type)) {
     179            PyObject *args, *res;
     180
     181            if (value == Py_None)
     182                args = PyTuple_New(0);
     183            else if (PyTuple_Check(value)) {
     184                Py_INCREF(value);
     185                args = value;
     186            }
     187            else
     188                args = PyTuple_Pack(1, value);
     189
     190            if (args == NULL)
     191                goto finally;
     192            res = PyEval_CallObject(type, args);
     193            Py_DECREF(args);
     194            if (res == NULL)
     195                goto finally;
     196            Py_DECREF(value);
     197            value = res;
     198        }
     199        /* if the class of the instance doesn't exactly match the
     200           class of the type, believe the instance
     201        */
     202        else if (inclass != type) {
     203            Py_DECREF(type);
     204            type = inclass;
     205            Py_INCREF(type);
     206        }
     207    }
     208    *exc = type;
     209    *val = value;
     210    return;
    203211finally:
    204         Py_DECREF(type);
    205         Py_DECREF(value);
    206         /* If the new exception doesn't set a traceback and the old
    207            exception had a traceback, use the old traceback for the
    208            new exception.  It's better than nothing.
    209         */
    210         initial_tb = *tb;
    211         PyErr_Fetch(exc, val, tb);
    212         if (initial_tb != NULL) {
    213                 if (*tb == NULL)
    214                         *tb = initial_tb;
    215                 else
    216                         Py_DECREF(initial_tb);
    217         }
    218         /* normalize recursively */
    219         tstate = PyThreadState_GET();
    220         if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
    221             --tstate->recursion_depth;
    222             /* throw away the old exception... */
    223             Py_DECREF(*exc);
    224             Py_DECREF(*val);
    225             /* ... and use the recursion error instead */
    226             *exc = PyExc_RuntimeError;
    227             *val = PyExc_RecursionErrorInst;
    228             Py_INCREF(*exc);
    229             Py_INCREF(*val);
    230             /* just keeping the old traceback */
    231             return;
    232         }
    233         PyErr_NormalizeException(exc, val, tb);
    234         --tstate->recursion_depth;
     212    Py_DECREF(type);
     213    Py_DECREF(value);
     214    /* If the new exception doesn't set a traceback and the old
     215       exception had a traceback, use the old traceback for the
     216       new exception.  It's better than nothing.
     217    */
     218    initial_tb = *tb;
     219    PyErr_Fetch(exc, val, tb);
     220    if (initial_tb != NULL) {
     221        if (*tb == NULL)
     222            *tb = initial_tb;
     223        else
     224            Py_DECREF(initial_tb);
     225    }
     226    /* normalize recursively */
     227    tstate = PyThreadState_GET();
     228    if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
     229        --tstate->recursion_depth;
     230        /* throw away the old exception... */
     231        Py_DECREF(*exc);
     232        Py_DECREF(*val);
     233        /* ... and use the recursion error instead */
     234        *exc = PyExc_RuntimeError;
     235        *val = PyExc_RecursionErrorInst;
     236        Py_INCREF(*exc);
     237        Py_INCREF(*val);
     238        /* just keeping the old traceback */
     239        return;
     240    }
     241    PyErr_NormalizeException(exc, val, tb);
     242    --tstate->recursion_depth;
    235243}
    236244
     
    239247PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
    240248{
    241         PyThreadState *tstate = PyThreadState_GET();
    242 
    243         *p_type = tstate->curexc_type;
    244         *p_value = tstate->curexc_value;
    245         *p_traceback = tstate->curexc_traceback;
    246 
    247         tstate->curexc_type = NULL;
    248         tstate->curexc_value = NULL;
    249         tstate->curexc_traceback = NULL;
     249    PyThreadState *tstate = PyThreadState_GET();
     250
     251    *p_type = tstate->curexc_type;
     252    *p_value = tstate->curexc_value;
     253    *p_traceback = tstate->curexc_traceback;
     254
     255    tstate->curexc_type = NULL;
     256    tstate->curexc_value = NULL;
     257    tstate->curexc_traceback = NULL;
    250258}
    251259
     
    253261PyErr_Clear(void)
    254262{
    255         PyErr_Restore(NULL, NULL, NULL);
     263    PyErr_Restore(NULL, NULL, NULL);
    256264}
    257265
     
    261269PyErr_BadArgument(void)
    262270{
    263         PyErr_SetString(PyExc_TypeError,
    264                         "bad argument type for built-in operation");
    265         return 0;
     271    PyErr_SetString(PyExc_TypeError,
     272                    "bad argument type for built-in operation");
     273    return 0;
    266274}
    267275
     
    269277PyErr_NoMemory(void)
    270278{
    271         if (PyErr_ExceptionMatches(PyExc_MemoryError))
    272                 /* already current */
    273                 return NULL;
    274 
    275         /* raise the pre-allocated instance if it still exists */
    276         if (PyExc_MemoryErrorInst)
    277                 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
    278         else
    279                 /* this will probably fail since there's no memory and hee,
    280                    hee, we have to instantiate this class
    281                 */
    282                 PyErr_SetNone(PyExc_MemoryError);
    283 
    284         return NULL;
     279    if (PyErr_ExceptionMatches(PyExc_MemoryError))
     280        /* already current */
     281        return NULL;
     282
     283    /* raise the pre-allocated instance if it still exists */
     284    if (PyExc_MemoryErrorInst)
     285        PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
     286    else
     287        /* this will probably fail since there's no memory and hee,
     288           hee, we have to instantiate this class
     289        */
     290        PyErr_SetNone(PyExc_MemoryError);
     291
     292    return NULL;
    285293}
    286294
     
    288296PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
    289297{
    290         PyObject *v;
    291         char *s;
    292         int i = errno;
     298    PyObject *v;
     299    char *s;
     300    int i = errno;
    293301#ifdef PLAN9
    294         char errbuf[ERRMAX];
     302    char errbuf[ERRMAX];
    295303#endif
    296304#ifdef MS_WINDOWS
    297         char *s_buf = NULL;
    298         char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
     305    char *s_buf = NULL;
     306    char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
    299307#endif
    300308#ifdef EINTR
    301         if (i == EINTR && PyErr_CheckSignals())
    302                 return NULL;
     309    if (i == EINTR && PyErr_CheckSignals())
     310        return NULL;
    303311#endif
    304312#ifdef PLAN9
    305         rerrstr(errbuf, sizeof errbuf);
    306         s = errbuf;
     313    rerrstr(errbuf, sizeof errbuf);
     314    s = errbuf;
    307315#else
    308         if (i == 0)
    309                 s = "Error"; /* Sometimes errno didn't get set */
    310         else
     316    if (i == 0)
     317        s = "Error"; /* Sometimes errno didn't get set */
     318    else
    311319#ifndef MS_WINDOWS
    312                 s = strerror(i);
     320        s = strerror(i);
    313321#else
    314         {
    315                 /* Note that the Win32 errors do not lineup with the
    316                    errno error.  So if the error is in the MSVC error
    317                    table, we use it, otherwise we assume it really _is_
    318                    a Win32 error code
    319                 */
    320                 if (i > 0 && i < _sys_nerr) {
    321                         s = _sys_errlist[i];
    322                 }
    323                 else {
    324                         int len = FormatMessage(
    325                                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
    326                                 FORMAT_MESSAGE_FROM_SYSTEM |
    327                                 FORMAT_MESSAGE_IGNORE_INSERTS,
    328                                 NULL,   /* no message source */
    329                                 i,
    330                                 MAKELANGID(LANG_NEUTRAL,
    331                                            SUBLANG_DEFAULT),
    332                                            /* Default language */
    333                                 (LPTSTR) &s_buf,
    334                                 0,      /* size not used */
    335                                 NULL);  /* no args */
    336                         if (len==0) {
    337                                 /* Only ever seen this in out-of-mem
    338                                    situations */
    339                                 sprintf(s_small_buf, "Windows Error 0x%X", i);
    340                                 s = s_small_buf;
    341                                 s_buf = NULL;
    342                         } else {
    343                                 s = s_buf;
    344                                 /* remove trailing cr/lf and dots */
    345                                 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
    346                                         s[--len] = '\0';
    347                         }
    348                 }
    349         }
     322    {
     323        /* Note that the Win32 errors do not lineup with the
     324           errno error.  So if the error is in the MSVC error
     325           table, we use it, otherwise we assume it really _is_
     326           a Win32 error code
     327        */
     328        if (i > 0 && i < _sys_nerr) {
     329            s = _sys_errlist[i];
     330        }
     331        else {
     332            int len = FormatMessage(
     333                FORMAT_MESSAGE_ALLOCATE_BUFFER |
     334                FORMAT_MESSAGE_FROM_SYSTEM |
     335                FORMAT_MESSAGE_IGNORE_INSERTS,
     336                NULL,                   /* no message source */
     337                i,
     338                MAKELANGID(LANG_NEUTRAL,
     339                           SUBLANG_DEFAULT),
     340                           /* Default language */
     341                (LPTSTR) &s_buf,
     342                0,                      /* size not used */
     343                NULL);                  /* no args */
     344            if (len==0) {
     345                /* Only ever seen this in out-of-mem
     346                   situations */
     347                sprintf(s_small_buf, "Windows Error 0x%X", i);
     348                s = s_small_buf;
     349                s_buf = NULL;
     350            } else {
     351                s = s_buf;
     352                /* remove trailing cr/lf and dots */
     353                while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
     354                    s[--len] = '\0';
     355            }
     356        }
     357    }
    350358#endif /* Unix/Windows */
    351359#endif /* PLAN 9*/
    352         if (filenameObject != NULL)
    353                 v = Py_BuildValue("(isO)", i, s, filenameObject);
    354         else
    355                 v = Py_BuildValue("(is)", i, s);
    356         if (v != NULL) {
    357                 PyErr_SetObject(exc, v);
    358                 Py_DECREF(v);
    359         }
     360    if (filenameObject != NULL)
     361        v = Py_BuildValue("(isO)", i, s, filenameObject);
     362    else
     363        v = Py_BuildValue("(is)", i, s);
     364    if (v != NULL) {
     365        PyErr_SetObject(exc, v);
     366        Py_DECREF(v);
     367    }
    360368#ifdef MS_WINDOWS
    361         LocalFree(s_buf);
    362 #endif
    363         return NULL;
    364 }
    365 
    366 
    367 PyObject *
    368 PyErr_SetFromErrnoWithFilename(PyObject *exc, char *filename)
    369 {
    370         PyObject *name = filename ? PyString_FromString(filename) : NULL;
    371         PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
    372         Py_XDECREF(name);
    373         return result;
    374 }
    375 
    376 #ifdef Py_WIN_WIDE_FILENAMES
    377 PyObject *
    378 PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, Py_UNICODE *filename)
    379 {
    380         PyObject *name = filename ?
    381                          PyUnicode_FromUnicode(filename, wcslen(filename)) :
    382                          NULL;
    383         PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
    384         Py_XDECREF(name);
    385         return result;
    386 }
    387 #endif /* Py_WIN_WIDE_FILENAMES */
     369    LocalFree(s_buf);
     370#endif
     371    return NULL;
     372}
     373
     374
     375PyObject *
     376PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
     377{
     378    PyObject *name = filename ? PyString_FromString(filename) : NULL;
     379    PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
     380    Py_XDECREF(name);
     381    return result;
     382}
     383
     384#ifdef MS_WINDOWS
     385PyObject *
     386PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
     387{
     388    PyObject *name = filename ?
     389                     PyUnicode_FromUnicode(filename, wcslen(filename)) :
     390             NULL;
     391    PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
     392    Py_XDECREF(name);
     393    return result;
     394}
     395#endif /* MS_WINDOWS */
    388396
    389397PyObject *
    390398PyErr_SetFromErrno(PyObject *exc)
    391399{
    392         return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
     400    return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
    393401}
    394402
     
    396404/* Windows specific error code handling */
    397405PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
    398         PyObject *exc,
    399         int ierr,
    400         PyObject *filenameObject)
    401 {
    402         int len;
    403         char *s;
    404         char *s_buf = NULL; /* Free via LocalFree */
    405         char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
    406         PyObject *v;
    407         DWORD err = (DWORD)ierr;
    408         if (err==0) err = GetLastError();
    409         len = FormatMessage(
    410                 /* Error API error */
    411                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
    412                 FORMAT_MESSAGE_FROM_SYSTEM |
    413                 FORMAT_MESSAGE_IGNORE_INSERTS,
    414                 NULL,   /* no message source */
    415                 err,
    416                 MAKELANGID(LANG_NEUTRAL,
    417                 SUBLANG_DEFAULT), /* Default language */
    418                 (LPTSTR) &s_buf,
    419                 0,      /* size not used */
    420                 NULL);  /* no args */
    421         if (len==0) {
    422                 /* Only seen this in out of mem situations */
    423                 sprintf(s_small_buf, "Windows Error 0x%X", err);
    424                 s = s_small_buf;
    425                 s_buf = NULL;
    426         } else {
    427                 s = s_buf;
    428                 /* remove trailing cr/lf and dots */
    429                 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
    430                         s[--len] = '\0';
    431         }
    432         if (filenameObject != NULL)
    433                 v = Py_BuildValue("(isO)", err, s, filenameObject);
    434         else
    435                 v = Py_BuildValue("(is)", err, s);
    436         if (v != NULL) {
    437                 PyErr_SetObject(exc, v);
    438                 Py_DECREF(v);
    439         }
    440         LocalFree(s_buf);
    441         return NULL;
     406    PyObject *exc,
     407    int ierr,
     408    PyObject *filenameObject)
     409{
     410    int len;
     411    char *s;
     412    char *s_buf = NULL; /* Free via LocalFree */
     413    char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
     414    PyObject *v;
     415    DWORD err = (DWORD)ierr;
     416    if (err==0) err = GetLastError();
     417    len = FormatMessage(
     418        /* Error API error */
     419        FORMAT_MESSAGE_ALLOCATE_BUFFER |
     420        FORMAT_MESSAGE_FROM_SYSTEM |
     421        FORMAT_MESSAGE_IGNORE_INSERTS,
     422        NULL,           /* no message source */
     423        err,
     424        MAKELANGID(LANG_NEUTRAL,
     425        SUBLANG_DEFAULT), /* Default language */
     426        (LPTSTR) &s_buf,
     427        0,              /* size not used */
     428        NULL);          /* no args */
     429    if (len==0) {
     430        /* Only seen this in out of mem situations */
     431        sprintf(s_small_buf, "Windows Error 0x%X", err);
     432        s = s_small_buf;
     433        s_buf = NULL;
     434    } else {
     435        s = s_buf;
     436        /* remove trailing cr/lf and dots */
     437        while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
     438            s[--len] = '\0';
     439    }
     440    if (filenameObject != NULL)
     441        v = Py_BuildValue("(isO)", err, s, filenameObject);
     442    else
     443        v = Py_BuildValue("(is)", err, s);
     444    if (v != NULL) {
     445        PyErr_SetObject(exc, v);
     446        Py_DECREF(v);
     447    }
     448    LocalFree(s_buf);
     449    return NULL;
    442450}
    443451
    444452PyObject *PyErr_SetExcFromWindowsErrWithFilename(
    445         PyObject *exc,
    446         int ierr,
    447         const char *filename)
    448 {
    449         PyObject *name = filename ? PyString_FromString(filename) : NULL;
    450         PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
    451                                                                      ierr,
    452                                                                      name);
    453         Py_XDECREF(name);
    454         return ret;
    455 }
    456 
    457 #ifdef Py_WIN_WIDE_FILENAMES
     453    PyObject *exc,
     454    int ierr,
     455    const char *filename)
     456{
     457    PyObject *name = filename ? PyString_FromString(filename) : NULL;
     458    PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
     459                                                                 ierr,
     460                                                                 name);
     461    Py_XDECREF(name);
     462    return ret;
     463}
     464
    458465PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
    459         PyObject *exc,
    460         int ierr,
    461         const Py_UNICODE *filename)
    462 {
    463         PyObject *name = filename ?
    464                          PyUnicode_FromUnicode(filename, wcslen(filename)) :
    465                          NULL;
    466         PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
    467                                                                      ierr,
    468                                                                      name);
    469         Py_XDECREF(name);
    470         return ret;
    471 }
    472 #endif /* Py_WIN_WIDE_FILENAMES */
     466    PyObject *exc,
     467    int ierr,
     468    const Py_UNICODE *filename)
     469{
     470    PyObject *name = filename ?
     471                     PyUnicode_FromUnicode(filename, wcslen(filename)) :
     472             NULL;
     473    PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
     474                                                                 ierr,
     475                                                                 name);
     476    Py_XDECREF(name);
     477    return ret;
     478}
    473479
    474480PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
    475481{
    476         return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
     482    return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
    477483}
    478484
    479485PyObject *PyErr_SetFromWindowsErr(int ierr)
    480486{
    481         return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
    482                                                       ierr, NULL);
     487    return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
     488                                                  ierr, NULL);
    483489}
    484490PyObject *PyErr_SetFromWindowsErrWithFilename(
    485         int ierr,
    486         const char *filename)
    487 {
    488         PyObject *name = filename ? PyString_FromString(filename) : NULL;
    489         PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
    490                                                       PyExc_WindowsError,
    491                                                       ierr, name);
    492         Py_XDECREF(name);
    493         return result;
    494 }
    495 
    496 #ifdef Py_WIN_WIDE_FILENAMES
     491    int ierr,
     492    const char *filename)
     493{
     494    PyObject *name = filename ? PyString_FromString(filename) : NULL;
     495    PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
     496                                                  PyExc_WindowsError,
     497                                                  ierr, name);
     498    Py_XDECREF(name);
     499    return result;
     500}
     501
    497502PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
    498         int ierr,
    499         const Py_UNICODE *filename)
    500 {
    501         PyObject *name = filename ?
    502                          PyUnicode_FromUnicode(filename, wcslen(filename)) :
    503                          NULL;
    504         PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
    505                                                       PyExc_WindowsError,
    506                                                       ierr, name);
    507         Py_XDECREF(name);
    508         return result;
    509 }
    510 #endif /* Py_WIN_WIDE_FILENAMES */
     503    int ierr,
     504    const Py_UNICODE *filename)
     505{
     506    PyObject *name = filename ?
     507                     PyUnicode_FromUnicode(filename, wcslen(filename)) :
     508             NULL;
     509    PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
     510                                                  PyExc_WindowsError,
     511                                                  ierr, name);
     512    Py_XDECREF(name);
     513    return result;
     514}
    511515#endif /* MS_WINDOWS */
    512516
     
    514518_PyErr_BadInternalCall(char *filename, int lineno)
    515519{
    516         PyErr_Format(PyExc_SystemError,
    517                      "%s:%d: bad argument to internal function",
    518                      filename, lineno);
     520    PyErr_Format(PyExc_SystemError,
     521                 "%s:%d: bad argument to internal function",
     522                 filename, lineno);
    519523}
    520524
     
    525529PyErr_BadInternalCall(void)
    526530{
    527         PyErr_Format(PyExc_SystemError,
    528                      "bad argument to internal function");
     531    PyErr_Format(PyExc_SystemError,
     532                 "bad argument to internal function");
    529533}
    530534#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
     
    535539PyErr_Format(PyObject *exception, const char *format, ...)
    536540{
    537         va_list vargs;
    538         PyObject* string;
     541    va_list vargs;
     542    PyObject* string;
    539543
    540544#ifdef HAVE_STDARG_PROTOTYPES
    541         va_start(vargs, format);
     545    va_start(vargs, format);
    542546#else
    543         va_start(vargs);
    544 #endif
    545 
    546         string = PyString_FromFormatV(format, vargs);
    547         PyErr_SetObject(exception, string);
    548         Py_XDECREF(string);
    549         va_end(vargs);
    550         return NULL;
     547    va_start(vargs);
     548#endif
     549
     550    string = PyString_FromFormatV(format, vargs);
     551    PyErr_SetObject(exception, string);
     552    Py_XDECREF(string);
     553    va_end(vargs);
     554    return NULL;
    551555}
    552556
     
    556560PyErr_NewException(char *name, PyObject *base, PyObject *dict)
    557561{
    558         char *dot;
    559         PyObject *modulename = NULL;
    560         PyObject *classname = NULL;
    561         PyObject *mydict = NULL;
    562         PyObject *bases = NULL;
    563         PyObject *result = NULL;
    564         dot = strrchr(name, '.');
    565         if (dot == NULL) {
    566                 PyErr_SetString(PyExc_SystemError,
    567                         "PyErr_NewException: name must be module.class");
    568                 return NULL;
    569         }
    570         if (base == NULL)
    571                 base = PyExc_Exception;
    572         if (dict == NULL) {
    573                 dict = mydict = PyDict_New();
    574                 if (dict == NULL)
    575                         goto failure;
    576         }
    577         if (PyDict_GetItemString(dict, "__module__") == NULL) {
    578                 modulename = PyString_FromStringAndSize(name,
    579                                                      (Py_ssize_t)(dot-name));
    580                 if (modulename == NULL)
    581                         goto failure;
    582                 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
    583                         goto failure;
    584         }
    585         if (PyTuple_Check(base)) {
    586                 bases = base;
    587                 /* INCREF as we create a new ref in the else branch */
    588                 Py_INCREF(bases);
    589         } else {
    590                 bases = PyTuple_Pack(1, base);
    591                 if (bases == NULL)
    592                         goto failure;
    593         }
    594         /* Create a real new-style class. */
    595         result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
    596                                        dot+1, bases, dict);
     562    char *dot;
     563    PyObject *modulename = NULL;
     564    PyObject *classname = NULL;
     565    PyObject *mydict = NULL;
     566    PyObject *bases = NULL;
     567    PyObject *result = NULL;
     568    dot = strrchr(name, '.');
     569    if (dot == NULL) {
     570        PyErr_SetString(PyExc_SystemError,
     571            "PyErr_NewException: name must be module.class");
     572        return NULL;
     573    }
     574    if (base == NULL)
     575        base = PyExc_Exception;
     576    if (dict == NULL) {
     577        dict = mydict = PyDict_New();
     578        if (dict == NULL)
     579            goto failure;
     580    }
     581    if (PyDict_GetItemString(dict, "__module__") == NULL) {
     582        modulename = PyString_FromStringAndSize(name,
     583                                             (Py_ssize_t)(dot-name));
     584        if (modulename == NULL)
     585            goto failure;
     586        if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
     587            goto failure;
     588    }
     589    if (PyTuple_Check(base)) {
     590        bases = base;
     591        /* INCREF as we create a new ref in the else branch */
     592        Py_INCREF(bases);
     593    } else {
     594        bases = PyTuple_Pack(1, base);
     595        if (bases == NULL)
     596            goto failure;
     597    }
     598    /* Create a real new-style class. */
     599    result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
     600                                   dot+1, bases, dict);
    597601  failure:
    598         Py_XDECREF(bases);
    599         Py_XDECREF(mydict);
    600         Py_XDECREF(classname);
    601         Py_XDECREF(modulename);
    602         return result;
    603 }
     602    Py_XDECREF(bases);
     603    Py_XDECREF(mydict);
     604    Py_XDECREF(classname);
     605    Py_XDECREF(modulename);
     606    return result;
     607}
     608
     609
     610/* Create an exception with docstring */
     611PyObject *
     612PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict)
     613{
     614    int result;
     615    PyObject *ret = NULL;
     616    PyObject *mydict = NULL; /* points to the dict only if we create it */
     617    PyObject *docobj;
     618
     619    if (dict == NULL) {
     620        dict = mydict = PyDict_New();
     621        if (dict == NULL) {
     622            return NULL;
     623        }
     624    }
     625
     626    if (doc != NULL) {
     627        docobj = PyString_FromString(doc);
     628        if (docobj == NULL)
     629            goto failure;
     630        result = PyDict_SetItemString(dict, "__doc__", docobj);
     631        Py_DECREF(docobj);
     632        if (result < 0)
     633            goto failure;
     634    }
     635
     636    ret = PyErr_NewException(name, base, dict);
     637  failure:
     638    Py_XDECREF(mydict);
     639    return ret;
     640}
     641
    604642
    605643/* Call when an exception has occurred but there is no way for Python
     
    608646PyErr_WriteUnraisable(PyObject *obj)
    609647{
    610         PyObject *f, *t, *v, *tb;
    611         PyErr_Fetch(&t, &v, &tb);
    612         f = PySys_GetObject("stderr");
    613         if (f != NULL) {
    614                 PyFile_WriteString("Exception ", f);
    615                 if (t) {
    616                         PyObject* moduleName;
    617                         char* className;
    618                         assert(PyExceptionClass_Check(t));
    619                         className = PyExceptionClass_Name(t);
    620                         if (className != NULL) {
    621                                 char *dot = strrchr(className, '.');
    622                                 if (dot != NULL)
    623                                         className = dot+1;
    624                         }
    625 
    626                         moduleName = PyObject_GetAttrString(t, "__module__");
    627                         if (moduleName == NULL)
    628                                 PyFile_WriteString("<unknown>", f);
    629                         else {
    630                                 char* modstr = PyString_AsString(moduleName);
    631                                 if (modstr &&
    632                                     strcmp(modstr, "exceptions") != 0)
    633                                 {
    634                                         PyFile_WriteString(modstr, f);
    635                                         PyFile_WriteString(".", f);
    636                                 }
    637                         }
    638                         if (className == NULL)
    639                                 PyFile_WriteString("<unknown>", f);
    640                         else
    641                                 PyFile_WriteString(className, f);
    642                         if (v && v != Py_None) {
    643                                 PyFile_WriteString(": ", f);
    644                                 PyFile_WriteObject(v, f, 0);
    645                         }
    646                         Py_XDECREF(moduleName);
    647                 }
    648                 PyFile_WriteString(" in ", f);
    649                 PyFile_WriteObject(obj, f, 0);
    650                 PyFile_WriteString(" ignored\n", f);
    651                 PyErr_Clear(); /* Just in case */
    652         }
    653         Py_XDECREF(t);
    654         Py_XDECREF(v);
    655         Py_XDECREF(tb);
     648    PyObject *f, *t, *v, *tb;
     649    PyErr_Fetch(&t, &v, &tb);
     650    f = PySys_GetObject("stderr");
     651    if (f != NULL) {
     652        PyFile_WriteString("Exception ", f);
     653        if (t) {
     654            PyObject* moduleName;
     655            char* className;
     656            assert(PyExceptionClass_Check(t));
     657            className = PyExceptionClass_Name(t);
     658            if (className != NULL) {
     659                char *dot = strrchr(className, '.');
     660                if (dot != NULL)
     661                    className = dot+1;
     662            }
     663
     664            moduleName = PyObject_GetAttrString(t, "__module__");
     665            if (moduleName == NULL)
     666                PyFile_WriteString("<unknown>", f);
     667            else {
     668                char* modstr = PyString_AsString(moduleName);
     669                if (modstr &&
     670                    strcmp(modstr, "exceptions") != 0)
     671                {
     672                    PyFile_WriteString(modstr, f);
     673                    PyFile_WriteString(".", f);
     674                }
     675            }
     676            if (className == NULL)
     677                PyFile_WriteString("<unknown>", f);
     678            else
     679                PyFile_WriteString(className, f);
     680            if (v && v != Py_None) {
     681                PyFile_WriteString(": ", f);
     682                PyFile_WriteObject(v, f, 0);
     683            }
     684            Py_XDECREF(moduleName);
     685        }
     686        PyFile_WriteString(" in ", f);
     687        PyFile_WriteObject(obj, f, 0);
     688        PyFile_WriteString(" ignored\n", f);
     689        PyErr_Clear(); /* Just in case */
     690    }
     691    Py_XDECREF(t);
     692    Py_XDECREF(v);
     693    Py_XDECREF(tb);
    656694}
    657695
     
    666704PyErr_SyntaxLocation(const char *filename, int lineno)
    667705{
    668         PyObject *exc, *v, *tb, *tmp;
    669 
    670         /* add attributes for the line number and filename for the error */
    671         PyErr_Fetch(&exc, &v, &tb);
    672         PyErr_NormalizeException(&exc, &v, &tb);
    673         /* XXX check that it is, indeed, a syntax error. It might not
    674         * be, though. */
    675         tmp = PyInt_FromLong(lineno);
    676         if (tmp == NULL)
    677                 PyErr_Clear();
    678         else {
    679                 if (PyObject_SetAttrString(v, "lineno", tmp))
    680                         PyErr_Clear();
    681                 Py_DECREF(tmp);
    682         }
    683         if (filename != NULL) {
    684                 tmp = PyString_FromString(filename);
    685                 if (tmp == NULL)
    686                         PyErr_Clear();
    687                 else {
    688                         if (PyObject_SetAttrString(v, "filename", tmp))
    689                                 PyErr_Clear();
    690                         Py_DECREF(tmp);
    691                 }
    692 
    693                 tmp = PyErr_ProgramText(filename, lineno);
    694                 if (tmp) {
    695                         if (PyObject_SetAttrString(v, "text", tmp))
    696                                 PyErr_Clear();
    697                         Py_DECREF(tmp);
    698                 }
    699         }
    700         if (PyObject_SetAttrString(v, "offset", Py_None)) {
    701                 PyErr_Clear();
    702         }
    703         if (exc != PyExc_SyntaxError) {
    704                 if (!PyObject_HasAttrString(v, "msg")) {
    705                         tmp = PyObject_Str(v);
    706                         if (tmp) {
    707                                 if (PyObject_SetAttrString(v, "msg", tmp))
    708                                         PyErr_Clear();
    709                                 Py_DECREF(tmp);
    710                         } else {
    711                                 PyErr_Clear();
    712                         }
    713                 }
    714                 if (!PyObject_HasAttrString(v, "print_file_and_line")) {
    715                         if (PyObject_SetAttrString(v, "print_file_and_line",
    716                                                    Py_None))
    717                                 PyErr_Clear();
    718                 }
    719         }
    720         PyErr_Restore(exc, v, tb);
     706    PyObject *exc, *v, *tb, *tmp;
     707
     708    /* add attributes for the line number and filename for the error */
     709    PyErr_Fetch(&exc, &v, &tb);
     710    PyErr_NormalizeException(&exc, &v, &tb);
     711    /* XXX check that it is, indeed, a syntax error. It might not
     712    * be, though. */
     713    tmp = PyInt_FromLong(lineno);
     714    if (tmp == NULL)
     715        PyErr_Clear();
     716    else {
     717        if (PyObject_SetAttrString(v, "lineno", tmp))
     718            PyErr_Clear();
     719        Py_DECREF(tmp);
     720    }
     721    if (filename != NULL) {
     722        tmp = PyString_FromString(filename);
     723        if (tmp == NULL)
     724            PyErr_Clear();
     725        else {
     726            if (PyObject_SetAttrString(v, "filename", tmp))
     727                PyErr_Clear();
     728            Py_DECREF(tmp);
     729        }
     730
     731        tmp = PyErr_ProgramText(filename, lineno);
     732        if (tmp) {
     733            if (PyObject_SetAttrString(v, "text", tmp))
     734                PyErr_Clear();
     735            Py_DECREF(tmp);
     736        }
     737    }
     738    if (PyObject_SetAttrString(v, "offset", Py_None)) {
     739        PyErr_Clear();
     740    }
     741    if (exc != PyExc_SyntaxError) {
     742        if (!PyObject_HasAttrString(v, "msg")) {
     743            tmp = PyObject_Str(v);
     744            if (tmp) {
     745                if (PyObject_SetAttrString(v, "msg", tmp))
     746                    PyErr_Clear();
     747                Py_DECREF(tmp);
     748            } else {
     749                PyErr_Clear();
     750            }
     751        }
     752        if (!PyObject_HasAttrString(v, "print_file_and_line")) {
     753            if (PyObject_SetAttrString(v, "print_file_and_line",
     754                                       Py_None))
     755                PyErr_Clear();
     756        }
     757    }
     758    PyErr_Restore(exc, v, tb);
    721759}
    722760
     
    732770PyErr_ProgramText(const char *filename, int lineno)
    733771{
    734         FILE *fp;
    735         int i;
    736         char linebuf[1000];
    737 
    738         if (filename == NULL || *filename == '\0' || lineno <= 0)
    739                 return NULL;
    740         fp = fopen(filename, "r" PY_STDIOTEXTMODE);
    741         if (fp == NULL)
    742                 return NULL;
    743         for (i = 0; i < lineno; i++) {
    744                 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
    745                 do {
    746                         *pLastChar = '\0';
    747                         if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
    748                                 break;
    749                         /* fgets read *something*; if it didn't get as
    750                            far as pLastChar, it must have found a newline
    751                            or hit the end of the file; if pLastChar is \n,
    752                            it obviously found a newline; else we haven't
    753                            yet seen a newline, so must continue */
    754                 } while (*pLastChar != '\0' && *pLastChar != '\n');
    755         }
    756         fclose(fp);
    757         if (i == lineno) {
    758                 char *p = linebuf;
    759                 while (*p == ' ' || *p == '\t' || *p == '\014')
    760                         p++;
    761                 return PyString_FromString(p);
    762         }
    763         return NULL;
     772    FILE *fp;
     773    int i;
     774    char linebuf[1000];
     775
     776    if (filename == NULL || *filename == '\0' || lineno <= 0)
     777        return NULL;
     778    fp = fopen(filename, "r" PY_STDIOTEXTMODE);
     779    if (fp == NULL)
     780        return NULL;
     781    for (i = 0; i < lineno; i++) {
     782        char *pLastChar = &linebuf[sizeof(linebuf) - 2];
     783        do {
     784            *pLastChar = '\0';
     785            if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
     786                break;
     787            /* fgets read *something*; if it didn't get as
     788               far as pLastChar, it must have found a newline
     789               or hit the end of the file; if pLastChar is \n,
     790               it obviously found a newline; else we haven't
     791               yet seen a newline, so must continue */
     792        } while (*pLastChar != '\0' && *pLastChar != '\n');
     793    }
     794    fclose(fp);
     795    if (i == lineno) {
     796        char *p = linebuf;
     797        while (*p == ' ' || *p == '\t' || *p == '\014')
     798            p++;
     799        return PyString_FromString(p);
     800    }
     801    return NULL;
    764802}
    765803
Note: See TracChangeset for help on using the changeset viewer.