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