Home | History | Annotate | Download | only in Objects
      1 /*
      2  * New exceptions.c written in Iceland by Richard Jones and Georg Brandl.
      3  *
      4  * Thanks go to Tim Peters and Michael Hudson for debugging.
      5  */
      6 
      7 #define PY_SSIZE_T_CLEAN
      8 #include <Python.h>
      9 #include "structmember.h"
     10 #include "osdefs.h"
     11 
     12 
     13 /* Compatibility aliases */
     14 PyObject *PyExc_EnvironmentError = NULL;
     15 PyObject *PyExc_IOError = NULL;
     16 #ifdef MS_WINDOWS
     17 PyObject *PyExc_WindowsError = NULL;
     18 #endif
     19 
     20 /* The dict map from errno codes to OSError subclasses */
     21 static PyObject *errnomap = NULL;
     22 
     23 
     24 /* NOTE: If the exception class hierarchy changes, don't forget to update
     25  * Lib/test/exception_hierarchy.txt
     26  */
     27 
     28 /*
     29  *    BaseException
     30  */
     31 static PyObject *
     32 BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     33 {
     34     PyBaseExceptionObject *self;
     35 
     36     self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
     37     if (!self)
     38         return NULL;
     39     /* the dict is created on the fly in PyObject_GenericSetAttr */
     40     self->dict = NULL;
     41     self->traceback = self->cause = self->context = NULL;
     42     self->suppress_context = 0;
     43 
     44     if (args) {
     45         self->args = args;
     46         Py_INCREF(args);
     47         return (PyObject *)self;
     48     }
     49 
     50     self->args = PyTuple_New(0);
     51     if (!self->args) {
     52         Py_DECREF(self);
     53         return NULL;
     54     }
     55 
     56     return (PyObject *)self;
     57 }
     58 
     59 static int
     60 BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
     61 {
     62     if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
     63         return -1;
     64 
     65     Py_INCREF(args);
     66     Py_XSETREF(self->args, args);
     67 
     68     return 0;
     69 }
     70 
     71 static int
     72 BaseException_clear(PyBaseExceptionObject *self)
     73 {
     74     Py_CLEAR(self->dict);
     75     Py_CLEAR(self->args);
     76     Py_CLEAR(self->traceback);
     77     Py_CLEAR(self->cause);
     78     Py_CLEAR(self->context);
     79     return 0;
     80 }
     81 
     82 static void
     83 BaseException_dealloc(PyBaseExceptionObject *self)
     84 {
     85     _PyObject_GC_UNTRACK(self);
     86     BaseException_clear(self);
     87     Py_TYPE(self)->tp_free((PyObject *)self);
     88 }
     89 
     90 static int
     91 BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
     92 {
     93     Py_VISIT(self->dict);
     94     Py_VISIT(self->args);
     95     Py_VISIT(self->traceback);
     96     Py_VISIT(self->cause);
     97     Py_VISIT(self->context);
     98     return 0;
     99 }
    100 
    101 static PyObject *
    102 BaseException_str(PyBaseExceptionObject *self)
    103 {
    104     switch (PyTuple_GET_SIZE(self->args)) {
    105     case 0:
    106         return PyUnicode_FromString("");
    107     case 1:
    108         return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
    109     default:
    110         return PyObject_Str(self->args);
    111     }
    112 }
    113 
    114 static PyObject *
    115 BaseException_repr(PyBaseExceptionObject *self)
    116 {
    117     const char *name;
    118     const char *dot;
    119 
    120     name = Py_TYPE(self)->tp_name;
    121     dot = (const char *) strrchr(name, '.');
    122     if (dot != NULL) name = dot+1;
    123 
    124     return PyUnicode_FromFormat("%s%R", name, self->args);
    125 }
    126 
    127 /* Pickling support */
    128 static PyObject *
    129 BaseException_reduce(PyBaseExceptionObject *self)
    130 {
    131     if (self->args && self->dict)
    132         return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
    133     else
    134         return PyTuple_Pack(2, Py_TYPE(self), self->args);
    135 }
    136 
    137 /*
    138  * Needed for backward compatibility, since exceptions used to store
    139  * all their attributes in the __dict__. Code is taken from cPickle's
    140  * load_build function.
    141  */
    142 static PyObject *
    143 BaseException_setstate(PyObject *self, PyObject *state)
    144 {
    145     PyObject *d_key, *d_value;
    146     Py_ssize_t i = 0;
    147 
    148     if (state != Py_None) {
    149         if (!PyDict_Check(state)) {
    150             PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
    151             return NULL;
    152         }
    153         while (PyDict_Next(state, &i, &d_key, &d_value)) {
    154             if (PyObject_SetAttr(self, d_key, d_value) < 0)
    155                 return NULL;
    156         }
    157     }
    158     Py_RETURN_NONE;
    159 }
    160 
    161 static PyObject *
    162 BaseException_with_traceback(PyObject *self, PyObject *tb) {
    163     if (PyException_SetTraceback(self, tb))
    164         return NULL;
    165 
    166     Py_INCREF(self);
    167     return self;
    168 }
    169 
    170 PyDoc_STRVAR(with_traceback_doc,
    171 "Exception.with_traceback(tb) --\n\
    172     set self.__traceback__ to tb and return self.");
    173 
    174 
    175 static PyMethodDef BaseException_methods[] = {
    176    {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
    177    {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
    178    {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
    179     with_traceback_doc},
    180    {NULL, NULL, 0, NULL},
    181 };
    182 
    183 static PyObject *
    184 BaseException_get_args(PyBaseExceptionObject *self)
    185 {
    186     if (self->args == NULL) {
    187         Py_INCREF(Py_None);
    188         return Py_None;
    189     }
    190     Py_INCREF(self->args);
    191     return self->args;
    192 }
    193 
    194 static int
    195 BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
    196 {
    197     PyObject *seq;
    198     if (val == NULL) {
    199         PyErr_SetString(PyExc_TypeError, "args may not be deleted");
    200         return -1;
    201     }
    202     seq = PySequence_Tuple(val);
    203     if (!seq)
    204         return -1;
    205     Py_XSETREF(self->args, seq);
    206     return 0;
    207 }
    208 
    209 static PyObject *
    210 BaseException_get_tb(PyBaseExceptionObject *self)
    211 {
    212     if (self->traceback == NULL) {
    213         Py_INCREF(Py_None);
    214         return Py_None;
    215     }
    216     Py_INCREF(self->traceback);
    217     return self->traceback;
    218 }
    219 
    220 static int
    221 BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb)
    222 {
    223     if (tb == NULL) {
    224         PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
    225         return -1;
    226     }
    227     else if (!(tb == Py_None || PyTraceBack_Check(tb))) {
    228         PyErr_SetString(PyExc_TypeError,
    229                         "__traceback__ must be a traceback or None");
    230         return -1;
    231     }
    232 
    233     Py_INCREF(tb);
    234     Py_XSETREF(self->traceback, tb);
    235     return 0;
    236 }
    237 
    238 static PyObject *
    239 BaseException_get_context(PyObject *self) {
    240     PyObject *res = PyException_GetContext(self);
    241     if (res)
    242         return res;  /* new reference already returned above */
    243     Py_RETURN_NONE;
    244 }
    245 
    246 static int
    247 BaseException_set_context(PyObject *self, PyObject *arg) {
    248     if (arg == NULL) {
    249         PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
    250         return -1;
    251     } else if (arg == Py_None) {
    252         arg = NULL;
    253     } else if (!PyExceptionInstance_Check(arg)) {
    254         PyErr_SetString(PyExc_TypeError, "exception context must be None "
    255                         "or derive from BaseException");
    256         return -1;
    257     } else {
    258         /* PyException_SetContext steals this reference */
    259         Py_INCREF(arg);
    260     }
    261     PyException_SetContext(self, arg);
    262     return 0;
    263 }
    264 
    265 static PyObject *
    266 BaseException_get_cause(PyObject *self) {
    267     PyObject *res = PyException_GetCause(self);
    268     if (res)
    269         return res;  /* new reference already returned above */
    270     Py_RETURN_NONE;
    271 }
    272 
    273 static int
    274 BaseException_set_cause(PyObject *self, PyObject *arg) {
    275     if (arg == NULL) {
    276         PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
    277         return -1;
    278     } else if (arg == Py_None) {
    279         arg = NULL;
    280     } else if (!PyExceptionInstance_Check(arg)) {
    281         PyErr_SetString(PyExc_TypeError, "exception cause must be None "
    282                         "or derive from BaseException");
    283         return -1;
    284     } else {
    285         /* PyException_SetCause steals this reference */
    286         Py_INCREF(arg);
    287     }
    288     PyException_SetCause(self, arg);
    289     return 0;
    290 }
    291 
    292 
    293 static PyGetSetDef BaseException_getset[] = {
    294     {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
    295     {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
    296     {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
    297     {"__context__", (getter)BaseException_get_context,
    298      (setter)BaseException_set_context, PyDoc_STR("exception context")},
    299     {"__cause__", (getter)BaseException_get_cause,
    300      (setter)BaseException_set_cause, PyDoc_STR("exception cause")},
    301     {NULL},
    302 };
    303 
    304 
    305 PyObject *
    306 PyException_GetTraceback(PyObject *self) {
    307     PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
    308     Py_XINCREF(base_self->traceback);
    309     return base_self->traceback;
    310 }
    311 
    312 
    313 int
    314 PyException_SetTraceback(PyObject *self, PyObject *tb) {
    315     return BaseException_set_tb((PyBaseExceptionObject *)self, tb);
    316 }
    317 
    318 PyObject *
    319 PyException_GetCause(PyObject *self) {
    320     PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
    321     Py_XINCREF(cause);
    322     return cause;
    323 }
    324 
    325 /* Steals a reference to cause */
    326 void
    327 PyException_SetCause(PyObject *self, PyObject *cause)
    328 {
    329     ((PyBaseExceptionObject *)self)->suppress_context = 1;
    330     Py_XSETREF(((PyBaseExceptionObject *)self)->cause, cause);
    331 }
    332 
    333 PyObject *
    334 PyException_GetContext(PyObject *self) {
    335     PyObject *context = ((PyBaseExceptionObject *)self)->context;
    336     Py_XINCREF(context);
    337     return context;
    338 }
    339 
    340 /* Steals a reference to context */
    341 void
    342 PyException_SetContext(PyObject *self, PyObject *context)
    343 {
    344     Py_XSETREF(((PyBaseExceptionObject *)self)->context, context);
    345 }
    346 
    347 
    348 static struct PyMemberDef BaseException_members[] = {
    349     {"__suppress_context__", T_BOOL,
    350      offsetof(PyBaseExceptionObject, suppress_context)},
    351     {NULL}
    352 };
    353 
    354 
    355 static PyTypeObject _PyExc_BaseException = {
    356     PyVarObject_HEAD_INIT(NULL, 0)
    357     "BaseException", /*tp_name*/
    358     sizeof(PyBaseExceptionObject), /*tp_basicsize*/
    359     0,                          /*tp_itemsize*/
    360     (destructor)BaseException_dealloc, /*tp_dealloc*/
    361     0,                          /*tp_print*/
    362     0,                          /*tp_getattr*/
    363     0,                          /*tp_setattr*/
    364     0,                          /* tp_reserved; */
    365     (reprfunc)BaseException_repr, /*tp_repr*/
    366     0,                          /*tp_as_number*/
    367     0,                          /*tp_as_sequence*/
    368     0,                          /*tp_as_mapping*/
    369     0,                          /*tp_hash */
    370     0,                          /*tp_call*/
    371     (reprfunc)BaseException_str,  /*tp_str*/
    372     PyObject_GenericGetAttr,    /*tp_getattro*/
    373     PyObject_GenericSetAttr,    /*tp_setattro*/
    374     0,                          /*tp_as_buffer*/
    375     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
    376         Py_TPFLAGS_BASE_EXC_SUBCLASS,  /*tp_flags*/
    377     PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
    378     (traverseproc)BaseException_traverse, /* tp_traverse */
    379     (inquiry)BaseException_clear, /* tp_clear */
    380     0,                          /* tp_richcompare */
    381     0,                          /* tp_weaklistoffset */
    382     0,                          /* tp_iter */
    383     0,                          /* tp_iternext */
    384     BaseException_methods,      /* tp_methods */
    385     BaseException_members,      /* tp_members */
    386     BaseException_getset,       /* tp_getset */
    387     0,                          /* tp_base */
    388     0,                          /* tp_dict */
    389     0,                          /* tp_descr_get */
    390     0,                          /* tp_descr_set */
    391     offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
    392     (initproc)BaseException_init, /* tp_init */
    393     0,                          /* tp_alloc */
    394     BaseException_new,          /* tp_new */
    395 };
    396 /* the CPython API expects exceptions to be (PyObject *) - both a hold-over
    397 from the previous implmentation and also allowing Python objects to be used
    398 in the API */
    399 PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
    400 
    401 /* note these macros omit the last semicolon so the macro invocation may
    402  * include it and not look strange.
    403  */
    404 #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
    405 static PyTypeObject _PyExc_ ## EXCNAME = { \
    406     PyVarObject_HEAD_INIT(NULL, 0) \
    407     # EXCNAME, \
    408     sizeof(PyBaseExceptionObject), \
    409     0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
    410     0, 0, 0, 0, 0, 0, 0, \
    411     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
    412     PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
    413     (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
    414     0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
    415     (initproc)BaseException_init, 0, BaseException_new,\
    416 }; \
    417 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
    418 
    419 #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
    420 static PyTypeObject _PyExc_ ## EXCNAME = { \
    421     PyVarObject_HEAD_INIT(NULL, 0) \
    422     # EXCNAME, \
    423     sizeof(Py ## EXCSTORE ## Object), \
    424     0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
    425     0, 0, 0, 0, 0, \
    426     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
    427     PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
    428     (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
    429     0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
    430     (initproc)EXCSTORE ## _init, 0, 0, \
    431 }; \
    432 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
    433 
    434 #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
    435                                 EXCMETHODS, EXCMEMBERS, EXCGETSET, \
    436                                 EXCSTR, EXCDOC) \
    437 static PyTypeObject _PyExc_ ## EXCNAME = { \
    438     PyVarObject_HEAD_INIT(NULL, 0) \
    439     # EXCNAME, \
    440     sizeof(Py ## EXCSTORE ## Object), 0, \
    441     (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
    442     (reprfunc)EXCSTR, 0, 0, 0, \
    443     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
    444     PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
    445     (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
    446     EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
    447     0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
    448     (initproc)EXCSTORE ## _init, 0, EXCNEW,\
    449 }; \
    450 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
    451 
    452 
    453 /*
    454  *    Exception extends BaseException
    455  */
    456 SimpleExtendsException(PyExc_BaseException, Exception,
    457                        "Common base class for all non-exit exceptions.");
    458 
    459 
    460 /*
    461  *    TypeError extends Exception
    462  */
    463 SimpleExtendsException(PyExc_Exception, TypeError,
    464                        "Inappropriate argument type.");
    465 
    466 
    467 /*
    468  *    StopAsyncIteration extends Exception
    469  */
    470 SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
    471                        "Signal the end from iterator.__anext__().");
    472 
    473 
    474 /*
    475  *    StopIteration extends Exception
    476  */
    477 
    478 static PyMemberDef StopIteration_members[] = {
    479     {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
    480         PyDoc_STR("generator return value")},
    481     {NULL}  /* Sentinel */
    482 };
    483 
    484 static int
    485 StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
    486 {
    487     Py_ssize_t size = PyTuple_GET_SIZE(args);
    488     PyObject *value;
    489 
    490     if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
    491         return -1;
    492     Py_CLEAR(self->value);
    493     if (size > 0)
    494         value = PyTuple_GET_ITEM(args, 0);
    495     else
    496         value = Py_None;
    497     Py_INCREF(value);
    498     self->value = value;
    499     return 0;
    500 }
    501 
    502 static int
    503 StopIteration_clear(PyStopIterationObject *self)
    504 {
    505     Py_CLEAR(self->value);
    506     return BaseException_clear((PyBaseExceptionObject *)self);
    507 }
    508 
    509 static void
    510 StopIteration_dealloc(PyStopIterationObject *self)
    511 {
    512     _PyObject_GC_UNTRACK(self);
    513     StopIteration_clear(self);
    514     Py_TYPE(self)->tp_free((PyObject *)self);
    515 }
    516 
    517 static int
    518 StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
    519 {
    520     Py_VISIT(self->value);
    521     return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
    522 }
    523 
    524 ComplexExtendsException(
    525     PyExc_Exception,       /* base */
    526     StopIteration,         /* name */
    527     StopIteration,         /* prefix for *_init, etc */
    528     0,                     /* new */
    529     0,                     /* methods */
    530     StopIteration_members, /* members */
    531     0,                     /* getset */
    532     0,                     /* str */
    533     "Signal the end from iterator.__next__()."
    534 );
    535 
    536 
    537 /*
    538  *    GeneratorExit extends BaseException
    539  */
    540 SimpleExtendsException(PyExc_BaseException, GeneratorExit,
    541                        "Request that a generator exit.");
    542 
    543 
    544 /*
    545  *    SystemExit extends BaseException
    546  */
    547 
    548 static int
    549 SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
    550 {
    551     Py_ssize_t size = PyTuple_GET_SIZE(args);
    552 
    553     if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
    554         return -1;
    555 
    556     if (size == 0)
    557         return 0;
    558     if (size == 1) {
    559         Py_INCREF(PyTuple_GET_ITEM(args, 0));
    560         Py_XSETREF(self->code, PyTuple_GET_ITEM(args, 0));
    561     }
    562     else { /* size > 1 */
    563         Py_INCREF(args);
    564         Py_XSETREF(self->code, args);
    565     }
    566     return 0;
    567 }
    568 
    569 static int
    570 SystemExit_clear(PySystemExitObject *self)
    571 {
    572     Py_CLEAR(self->code);
    573     return BaseException_clear((PyBaseExceptionObject *)self);
    574 }
    575 
    576 static void
    577 SystemExit_dealloc(PySystemExitObject *self)
    578 {
    579     _PyObject_GC_UNTRACK(self);
    580     SystemExit_clear(self);
    581     Py_TYPE(self)->tp_free((PyObject *)self);
    582 }
    583 
    584 static int
    585 SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
    586 {
    587     Py_VISIT(self->code);
    588     return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
    589 }
    590 
    591 static PyMemberDef SystemExit_members[] = {
    592     {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
    593         PyDoc_STR("exception code")},
    594     {NULL}  /* Sentinel */
    595 };
    596 
    597 ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
    598                         0, 0, SystemExit_members, 0, 0,
    599                         "Request to exit from the interpreter.");
    600 
    601 /*
    602  *    KeyboardInterrupt extends BaseException
    603  */
    604 SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
    605                        "Program interrupted by user.");
    606 
    607 
    608 /*
    609  *    ImportError extends Exception
    610  */
    611 
    612 static int
    613 ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
    614 {
    615     static char *kwlist[] = {"name", "path", 0};
    616     PyObject *empty_tuple;
    617     PyObject *msg = NULL;
    618     PyObject *name = NULL;
    619     PyObject *path = NULL;
    620 
    621     if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1)
    622         return -1;
    623 
    624     empty_tuple = PyTuple_New(0);
    625     if (!empty_tuple)
    626         return -1;
    627     if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OO:ImportError", kwlist,
    628                                      &name, &path)) {
    629         Py_DECREF(empty_tuple);
    630         return -1;
    631     }
    632     Py_DECREF(empty_tuple);
    633 
    634     if (name) {
    635         Py_INCREF(name);
    636         Py_XSETREF(self->name, name);
    637     }
    638     if (path) {
    639         Py_INCREF(path);
    640         Py_XSETREF(self->path, path);
    641     }
    642     if (PyTuple_GET_SIZE(args) == 1) {
    643         msg = PyTuple_GET_ITEM(args, 0);
    644         Py_INCREF(msg);
    645         Py_XSETREF(self->msg, msg);
    646     }
    647 
    648     return 0;
    649 }
    650 
    651 static int
    652 ImportError_clear(PyImportErrorObject *self)
    653 {
    654     Py_CLEAR(self->msg);
    655     Py_CLEAR(self->name);
    656     Py_CLEAR(self->path);
    657     return BaseException_clear((PyBaseExceptionObject *)self);
    658 }
    659 
    660 static void
    661 ImportError_dealloc(PyImportErrorObject *self)
    662 {
    663     _PyObject_GC_UNTRACK(self);
    664     ImportError_clear(self);
    665     Py_TYPE(self)->tp_free((PyObject *)self);
    666 }
    667 
    668 static int
    669 ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
    670 {
    671     Py_VISIT(self->msg);
    672     Py_VISIT(self->name);
    673     Py_VISIT(self->path);
    674     return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
    675 }
    676 
    677 static PyObject *
    678 ImportError_str(PyImportErrorObject *self)
    679 {
    680     if (self->msg && PyUnicode_CheckExact(self->msg)) {
    681         Py_INCREF(self->msg);
    682         return self->msg;
    683     }
    684     else {
    685         return BaseException_str((PyBaseExceptionObject *)self);
    686     }
    687 }
    688 
    689 static PyMemberDef ImportError_members[] = {
    690     {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
    691         PyDoc_STR("exception message")},
    692     {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
    693         PyDoc_STR("module name")},
    694     {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
    695         PyDoc_STR("module path")},
    696     {NULL}  /* Sentinel */
    697 };
    698 
    699 static PyMethodDef ImportError_methods[] = {
    700     {NULL}
    701 };
    702 
    703 ComplexExtendsException(PyExc_Exception, ImportError,
    704                         ImportError, 0 /* new */,
    705                         ImportError_methods, ImportError_members,
    706                         0 /* getset */, ImportError_str,
    707                         "Import can't find module, or can't find name in "
    708                         "module.");
    709 
    710 /*
    711  *    ModuleNotFoundError extends ImportError
    712  */
    713 
    714 MiddlingExtendsException(PyExc_ImportError, ModuleNotFoundError, ImportError,
    715                          "Module not found.");
    716 
    717 /*
    718  *    OSError extends Exception
    719  */
    720 
    721 #ifdef MS_WINDOWS
    722 #include "errmap.h"
    723 #endif
    724 
    725 /* Where a function has a single filename, such as open() or some
    726  * of the os module functions, PyErr_SetFromErrnoWithFilename() is
    727  * called, giving a third argument which is the filename.  But, so
    728  * that old code using in-place unpacking doesn't break, e.g.:
    729  *
    730  * except OSError, (errno, strerror):
    731  *
    732  * we hack args so that it only contains two items.  This also
    733  * means we need our own __str__() which prints out the filename
    734  * when it was supplied.
    735  *
    736  * (If a function has two filenames, such as rename(), symlink(),
    737  * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
    738  * which allows passing in a second filename.)
    739  */
    740 
    741 /* This function doesn't cleanup on error, the caller should */
    742 static int
    743 oserror_parse_args(PyObject **p_args,
    744                    PyObject **myerrno, PyObject **strerror,
    745                    PyObject **filename, PyObject **filename2
    746 #ifdef MS_WINDOWS
    747                    , PyObject **winerror
    748 #endif
    749                   )
    750 {
    751     Py_ssize_t nargs;
    752     PyObject *args = *p_args;
    753 #ifndef MS_WINDOWS
    754     /*
    755      * ignored on non-Windows platforms,
    756      * but parsed so OSError has a consistent signature
    757      */
    758     PyObject *_winerror = NULL;
    759     PyObject **winerror = &_winerror;
    760 #endif /* MS_WINDOWS */
    761 
    762     nargs = PyTuple_GET_SIZE(args);
    763 
    764     if (nargs >= 2 && nargs <= 5) {
    765         if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
    766                                myerrno, strerror,
    767                                filename, winerror, filename2))
    768             return -1;
    769 #ifdef MS_WINDOWS
    770         if (*winerror && PyLong_Check(*winerror)) {
    771             long errcode, winerrcode;
    772             PyObject *newargs;
    773             Py_ssize_t i;
    774 
    775             winerrcode = PyLong_AsLong(*winerror);
    776             if (winerrcode == -1 && PyErr_Occurred())
    777                 return -1;
    778             /* Set errno to the corresponding POSIX errno (overriding
    779                first argument).  Windows Socket error codes (>= 10000)
    780                have the same value as their POSIX counterparts.
    781             */
    782             if (winerrcode < 10000)
    783                 errcode = winerror_to_errno(winerrcode);
    784             else
    785                 errcode = winerrcode;
    786             *myerrno = PyLong_FromLong(errcode);
    787             if (!*myerrno)
    788                 return -1;
    789             newargs = PyTuple_New(nargs);
    790             if (!newargs)
    791                 return -1;
    792             PyTuple_SET_ITEM(newargs, 0, *myerrno);
    793             for (i = 1; i < nargs; i++) {
    794                 PyObject *val = PyTuple_GET_ITEM(args, i);
    795                 Py_INCREF(val);
    796                 PyTuple_SET_ITEM(newargs, i, val);
    797             }
    798             Py_DECREF(args);
    799             args = *p_args = newargs;
    800         }
    801 #endif /* MS_WINDOWS */
    802     }
    803 
    804     return 0;
    805 }
    806 
    807 static int
    808 oserror_init(PyOSErrorObject *self, PyObject **p_args,
    809              PyObject *myerrno, PyObject *strerror,
    810              PyObject *filename, PyObject *filename2
    811 #ifdef MS_WINDOWS
    812              , PyObject *winerror
    813 #endif
    814              )
    815 {
    816     PyObject *args = *p_args;
    817     Py_ssize_t nargs = PyTuple_GET_SIZE(args);
    818 
    819     /* self->filename will remain Py_None otherwise */
    820     if (filename && filename != Py_None) {
    821         if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
    822             PyNumber_Check(filename)) {
    823             /* BlockingIOError's 3rd argument can be the number of
    824              * characters written.
    825              */
    826             self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
    827             if (self->written == -1 && PyErr_Occurred())
    828                 return -1;
    829         }
    830         else {
    831             Py_INCREF(filename);
    832             self->filename = filename;
    833 
    834             if (filename2 && filename2 != Py_None) {
    835                 Py_INCREF(filename2);
    836                 self->filename2 = filename2;
    837             }
    838 
    839             if (nargs >= 2 && nargs <= 5) {
    840                 /* filename, filename2, and winerror are removed from the args tuple
    841                    (for compatibility purposes, see test_exceptions.py) */
    842                 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
    843                 if (!subslice)
    844                     return -1;
    845 
    846                 Py_DECREF(args);  /* replacing args */
    847                 *p_args = args = subslice;
    848             }
    849         }
    850     }
    851     Py_XINCREF(myerrno);
    852     self->myerrno = myerrno;
    853 
    854     Py_XINCREF(strerror);
    855     self->strerror = strerror;
    856 
    857 #ifdef MS_WINDOWS
    858     Py_XINCREF(winerror);
    859     self->winerror = winerror;
    860 #endif
    861 
    862     /* Steals the reference to args */
    863     Py_XSETREF(self->args, args);
    864     *p_args = args = NULL;
    865 
    866     return 0;
    867 }
    868 
    869 static PyObject *
    870 OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
    871 static int
    872 OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
    873 
    874 static int
    875 oserror_use_init(PyTypeObject *type)
    876 {
    877     /* When __init__ is defined in an OSError subclass, we want any
    878        extraneous argument to __new__ to be ignored.  The only reasonable
    879        solution, given __new__ takes a variable number of arguments,
    880        is to defer arg parsing and initialization to __init__.
    881 
    882        But when __new__ is overridden as well, it should call our __new__
    883        with the right arguments.
    884 
    885        (see http://bugs.python.org/issue12555#msg148829 )
    886     */
    887     if (type->tp_init != (initproc) OSError_init &&
    888         type->tp_new == (newfunc) OSError_new) {
    889         assert((PyObject *) type != PyExc_OSError);
    890         return 1;
    891     }
    892     return 0;
    893 }
    894 
    895 static PyObject *
    896 OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    897 {
    898     PyOSErrorObject *self = NULL;
    899     PyObject *myerrno = NULL, *strerror = NULL;
    900     PyObject *filename = NULL, *filename2 = NULL;
    901 #ifdef MS_WINDOWS
    902     PyObject *winerror = NULL;
    903 #endif
    904 
    905     Py_INCREF(args);
    906 
    907     if (!oserror_use_init(type)) {
    908         if (!_PyArg_NoKeywords(type->tp_name, kwds))
    909             goto error;
    910 
    911         if (oserror_parse_args(&args, &myerrno, &strerror,
    912                                &filename, &filename2
    913 #ifdef MS_WINDOWS
    914                                , &winerror
    915 #endif
    916             ))
    917             goto error;
    918 
    919         if (myerrno && PyLong_Check(myerrno) &&
    920             errnomap && (PyObject *) type == PyExc_OSError) {
    921             PyObject *newtype;
    922             newtype = PyDict_GetItem(errnomap, myerrno);
    923             if (newtype) {
    924                 assert(PyType_Check(newtype));
    925                 type = (PyTypeObject *) newtype;
    926             }
    927             else if (PyErr_Occurred())
    928                 goto error;
    929         }
    930     }
    931 
    932     self = (PyOSErrorObject *) type->tp_alloc(type, 0);
    933     if (!self)
    934         goto error;
    935 
    936     self->dict = NULL;
    937     self->traceback = self->cause = self->context = NULL;
    938     self->written = -1;
    939 
    940     if (!oserror_use_init(type)) {
    941         if (oserror_init(self, &args, myerrno, strerror, filename, filename2
    942 #ifdef MS_WINDOWS
    943                          , winerror
    944 #endif
    945             ))
    946             goto error;
    947     }
    948     else {
    949         self->args = PyTuple_New(0);
    950         if (self->args == NULL)
    951             goto error;
    952     }
    953 
    954     Py_XDECREF(args);
    955     return (PyObject *) self;
    956 
    957 error:
    958     Py_XDECREF(args);
    959     Py_XDECREF(self);
    960     return NULL;
    961 }
    962 
    963 static int
    964 OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
    965 {
    966     PyObject *myerrno = NULL, *strerror = NULL;
    967     PyObject *filename = NULL, *filename2 = NULL;
    968 #ifdef MS_WINDOWS
    969     PyObject *winerror = NULL;
    970 #endif
    971 
    972     if (!oserror_use_init(Py_TYPE(self)))
    973         /* Everything already done in OSError_new */
    974         return 0;
    975 
    976     if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
    977         return -1;
    978 
    979     Py_INCREF(args);
    980     if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
    981 #ifdef MS_WINDOWS
    982                            , &winerror
    983 #endif
    984         ))
    985         goto error;
    986 
    987     if (oserror_init(self, &args, myerrno, strerror, filename, filename2
    988 #ifdef MS_WINDOWS
    989                      , winerror
    990 #endif
    991         ))
    992         goto error;
    993 
    994     return 0;
    995 
    996 error:
    997     Py_DECREF(args);
    998     return -1;
    999 }
   1000 
   1001 static int
   1002 OSError_clear(PyOSErrorObject *self)
   1003 {
   1004     Py_CLEAR(self->myerrno);
   1005     Py_CLEAR(self->strerror);
   1006     Py_CLEAR(self->filename);
   1007     Py_CLEAR(self->filename2);
   1008 #ifdef MS_WINDOWS
   1009     Py_CLEAR(self->winerror);
   1010 #endif
   1011     return BaseException_clear((PyBaseExceptionObject *)self);
   1012 }
   1013 
   1014 static void
   1015 OSError_dealloc(PyOSErrorObject *self)
   1016 {
   1017     _PyObject_GC_UNTRACK(self);
   1018     OSError_clear(self);
   1019     Py_TYPE(self)->tp_free((PyObject *)self);
   1020 }
   1021 
   1022 static int
   1023 OSError_traverse(PyOSErrorObject *self, visitproc visit,
   1024         void *arg)
   1025 {
   1026     Py_VISIT(self->myerrno);
   1027     Py_VISIT(self->strerror);
   1028     Py_VISIT(self->filename);
   1029     Py_VISIT(self->filename2);
   1030 #ifdef MS_WINDOWS
   1031     Py_VISIT(self->winerror);
   1032 #endif
   1033     return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
   1034 }
   1035 
   1036 static PyObject *
   1037 OSError_str(PyOSErrorObject *self)
   1038 {
   1039 #define OR_NONE(x) ((x)?(x):Py_None)
   1040 #ifdef MS_WINDOWS
   1041     /* If available, winerror has the priority over myerrno */
   1042     if (self->winerror && self->filename) {
   1043         if (self->filename2) {
   1044             return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
   1045                                         OR_NONE(self->winerror),
   1046                                         OR_NONE(self->strerror),
   1047                                         self->filename,
   1048                                         self->filename2);
   1049         } else {
   1050             return PyUnicode_FromFormat("[WinError %S] %S: %R",
   1051                                         OR_NONE(self->winerror),
   1052                                         OR_NONE(self->strerror),
   1053                                         self->filename);
   1054         }
   1055     }
   1056     if (self->winerror && self->strerror)
   1057         return PyUnicode_FromFormat("[WinError %S] %S",
   1058                                     self->winerror ? self->winerror: Py_None,
   1059                                     self->strerror ? self->strerror: Py_None);
   1060 #endif
   1061     if (self->filename) {
   1062         if (self->filename2) {
   1063             return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
   1064                                         OR_NONE(self->myerrno),
   1065                                         OR_NONE(self->strerror),
   1066                                         self->filename,
   1067                                         self->filename2);
   1068         } else {
   1069             return PyUnicode_FromFormat("[Errno %S] %S: %R",
   1070                                         OR_NONE(self->myerrno),
   1071                                         OR_NONE(self->strerror),
   1072                                         self->filename);
   1073         }
   1074     }
   1075     if (self->myerrno && self->strerror)
   1076         return PyUnicode_FromFormat("[Errno %S] %S",
   1077                                     self->myerrno, self->strerror);
   1078     return BaseException_str((PyBaseExceptionObject *)self);
   1079 }
   1080 
   1081 static PyObject *
   1082 OSError_reduce(PyOSErrorObject *self)
   1083 {
   1084     PyObject *args = self->args;
   1085     PyObject *res = NULL, *tmp;
   1086 
   1087     /* self->args is only the first two real arguments if there was a
   1088      * file name given to OSError. */
   1089     if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
   1090         Py_ssize_t size = self->filename2 ? 5 : 3;
   1091         args = PyTuple_New(size);
   1092         if (!args)
   1093             return NULL;
   1094 
   1095         tmp = PyTuple_GET_ITEM(self->args, 0);
   1096         Py_INCREF(tmp);
   1097         PyTuple_SET_ITEM(args, 0, tmp);
   1098 
   1099         tmp = PyTuple_GET_ITEM(self->args, 1);
   1100         Py_INCREF(tmp);
   1101         PyTuple_SET_ITEM(args, 1, tmp);
   1102 
   1103         Py_INCREF(self->filename);
   1104         PyTuple_SET_ITEM(args, 2, self->filename);
   1105 
   1106         if (self->filename2) {
   1107             /*
   1108              * This tuple is essentially used as OSError(*args).
   1109              * So, to recreate filename2, we need to pass in
   1110              * winerror as well.
   1111              */
   1112             Py_INCREF(Py_None);
   1113             PyTuple_SET_ITEM(args, 3, Py_None);
   1114 
   1115             /* filename2 */
   1116             Py_INCREF(self->filename2);
   1117             PyTuple_SET_ITEM(args, 4, self->filename2);
   1118         }
   1119     } else
   1120         Py_INCREF(args);
   1121 
   1122     if (self->dict)
   1123         res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
   1124     else
   1125         res = PyTuple_Pack(2, Py_TYPE(self), args);
   1126     Py_DECREF(args);
   1127     return res;
   1128 }
   1129 
   1130 static PyObject *
   1131 OSError_written_get(PyOSErrorObject *self, void *context)
   1132 {
   1133     if (self->written == -1) {
   1134         PyErr_SetString(PyExc_AttributeError, "characters_written");
   1135         return NULL;
   1136     }
   1137     return PyLong_FromSsize_t(self->written);
   1138 }
   1139 
   1140 static int
   1141 OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
   1142 {
   1143     Py_ssize_t n;
   1144     n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
   1145     if (n == -1 && PyErr_Occurred())
   1146         return -1;
   1147     self->written = n;
   1148     return 0;
   1149 }
   1150 
   1151 static PyMemberDef OSError_members[] = {
   1152     {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
   1153         PyDoc_STR("POSIX exception code")},
   1154     {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
   1155         PyDoc_STR("exception strerror")},
   1156     {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
   1157         PyDoc_STR("exception filename")},
   1158     {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
   1159         PyDoc_STR("second exception filename")},
   1160 #ifdef MS_WINDOWS
   1161     {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
   1162         PyDoc_STR("Win32 exception code")},
   1163 #endif
   1164     {NULL}  /* Sentinel */
   1165 };
   1166 
   1167 static PyMethodDef OSError_methods[] = {
   1168     {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
   1169     {NULL}
   1170 };
   1171 
   1172 static PyGetSetDef OSError_getset[] = {
   1173     {"characters_written", (getter) OSError_written_get,
   1174                            (setter) OSError_written_set, NULL},
   1175     {NULL}
   1176 };
   1177 
   1178 
   1179 ComplexExtendsException(PyExc_Exception, OSError,
   1180                         OSError, OSError_new,
   1181                         OSError_methods, OSError_members, OSError_getset,
   1182                         OSError_str,
   1183                         "Base class for I/O related errors.");
   1184 
   1185 
   1186 /*
   1187  *    Various OSError subclasses
   1188  */
   1189 MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
   1190                          "I/O operation would block.");
   1191 MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
   1192                          "Connection error.");
   1193 MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
   1194                          "Child process error.");
   1195 MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
   1196                          "Broken pipe.");
   1197 MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
   1198                          "Connection aborted.");
   1199 MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
   1200                          "Connection refused.");
   1201 MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
   1202                          "Connection reset.");
   1203 MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
   1204                          "File already exists.");
   1205 MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
   1206                          "File not found.");
   1207 MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
   1208                          "Operation doesn't work on directories.");
   1209 MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
   1210                          "Operation only works on directories.");
   1211 MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
   1212                          "Interrupted by signal.");
   1213 MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
   1214                          "Not enough permissions.");
   1215 MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
   1216                          "Process not found.");
   1217 MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
   1218                          "Timeout expired.");
   1219 
   1220 /*
   1221  *    EOFError extends Exception
   1222  */
   1223 SimpleExtendsException(PyExc_Exception, EOFError,
   1224                        "Read beyond end of file.");
   1225 
   1226 
   1227 /*
   1228  *    RuntimeError extends Exception
   1229  */
   1230 SimpleExtendsException(PyExc_Exception, RuntimeError,
   1231                        "Unspecified run-time error.");
   1232 
   1233 /*
   1234  *    RecursionError extends RuntimeError
   1235  */
   1236 SimpleExtendsException(PyExc_RuntimeError, RecursionError,
   1237                        "Recursion limit exceeded.");
   1238 
   1239 /*
   1240  *    NotImplementedError extends RuntimeError
   1241  */
   1242 SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
   1243                        "Method or function hasn't been implemented yet.");
   1244 
   1245 /*
   1246  *    NameError extends Exception
   1247  */
   1248 SimpleExtendsException(PyExc_Exception, NameError,
   1249                        "Name not found globally.");
   1250 
   1251 /*
   1252  *    UnboundLocalError extends NameError
   1253  */
   1254 SimpleExtendsException(PyExc_NameError, UnboundLocalError,
   1255                        "Local name referenced but not bound to a value.");
   1256 
   1257 /*
   1258  *    AttributeError extends Exception
   1259  */
   1260 SimpleExtendsException(PyExc_Exception, AttributeError,
   1261                        "Attribute not found.");
   1262 
   1263 
   1264 /*
   1265  *    SyntaxError extends Exception
   1266  */
   1267 
   1268 /* Helper function to customize error message for some syntax errors */
   1269 static int _report_missing_parentheses(PySyntaxErrorObject *self);
   1270 
   1271 static int
   1272 SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
   1273 {
   1274     PyObject *info = NULL;
   1275     Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
   1276 
   1277     if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
   1278         return -1;
   1279 
   1280     if (lenargs >= 1) {
   1281         Py_INCREF(PyTuple_GET_ITEM(args, 0));
   1282         Py_XSETREF(self->msg, PyTuple_GET_ITEM(args, 0));
   1283     }
   1284     if (lenargs == 2) {
   1285         info = PyTuple_GET_ITEM(args, 1);
   1286         info = PySequence_Tuple(info);
   1287         if (!info)
   1288             return -1;
   1289 
   1290         if (PyTuple_GET_SIZE(info) != 4) {
   1291             /* not a very good error message, but it's what Python 2.4 gives */
   1292             PyErr_SetString(PyExc_IndexError, "tuple index out of range");
   1293             Py_DECREF(info);
   1294             return -1;
   1295         }
   1296 
   1297         Py_INCREF(PyTuple_GET_ITEM(info, 0));
   1298         Py_XSETREF(self->filename, PyTuple_GET_ITEM(info, 0));
   1299 
   1300         Py_INCREF(PyTuple_GET_ITEM(info, 1));
   1301         Py_XSETREF(self->lineno, PyTuple_GET_ITEM(info, 1));
   1302 
   1303         Py_INCREF(PyTuple_GET_ITEM(info, 2));
   1304         Py_XSETREF(self->offset, PyTuple_GET_ITEM(info, 2));
   1305 
   1306         Py_INCREF(PyTuple_GET_ITEM(info, 3));
   1307         Py_XSETREF(self->text, PyTuple_GET_ITEM(info, 3));
   1308 
   1309         Py_DECREF(info);
   1310 
   1311         /* Issue #21669: Custom error for 'print' & 'exec' as statements */
   1312         if (self->text && PyUnicode_Check(self->text)) {
   1313             if (_report_missing_parentheses(self) < 0) {
   1314                 return -1;
   1315             }
   1316         }
   1317     }
   1318     return 0;
   1319 }
   1320 
   1321 static int
   1322 SyntaxError_clear(PySyntaxErrorObject *self)
   1323 {
   1324     Py_CLEAR(self->msg);
   1325     Py_CLEAR(self->filename);
   1326     Py_CLEAR(self->lineno);
   1327     Py_CLEAR(self->offset);
   1328     Py_CLEAR(self->text);
   1329     Py_CLEAR(self->print_file_and_line);
   1330     return BaseException_clear((PyBaseExceptionObject *)self);
   1331 }
   1332 
   1333 static void
   1334 SyntaxError_dealloc(PySyntaxErrorObject *self)
   1335 {
   1336     _PyObject_GC_UNTRACK(self);
   1337     SyntaxError_clear(self);
   1338     Py_TYPE(self)->tp_free((PyObject *)self);
   1339 }
   1340 
   1341 static int
   1342 SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
   1343 {
   1344     Py_VISIT(self->msg);
   1345     Py_VISIT(self->filename);
   1346     Py_VISIT(self->lineno);
   1347     Py_VISIT(self->offset);
   1348     Py_VISIT(self->text);
   1349     Py_VISIT(self->print_file_and_line);
   1350     return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
   1351 }
   1352 
   1353 /* This is called "my_basename" instead of just "basename" to avoid name
   1354    conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
   1355    defined, and Python does define that. */
   1356 static PyObject*
   1357 my_basename(PyObject *name)
   1358 {
   1359     Py_ssize_t i, size, offset;
   1360     int kind;
   1361     void *data;
   1362 
   1363     if (PyUnicode_READY(name))
   1364         return NULL;
   1365     kind = PyUnicode_KIND(name);
   1366     data = PyUnicode_DATA(name);
   1367     size = PyUnicode_GET_LENGTH(name);
   1368     offset = 0;
   1369     for(i=0; i < size; i++) {
   1370         if (PyUnicode_READ(kind, data, i) == SEP)
   1371             offset = i + 1;
   1372     }
   1373     if (offset != 0)
   1374         return PyUnicode_Substring(name, offset, size);
   1375     else {
   1376         Py_INCREF(name);
   1377         return name;
   1378     }
   1379 }
   1380 
   1381 
   1382 static PyObject *
   1383 SyntaxError_str(PySyntaxErrorObject *self)
   1384 {
   1385     int have_lineno = 0;
   1386     PyObject *filename;
   1387     PyObject *result;
   1388     /* Below, we always ignore overflow errors, just printing -1.
   1389        Still, we cannot allow an OverflowError to be raised, so
   1390        we need to call PyLong_AsLongAndOverflow. */
   1391     int overflow;
   1392 
   1393     /* XXX -- do all the additional formatting with filename and
   1394        lineno here */
   1395 
   1396     if (self->filename && PyUnicode_Check(self->filename)) {
   1397         filename = my_basename(self->filename);
   1398         if (filename == NULL)
   1399             return NULL;
   1400     } else {
   1401         filename = NULL;
   1402     }
   1403     have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
   1404 
   1405     if (!filename && !have_lineno)
   1406         return PyObject_Str(self->msg ? self->msg : Py_None);
   1407 
   1408     if (filename && have_lineno)
   1409         result = PyUnicode_FromFormat("%S (%U, line %ld)",
   1410                    self->msg ? self->msg : Py_None,
   1411                    filename,
   1412                    PyLong_AsLongAndOverflow(self->lineno, &overflow));
   1413     else if (filename)
   1414         result = PyUnicode_FromFormat("%S (%U)",
   1415                    self->msg ? self->msg : Py_None,
   1416                    filename);
   1417     else /* only have_lineno */
   1418         result = PyUnicode_FromFormat("%S (line %ld)",
   1419                    self->msg ? self->msg : Py_None,
   1420                    PyLong_AsLongAndOverflow(self->lineno, &overflow));
   1421     Py_XDECREF(filename);
   1422     return result;
   1423 }
   1424 
   1425 static PyMemberDef SyntaxError_members[] = {
   1426     {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
   1427         PyDoc_STR("exception msg")},
   1428     {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
   1429         PyDoc_STR("exception filename")},
   1430     {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
   1431         PyDoc_STR("exception lineno")},
   1432     {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
   1433         PyDoc_STR("exception offset")},
   1434     {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
   1435         PyDoc_STR("exception text")},
   1436     {"print_file_and_line", T_OBJECT,
   1437         offsetof(PySyntaxErrorObject, print_file_and_line), 0,
   1438         PyDoc_STR("exception print_file_and_line")},
   1439     {NULL}  /* Sentinel */
   1440 };
   1441 
   1442 ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
   1443                         0, 0, SyntaxError_members, 0,
   1444                         SyntaxError_str, "Invalid syntax.");
   1445 
   1446 
   1447 /*
   1448  *    IndentationError extends SyntaxError
   1449  */
   1450 MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
   1451                          "Improper indentation.");
   1452 
   1453 
   1454 /*
   1455  *    TabError extends IndentationError
   1456  */
   1457 MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
   1458                          "Improper mixture of spaces and tabs.");
   1459 
   1460 
   1461 /*
   1462  *    LookupError extends Exception
   1463  */
   1464 SimpleExtendsException(PyExc_Exception, LookupError,
   1465                        "Base class for lookup errors.");
   1466 
   1467 
   1468 /*
   1469  *    IndexError extends LookupError
   1470  */
   1471 SimpleExtendsException(PyExc_LookupError, IndexError,
   1472                        "Sequence index out of range.");
   1473 
   1474 
   1475 /*
   1476  *    KeyError extends LookupError
   1477  */
   1478 static PyObject *
   1479 KeyError_str(PyBaseExceptionObject *self)
   1480 {
   1481     /* If args is a tuple of exactly one item, apply repr to args[0].
   1482        This is done so that e.g. the exception raised by {}[''] prints
   1483          KeyError: ''
   1484        rather than the confusing
   1485          KeyError
   1486        alone.  The downside is that if KeyError is raised with an explanatory
   1487        string, that string will be displayed in quotes.  Too bad.
   1488        If args is anything else, use the default BaseException__str__().
   1489     */
   1490     if (PyTuple_GET_SIZE(self->args) == 1) {
   1491         return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
   1492     }
   1493     return BaseException_str(self);
   1494 }
   1495 
   1496 ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
   1497                         0, 0, 0, 0, KeyError_str, "Mapping key not found.");
   1498 
   1499 
   1500 /*
   1501  *    ValueError extends Exception
   1502  */
   1503 SimpleExtendsException(PyExc_Exception, ValueError,
   1504                        "Inappropriate argument value (of correct type).");
   1505 
   1506 /*
   1507  *    UnicodeError extends ValueError
   1508  */
   1509 
   1510 SimpleExtendsException(PyExc_ValueError, UnicodeError,
   1511                        "Unicode related error.");
   1512 
   1513 static PyObject *
   1514 get_string(PyObject *attr, const char *name)
   1515 {
   1516     if (!attr) {
   1517         PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
   1518         return NULL;
   1519     }
   1520 
   1521     if (!PyBytes_Check(attr)) {
   1522         PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
   1523         return NULL;
   1524     }
   1525     Py_INCREF(attr);
   1526     return attr;
   1527 }
   1528 
   1529 static PyObject *
   1530 get_unicode(PyObject *attr, const char *name)
   1531 {
   1532     if (!attr) {
   1533         PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
   1534         return NULL;
   1535     }
   1536 
   1537     if (!PyUnicode_Check(attr)) {
   1538         PyErr_Format(PyExc_TypeError,
   1539                      "%.200s attribute must be unicode", name);
   1540         return NULL;
   1541     }
   1542     Py_INCREF(attr);
   1543     return attr;
   1544 }
   1545 
   1546 static int
   1547 set_unicodefromstring(PyObject **attr, const char *value)
   1548 {
   1549     PyObject *obj = PyUnicode_FromString(value);
   1550     if (!obj)
   1551         return -1;
   1552     Py_XSETREF(*attr, obj);
   1553     return 0;
   1554 }
   1555 
   1556 PyObject *
   1557 PyUnicodeEncodeError_GetEncoding(PyObject *exc)
   1558 {
   1559     return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
   1560 }
   1561 
   1562 PyObject *
   1563 PyUnicodeDecodeError_GetEncoding(PyObject *exc)
   1564 {
   1565     return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
   1566 }
   1567 
   1568 PyObject *
   1569 PyUnicodeEncodeError_GetObject(PyObject *exc)
   1570 {
   1571     return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
   1572 }
   1573 
   1574 PyObject *
   1575 PyUnicodeDecodeError_GetObject(PyObject *exc)
   1576 {
   1577     return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
   1578 }
   1579 
   1580 PyObject *
   1581 PyUnicodeTranslateError_GetObject(PyObject *exc)
   1582 {
   1583     return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
   1584 }
   1585 
   1586 int
   1587 PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
   1588 {
   1589     Py_ssize_t size;
   1590     PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
   1591                                 "object");
   1592     if (!obj)
   1593         return -1;
   1594     *start = ((PyUnicodeErrorObject *)exc)->start;
   1595     size = PyUnicode_GET_LENGTH(obj);
   1596     if (*start<0)
   1597         *start = 0; /*XXX check for values <0*/
   1598     if (*start>=size)
   1599         *start = size-1;
   1600     Py_DECREF(obj);
   1601     return 0;
   1602 }
   1603 
   1604 
   1605 int
   1606 PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
   1607 {
   1608     Py_ssize_t size;
   1609     PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
   1610     if (!obj)
   1611         return -1;
   1612     size = PyBytes_GET_SIZE(obj);
   1613     *start = ((PyUnicodeErrorObject *)exc)->start;
   1614     if (*start<0)
   1615         *start = 0;
   1616     if (*start>=size)
   1617         *start = size-1;
   1618     Py_DECREF(obj);
   1619     return 0;
   1620 }
   1621 
   1622 
   1623 int
   1624 PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
   1625 {
   1626     return PyUnicodeEncodeError_GetStart(exc, start);
   1627 }
   1628 
   1629 
   1630 int
   1631 PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
   1632 {
   1633     ((PyUnicodeErrorObject *)exc)->start = start;
   1634     return 0;
   1635 }
   1636 
   1637 
   1638 int
   1639 PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
   1640 {
   1641     ((PyUnicodeErrorObject *)exc)->start = start;
   1642     return 0;
   1643 }
   1644 
   1645 
   1646 int
   1647 PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
   1648 {
   1649     ((PyUnicodeErrorObject *)exc)->start = start;
   1650     return 0;
   1651 }
   1652 
   1653 
   1654 int
   1655 PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
   1656 {
   1657     Py_ssize_t size;
   1658     PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
   1659                                 "object");
   1660     if (!obj)
   1661         return -1;
   1662     *end = ((PyUnicodeErrorObject *)exc)->end;
   1663     size = PyUnicode_GET_LENGTH(obj);
   1664     if (*end<1)
   1665         *end = 1;
   1666     if (*end>size)
   1667         *end = size;
   1668     Py_DECREF(obj);
   1669     return 0;
   1670 }
   1671 
   1672 
   1673 int
   1674 PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
   1675 {
   1676     Py_ssize_t size;
   1677     PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
   1678     if (!obj)
   1679         return -1;
   1680     size = PyBytes_GET_SIZE(obj);
   1681     *end = ((PyUnicodeErrorObject *)exc)->end;
   1682     if (*end<1)
   1683         *end = 1;
   1684     if (*end>size)
   1685         *end = size;
   1686     Py_DECREF(obj);
   1687     return 0;
   1688 }
   1689 
   1690 
   1691 int
   1692 PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
   1693 {
   1694     return PyUnicodeEncodeError_GetEnd(exc, start);
   1695 }
   1696 
   1697 
   1698 int
   1699 PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
   1700 {
   1701     ((PyUnicodeErrorObject *)exc)->end = end;
   1702     return 0;
   1703 }
   1704 
   1705 
   1706 int
   1707 PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
   1708 {
   1709     ((PyUnicodeErrorObject *)exc)->end = end;
   1710     return 0;
   1711 }
   1712 
   1713 
   1714 int
   1715 PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
   1716 {
   1717     ((PyUnicodeErrorObject *)exc)->end = end;
   1718     return 0;
   1719 }
   1720 
   1721 PyObject *
   1722 PyUnicodeEncodeError_GetReason(PyObject *exc)
   1723 {
   1724     return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
   1725 }
   1726 
   1727 
   1728 PyObject *
   1729 PyUnicodeDecodeError_GetReason(PyObject *exc)
   1730 {
   1731     return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
   1732 }
   1733 
   1734 
   1735 PyObject *
   1736 PyUnicodeTranslateError_GetReason(PyObject *exc)
   1737 {
   1738     return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
   1739 }
   1740 
   1741 
   1742 int
   1743 PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
   1744 {
   1745     return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
   1746                                  reason);
   1747 }
   1748 
   1749 
   1750 int
   1751 PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
   1752 {
   1753     return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
   1754                                  reason);
   1755 }
   1756 
   1757 
   1758 int
   1759 PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
   1760 {
   1761     return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
   1762                                  reason);
   1763 }
   1764 
   1765 
   1766 static int
   1767 UnicodeError_clear(PyUnicodeErrorObject *self)
   1768 {
   1769     Py_CLEAR(self->encoding);
   1770     Py_CLEAR(self->object);
   1771     Py_CLEAR(self->reason);
   1772     return BaseException_clear((PyBaseExceptionObject *)self);
   1773 }
   1774 
   1775 static void
   1776 UnicodeError_dealloc(PyUnicodeErrorObject *self)
   1777 {
   1778     _PyObject_GC_UNTRACK(self);
   1779     UnicodeError_clear(self);
   1780     Py_TYPE(self)->tp_free((PyObject *)self);
   1781 }
   1782 
   1783 static int
   1784 UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
   1785 {
   1786     Py_VISIT(self->encoding);
   1787     Py_VISIT(self->object);
   1788     Py_VISIT(self->reason);
   1789     return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
   1790 }
   1791 
   1792 static PyMemberDef UnicodeError_members[] = {
   1793     {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
   1794         PyDoc_STR("exception encoding")},
   1795     {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
   1796         PyDoc_STR("exception object")},
   1797     {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
   1798         PyDoc_STR("exception start")},
   1799     {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
   1800         PyDoc_STR("exception end")},
   1801     {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
   1802         PyDoc_STR("exception reason")},
   1803     {NULL}  /* Sentinel */
   1804 };
   1805 
   1806 
   1807 /*
   1808  *    UnicodeEncodeError extends UnicodeError
   1809  */
   1810 
   1811 static int
   1812 UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
   1813 {
   1814     PyUnicodeErrorObject *err;
   1815 
   1816     if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
   1817         return -1;
   1818 
   1819     err = (PyUnicodeErrorObject *)self;
   1820 
   1821     Py_CLEAR(err->encoding);
   1822     Py_CLEAR(err->object);
   1823     Py_CLEAR(err->reason);
   1824 
   1825     if (!PyArg_ParseTuple(args, "O!O!nnO!",
   1826         &PyUnicode_Type, &err->encoding,
   1827         &PyUnicode_Type, &err->object,
   1828         &err->start,
   1829         &err->end,
   1830         &PyUnicode_Type, &err->reason)) {
   1831           err->encoding = err->object = err->reason = NULL;
   1832           return -1;
   1833     }
   1834 
   1835     if (PyUnicode_READY(err->object) < -1) {
   1836         err->encoding = NULL;
   1837         return -1;
   1838     }
   1839 
   1840     Py_INCREF(err->encoding);
   1841     Py_INCREF(err->object);
   1842     Py_INCREF(err->reason);
   1843 
   1844     return 0;
   1845 }
   1846 
   1847 static PyObject *
   1848 UnicodeEncodeError_str(PyObject *self)
   1849 {
   1850     PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
   1851     PyObject *result = NULL;
   1852     PyObject *reason_str = NULL;
   1853     PyObject *encoding_str = NULL;
   1854 
   1855     if (!uself->object)
   1856         /* Not properly initialized. */
   1857         return PyUnicode_FromString("");
   1858 
   1859     /* Get reason and encoding as strings, which they might not be if
   1860        they've been modified after we were constructed. */
   1861     reason_str = PyObject_Str(uself->reason);
   1862     if (reason_str == NULL)
   1863         goto done;
   1864     encoding_str = PyObject_Str(uself->encoding);
   1865     if (encoding_str == NULL)
   1866         goto done;
   1867 
   1868     if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
   1869         Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
   1870         const char *fmt;
   1871         if (badchar <= 0xff)
   1872             fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
   1873         else if (badchar <= 0xffff)
   1874             fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
   1875         else
   1876             fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
   1877         result = PyUnicode_FromFormat(
   1878             fmt,
   1879             encoding_str,
   1880             (int)badchar,
   1881             uself->start,
   1882             reason_str);
   1883     }
   1884     else {
   1885         result = PyUnicode_FromFormat(
   1886             "'%U' codec can't encode characters in position %zd-%zd: %U",
   1887             encoding_str,
   1888             uself->start,
   1889             uself->end-1,
   1890             reason_str);
   1891     }
   1892 done:
   1893     Py_XDECREF(reason_str);
   1894     Py_XDECREF(encoding_str);
   1895     return result;
   1896 }
   1897 
   1898 static PyTypeObject _PyExc_UnicodeEncodeError = {
   1899     PyVarObject_HEAD_INIT(NULL, 0)
   1900     "UnicodeEncodeError",
   1901     sizeof(PyUnicodeErrorObject), 0,
   1902     (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   1903     (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
   1904     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
   1905     PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
   1906     (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
   1907     0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
   1908     (initproc)UnicodeEncodeError_init, 0, BaseException_new,
   1909 };
   1910 PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
   1911 
   1912 PyObject *
   1913 PyUnicodeEncodeError_Create(
   1914     const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
   1915     Py_ssize_t start, Py_ssize_t end, const char *reason)
   1916 {
   1917     return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
   1918                                  encoding, object, length, start, end, reason);
   1919 }
   1920 
   1921 
   1922 /*
   1923  *    UnicodeDecodeError extends UnicodeError
   1924  */
   1925 
   1926 static int
   1927 UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
   1928 {
   1929     PyUnicodeErrorObject *ude;
   1930 
   1931     if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
   1932         return -1;
   1933 
   1934     ude = (PyUnicodeErrorObject *)self;
   1935 
   1936     Py_CLEAR(ude->encoding);
   1937     Py_CLEAR(ude->object);
   1938     Py_CLEAR(ude->reason);
   1939 
   1940     if (!PyArg_ParseTuple(args, "O!OnnO!",
   1941          &PyUnicode_Type, &ude->encoding,
   1942          &ude->object,
   1943          &ude->start,
   1944          &ude->end,
   1945          &PyUnicode_Type, &ude->reason)) {
   1946              ude->encoding = ude->object = ude->reason = NULL;
   1947              return -1;
   1948     }
   1949 
   1950     Py_INCREF(ude->encoding);
   1951     Py_INCREF(ude->object);
   1952     Py_INCREF(ude->reason);
   1953 
   1954     if (!PyBytes_Check(ude->object)) {
   1955         Py_buffer view;
   1956         if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
   1957             goto error;
   1958         Py_XSETREF(ude->object, PyBytes_FromStringAndSize(view.buf, view.len));
   1959         PyBuffer_Release(&view);
   1960         if (!ude->object)
   1961             goto error;
   1962     }
   1963     return 0;
   1964 
   1965 error:
   1966     Py_CLEAR(ude->encoding);
   1967     Py_CLEAR(ude->object);
   1968     Py_CLEAR(ude->reason);
   1969     return -1;
   1970 }
   1971 
   1972 static PyObject *
   1973 UnicodeDecodeError_str(PyObject *self)
   1974 {
   1975     PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
   1976     PyObject *result = NULL;
   1977     PyObject *reason_str = NULL;
   1978     PyObject *encoding_str = NULL;
   1979 
   1980     if (!uself->object)
   1981         /* Not properly initialized. */
   1982         return PyUnicode_FromString("");
   1983 
   1984     /* Get reason and encoding as strings, which they might not be if
   1985        they've been modified after we were constructed. */
   1986     reason_str = PyObject_Str(uself->reason);
   1987     if (reason_str == NULL)
   1988         goto done;
   1989     encoding_str = PyObject_Str(uself->encoding);
   1990     if (encoding_str == NULL)
   1991         goto done;
   1992 
   1993     if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
   1994         int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
   1995         result = PyUnicode_FromFormat(
   1996             "'%U' codec can't decode byte 0x%02x in position %zd: %U",
   1997             encoding_str,
   1998             byte,
   1999             uself->start,
   2000             reason_str);
   2001     }
   2002     else {
   2003         result = PyUnicode_FromFormat(
   2004             "'%U' codec can't decode bytes in position %zd-%zd: %U",
   2005             encoding_str,
   2006             uself->start,
   2007             uself->end-1,
   2008             reason_str
   2009             );
   2010     }
   2011 done:
   2012     Py_XDECREF(reason_str);
   2013     Py_XDECREF(encoding_str);
   2014     return result;
   2015 }
   2016 
   2017 static PyTypeObject _PyExc_UnicodeDecodeError = {
   2018     PyVarObject_HEAD_INIT(NULL, 0)
   2019     "UnicodeDecodeError",
   2020     sizeof(PyUnicodeErrorObject), 0,
   2021     (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   2022     (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
   2023     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
   2024     PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
   2025     (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
   2026     0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
   2027     (initproc)UnicodeDecodeError_init, 0, BaseException_new,
   2028 };
   2029 PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
   2030 
   2031 PyObject *
   2032 PyUnicodeDecodeError_Create(
   2033     const char *encoding, const char *object, Py_ssize_t length,
   2034     Py_ssize_t start, Py_ssize_t end, const char *reason)
   2035 {
   2036     return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
   2037                                  encoding, object, length, start, end, reason);
   2038 }
   2039 
   2040 
   2041 /*
   2042  *    UnicodeTranslateError extends UnicodeError
   2043  */
   2044 
   2045 static int
   2046 UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
   2047                            PyObject *kwds)
   2048 {
   2049     if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
   2050         return -1;
   2051 
   2052     Py_CLEAR(self->object);
   2053     Py_CLEAR(self->reason);
   2054 
   2055     if (!PyArg_ParseTuple(args, "O!nnO!",
   2056         &PyUnicode_Type, &self->object,
   2057         &self->start,
   2058         &self->end,
   2059         &PyUnicode_Type, &self->reason)) {
   2060         self->object = self->reason = NULL;
   2061         return -1;
   2062     }
   2063 
   2064     Py_INCREF(self->object);
   2065     Py_INCREF(self->reason);
   2066 
   2067     return 0;
   2068 }
   2069 
   2070 
   2071 static PyObject *
   2072 UnicodeTranslateError_str(PyObject *self)
   2073 {
   2074     PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
   2075     PyObject *result = NULL;
   2076     PyObject *reason_str = NULL;
   2077 
   2078     if (!uself->object)
   2079         /* Not properly initialized. */
   2080         return PyUnicode_FromString("");
   2081 
   2082     /* Get reason as a string, which it might not be if it's been
   2083        modified after we were constructed. */
   2084     reason_str = PyObject_Str(uself->reason);
   2085     if (reason_str == NULL)
   2086         goto done;
   2087 
   2088     if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
   2089         Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
   2090         const char *fmt;
   2091         if (badchar <= 0xff)
   2092             fmt = "can't translate character '\\x%02x' in position %zd: %U";
   2093         else if (badchar <= 0xffff)
   2094             fmt = "can't translate character '\\u%04x' in position %zd: %U";
   2095         else
   2096             fmt = "can't translate character '\\U%08x' in position %zd: %U";
   2097         result = PyUnicode_FromFormat(
   2098             fmt,
   2099             (int)badchar,
   2100             uself->start,
   2101             reason_str
   2102         );
   2103     } else {
   2104         result = PyUnicode_FromFormat(
   2105             "can't translate characters in position %zd-%zd: %U",
   2106             uself->start,
   2107             uself->end-1,
   2108             reason_str
   2109             );
   2110     }
   2111 done:
   2112     Py_XDECREF(reason_str);
   2113     return result;
   2114 }
   2115 
   2116 static PyTypeObject _PyExc_UnicodeTranslateError = {
   2117     PyVarObject_HEAD_INIT(NULL, 0)
   2118     "UnicodeTranslateError",
   2119     sizeof(PyUnicodeErrorObject), 0,
   2120     (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   2121     (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
   2122     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
   2123     PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
   2124     (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
   2125     0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
   2126     (initproc)UnicodeTranslateError_init, 0, BaseException_new,
   2127 };
   2128 PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
   2129 
   2130 /* Deprecated. */
   2131 PyObject *
   2132 PyUnicodeTranslateError_Create(
   2133     const Py_UNICODE *object, Py_ssize_t length,
   2134     Py_ssize_t start, Py_ssize_t end, const char *reason)
   2135 {
   2136     return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
   2137                                  object, length, start, end, reason);
   2138 }
   2139 
   2140 PyObject *
   2141 _PyUnicodeTranslateError_Create(
   2142     PyObject *object,
   2143     Py_ssize_t start, Py_ssize_t end, const char *reason)
   2144 {
   2145     return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
   2146                                  object, start, end, reason);
   2147 }
   2148 
   2149 /*
   2150  *    AssertionError extends Exception
   2151  */
   2152 SimpleExtendsException(PyExc_Exception, AssertionError,
   2153                        "Assertion failed.");
   2154 
   2155 
   2156 /*
   2157  *    ArithmeticError extends Exception
   2158  */
   2159 SimpleExtendsException(PyExc_Exception, ArithmeticError,
   2160                        "Base class for arithmetic errors.");
   2161 
   2162 
   2163 /*
   2164  *    FloatingPointError extends ArithmeticError
   2165  */
   2166 SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
   2167                        "Floating point operation failed.");
   2168 
   2169 
   2170 /*
   2171  *    OverflowError extends ArithmeticError
   2172  */
   2173 SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
   2174                        "Result too large to be represented.");
   2175 
   2176 
   2177 /*
   2178  *    ZeroDivisionError extends ArithmeticError
   2179  */
   2180 SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
   2181           "Second argument to a division or modulo operation was zero.");
   2182 
   2183 
   2184 /*
   2185  *    SystemError extends Exception
   2186  */
   2187 SimpleExtendsException(PyExc_Exception, SystemError,
   2188     "Internal error in the Python interpreter.\n"
   2189     "\n"
   2190     "Please report this to the Python maintainer, along with the traceback,\n"
   2191     "the Python version, and the hardware/OS platform and version.");
   2192 
   2193 
   2194 /*
   2195  *    ReferenceError extends Exception
   2196  */
   2197 SimpleExtendsException(PyExc_Exception, ReferenceError,
   2198                        "Weak ref proxy used after referent went away.");
   2199 
   2200 
   2201 /*
   2202  *    MemoryError extends Exception
   2203  */
   2204 
   2205 #define MEMERRORS_SAVE 16
   2206 static PyBaseExceptionObject *memerrors_freelist = NULL;
   2207 static int memerrors_numfree = 0;
   2208 
   2209 static PyObject *
   2210 MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
   2211 {
   2212     PyBaseExceptionObject *self;
   2213 
   2214     if (type != (PyTypeObject *) PyExc_MemoryError)
   2215         return BaseException_new(type, args, kwds);
   2216     if (memerrors_freelist == NULL)
   2217         return BaseException_new(type, args, kwds);
   2218     /* Fetch object from freelist and revive it */
   2219     self = memerrors_freelist;
   2220     self->args = PyTuple_New(0);
   2221     /* This shouldn't happen since the empty tuple is persistent */
   2222     if (self->args == NULL)
   2223         return NULL;
   2224     memerrors_freelist = (PyBaseExceptionObject *) self->dict;
   2225     memerrors_numfree--;
   2226     self->dict = NULL;
   2227     _Py_NewReference((PyObject *)self);
   2228     _PyObject_GC_TRACK(self);
   2229     return (PyObject *)self;
   2230 }
   2231 
   2232 static void
   2233 MemoryError_dealloc(PyBaseExceptionObject *self)
   2234 {
   2235     _PyObject_GC_UNTRACK(self);
   2236     BaseException_clear(self);
   2237     if (memerrors_numfree >= MEMERRORS_SAVE)
   2238         Py_TYPE(self)->tp_free((PyObject *)self);
   2239     else {
   2240         self->dict = (PyObject *) memerrors_freelist;
   2241         memerrors_freelist = self;
   2242         memerrors_numfree++;
   2243     }
   2244 }
   2245 
   2246 static void
   2247 preallocate_memerrors(void)
   2248 {
   2249     /* We create enough MemoryErrors and then decref them, which will fill
   2250        up the freelist. */
   2251     int i;
   2252     PyObject *errors[MEMERRORS_SAVE];
   2253     for (i = 0; i < MEMERRORS_SAVE; i++) {
   2254         errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
   2255                                     NULL, NULL);
   2256         if (!errors[i])
   2257             Py_FatalError("Could not preallocate MemoryError object");
   2258     }
   2259     for (i = 0; i < MEMERRORS_SAVE; i++) {
   2260         Py_DECREF(errors[i]);
   2261     }
   2262 }
   2263 
   2264 static void
   2265 free_preallocated_memerrors(void)
   2266 {
   2267     while (memerrors_freelist != NULL) {
   2268         PyObject *self = (PyObject *) memerrors_freelist;
   2269         memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
   2270         Py_TYPE(self)->tp_free((PyObject *)self);
   2271     }
   2272 }
   2273 
   2274 
   2275 static PyTypeObject _PyExc_MemoryError = {
   2276     PyVarObject_HEAD_INIT(NULL, 0)
   2277     "MemoryError",
   2278     sizeof(PyBaseExceptionObject),
   2279     0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
   2280     0, 0, 0, 0, 0, 0, 0,
   2281     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
   2282     PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
   2283     (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
   2284     0, 0, 0, offsetof(PyBaseExceptionObject, dict),
   2285     (initproc)BaseException_init, 0, MemoryError_new
   2286 };
   2287 PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
   2288 
   2289 
   2290 /*
   2291  *    BufferError extends Exception
   2292  */
   2293 SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
   2294 
   2295 
   2296 /* Warning category docstrings */
   2297 
   2298 /*
   2299  *    Warning extends Exception
   2300  */
   2301 SimpleExtendsException(PyExc_Exception, Warning,
   2302                        "Base class for warning categories.");
   2303 
   2304 
   2305 /*
   2306  *    UserWarning extends Warning
   2307  */
   2308 SimpleExtendsException(PyExc_Warning, UserWarning,
   2309                        "Base class for warnings generated by user code.");
   2310 
   2311 
   2312 /*
   2313  *    DeprecationWarning extends Warning
   2314  */
   2315 SimpleExtendsException(PyExc_Warning, DeprecationWarning,
   2316                        "Base class for warnings about deprecated features.");
   2317 
   2318 
   2319 /*
   2320  *    PendingDeprecationWarning extends Warning
   2321  */
   2322 SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
   2323     "Base class for warnings about features which will be deprecated\n"
   2324     "in the future.");
   2325 
   2326 
   2327 /*
   2328  *    SyntaxWarning extends Warning
   2329  */
   2330 SimpleExtendsException(PyExc_Warning, SyntaxWarning,
   2331                        "Base class for warnings about dubious syntax.");
   2332 
   2333 
   2334 /*
   2335  *    RuntimeWarning extends Warning
   2336  */
   2337 SimpleExtendsException(PyExc_Warning, RuntimeWarning,
   2338                  "Base class for warnings about dubious runtime behavior.");
   2339 
   2340 
   2341 /*
   2342  *    FutureWarning extends Warning
   2343  */
   2344 SimpleExtendsException(PyExc_Warning, FutureWarning,
   2345     "Base class for warnings about constructs that will change semantically\n"
   2346     "in the future.");
   2347 
   2348 
   2349 /*
   2350  *    ImportWarning extends Warning
   2351  */
   2352 SimpleExtendsException(PyExc_Warning, ImportWarning,
   2353           "Base class for warnings about probable mistakes in module imports");
   2354 
   2355 
   2356 /*
   2357  *    UnicodeWarning extends Warning
   2358  */
   2359 SimpleExtendsException(PyExc_Warning, UnicodeWarning,
   2360     "Base class for warnings about Unicode related problems, mostly\n"
   2361     "related to conversion problems.");
   2362 
   2363 
   2364 /*
   2365  *    BytesWarning extends Warning
   2366  */
   2367 SimpleExtendsException(PyExc_Warning, BytesWarning,
   2368     "Base class for warnings about bytes and buffer related problems, mostly\n"
   2369     "related to conversion from str or comparing to str.");
   2370 
   2371 
   2372 /*
   2373  *    ResourceWarning extends Warning
   2374  */
   2375 SimpleExtendsException(PyExc_Warning, ResourceWarning,
   2376     "Base class for warnings about resource usage.");
   2377 
   2378 
   2379 
   2380 /* Pre-computed RecursionError instance for when recursion depth is reached.
   2381    Meant to be used when normalizing the exception for exceeding the recursion
   2382    depth will cause its own infinite recursion.
   2383 */
   2384 PyObject *PyExc_RecursionErrorInst = NULL;
   2385 
   2386 #define PRE_INIT(TYPE) \
   2387     if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
   2388         if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
   2389             Py_FatalError("exceptions bootstrapping error."); \
   2390         Py_INCREF(PyExc_ ## TYPE); \
   2391     }
   2392 
   2393 #define POST_INIT(TYPE) \
   2394     if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
   2395         Py_FatalError("Module dictionary insertion problem.");
   2396 
   2397 #define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
   2398     Py_XDECREF(PyExc_ ## NAME); \
   2399     PyExc_ ## NAME = PyExc_ ## TYPE; \
   2400     if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
   2401         Py_FatalError("Module dictionary insertion problem.");
   2402 
   2403 #define ADD_ERRNO(TYPE, CODE) { \
   2404     PyObject *_code = PyLong_FromLong(CODE); \
   2405     assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
   2406     if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
   2407         Py_FatalError("errmap insertion problem."); \
   2408     Py_DECREF(_code); \
   2409     }
   2410 
   2411 #ifdef MS_WINDOWS
   2412 #include <winsock2.h>
   2413 /* The following constants were added to errno.h in VS2010 but have
   2414    preferred WSA equivalents. */
   2415 #undef EADDRINUSE
   2416 #undef EADDRNOTAVAIL
   2417 #undef EAFNOSUPPORT
   2418 #undef EALREADY
   2419 #undef ECONNABORTED
   2420 #undef ECONNREFUSED
   2421 #undef ECONNRESET
   2422 #undef EDESTADDRREQ
   2423 #undef EHOSTUNREACH
   2424 #undef EINPROGRESS
   2425 #undef EISCONN
   2426 #undef ELOOP
   2427 #undef EMSGSIZE
   2428 #undef ENETDOWN
   2429 #undef ENETRESET
   2430 #undef ENETUNREACH
   2431 #undef ENOBUFS
   2432 #undef ENOPROTOOPT
   2433 #undef ENOTCONN
   2434 #undef ENOTSOCK
   2435 #undef EOPNOTSUPP
   2436 #undef EPROTONOSUPPORT
   2437 #undef EPROTOTYPE
   2438 #undef ETIMEDOUT
   2439 #undef EWOULDBLOCK
   2440 
   2441 #if defined(WSAEALREADY) && !defined(EALREADY)
   2442 #define EALREADY WSAEALREADY
   2443 #endif
   2444 #if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
   2445 #define ECONNABORTED WSAECONNABORTED
   2446 #endif
   2447 #if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
   2448 #define ECONNREFUSED WSAECONNREFUSED
   2449 #endif
   2450 #if defined(WSAECONNRESET) && !defined(ECONNRESET)
   2451 #define ECONNRESET WSAECONNRESET
   2452 #endif
   2453 #if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
   2454 #define EINPROGRESS WSAEINPROGRESS
   2455 #endif
   2456 #if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
   2457 #define ESHUTDOWN WSAESHUTDOWN
   2458 #endif
   2459 #if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
   2460 #define ETIMEDOUT WSAETIMEDOUT
   2461 #endif
   2462 #if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
   2463 #define EWOULDBLOCK WSAEWOULDBLOCK
   2464 #endif
   2465 #endif /* MS_WINDOWS */
   2466 
   2467 void
   2468 _PyExc_Init(PyObject *bltinmod)
   2469 {
   2470     PyObject *bdict;
   2471 
   2472     PRE_INIT(BaseException)
   2473     PRE_INIT(Exception)
   2474     PRE_INIT(TypeError)
   2475     PRE_INIT(StopAsyncIteration)
   2476     PRE_INIT(StopIteration)
   2477     PRE_INIT(GeneratorExit)
   2478     PRE_INIT(SystemExit)
   2479     PRE_INIT(KeyboardInterrupt)
   2480     PRE_INIT(ImportError)
   2481     PRE_INIT(ModuleNotFoundError)
   2482     PRE_INIT(OSError)
   2483     PRE_INIT(EOFError)
   2484     PRE_INIT(RuntimeError)
   2485     PRE_INIT(RecursionError)
   2486     PRE_INIT(NotImplementedError)
   2487     PRE_INIT(NameError)
   2488     PRE_INIT(UnboundLocalError)
   2489     PRE_INIT(AttributeError)
   2490     PRE_INIT(SyntaxError)
   2491     PRE_INIT(IndentationError)
   2492     PRE_INIT(TabError)
   2493     PRE_INIT(LookupError)
   2494     PRE_INIT(IndexError)
   2495     PRE_INIT(KeyError)
   2496     PRE_INIT(ValueError)
   2497     PRE_INIT(UnicodeError)
   2498     PRE_INIT(UnicodeEncodeError)
   2499     PRE_INIT(UnicodeDecodeError)
   2500     PRE_INIT(UnicodeTranslateError)
   2501     PRE_INIT(AssertionError)
   2502     PRE_INIT(ArithmeticError)
   2503     PRE_INIT(FloatingPointError)
   2504     PRE_INIT(OverflowError)
   2505     PRE_INIT(ZeroDivisionError)
   2506     PRE_INIT(SystemError)
   2507     PRE_INIT(ReferenceError)
   2508     PRE_INIT(BufferError)
   2509     PRE_INIT(MemoryError)
   2510     PRE_INIT(BufferError)
   2511     PRE_INIT(Warning)
   2512     PRE_INIT(UserWarning)
   2513     PRE_INIT(DeprecationWarning)
   2514     PRE_INIT(PendingDeprecationWarning)
   2515     PRE_INIT(SyntaxWarning)
   2516     PRE_INIT(RuntimeWarning)
   2517     PRE_INIT(FutureWarning)
   2518     PRE_INIT(ImportWarning)
   2519     PRE_INIT(UnicodeWarning)
   2520     PRE_INIT(BytesWarning)
   2521     PRE_INIT(ResourceWarning)
   2522 
   2523     /* OSError subclasses */
   2524     PRE_INIT(ConnectionError);
   2525 
   2526     PRE_INIT(BlockingIOError);
   2527     PRE_INIT(BrokenPipeError);
   2528     PRE_INIT(ChildProcessError);
   2529     PRE_INIT(ConnectionAbortedError);
   2530     PRE_INIT(ConnectionRefusedError);
   2531     PRE_INIT(ConnectionResetError);
   2532     PRE_INIT(FileExistsError);
   2533     PRE_INIT(FileNotFoundError);
   2534     PRE_INIT(IsADirectoryError);
   2535     PRE_INIT(NotADirectoryError);
   2536     PRE_INIT(InterruptedError);
   2537     PRE_INIT(PermissionError);
   2538     PRE_INIT(ProcessLookupError);
   2539     PRE_INIT(TimeoutError);
   2540 
   2541     bdict = PyModule_GetDict(bltinmod);
   2542     if (bdict == NULL)
   2543         Py_FatalError("exceptions bootstrapping error.");
   2544 
   2545     POST_INIT(BaseException)
   2546     POST_INIT(Exception)
   2547     POST_INIT(TypeError)
   2548     POST_INIT(StopAsyncIteration)
   2549     POST_INIT(StopIteration)
   2550     POST_INIT(GeneratorExit)
   2551     POST_INIT(SystemExit)
   2552     POST_INIT(KeyboardInterrupt)
   2553     POST_INIT(ImportError)
   2554     POST_INIT(ModuleNotFoundError)
   2555     POST_INIT(OSError)
   2556     INIT_ALIAS(EnvironmentError, OSError)
   2557     INIT_ALIAS(IOError, OSError)
   2558 #ifdef MS_WINDOWS
   2559     INIT_ALIAS(WindowsError, OSError)
   2560 #endif
   2561     POST_INIT(EOFError)
   2562     POST_INIT(RuntimeError)
   2563     POST_INIT(RecursionError)
   2564     POST_INIT(NotImplementedError)
   2565     POST_INIT(NameError)
   2566     POST_INIT(UnboundLocalError)
   2567     POST_INIT(AttributeError)
   2568     POST_INIT(SyntaxError)
   2569     POST_INIT(IndentationError)
   2570     POST_INIT(TabError)
   2571     POST_INIT(LookupError)
   2572     POST_INIT(IndexError)
   2573     POST_INIT(KeyError)
   2574     POST_INIT(ValueError)
   2575     POST_INIT(UnicodeError)
   2576     POST_INIT(UnicodeEncodeError)
   2577     POST_INIT(UnicodeDecodeError)
   2578     POST_INIT(UnicodeTranslateError)
   2579     POST_INIT(AssertionError)
   2580     POST_INIT(ArithmeticError)
   2581     POST_INIT(FloatingPointError)
   2582     POST_INIT(OverflowError)
   2583     POST_INIT(ZeroDivisionError)
   2584     POST_INIT(SystemError)
   2585     POST_INIT(ReferenceError)
   2586     POST_INIT(BufferError)
   2587     POST_INIT(MemoryError)
   2588     POST_INIT(BufferError)
   2589     POST_INIT(Warning)
   2590     POST_INIT(UserWarning)
   2591     POST_INIT(DeprecationWarning)
   2592     POST_INIT(PendingDeprecationWarning)
   2593     POST_INIT(SyntaxWarning)
   2594     POST_INIT(RuntimeWarning)
   2595     POST_INIT(FutureWarning)
   2596     POST_INIT(ImportWarning)
   2597     POST_INIT(UnicodeWarning)
   2598     POST_INIT(BytesWarning)
   2599     POST_INIT(ResourceWarning)
   2600 
   2601     if (!errnomap) {
   2602         errnomap = PyDict_New();
   2603         if (!errnomap)
   2604             Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
   2605     }
   2606 
   2607     /* OSError subclasses */
   2608     POST_INIT(ConnectionError);
   2609 
   2610     POST_INIT(BlockingIOError);
   2611     ADD_ERRNO(BlockingIOError, EAGAIN);
   2612     ADD_ERRNO(BlockingIOError, EALREADY);
   2613     ADD_ERRNO(BlockingIOError, EINPROGRESS);
   2614     ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
   2615     POST_INIT(BrokenPipeError);
   2616     ADD_ERRNO(BrokenPipeError, EPIPE);
   2617 #ifdef ESHUTDOWN
   2618     ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
   2619 #endif
   2620     POST_INIT(ChildProcessError);
   2621     ADD_ERRNO(ChildProcessError, ECHILD);
   2622     POST_INIT(ConnectionAbortedError);
   2623     ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
   2624     POST_INIT(ConnectionRefusedError);
   2625     ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
   2626     POST_INIT(ConnectionResetError);
   2627     ADD_ERRNO(ConnectionResetError, ECONNRESET);
   2628     POST_INIT(FileExistsError);
   2629     ADD_ERRNO(FileExistsError, EEXIST);
   2630     POST_INIT(FileNotFoundError);
   2631     ADD_ERRNO(FileNotFoundError, ENOENT);
   2632     POST_INIT(IsADirectoryError);
   2633     ADD_ERRNO(IsADirectoryError, EISDIR);
   2634     POST_INIT(NotADirectoryError);
   2635     ADD_ERRNO(NotADirectoryError, ENOTDIR);
   2636     POST_INIT(InterruptedError);
   2637     ADD_ERRNO(InterruptedError, EINTR);
   2638     POST_INIT(PermissionError);
   2639     ADD_ERRNO(PermissionError, EACCES);
   2640     ADD_ERRNO(PermissionError, EPERM);
   2641     POST_INIT(ProcessLookupError);
   2642     ADD_ERRNO(ProcessLookupError, ESRCH);
   2643     POST_INIT(TimeoutError);
   2644     ADD_ERRNO(TimeoutError, ETIMEDOUT);
   2645 
   2646     preallocate_memerrors();
   2647 
   2648     if (!PyExc_RecursionErrorInst) {
   2649         PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RecursionError, NULL, NULL);
   2650         if (!PyExc_RecursionErrorInst)
   2651             Py_FatalError("Cannot pre-allocate RecursionError instance for "
   2652                             "recursion errors");
   2653         else {
   2654             PyBaseExceptionObject *err_inst =
   2655                 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
   2656             PyObject *args_tuple;
   2657             PyObject *exc_message;
   2658             exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
   2659             if (!exc_message)
   2660                 Py_FatalError("cannot allocate argument for RecursionError "
   2661                                 "pre-allocation");
   2662             args_tuple = PyTuple_Pack(1, exc_message);
   2663             if (!args_tuple)
   2664                 Py_FatalError("cannot allocate tuple for RecursionError "
   2665                                 "pre-allocation");
   2666             Py_DECREF(exc_message);
   2667             if (BaseException_init(err_inst, args_tuple, NULL))
   2668                 Py_FatalError("init of pre-allocated RecursionError failed");
   2669             Py_DECREF(args_tuple);
   2670         }
   2671     }
   2672 }
   2673 
   2674 void
   2675 _PyExc_Fini(void)
   2676 {
   2677     Py_CLEAR(PyExc_RecursionErrorInst);
   2678     free_preallocated_memerrors();
   2679     Py_CLEAR(errnomap);
   2680 }
   2681 
   2682 /* Helper to do the equivalent of "raise X from Y" in C, but always using
   2683  * the current exception rather than passing one in.
   2684  *
   2685  * We currently limit this to *only* exceptions that use the BaseException
   2686  * tp_init and tp_new methods, since we can be reasonably sure we can wrap
   2687  * those correctly without losing data and without losing backwards
   2688  * compatibility.
   2689  *
   2690  * We also aim to rule out *all* exceptions that might be storing additional
   2691  * state, whether by having a size difference relative to BaseException,
   2692  * additional arguments passed in during construction or by having a
   2693  * non-empty instance dict.
   2694  *
   2695  * We need to be very careful with what we wrap, since changing types to
   2696  * a broader exception type would be backwards incompatible for
   2697  * existing codecs, and with different init or new method implementations
   2698  * may either not support instantiation with PyErr_Format or lose
   2699  * information when instantiated that way.
   2700  *
   2701  * XXX (ncoghlan): This could be made more comprehensive by exploiting the
   2702  * fact that exceptions are expected to support pickling. If more builtin
   2703  * exceptions (e.g. AttributeError) start to be converted to rich
   2704  * exceptions with additional attributes, that's probably a better approach
   2705  * to pursue over adding special cases for particular stateful subclasses.
   2706  *
   2707  * Returns a borrowed reference to the new exception (if any), NULL if the
   2708  * existing exception was left in place.
   2709  */
   2710 PyObject *
   2711 _PyErr_TrySetFromCause(const char *format, ...)
   2712 {
   2713     PyObject* msg_prefix;
   2714     PyObject *exc, *val, *tb;
   2715     PyTypeObject *caught_type;
   2716     PyObject **dictptr;
   2717     PyObject *instance_args;
   2718     Py_ssize_t num_args, caught_type_size, base_exc_size;
   2719     PyObject *new_exc, *new_val, *new_tb;
   2720     va_list vargs;
   2721     int same_basic_size;
   2722 
   2723     PyErr_Fetch(&exc, &val, &tb);
   2724     caught_type = (PyTypeObject *)exc;
   2725     /* Ensure type info indicates no extra state is stored at the C level
   2726      * and that the type can be reinstantiated using PyErr_Format
   2727      */
   2728     caught_type_size = caught_type->tp_basicsize;
   2729     base_exc_size = _PyExc_BaseException.tp_basicsize;
   2730     same_basic_size = (
   2731         caught_type_size == base_exc_size ||
   2732         (PyType_SUPPORTS_WEAKREFS(caught_type) &&
   2733             (caught_type_size == base_exc_size + (Py_ssize_t)sizeof(PyObject *))
   2734         )
   2735     );
   2736     if (caught_type->tp_init != (initproc)BaseException_init ||
   2737         caught_type->tp_new != BaseException_new ||
   2738         !same_basic_size ||
   2739         caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
   2740         /* We can't be sure we can wrap this safely, since it may contain
   2741          * more state than just the exception type. Accordingly, we just
   2742          * leave it alone.
   2743          */
   2744         PyErr_Restore(exc, val, tb);
   2745         return NULL;
   2746     }
   2747 
   2748     /* Check the args are empty or contain a single string */
   2749     PyErr_NormalizeException(&exc, &val, &tb);
   2750     instance_args = ((PyBaseExceptionObject *)val)->args;
   2751     num_args = PyTuple_GET_SIZE(instance_args);
   2752     if (num_args > 1 ||
   2753         (num_args == 1 &&
   2754          !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
   2755         /* More than 1 arg, or the one arg we do have isn't a string
   2756          */
   2757         PyErr_Restore(exc, val, tb);
   2758         return NULL;
   2759     }
   2760 
   2761     /* Ensure the instance dict is also empty */
   2762     dictptr = _PyObject_GetDictPtr(val);
   2763     if (dictptr != NULL && *dictptr != NULL &&
   2764         PyObject_Length(*dictptr) > 0) {
   2765         /* While we could potentially copy a non-empty instance dictionary
   2766          * to the replacement exception, for now we take the more
   2767          * conservative path of leaving exceptions with attributes set
   2768          * alone.
   2769          */
   2770         PyErr_Restore(exc, val, tb);
   2771         return NULL;
   2772     }
   2773 
   2774     /* For exceptions that we can wrap safely, we chain the original
   2775      * exception to a new one of the exact same type with an
   2776      * error message that mentions the additional details and the
   2777      * original exception.
   2778      *
   2779      * It would be nice to wrap OSError and various other exception
   2780      * types as well, but that's quite a bit trickier due to the extra
   2781      * state potentially stored on OSError instances.
   2782      */
   2783     /* Ensure the traceback is set correctly on the existing exception */
   2784     if (tb != NULL) {
   2785         PyException_SetTraceback(val, tb);
   2786         Py_DECREF(tb);
   2787     }
   2788 
   2789 #ifdef HAVE_STDARG_PROTOTYPES
   2790     va_start(vargs, format);
   2791 #else
   2792     va_start(vargs);
   2793 #endif
   2794     msg_prefix = PyUnicode_FromFormatV(format, vargs);
   2795     va_end(vargs);
   2796     if (msg_prefix == NULL) {
   2797         Py_DECREF(exc);
   2798         Py_DECREF(val);
   2799         return NULL;
   2800     }
   2801 
   2802     PyErr_Format(exc, "%U (%s: %S)",
   2803                  msg_prefix, Py_TYPE(val)->tp_name, val);
   2804     Py_DECREF(exc);
   2805     Py_DECREF(msg_prefix);
   2806     PyErr_Fetch(&new_exc, &new_val, &new_tb);
   2807     PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
   2808     PyException_SetCause(new_val, val);
   2809     PyErr_Restore(new_exc, new_val, new_tb);
   2810     return new_val;
   2811 }
   2812 
   2813 
   2814 /* To help with migration from Python 2, SyntaxError.__init__ applies some
   2815  * heuristics to try to report a more meaningful exception when print and
   2816  * exec are used like statements.
   2817  *
   2818  * The heuristics are currently expected to detect the following cases:
   2819  *   - top level statement
   2820  *   - statement in a nested suite
   2821  *   - trailing section of a one line complex statement
   2822  *
   2823  * They're currently known not to trigger:
   2824  *   - after a semi-colon
   2825  *
   2826  * The error message can be a bit odd in cases where the "arguments" are
   2827  * completely illegal syntactically, but that isn't worth the hassle of
   2828  * fixing.
   2829  *
   2830  * We also can't do anything about cases that are legal Python 3 syntax
   2831  * but mean something entirely different from what they did in Python 2
   2832  * (omitting the arguments entirely, printing items preceded by a unary plus
   2833  * or minus, using the stream redirection syntax).
   2834  */
   2835 
   2836 static int
   2837 _check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start)
   2838 {
   2839     /* Return values:
   2840      *   -1: an error occurred
   2841      *    0: nothing happened
   2842      *    1: the check triggered & the error message was changed
   2843      */
   2844     static PyObject *print_prefix = NULL;
   2845     static PyObject *exec_prefix = NULL;
   2846     Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
   2847     int kind = PyUnicode_KIND(self->text);
   2848     void *data = PyUnicode_DATA(self->text);
   2849 
   2850     /* Ignore leading whitespace */
   2851     while (start < text_len) {
   2852         Py_UCS4 ch = PyUnicode_READ(kind, data, start);
   2853         if (!Py_UNICODE_ISSPACE(ch))
   2854             break;
   2855         start++;
   2856     }
   2857     /* Checking against an empty or whitespace-only part of the string */
   2858     if (start == text_len) {
   2859         return 0;
   2860     }
   2861 
   2862     /* Check for legacy print statements */
   2863     if (print_prefix == NULL) {
   2864         print_prefix = PyUnicode_InternFromString("print ");
   2865         if (print_prefix == NULL) {
   2866             return -1;
   2867         }
   2868     }
   2869     if (PyUnicode_Tailmatch(self->text, print_prefix,
   2870                             start, text_len, -1)) {
   2871         Py_XSETREF(self->msg,
   2872                   PyUnicode_FromString("Missing parentheses in call to 'print'"));
   2873         return 1;
   2874     }
   2875 
   2876     /* Check for legacy exec statements */
   2877     if (exec_prefix == NULL) {
   2878         exec_prefix = PyUnicode_InternFromString("exec ");
   2879         if (exec_prefix == NULL) {
   2880             return -1;
   2881         }
   2882     }
   2883     if (PyUnicode_Tailmatch(self->text, exec_prefix,
   2884                             start, text_len, -1)) {
   2885         Py_XSETREF(self->msg,
   2886                   PyUnicode_FromString("Missing parentheses in call to 'exec'"));
   2887         return 1;
   2888     }
   2889     /* Fall back to the default error message */
   2890     return 0;
   2891 }
   2892 
   2893 static int
   2894 _report_missing_parentheses(PySyntaxErrorObject *self)
   2895 {
   2896     Py_UCS4 left_paren = 40;
   2897     Py_ssize_t left_paren_index;
   2898     Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
   2899     int legacy_check_result = 0;
   2900 
   2901     /* Skip entirely if there is an opening parenthesis */
   2902     left_paren_index = PyUnicode_FindChar(self->text, left_paren,
   2903                                           0, text_len, 1);
   2904     if (left_paren_index < -1) {
   2905         return -1;
   2906     }
   2907     if (left_paren_index != -1) {
   2908         /* Use default error message for any line with an opening paren */
   2909         return 0;
   2910     }
   2911     /* Handle the simple statement case */
   2912     legacy_check_result = _check_for_legacy_statements(self, 0);
   2913     if (legacy_check_result < 0) {
   2914         return -1;
   2915 
   2916     }
   2917     if (legacy_check_result == 0) {
   2918         /* Handle the one-line complex statement case */
   2919         Py_UCS4 colon = 58;
   2920         Py_ssize_t colon_index;
   2921         colon_index = PyUnicode_FindChar(self->text, colon,
   2922                                          0, text_len, 1);
   2923         if (colon_index < -1) {
   2924             return -1;
   2925         }
   2926         if (colon_index >= 0 && colon_index < text_len) {
   2927             /* Check again, starting from just after the colon */
   2928             if (_check_for_legacy_statements(self, colon_index+1) < 0) {
   2929                 return -1;
   2930             }
   2931         }
   2932     }
   2933     return 0;
   2934 }
   2935