blob: bb61ea5a3c6090aa8c59df8837a5140234adb096 [file] [log] [blame]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001/*
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
Thomas Wouters477c8d52006-05-27 19:21:47 +00007#define PY_SSIZE_T_CLEAN
8#include <Python.h>
9#include "structmember.h"
10#include "osdefs.h"
11
Thomas Wouters477c8d52006-05-27 19:21:47 +000012
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020013/* Compatibility aliases */
14PyObject *PyExc_EnvironmentError = NULL;
15PyObject *PyExc_IOError = NULL;
16#ifdef MS_WINDOWS
17PyObject *PyExc_WindowsError = NULL;
18#endif
19#ifdef __VMS
20PyObject *PyExc_VMSError = NULL;
21#endif
22
23/* The dict map from errno codes to OSError subclasses */
24static PyObject *errnomap = NULL;
25
26
Thomas Wouters477c8d52006-05-27 19:21:47 +000027/* NOTE: If the exception class hierarchy changes, don't forget to update
28 * Lib/test/exception_hierarchy.txt
29 */
30
Thomas Wouters477c8d52006-05-27 19:21:47 +000031/*
32 * BaseException
33 */
34static PyObject *
35BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
36{
37 PyBaseExceptionObject *self;
38
39 self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +000040 if (!self)
41 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000042 /* the dict is created on the fly in PyObject_GenericSetAttr */
Guido van Rossumebe3e162007-05-17 18:20:34 +000043 self->dict = NULL;
Collin Winter1966f1c2007-09-01 20:26:44 +000044 self->traceback = self->cause = self->context = NULL;
Benjamin Petersond5a1c442012-05-14 22:09:31 -070045 self->suppress_context = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000046
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010047 if (args) {
48 self->args = args;
49 Py_INCREF(args);
50 return (PyObject *)self;
51 }
52
Thomas Wouters477c8d52006-05-27 19:21:47 +000053 self->args = PyTuple_New(0);
54 if (!self->args) {
55 Py_DECREF(self);
56 return NULL;
57 }
58
Thomas Wouters477c8d52006-05-27 19:21:47 +000059 return (PyObject *)self;
60}
61
62static int
63BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
64{
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010065 PyObject *tmp;
66
Christian Heimes90aa7642007-12-19 02:45:37 +000067 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000068 return -1;
69
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010070 tmp = self->args;
Thomas Wouters477c8d52006-05-27 19:21:47 +000071 self->args = args;
72 Py_INCREF(self->args);
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010073 Py_XDECREF(tmp);
Thomas Wouters477c8d52006-05-27 19:21:47 +000074
Thomas Wouters477c8d52006-05-27 19:21:47 +000075 return 0;
76}
77
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000078static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000079BaseException_clear(PyBaseExceptionObject *self)
80{
81 Py_CLEAR(self->dict);
82 Py_CLEAR(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +000083 Py_CLEAR(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +000084 Py_CLEAR(self->cause);
85 Py_CLEAR(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +000086 return 0;
87}
88
89static void
90BaseException_dealloc(PyBaseExceptionObject *self)
91{
Thomas Wouters89f507f2006-12-13 04:49:30 +000092 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000093 BaseException_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +000094 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000095}
96
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000097static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000098BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
99{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000100 Py_VISIT(self->dict);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000101 Py_VISIT(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +0000102 Py_VISIT(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +0000103 Py_VISIT(self->cause);
104 Py_VISIT(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000105 return 0;
106}
107
108static PyObject *
109BaseException_str(PyBaseExceptionObject *self)
110{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000111 switch (PyTuple_GET_SIZE(self->args)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000112 case 0:
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +0000113 return PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000114 case 1:
Thomas Heller519a0422007-11-15 20:48:54 +0000115 return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000116 default:
Thomas Heller519a0422007-11-15 20:48:54 +0000117 return PyObject_Str(self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000118 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000119}
120
121static PyObject *
122BaseException_repr(PyBaseExceptionObject *self)
123{
Serhiy Storchakac6792272013-10-19 21:03:34 +0300124 const char *name;
125 const char *dot;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126
Serhiy Storchakac6792272013-10-19 21:03:34 +0300127 name = Py_TYPE(self)->tp_name;
128 dot = (const char *) strrchr(name, '.');
Thomas Wouters477c8d52006-05-27 19:21:47 +0000129 if (dot != NULL) name = dot+1;
130
Walter Dörwald7569dfe2007-05-19 21:49:49 +0000131 return PyUnicode_FromFormat("%s%R", name, self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000132}
133
134/* Pickling support */
135static PyObject *
136BaseException_reduce(PyBaseExceptionObject *self)
137{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000138 if (self->args && self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +0000139 return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000140 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000141 return PyTuple_Pack(2, Py_TYPE(self), self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000142}
143
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000144/*
145 * Needed for backward compatibility, since exceptions used to store
146 * all their attributes in the __dict__. Code is taken from cPickle's
147 * load_build function.
148 */
149static PyObject *
150BaseException_setstate(PyObject *self, PyObject *state)
151{
152 PyObject *d_key, *d_value;
153 Py_ssize_t i = 0;
154
155 if (state != Py_None) {
156 if (!PyDict_Check(state)) {
157 PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
158 return NULL;
159 }
160 while (PyDict_Next(state, &i, &d_key, &d_value)) {
161 if (PyObject_SetAttr(self, d_key, d_value) < 0)
162 return NULL;
163 }
164 }
165 Py_RETURN_NONE;
166}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000167
Collin Winter828f04a2007-08-31 00:04:24 +0000168static PyObject *
169BaseException_with_traceback(PyObject *self, PyObject *tb) {
170 if (PyException_SetTraceback(self, tb))
171 return NULL;
172
173 Py_INCREF(self);
174 return self;
175}
176
Georg Brandl76941002008-05-05 21:38:47 +0000177PyDoc_STRVAR(with_traceback_doc,
178"Exception.with_traceback(tb) --\n\
179 set self.__traceback__ to tb and return self.");
180
Thomas Wouters477c8d52006-05-27 19:21:47 +0000181
182static PyMethodDef BaseException_methods[] = {
183 {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000184 {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
Georg Brandl76941002008-05-05 21:38:47 +0000185 {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
186 with_traceback_doc},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000187 {NULL, NULL, 0, NULL},
188};
189
Thomas Wouters477c8d52006-05-27 19:21:47 +0000190static PyObject *
191BaseException_get_args(PyBaseExceptionObject *self)
192{
193 if (self->args == NULL) {
194 Py_INCREF(Py_None);
195 return Py_None;
196 }
197 Py_INCREF(self->args);
198 return self->args;
199}
200
201static int
202BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
203{
204 PyObject *seq;
205 if (val == NULL) {
206 PyErr_SetString(PyExc_TypeError, "args may not be deleted");
207 return -1;
208 }
209 seq = PySequence_Tuple(val);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500210 if (!seq)
211 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000212 Py_CLEAR(self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000213 self->args = seq;
214 return 0;
215}
216
Collin Winter828f04a2007-08-31 00:04:24 +0000217static PyObject *
218BaseException_get_tb(PyBaseExceptionObject *self)
219{
220 if (self->traceback == NULL) {
221 Py_INCREF(Py_None);
222 return Py_None;
223 }
224 Py_INCREF(self->traceback);
225 return self->traceback;
226}
227
228static int
229BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb)
230{
231 if (tb == NULL) {
232 PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
233 return -1;
234 }
235 else if (!(tb == Py_None || PyTraceBack_Check(tb))) {
236 PyErr_SetString(PyExc_TypeError,
237 "__traceback__ must be a traceback or None");
238 return -1;
239 }
240
241 Py_XINCREF(tb);
242 Py_XDECREF(self->traceback);
243 self->traceback = tb;
244 return 0;
245}
246
Georg Brandlab6f2f62009-03-31 04:16:10 +0000247static PyObject *
248BaseException_get_context(PyObject *self) {
249 PyObject *res = PyException_GetContext(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500250 if (res)
251 return res; /* new reference already returned above */
Georg Brandlab6f2f62009-03-31 04:16:10 +0000252 Py_RETURN_NONE;
253}
254
255static int
256BaseException_set_context(PyObject *self, PyObject *arg) {
257 if (arg == NULL) {
258 PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
259 return -1;
260 } else if (arg == Py_None) {
261 arg = NULL;
262 } else if (!PyExceptionInstance_Check(arg)) {
263 PyErr_SetString(PyExc_TypeError, "exception context must be None "
264 "or derive from BaseException");
265 return -1;
266 } else {
267 /* PyException_SetContext steals this reference */
268 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 }
Georg Brandlab6f2f62009-03-31 04:16:10 +0000270 PyException_SetContext(self, arg);
271 return 0;
272}
273
274static PyObject *
275BaseException_get_cause(PyObject *self) {
276 PyObject *res = PyException_GetCause(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500277 if (res)
278 return res; /* new reference already returned above */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700279 Py_RETURN_NONE;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000280}
281
282static int
283BaseException_set_cause(PyObject *self, PyObject *arg) {
284 if (arg == NULL) {
285 PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
286 return -1;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700287 } else if (arg == Py_None) {
288 arg = NULL;
289 } else if (!PyExceptionInstance_Check(arg)) {
290 PyErr_SetString(PyExc_TypeError, "exception cause must be None "
291 "or derive from BaseException");
292 return -1;
293 } else {
294 /* PyException_SetCause steals this reference */
295 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700297 PyException_SetCause(self, arg);
298 return 0;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000299}
300
Guido van Rossum360e4b82007-05-14 22:51:27 +0000301
Thomas Wouters477c8d52006-05-27 19:21:47 +0000302static PyGetSetDef BaseException_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500303 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000304 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
Collin Winter828f04a2007-08-31 00:04:24 +0000305 {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
Georg Brandlab6f2f62009-03-31 04:16:10 +0000306 {"__context__", (getter)BaseException_get_context,
307 (setter)BaseException_set_context, PyDoc_STR("exception context")},
308 {"__cause__", (getter)BaseException_get_cause,
309 (setter)BaseException_set_cause, PyDoc_STR("exception cause")},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000310 {NULL},
311};
312
313
Collin Winter828f04a2007-08-31 00:04:24 +0000314PyObject *
315PyException_GetTraceback(PyObject *self) {
316 PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
317 Py_XINCREF(base_self->traceback);
318 return base_self->traceback;
319}
320
321
322int
323PyException_SetTraceback(PyObject *self, PyObject *tb) {
324 return BaseException_set_tb((PyBaseExceptionObject *)self, tb);
325}
326
327PyObject *
328PyException_GetCause(PyObject *self) {
329 PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
330 Py_XINCREF(cause);
331 return cause;
332}
333
334/* Steals a reference to cause */
335void
336PyException_SetCause(PyObject *self, PyObject *cause) {
337 PyObject *old_cause = ((PyBaseExceptionObject *)self)->cause;
338 ((PyBaseExceptionObject *)self)->cause = cause;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700339 ((PyBaseExceptionObject *)self)->suppress_context = 1;
Collin Winter828f04a2007-08-31 00:04:24 +0000340 Py_XDECREF(old_cause);
341}
342
343PyObject *
344PyException_GetContext(PyObject *self) {
345 PyObject *context = ((PyBaseExceptionObject *)self)->context;
346 Py_XINCREF(context);
347 return context;
348}
349
350/* Steals a reference to context */
351void
352PyException_SetContext(PyObject *self, PyObject *context) {
353 PyObject *old_context = ((PyBaseExceptionObject *)self)->context;
354 ((PyBaseExceptionObject *)self)->context = context;
355 Py_XDECREF(old_context);
356}
357
358
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700359static struct PyMemberDef BaseException_members[] = {
360 {"__suppress_context__", T_BOOL,
Antoine Pitrou32bc80c2012-05-16 12:51:55 +0200361 offsetof(PyBaseExceptionObject, suppress_context)},
362 {NULL}
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700363};
364
365
Thomas Wouters477c8d52006-05-27 19:21:47 +0000366static PyTypeObject _PyExc_BaseException = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000367 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +0000368 "BaseException", /*tp_name*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000369 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
370 0, /*tp_itemsize*/
371 (destructor)BaseException_dealloc, /*tp_dealloc*/
372 0, /*tp_print*/
373 0, /*tp_getattr*/
374 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000375 0, /* tp_reserved; */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000376 (reprfunc)BaseException_repr, /*tp_repr*/
377 0, /*tp_as_number*/
Brett Cannonba7bf492007-02-27 00:15:55 +0000378 0, /*tp_as_sequence*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000379 0, /*tp_as_mapping*/
380 0, /*tp_hash */
381 0, /*tp_call*/
382 (reprfunc)BaseException_str, /*tp_str*/
383 PyObject_GenericGetAttr, /*tp_getattro*/
384 PyObject_GenericSetAttr, /*tp_setattro*/
385 0, /*tp_as_buffer*/
Thomas Wouters27d517b2007-02-25 20:39:11 +0000386 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000388 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
389 (traverseproc)BaseException_traverse, /* tp_traverse */
390 (inquiry)BaseException_clear, /* tp_clear */
391 0, /* tp_richcompare */
392 0, /* tp_weaklistoffset */
393 0, /* tp_iter */
394 0, /* tp_iternext */
395 BaseException_methods, /* tp_methods */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700396 BaseException_members, /* tp_members */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000397 BaseException_getset, /* tp_getset */
398 0, /* tp_base */
399 0, /* tp_dict */
400 0, /* tp_descr_get */
401 0, /* tp_descr_set */
402 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
403 (initproc)BaseException_init, /* tp_init */
404 0, /* tp_alloc */
405 BaseException_new, /* tp_new */
406};
407/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
408from the previous implmentation and also allowing Python objects to be used
409in the API */
410PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
411
412/* note these macros omit the last semicolon so the macro invocation may
413 * include it and not look strange.
414 */
415#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
416static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000417 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000418 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000419 sizeof(PyBaseExceptionObject), \
420 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
421 0, 0, 0, 0, 0, 0, 0, \
422 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
423 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
424 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
425 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
426 (initproc)BaseException_init, 0, BaseException_new,\
427}; \
428PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
429
430#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
431static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000432 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000433 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000434 sizeof(Py ## EXCSTORE ## Object), \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000435 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000436 0, 0, 0, 0, 0, \
437 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000438 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
439 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000440 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200441 (initproc)EXCSTORE ## _init, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000442}; \
443PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
444
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200445#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
446 EXCMETHODS, EXCMEMBERS, EXCGETSET, \
447 EXCSTR, EXCDOC) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000448static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000449 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000450 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000451 sizeof(Py ## EXCSTORE ## Object), 0, \
452 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
453 (reprfunc)EXCSTR, 0, 0, 0, \
454 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
455 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
456 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200457 EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200459 (initproc)EXCSTORE ## _init, 0, EXCNEW,\
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460}; \
461PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
462
463
464/*
465 * Exception extends BaseException
466 */
467SimpleExtendsException(PyExc_BaseException, Exception,
468 "Common base class for all non-exit exceptions.");
469
470
471/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000472 * TypeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000473 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000474SimpleExtendsException(PyExc_Exception, TypeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000475 "Inappropriate argument type.");
476
477
478/*
479 * StopIteration extends Exception
480 */
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000481
482static PyMemberDef StopIteration_members[] = {
483 {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
484 PyDoc_STR("generator return value")},
485 {NULL} /* Sentinel */
486};
487
488static int
489StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
490{
491 Py_ssize_t size = PyTuple_GET_SIZE(args);
492 PyObject *value;
493
494 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
495 return -1;
496 Py_CLEAR(self->value);
497 if (size > 0)
498 value = PyTuple_GET_ITEM(args, 0);
499 else
500 value = Py_None;
501 Py_INCREF(value);
502 self->value = value;
503 return 0;
504}
505
506static int
507StopIteration_clear(PyStopIterationObject *self)
508{
509 Py_CLEAR(self->value);
510 return BaseException_clear((PyBaseExceptionObject *)self);
511}
512
513static void
514StopIteration_dealloc(PyStopIterationObject *self)
515{
516 _PyObject_GC_UNTRACK(self);
517 StopIteration_clear(self);
518 Py_TYPE(self)->tp_free((PyObject *)self);
519}
520
521static int
522StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
523{
524 Py_VISIT(self->value);
525 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
526}
527
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000528ComplexExtendsException(
529 PyExc_Exception, /* base */
530 StopIteration, /* name */
531 StopIteration, /* prefix for *_init, etc */
532 0, /* new */
533 0, /* methods */
534 StopIteration_members, /* members */
535 0, /* getset */
536 0, /* str */
537 "Signal the end from iterator.__next__()."
538);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539
540
541/*
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000542 * GeneratorExit extends BaseException
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 */
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000544SimpleExtendsException(PyExc_BaseException, GeneratorExit,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545 "Request that a generator exit.");
546
547
548/*
549 * SystemExit extends BaseException
550 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551
552static int
553SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
554{
555 Py_ssize_t size = PyTuple_GET_SIZE(args);
556
557 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
558 return -1;
559
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000560 if (size == 0)
561 return 0;
562 Py_CLEAR(self->code);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000563 if (size == 1)
564 self->code = PyTuple_GET_ITEM(args, 0);
Victor Stinner92236e52011-05-26 14:25:54 +0200565 else /* size > 1 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000566 self->code = args;
567 Py_INCREF(self->code);
568 return 0;
569}
570
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000571static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572SystemExit_clear(PySystemExitObject *self)
573{
574 Py_CLEAR(self->code);
575 return BaseException_clear((PyBaseExceptionObject *)self);
576}
577
578static void
579SystemExit_dealloc(PySystemExitObject *self)
580{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000581 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000582 SystemExit_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000583 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000584}
585
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000586static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
588{
589 Py_VISIT(self->code);
590 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
591}
592
593static PyMemberDef SystemExit_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000594 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
595 PyDoc_STR("exception code")},
596 {NULL} /* Sentinel */
597};
598
599ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200600 0, 0, SystemExit_members, 0, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000601 "Request to exit from the interpreter.");
602
603/*
604 * KeyboardInterrupt extends BaseException
605 */
606SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
607 "Program interrupted by user.");
608
609
610/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000611 * ImportError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000612 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000613
Brett Cannon79ec55e2012-04-12 20:24:54 -0400614static int
615ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
616{
617 PyObject *msg = NULL;
618 PyObject *name = NULL;
619 PyObject *path = NULL;
620
621/* Macro replacement doesn't allow ## to start the first line of a macro,
622 so we move the assignment and NULL check into the if-statement. */
623#define GET_KWD(kwd) { \
624 kwd = PyDict_GetItemString(kwds, #kwd); \
625 if (kwd) { \
626 Py_CLEAR(self->kwd); \
627 self->kwd = kwd; \
628 Py_INCREF(self->kwd);\
629 if (PyDict_DelItemString(kwds, #kwd)) \
630 return -1; \
631 } \
632 }
633
634 if (kwds) {
635 GET_KWD(name);
636 GET_KWD(path);
637 }
638
639 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
640 return -1;
641 if (PyTuple_GET_SIZE(args) != 1)
642 return 0;
643 if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
644 return -1;
645
646 Py_CLEAR(self->msg); /* replacing */
647 self->msg = msg;
648 Py_INCREF(self->msg);
649
650 return 0;
651}
652
653static int
654ImportError_clear(PyImportErrorObject *self)
655{
656 Py_CLEAR(self->msg);
657 Py_CLEAR(self->name);
658 Py_CLEAR(self->path);
659 return BaseException_clear((PyBaseExceptionObject *)self);
660}
661
662static void
663ImportError_dealloc(PyImportErrorObject *self)
664{
665 _PyObject_GC_UNTRACK(self);
666 ImportError_clear(self);
667 Py_TYPE(self)->tp_free((PyObject *)self);
668}
669
670static int
671ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
672{
673 Py_VISIT(self->msg);
674 Py_VISIT(self->name);
675 Py_VISIT(self->path);
676 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
677}
678
679static PyObject *
680ImportError_str(PyImportErrorObject *self)
681{
Brett Cannon07c6e712012-08-24 13:05:09 -0400682 if (self->msg && PyUnicode_CheckExact(self->msg)) {
Brett Cannon79ec55e2012-04-12 20:24:54 -0400683 Py_INCREF(self->msg);
684 return self->msg;
685 }
686 else {
687 return BaseException_str((PyBaseExceptionObject *)self);
688 }
689}
690
691static PyMemberDef ImportError_members[] = {
692 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
693 PyDoc_STR("exception message")},
694 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
695 PyDoc_STR("module name")},
696 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
697 PyDoc_STR("module path")},
698 {NULL} /* Sentinel */
699};
700
701static PyMethodDef ImportError_methods[] = {
702 {NULL}
703};
704
705ComplexExtendsException(PyExc_Exception, ImportError,
706 ImportError, 0 /* new */,
707 ImportError_methods, ImportError_members,
708 0 /* getset */, ImportError_str,
709 "Import can't find module, or can't find name in "
710 "module.");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711
712/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200713 * OSError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000714 */
715
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200716#ifdef MS_WINDOWS
717#include "errmap.h"
718#endif
719
Thomas Wouters477c8d52006-05-27 19:21:47 +0000720/* Where a function has a single filename, such as open() or some
721 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
722 * called, giving a third argument which is the filename. But, so
723 * that old code using in-place unpacking doesn't break, e.g.:
724 *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200725 * except OSError, (errno, strerror):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000726 *
727 * we hack args so that it only contains two items. This also
728 * means we need our own __str__() which prints out the filename
729 * when it was supplied.
730 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200731
Antoine Pitroue0e27352011-12-15 14:31:28 +0100732/* This function doesn't cleanup on error, the caller should */
733static int
734oserror_parse_args(PyObject **p_args,
735 PyObject **myerrno, PyObject **strerror,
736 PyObject **filename
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200737#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100738 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200739#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100740 )
741{
742 Py_ssize_t nargs;
743 PyObject *args = *p_args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000744
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200745 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000746
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200747#ifdef MS_WINDOWS
748 if (nargs >= 2 && nargs <= 4) {
749 if (!PyArg_UnpackTuple(args, "OSError", 2, 4,
Antoine Pitroue0e27352011-12-15 14:31:28 +0100750 myerrno, strerror, filename, winerror))
751 return -1;
752 if (*winerror && PyLong_Check(*winerror)) {
753 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200754 PyObject *newargs;
755 Py_ssize_t i;
756
Antoine Pitroue0e27352011-12-15 14:31:28 +0100757 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200758 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100759 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200760 /* Set errno to the corresponding POSIX errno (overriding
761 first argument). Windows Socket error codes (>= 10000)
762 have the same value as their POSIX counterparts.
763 */
764 if (winerrcode < 10000)
765 errcode = winerror_to_errno(winerrcode);
766 else
767 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100768 *myerrno = PyLong_FromLong(errcode);
769 if (!*myerrno)
770 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200771 newargs = PyTuple_New(nargs);
772 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100773 return -1;
774 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200775 for (i = 1; i < nargs; i++) {
776 PyObject *val = PyTuple_GET_ITEM(args, i);
777 Py_INCREF(val);
778 PyTuple_SET_ITEM(newargs, i, val);
779 }
780 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100781 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200782 }
783 }
784#else
785 if (nargs >= 2 && nargs <= 3) {
786 if (!PyArg_UnpackTuple(args, "OSError", 2, 3,
Antoine Pitroue0e27352011-12-15 14:31:28 +0100787 myerrno, strerror, filename))
788 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200789 }
790#endif
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000791
Antoine Pitroue0e27352011-12-15 14:31:28 +0100792 return 0;
793}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000794
Antoine Pitroue0e27352011-12-15 14:31:28 +0100795static int
796oserror_init(PyOSErrorObject *self, PyObject **p_args,
797 PyObject *myerrno, PyObject *strerror,
798 PyObject *filename
799#ifdef MS_WINDOWS
800 , PyObject *winerror
801#endif
802 )
803{
804 PyObject *args = *p_args;
805 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000806
807 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200808 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100809 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200810 PyNumber_Check(filename)) {
811 /* BlockingIOError's 3rd argument can be the number of
812 * characters written.
813 */
814 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
815 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100816 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200817 }
818 else {
819 Py_INCREF(filename);
820 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000821
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200822 if (nargs >= 2 && nargs <= 3) {
823 /* filename is removed from the args tuple (for compatibility
824 purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100825 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200826 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100827 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000828
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200829 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100830 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200831 }
832 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000833 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200834 Py_XINCREF(myerrno);
835 self->myerrno = myerrno;
836
837 Py_XINCREF(strerror);
838 self->strerror = strerror;
839
840#ifdef MS_WINDOWS
841 Py_XINCREF(winerror);
842 self->winerror = winerror;
843#endif
844
Antoine Pitroue0e27352011-12-15 14:31:28 +0100845 /* Steals the reference to args */
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200846 Py_CLEAR(self->args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100847 self->args = args;
Victor Stinner46ef3192013-11-14 22:31:41 +0100848 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100849
850 return 0;
851}
852
853static PyObject *
854OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
855static int
856OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
857
858static int
859oserror_use_init(PyTypeObject *type)
860{
861 /* When __init__ is defined in a OSError subclass, we want any
862 extraneous argument to __new__ to be ignored. The only reasonable
863 solution, given __new__ takes a variable number of arguments,
864 is to defer arg parsing and initialization to __init__.
865
866 But when __new__ is overriden as well, it should call our __new__
867 with the right arguments.
868
869 (see http://bugs.python.org/issue12555#msg148829 )
870 */
871 if (type->tp_init != (initproc) OSError_init &&
872 type->tp_new == (newfunc) OSError_new) {
873 assert((PyObject *) type != PyExc_OSError);
874 return 1;
875 }
876 return 0;
877}
878
879static PyObject *
880OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
881{
882 PyOSErrorObject *self = NULL;
883 PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL;
884#ifdef MS_WINDOWS
885 PyObject *winerror = NULL;
886#endif
887
Victor Stinner46ef3192013-11-14 22:31:41 +0100888 Py_INCREF(args);
889
Antoine Pitroue0e27352011-12-15 14:31:28 +0100890 if (!oserror_use_init(type)) {
891 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100892 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100893
Antoine Pitroue0e27352011-12-15 14:31:28 +0100894 if (oserror_parse_args(&args, &myerrno, &strerror, &filename
895#ifdef MS_WINDOWS
896 , &winerror
897#endif
898 ))
899 goto error;
900
901 if (myerrno && PyLong_Check(myerrno) &&
902 errnomap && (PyObject *) type == PyExc_OSError) {
903 PyObject *newtype;
904 newtype = PyDict_GetItem(errnomap, myerrno);
905 if (newtype) {
906 assert(PyType_Check(newtype));
907 type = (PyTypeObject *) newtype;
908 }
909 else if (PyErr_Occurred())
910 goto error;
911 }
912 }
913
914 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
915 if (!self)
916 goto error;
917
918 self->dict = NULL;
919 self->traceback = self->cause = self->context = NULL;
920 self->written = -1;
921
922 if (!oserror_use_init(type)) {
923 if (oserror_init(self, &args, myerrno, strerror, filename
924#ifdef MS_WINDOWS
925 , winerror
926#endif
927 ))
928 goto error;
929 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200930 else {
931 self->args = PyTuple_New(0);
932 if (self->args == NULL)
933 goto error;
934 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100935
Victor Stinner46ef3192013-11-14 22:31:41 +0100936 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200937 return (PyObject *) self;
938
939error:
940 Py_XDECREF(args);
941 Py_XDECREF(self);
942 return NULL;
943}
944
945static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100946OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200947{
Antoine Pitroue0e27352011-12-15 14:31:28 +0100948 PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL;
949#ifdef MS_WINDOWS
950 PyObject *winerror = NULL;
951#endif
952
953 if (!oserror_use_init(Py_TYPE(self)))
954 /* Everything already done in OSError_new */
955 return 0;
956
957 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
958 return -1;
959
960 Py_INCREF(args);
961 if (oserror_parse_args(&args, &myerrno, &strerror, &filename
962#ifdef MS_WINDOWS
963 , &winerror
964#endif
965 ))
966 goto error;
967
968 if (oserror_init(self, &args, myerrno, strerror, filename
969#ifdef MS_WINDOWS
970 , winerror
971#endif
972 ))
973 goto error;
974
Thomas Wouters477c8d52006-05-27 19:21:47 +0000975 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100976
977error:
978 Py_XDECREF(args);
979 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000980}
981
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000982static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200983OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000984{
985 Py_CLEAR(self->myerrno);
986 Py_CLEAR(self->strerror);
987 Py_CLEAR(self->filename);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200988#ifdef MS_WINDOWS
989 Py_CLEAR(self->winerror);
990#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +0000991 return BaseException_clear((PyBaseExceptionObject *)self);
992}
993
994static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200995OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000996{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000997 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200998 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000999 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001000}
1001
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001002static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001003OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001004 void *arg)
1005{
1006 Py_VISIT(self->myerrno);
1007 Py_VISIT(self->strerror);
1008 Py_VISIT(self->filename);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001009#ifdef MS_WINDOWS
1010 Py_VISIT(self->winerror);
1011#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001012 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1013}
1014
1015static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001016OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001017{
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001018#ifdef MS_WINDOWS
1019 /* If available, winerror has the priority over myerrno */
1020 if (self->winerror && self->filename)
Richard Oudkerk30147712012-08-28 19:33:26 +01001021 return PyUnicode_FromFormat("[WinError %S] %S: %R",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001022 self->winerror ? self->winerror: Py_None,
1023 self->strerror ? self->strerror: Py_None,
1024 self->filename);
1025 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001026 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001027 self->winerror ? self->winerror: Py_None,
1028 self->strerror ? self->strerror: Py_None);
1029#endif
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001030 if (self->filename)
1031 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1032 self->myerrno ? self->myerrno: Py_None,
1033 self->strerror ? self->strerror: Py_None,
1034 self->filename);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001035 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001036 return PyUnicode_FromFormat("[Errno %S] %S",
1037 self->myerrno ? self->myerrno: Py_None,
1038 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001039 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001040}
1041
Thomas Wouters477c8d52006-05-27 19:21:47 +00001042static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001043OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001044{
1045 PyObject *args = self->args;
1046 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001047
Thomas Wouters477c8d52006-05-27 19:21:47 +00001048 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001049 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001050 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001051 args = PyTuple_New(3);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001052 if (!args)
1053 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001054
1055 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001056 Py_INCREF(tmp);
1057 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001058
1059 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001060 Py_INCREF(tmp);
1061 PyTuple_SET_ITEM(args, 1, tmp);
1062
1063 Py_INCREF(self->filename);
1064 PyTuple_SET_ITEM(args, 2, self->filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001065 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001066 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001067
1068 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001069 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001070 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001071 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072 Py_DECREF(args);
1073 return res;
1074}
1075
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001076static PyObject *
1077OSError_written_get(PyOSErrorObject *self, void *context)
1078{
1079 if (self->written == -1) {
1080 PyErr_SetString(PyExc_AttributeError, "characters_written");
1081 return NULL;
1082 }
1083 return PyLong_FromSsize_t(self->written);
1084}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001085
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001086static int
1087OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1088{
1089 Py_ssize_t n;
1090 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1091 if (n == -1 && PyErr_Occurred())
1092 return -1;
1093 self->written = n;
1094 return 0;
1095}
1096
1097static PyMemberDef OSError_members[] = {
1098 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1099 PyDoc_STR("POSIX exception code")},
1100 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1101 PyDoc_STR("exception strerror")},
1102 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1103 PyDoc_STR("exception filename")},
1104#ifdef MS_WINDOWS
1105 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1106 PyDoc_STR("Win32 exception code")},
1107#endif
1108 {NULL} /* Sentinel */
1109};
1110
1111static PyMethodDef OSError_methods[] = {
1112 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001113 {NULL}
1114};
1115
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001116static PyGetSetDef OSError_getset[] = {
1117 {"characters_written", (getter) OSError_written_get,
1118 (setter) OSError_written_set, NULL},
1119 {NULL}
1120};
1121
1122
1123ComplexExtendsException(PyExc_Exception, OSError,
1124 OSError, OSError_new,
1125 OSError_methods, OSError_members, OSError_getset,
1126 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127 "Base class for I/O related errors.");
1128
1129
1130/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001131 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001132 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001133MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1134 "I/O operation would block.");
1135MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1136 "Connection error.");
1137MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1138 "Child process error.");
1139MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1140 "Broken pipe.");
1141MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1142 "Connection aborted.");
1143MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1144 "Connection refused.");
1145MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1146 "Connection reset.");
1147MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1148 "File already exists.");
1149MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1150 "File not found.");
1151MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1152 "Operation doesn't work on directories.");
1153MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1154 "Operation only works on directories.");
1155MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1156 "Interrupted by signal.");
1157MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1158 "Not enough permissions.");
1159MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1160 "Process not found.");
1161MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1162 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163
1164/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001165 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001167SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001168 "Read beyond end of file.");
1169
1170
1171/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001172 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001173 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001174SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001175 "Unspecified run-time error.");
1176
1177
1178/*
1179 * NotImplementedError extends RuntimeError
1180 */
1181SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1182 "Method or function hasn't been implemented yet.");
1183
1184/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001185 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001186 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001187SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001188 "Name not found globally.");
1189
1190/*
1191 * UnboundLocalError extends NameError
1192 */
1193SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1194 "Local name referenced but not bound to a value.");
1195
1196/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001197 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001198 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001199SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001200 "Attribute not found.");
1201
1202
1203/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001204 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001205 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001206
1207static int
1208SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1209{
1210 PyObject *info = NULL;
1211 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1212
1213 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1214 return -1;
1215
1216 if (lenargs >= 1) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001217 Py_CLEAR(self->msg);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001218 self->msg = PyTuple_GET_ITEM(args, 0);
1219 Py_INCREF(self->msg);
1220 }
1221 if (lenargs == 2) {
1222 info = PyTuple_GET_ITEM(args, 1);
1223 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001224 if (!info)
1225 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001226
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001227 if (PyTuple_GET_SIZE(info) != 4) {
1228 /* not a very good error message, but it's what Python 2.4 gives */
1229 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1230 Py_DECREF(info);
1231 return -1;
1232 }
1233
1234 Py_CLEAR(self->filename);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001235 self->filename = PyTuple_GET_ITEM(info, 0);
1236 Py_INCREF(self->filename);
1237
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001238 Py_CLEAR(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001239 self->lineno = PyTuple_GET_ITEM(info, 1);
1240 Py_INCREF(self->lineno);
1241
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001242 Py_CLEAR(self->offset);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001243 self->offset = PyTuple_GET_ITEM(info, 2);
1244 Py_INCREF(self->offset);
1245
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001246 Py_CLEAR(self->text);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001247 self->text = PyTuple_GET_ITEM(info, 3);
1248 Py_INCREF(self->text);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001249
1250 Py_DECREF(info);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001251 }
1252 return 0;
1253}
1254
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001255static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256SyntaxError_clear(PySyntaxErrorObject *self)
1257{
1258 Py_CLEAR(self->msg);
1259 Py_CLEAR(self->filename);
1260 Py_CLEAR(self->lineno);
1261 Py_CLEAR(self->offset);
1262 Py_CLEAR(self->text);
1263 Py_CLEAR(self->print_file_and_line);
1264 return BaseException_clear((PyBaseExceptionObject *)self);
1265}
1266
1267static void
1268SyntaxError_dealloc(PySyntaxErrorObject *self)
1269{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001270 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001271 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001272 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001273}
1274
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001275static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001276SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1277{
1278 Py_VISIT(self->msg);
1279 Py_VISIT(self->filename);
1280 Py_VISIT(self->lineno);
1281 Py_VISIT(self->offset);
1282 Py_VISIT(self->text);
1283 Py_VISIT(self->print_file_and_line);
1284 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1285}
1286
1287/* This is called "my_basename" instead of just "basename" to avoid name
1288 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1289 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001290static PyObject*
1291my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001292{
Victor Stinner6237daf2010-04-28 17:26:19 +00001293 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001294 int kind;
1295 void *data;
1296
1297 if (PyUnicode_READY(name))
1298 return NULL;
1299 kind = PyUnicode_KIND(name);
1300 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001301 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001302 offset = 0;
1303 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001305 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001306 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307 if (offset != 0)
1308 return PyUnicode_Substring(name, offset, size);
1309 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001310 Py_INCREF(name);
1311 return name;
1312 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001313}
1314
1315
1316static PyObject *
1317SyntaxError_str(PySyntaxErrorObject *self)
1318{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001319 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001320 PyObject *filename;
1321 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001322 /* Below, we always ignore overflow errors, just printing -1.
1323 Still, we cannot allow an OverflowError to be raised, so
1324 we need to call PyLong_AsLongAndOverflow. */
1325 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001326
1327 /* XXX -- do all the additional formatting with filename and
1328 lineno here */
1329
Neal Norwitzed2b7392007-08-26 04:51:10 +00001330 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001331 filename = my_basename(self->filename);
1332 if (filename == NULL)
1333 return NULL;
1334 } else {
1335 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001336 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001337 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001338
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001339 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001340 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001341
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001342 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001343 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001344 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001345 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001347 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001348 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001349 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001350 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001351 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001352 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001353 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001354 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001355 Py_XDECREF(filename);
1356 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001357}
1358
1359static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001360 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1361 PyDoc_STR("exception msg")},
1362 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1363 PyDoc_STR("exception filename")},
1364 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1365 PyDoc_STR("exception lineno")},
1366 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1367 PyDoc_STR("exception offset")},
1368 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1369 PyDoc_STR("exception text")},
1370 {"print_file_and_line", T_OBJECT,
1371 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1372 PyDoc_STR("exception print_file_and_line")},
1373 {NULL} /* Sentinel */
1374};
1375
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001376ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001377 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378 SyntaxError_str, "Invalid syntax.");
1379
1380
1381/*
1382 * IndentationError extends SyntaxError
1383 */
1384MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1385 "Improper indentation.");
1386
1387
1388/*
1389 * TabError extends IndentationError
1390 */
1391MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1392 "Improper mixture of spaces and tabs.");
1393
1394
1395/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001396 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001397 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001398SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001399 "Base class for lookup errors.");
1400
1401
1402/*
1403 * IndexError extends LookupError
1404 */
1405SimpleExtendsException(PyExc_LookupError, IndexError,
1406 "Sequence index out of range.");
1407
1408
1409/*
1410 * KeyError extends LookupError
1411 */
1412static PyObject *
1413KeyError_str(PyBaseExceptionObject *self)
1414{
1415 /* If args is a tuple of exactly one item, apply repr to args[0].
1416 This is done so that e.g. the exception raised by {}[''] prints
1417 KeyError: ''
1418 rather than the confusing
1419 KeyError
1420 alone. The downside is that if KeyError is raised with an explanatory
1421 string, that string will be displayed in quotes. Too bad.
1422 If args is anything else, use the default BaseException__str__().
1423 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001424 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001425 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001426 }
1427 return BaseException_str(self);
1428}
1429
1430ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001431 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001432
1433
1434/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001435 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001436 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001437SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001438 "Inappropriate argument value (of correct type).");
1439
1440/*
1441 * UnicodeError extends ValueError
1442 */
1443
1444SimpleExtendsException(PyExc_ValueError, UnicodeError,
1445 "Unicode related error.");
1446
Thomas Wouters477c8d52006-05-27 19:21:47 +00001447static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001448get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001449{
1450 if (!attr) {
1451 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1452 return NULL;
1453 }
1454
Christian Heimes72b710a2008-05-26 13:28:38 +00001455 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001456 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1457 return NULL;
1458 }
1459 Py_INCREF(attr);
1460 return attr;
1461}
1462
1463static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001464get_unicode(PyObject *attr, const char *name)
1465{
1466 if (!attr) {
1467 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1468 return NULL;
1469 }
1470
1471 if (!PyUnicode_Check(attr)) {
1472 PyErr_Format(PyExc_TypeError,
1473 "%.200s attribute must be unicode", name);
1474 return NULL;
1475 }
1476 Py_INCREF(attr);
1477 return attr;
1478}
1479
Walter Dörwaldd2034312007-05-18 16:29:38 +00001480static int
1481set_unicodefromstring(PyObject **attr, const char *value)
1482{
1483 PyObject *obj = PyUnicode_FromString(value);
1484 if (!obj)
1485 return -1;
1486 Py_CLEAR(*attr);
1487 *attr = obj;
1488 return 0;
1489}
1490
Thomas Wouters477c8d52006-05-27 19:21:47 +00001491PyObject *
1492PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1493{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001494 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001495}
1496
1497PyObject *
1498PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1499{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001500 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001501}
1502
1503PyObject *
1504PyUnicodeEncodeError_GetObject(PyObject *exc)
1505{
1506 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1507}
1508
1509PyObject *
1510PyUnicodeDecodeError_GetObject(PyObject *exc)
1511{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001512 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001513}
1514
1515PyObject *
1516PyUnicodeTranslateError_GetObject(PyObject *exc)
1517{
1518 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1519}
1520
1521int
1522PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1523{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001524 Py_ssize_t size;
1525 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1526 "object");
1527 if (!obj)
1528 return -1;
1529 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001530 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001531 if (*start<0)
1532 *start = 0; /*XXX check for values <0*/
1533 if (*start>=size)
1534 *start = size-1;
1535 Py_DECREF(obj);
1536 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001537}
1538
1539
1540int
1541PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1542{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001543 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001544 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001545 if (!obj)
1546 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001547 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001548 *start = ((PyUnicodeErrorObject *)exc)->start;
1549 if (*start<0)
1550 *start = 0;
1551 if (*start>=size)
1552 *start = size-1;
1553 Py_DECREF(obj);
1554 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001555}
1556
1557
1558int
1559PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1560{
1561 return PyUnicodeEncodeError_GetStart(exc, start);
1562}
1563
1564
1565int
1566PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1567{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001568 ((PyUnicodeErrorObject *)exc)->start = start;
1569 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001570}
1571
1572
1573int
1574PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1575{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001576 ((PyUnicodeErrorObject *)exc)->start = start;
1577 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001578}
1579
1580
1581int
1582PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1583{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001584 ((PyUnicodeErrorObject *)exc)->start = start;
1585 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001586}
1587
1588
1589int
1590PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1591{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001592 Py_ssize_t size;
1593 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1594 "object");
1595 if (!obj)
1596 return -1;
1597 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001598 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001599 if (*end<1)
1600 *end = 1;
1601 if (*end>size)
1602 *end = size;
1603 Py_DECREF(obj);
1604 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001605}
1606
1607
1608int
1609PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1610{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001611 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001612 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001613 if (!obj)
1614 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001615 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001616 *end = ((PyUnicodeErrorObject *)exc)->end;
1617 if (*end<1)
1618 *end = 1;
1619 if (*end>size)
1620 *end = size;
1621 Py_DECREF(obj);
1622 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001623}
1624
1625
1626int
1627PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1628{
1629 return PyUnicodeEncodeError_GetEnd(exc, start);
1630}
1631
1632
1633int
1634PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1635{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001636 ((PyUnicodeErrorObject *)exc)->end = end;
1637 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001638}
1639
1640
1641int
1642PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1643{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001644 ((PyUnicodeErrorObject *)exc)->end = end;
1645 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001646}
1647
1648
1649int
1650PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1651{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001652 ((PyUnicodeErrorObject *)exc)->end = end;
1653 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001654}
1655
1656PyObject *
1657PyUnicodeEncodeError_GetReason(PyObject *exc)
1658{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001659 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001660}
1661
1662
1663PyObject *
1664PyUnicodeDecodeError_GetReason(PyObject *exc)
1665{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001666 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001667}
1668
1669
1670PyObject *
1671PyUnicodeTranslateError_GetReason(PyObject *exc)
1672{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001673 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001674}
1675
1676
1677int
1678PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1679{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001680 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1681 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001682}
1683
1684
1685int
1686PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1687{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001688 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1689 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001690}
1691
1692
1693int
1694PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1695{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001696 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1697 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001698}
1699
1700
Thomas Wouters477c8d52006-05-27 19:21:47 +00001701static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001702UnicodeError_clear(PyUnicodeErrorObject *self)
1703{
1704 Py_CLEAR(self->encoding);
1705 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001706 Py_CLEAR(self->reason);
1707 return BaseException_clear((PyBaseExceptionObject *)self);
1708}
1709
1710static void
1711UnicodeError_dealloc(PyUnicodeErrorObject *self)
1712{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001713 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001714 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001715 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716}
1717
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001718static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001719UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1720{
1721 Py_VISIT(self->encoding);
1722 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001723 Py_VISIT(self->reason);
1724 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1725}
1726
1727static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001728 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1729 PyDoc_STR("exception encoding")},
1730 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1731 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001732 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001733 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001734 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001735 PyDoc_STR("exception end")},
1736 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1737 PyDoc_STR("exception reason")},
1738 {NULL} /* Sentinel */
1739};
1740
1741
1742/*
1743 * UnicodeEncodeError extends UnicodeError
1744 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001745
1746static int
1747UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1748{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001749 PyUnicodeErrorObject *err;
1750
Thomas Wouters477c8d52006-05-27 19:21:47 +00001751 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1752 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001753
1754 err = (PyUnicodeErrorObject *)self;
1755
1756 Py_CLEAR(err->encoding);
1757 Py_CLEAR(err->object);
1758 Py_CLEAR(err->reason);
1759
1760 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1761 &PyUnicode_Type, &err->encoding,
1762 &PyUnicode_Type, &err->object,
1763 &err->start,
1764 &err->end,
1765 &PyUnicode_Type, &err->reason)) {
1766 err->encoding = err->object = err->reason = NULL;
1767 return -1;
1768 }
1769
Martin v. Löwisb09af032011-11-04 11:16:41 +01001770 if (PyUnicode_READY(err->object) < -1) {
1771 err->encoding = NULL;
1772 return -1;
1773 }
1774
Guido van Rossum98297ee2007-11-06 21:34:58 +00001775 Py_INCREF(err->encoding);
1776 Py_INCREF(err->object);
1777 Py_INCREF(err->reason);
1778
1779 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001780}
1781
1782static PyObject *
1783UnicodeEncodeError_str(PyObject *self)
1784{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001785 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001786 PyObject *result = NULL;
1787 PyObject *reason_str = NULL;
1788 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001789
Eric Smith0facd772010-02-24 15:42:29 +00001790 /* Get reason and encoding as strings, which they might not be if
1791 they've been modified after we were contructed. */
1792 reason_str = PyObject_Str(uself->reason);
1793 if (reason_str == NULL)
1794 goto done;
1795 encoding_str = PyObject_Str(uself->encoding);
1796 if (encoding_str == NULL)
1797 goto done;
1798
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001799 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1800 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001801 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001802 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001803 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001804 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001805 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001806 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001807 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001808 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001809 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001810 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001811 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001812 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001813 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001814 }
Eric Smith0facd772010-02-24 15:42:29 +00001815 else {
1816 result = PyUnicode_FromFormat(
1817 "'%U' codec can't encode characters in position %zd-%zd: %U",
1818 encoding_str,
1819 uself->start,
1820 uself->end-1,
1821 reason_str);
1822 }
1823done:
1824 Py_XDECREF(reason_str);
1825 Py_XDECREF(encoding_str);
1826 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001827}
1828
1829static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001830 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001831 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001832 sizeof(PyUnicodeErrorObject), 0,
1833 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1834 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1835 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001836 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1837 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001838 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001839 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001840};
1841PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1842
1843PyObject *
1844PyUnicodeEncodeError_Create(
1845 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1846 Py_ssize_t start, Py_ssize_t end, const char *reason)
1847{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001848 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001849 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001850}
1851
1852
1853/*
1854 * UnicodeDecodeError extends UnicodeError
1855 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001856
1857static int
1858UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1859{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001860 PyUnicodeErrorObject *ude;
1861 const char *data;
1862 Py_ssize_t size;
1863
Thomas Wouters477c8d52006-05-27 19:21:47 +00001864 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1865 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001866
1867 ude = (PyUnicodeErrorObject *)self;
1868
1869 Py_CLEAR(ude->encoding);
1870 Py_CLEAR(ude->object);
1871 Py_CLEAR(ude->reason);
1872
1873 if (!PyArg_ParseTuple(args, "O!OnnO!",
1874 &PyUnicode_Type, &ude->encoding,
1875 &ude->object,
1876 &ude->start,
1877 &ude->end,
1878 &PyUnicode_Type, &ude->reason)) {
1879 ude->encoding = ude->object = ude->reason = NULL;
1880 return -1;
1881 }
1882
Christian Heimes72b710a2008-05-26 13:28:38 +00001883 if (!PyBytes_Check(ude->object)) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00001884 if (PyObject_AsReadBuffer(ude->object, (const void **)&data, &size)) {
1885 ude->encoding = ude->object = ude->reason = NULL;
1886 return -1;
1887 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001888 ude->object = PyBytes_FromStringAndSize(data, size);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001889 }
1890 else {
1891 Py_INCREF(ude->object);
1892 }
1893
1894 Py_INCREF(ude->encoding);
1895 Py_INCREF(ude->reason);
1896
1897 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001898}
1899
1900static PyObject *
1901UnicodeDecodeError_str(PyObject *self)
1902{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001903 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001904 PyObject *result = NULL;
1905 PyObject *reason_str = NULL;
1906 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001907
Eric Smith0facd772010-02-24 15:42:29 +00001908 /* Get reason and encoding as strings, which they might not be if
1909 they've been modified after we were contructed. */
1910 reason_str = PyObject_Str(uself->reason);
1911 if (reason_str == NULL)
1912 goto done;
1913 encoding_str = PyObject_Str(uself->encoding);
1914 if (encoding_str == NULL)
1915 goto done;
1916
1917 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001918 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00001919 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001920 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00001921 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001922 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001923 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001924 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001925 }
Eric Smith0facd772010-02-24 15:42:29 +00001926 else {
1927 result = PyUnicode_FromFormat(
1928 "'%U' codec can't decode bytes in position %zd-%zd: %U",
1929 encoding_str,
1930 uself->start,
1931 uself->end-1,
1932 reason_str
1933 );
1934 }
1935done:
1936 Py_XDECREF(reason_str);
1937 Py_XDECREF(encoding_str);
1938 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001939}
1940
1941static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001942 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001943 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001944 sizeof(PyUnicodeErrorObject), 0,
1945 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1946 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
1947 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001948 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
1949 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001950 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001951 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001952};
1953PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
1954
1955PyObject *
1956PyUnicodeDecodeError_Create(
1957 const char *encoding, const char *object, Py_ssize_t length,
1958 Py_ssize_t start, Py_ssize_t end, const char *reason)
1959{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001960 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001961 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001962}
1963
1964
1965/*
1966 * UnicodeTranslateError extends UnicodeError
1967 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001968
1969static int
1970UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
1971 PyObject *kwds)
1972{
1973 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1974 return -1;
1975
1976 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001977 Py_CLEAR(self->reason);
1978
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001979 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001980 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001981 &self->start,
1982 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00001983 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001984 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001985 return -1;
1986 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001987
Thomas Wouters477c8d52006-05-27 19:21:47 +00001988 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001989 Py_INCREF(self->reason);
1990
1991 return 0;
1992}
1993
1994
1995static PyObject *
1996UnicodeTranslateError_str(PyObject *self)
1997{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001998 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001999 PyObject *result = NULL;
2000 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002001
Eric Smith0facd772010-02-24 15:42:29 +00002002 /* Get reason as a string, which it might not be if it's been
2003 modified after we were contructed. */
2004 reason_str = PyObject_Str(uself->reason);
2005 if (reason_str == NULL)
2006 goto done;
2007
Victor Stinner53b33e72011-11-21 01:17:27 +01002008 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2009 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002010 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002011 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002012 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002013 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002014 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002015 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002016 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002017 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002018 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002019 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002020 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002021 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002022 );
Eric Smith0facd772010-02-24 15:42:29 +00002023 } else {
2024 result = PyUnicode_FromFormat(
2025 "can't translate characters in position %zd-%zd: %U",
2026 uself->start,
2027 uself->end-1,
2028 reason_str
2029 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002030 }
Eric Smith0facd772010-02-24 15:42:29 +00002031done:
2032 Py_XDECREF(reason_str);
2033 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002034}
2035
2036static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002037 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002038 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002039 sizeof(PyUnicodeErrorObject), 0,
2040 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2041 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2042 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002043 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002044 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2045 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002046 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002047};
2048PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002051PyObject *
2052PyUnicodeTranslateError_Create(
2053 const Py_UNICODE *object, Py_ssize_t length,
2054 Py_ssize_t start, Py_ssize_t end, const char *reason)
2055{
2056 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002057 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002058}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002059
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002060PyObject *
2061_PyUnicodeTranslateError_Create(
2062 PyObject *object,
2063 Py_ssize_t start, Py_ssize_t end, const char *reason)
2064{
2065 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Ons",
2066 object, start, end, reason);
2067}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002068
2069/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002070 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002071 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002072SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002073 "Assertion failed.");
2074
2075
2076/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002077 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002078 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002079SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002080 "Base class for arithmetic errors.");
2081
2082
2083/*
2084 * FloatingPointError extends ArithmeticError
2085 */
2086SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2087 "Floating point operation failed.");
2088
2089
2090/*
2091 * OverflowError extends ArithmeticError
2092 */
2093SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2094 "Result too large to be represented.");
2095
2096
2097/*
2098 * ZeroDivisionError extends ArithmeticError
2099 */
2100SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2101 "Second argument to a division or modulo operation was zero.");
2102
2103
2104/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002105 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002106 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002107SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002108 "Internal error in the Python interpreter.\n"
2109 "\n"
2110 "Please report this to the Python maintainer, along with the traceback,\n"
2111 "the Python version, and the hardware/OS platform and version.");
2112
2113
2114/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002115 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002116 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002117SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002118 "Weak ref proxy used after referent went away.");
2119
2120
2121/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002122 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002123 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002124
2125#define MEMERRORS_SAVE 16
2126static PyBaseExceptionObject *memerrors_freelist = NULL;
2127static int memerrors_numfree = 0;
2128
2129static PyObject *
2130MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2131{
2132 PyBaseExceptionObject *self;
2133
2134 if (type != (PyTypeObject *) PyExc_MemoryError)
2135 return BaseException_new(type, args, kwds);
2136 if (memerrors_freelist == NULL)
2137 return BaseException_new(type, args, kwds);
2138 /* Fetch object from freelist and revive it */
2139 self = memerrors_freelist;
2140 self->args = PyTuple_New(0);
2141 /* This shouldn't happen since the empty tuple is persistent */
2142 if (self->args == NULL)
2143 return NULL;
2144 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2145 memerrors_numfree--;
2146 self->dict = NULL;
2147 _Py_NewReference((PyObject *)self);
2148 _PyObject_GC_TRACK(self);
2149 return (PyObject *)self;
2150}
2151
2152static void
2153MemoryError_dealloc(PyBaseExceptionObject *self)
2154{
2155 _PyObject_GC_UNTRACK(self);
2156 BaseException_clear(self);
2157 if (memerrors_numfree >= MEMERRORS_SAVE)
2158 Py_TYPE(self)->tp_free((PyObject *)self);
2159 else {
2160 self->dict = (PyObject *) memerrors_freelist;
2161 memerrors_freelist = self;
2162 memerrors_numfree++;
2163 }
2164}
2165
2166static void
2167preallocate_memerrors(void)
2168{
2169 /* We create enough MemoryErrors and then decref them, which will fill
2170 up the freelist. */
2171 int i;
2172 PyObject *errors[MEMERRORS_SAVE];
2173 for (i = 0; i < MEMERRORS_SAVE; i++) {
2174 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2175 NULL, NULL);
2176 if (!errors[i])
2177 Py_FatalError("Could not preallocate MemoryError object");
2178 }
2179 for (i = 0; i < MEMERRORS_SAVE; i++) {
2180 Py_DECREF(errors[i]);
2181 }
2182}
2183
2184static void
2185free_preallocated_memerrors(void)
2186{
2187 while (memerrors_freelist != NULL) {
2188 PyObject *self = (PyObject *) memerrors_freelist;
2189 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2190 Py_TYPE(self)->tp_free((PyObject *)self);
2191 }
2192}
2193
2194
2195static PyTypeObject _PyExc_MemoryError = {
2196 PyVarObject_HEAD_INIT(NULL, 0)
2197 "MemoryError",
2198 sizeof(PyBaseExceptionObject),
2199 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2200 0, 0, 0, 0, 0, 0, 0,
2201 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2202 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2203 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2204 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2205 (initproc)BaseException_init, 0, MemoryError_new
2206};
2207PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2208
Thomas Wouters477c8d52006-05-27 19:21:47 +00002209
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002210/*
2211 * BufferError extends Exception
2212 */
2213SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2214
Thomas Wouters477c8d52006-05-27 19:21:47 +00002215
2216/* Warning category docstrings */
2217
2218/*
2219 * Warning extends Exception
2220 */
2221SimpleExtendsException(PyExc_Exception, Warning,
2222 "Base class for warning categories.");
2223
2224
2225/*
2226 * UserWarning extends Warning
2227 */
2228SimpleExtendsException(PyExc_Warning, UserWarning,
2229 "Base class for warnings generated by user code.");
2230
2231
2232/*
2233 * DeprecationWarning extends Warning
2234 */
2235SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2236 "Base class for warnings about deprecated features.");
2237
2238
2239/*
2240 * PendingDeprecationWarning extends Warning
2241 */
2242SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2243 "Base class for warnings about features which will be deprecated\n"
2244 "in the future.");
2245
2246
2247/*
2248 * SyntaxWarning extends Warning
2249 */
2250SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2251 "Base class for warnings about dubious syntax.");
2252
2253
2254/*
2255 * RuntimeWarning extends Warning
2256 */
2257SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2258 "Base class for warnings about dubious runtime behavior.");
2259
2260
2261/*
2262 * FutureWarning extends Warning
2263 */
2264SimpleExtendsException(PyExc_Warning, FutureWarning,
2265 "Base class for warnings about constructs that will change semantically\n"
2266 "in the future.");
2267
2268
2269/*
2270 * ImportWarning extends Warning
2271 */
2272SimpleExtendsException(PyExc_Warning, ImportWarning,
2273 "Base class for warnings about probable mistakes in module imports");
2274
2275
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002276/*
2277 * UnicodeWarning extends Warning
2278 */
2279SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2280 "Base class for warnings about Unicode related problems, mostly\n"
2281 "related to conversion problems.");
2282
Georg Brandl08be72d2010-10-24 15:11:22 +00002283
Guido van Rossum98297ee2007-11-06 21:34:58 +00002284/*
2285 * BytesWarning extends Warning
2286 */
2287SimpleExtendsException(PyExc_Warning, BytesWarning,
2288 "Base class for warnings about bytes and buffer related problems, mostly\n"
2289 "related to conversion from str or comparing to str.");
2290
2291
Georg Brandl08be72d2010-10-24 15:11:22 +00002292/*
2293 * ResourceWarning extends Warning
2294 */
2295SimpleExtendsException(PyExc_Warning, ResourceWarning,
2296 "Base class for warnings about resource usage.");
2297
2298
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002299
Thomas Wouters89d996e2007-09-08 17:39:28 +00002300/* Pre-computed RuntimeError instance for when recursion depth is reached.
2301 Meant to be used when normalizing the exception for exceeding the recursion
2302 depth will cause its own infinite recursion.
2303*/
2304PyObject *PyExc_RecursionErrorInst = NULL;
2305
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002306#define PRE_INIT(TYPE) \
2307 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2308 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2309 Py_FatalError("exceptions bootstrapping error."); \
2310 Py_INCREF(PyExc_ ## TYPE); \
2311 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002312
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002313#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002314 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2315 Py_FatalError("Module dictionary insertion problem.");
2316
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002317#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002318 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002319 PyExc_ ## NAME = PyExc_ ## TYPE; \
2320 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2321 Py_FatalError("Module dictionary insertion problem.");
2322
2323#define ADD_ERRNO(TYPE, CODE) { \
2324 PyObject *_code = PyLong_FromLong(CODE); \
2325 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2326 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2327 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002328 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002329 }
2330
2331#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002332#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002333/* The following constants were added to errno.h in VS2010 but have
2334 preferred WSA equivalents. */
2335#undef EADDRINUSE
2336#undef EADDRNOTAVAIL
2337#undef EAFNOSUPPORT
2338#undef EALREADY
2339#undef ECONNABORTED
2340#undef ECONNREFUSED
2341#undef ECONNRESET
2342#undef EDESTADDRREQ
2343#undef EHOSTUNREACH
2344#undef EINPROGRESS
2345#undef EISCONN
2346#undef ELOOP
2347#undef EMSGSIZE
2348#undef ENETDOWN
2349#undef ENETRESET
2350#undef ENETUNREACH
2351#undef ENOBUFS
2352#undef ENOPROTOOPT
2353#undef ENOTCONN
2354#undef ENOTSOCK
2355#undef EOPNOTSUPP
2356#undef EPROTONOSUPPORT
2357#undef EPROTOTYPE
2358#undef ETIMEDOUT
2359#undef EWOULDBLOCK
2360
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002361#if defined(WSAEALREADY) && !defined(EALREADY)
2362#define EALREADY WSAEALREADY
2363#endif
2364#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2365#define ECONNABORTED WSAECONNABORTED
2366#endif
2367#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2368#define ECONNREFUSED WSAECONNREFUSED
2369#endif
2370#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2371#define ECONNRESET WSAECONNRESET
2372#endif
2373#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2374#define EINPROGRESS WSAEINPROGRESS
2375#endif
2376#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2377#define ESHUTDOWN WSAESHUTDOWN
2378#endif
2379#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2380#define ETIMEDOUT WSAETIMEDOUT
2381#endif
2382#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2383#define EWOULDBLOCK WSAEWOULDBLOCK
2384#endif
2385#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002386
Martin v. Löwis1a214512008-06-11 05:26:20 +00002387void
Brett Cannonfd074152012-04-14 14:10:13 -04002388_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002389{
Brett Cannonfd074152012-04-14 14:10:13 -04002390 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002391
2392 PRE_INIT(BaseException)
2393 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002394 PRE_INIT(TypeError)
2395 PRE_INIT(StopIteration)
2396 PRE_INIT(GeneratorExit)
2397 PRE_INIT(SystemExit)
2398 PRE_INIT(KeyboardInterrupt)
2399 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002400 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002401 PRE_INIT(EOFError)
2402 PRE_INIT(RuntimeError)
2403 PRE_INIT(NotImplementedError)
2404 PRE_INIT(NameError)
2405 PRE_INIT(UnboundLocalError)
2406 PRE_INIT(AttributeError)
2407 PRE_INIT(SyntaxError)
2408 PRE_INIT(IndentationError)
2409 PRE_INIT(TabError)
2410 PRE_INIT(LookupError)
2411 PRE_INIT(IndexError)
2412 PRE_INIT(KeyError)
2413 PRE_INIT(ValueError)
2414 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002415 PRE_INIT(UnicodeEncodeError)
2416 PRE_INIT(UnicodeDecodeError)
2417 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002418 PRE_INIT(AssertionError)
2419 PRE_INIT(ArithmeticError)
2420 PRE_INIT(FloatingPointError)
2421 PRE_INIT(OverflowError)
2422 PRE_INIT(ZeroDivisionError)
2423 PRE_INIT(SystemError)
2424 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002425 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002426 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002427 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002428 PRE_INIT(Warning)
2429 PRE_INIT(UserWarning)
2430 PRE_INIT(DeprecationWarning)
2431 PRE_INIT(PendingDeprecationWarning)
2432 PRE_INIT(SyntaxWarning)
2433 PRE_INIT(RuntimeWarning)
2434 PRE_INIT(FutureWarning)
2435 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002436 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002437 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002438 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002439
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002440 /* OSError subclasses */
2441 PRE_INIT(ConnectionError);
2442
2443 PRE_INIT(BlockingIOError);
2444 PRE_INIT(BrokenPipeError);
2445 PRE_INIT(ChildProcessError);
2446 PRE_INIT(ConnectionAbortedError);
2447 PRE_INIT(ConnectionRefusedError);
2448 PRE_INIT(ConnectionResetError);
2449 PRE_INIT(FileExistsError);
2450 PRE_INIT(FileNotFoundError);
2451 PRE_INIT(IsADirectoryError);
2452 PRE_INIT(NotADirectoryError);
2453 PRE_INIT(InterruptedError);
2454 PRE_INIT(PermissionError);
2455 PRE_INIT(ProcessLookupError);
2456 PRE_INIT(TimeoutError);
2457
Thomas Wouters477c8d52006-05-27 19:21:47 +00002458 bdict = PyModule_GetDict(bltinmod);
2459 if (bdict == NULL)
2460 Py_FatalError("exceptions bootstrapping error.");
2461
2462 POST_INIT(BaseException)
2463 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002464 POST_INIT(TypeError)
2465 POST_INIT(StopIteration)
2466 POST_INIT(GeneratorExit)
2467 POST_INIT(SystemExit)
2468 POST_INIT(KeyboardInterrupt)
2469 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002470 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002471 INIT_ALIAS(EnvironmentError, OSError)
2472 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002473#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002474 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002475#endif
2476#ifdef __VMS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002477 INIT_ALIAS(VMSError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002478#endif
2479 POST_INIT(EOFError)
2480 POST_INIT(RuntimeError)
2481 POST_INIT(NotImplementedError)
2482 POST_INIT(NameError)
2483 POST_INIT(UnboundLocalError)
2484 POST_INIT(AttributeError)
2485 POST_INIT(SyntaxError)
2486 POST_INIT(IndentationError)
2487 POST_INIT(TabError)
2488 POST_INIT(LookupError)
2489 POST_INIT(IndexError)
2490 POST_INIT(KeyError)
2491 POST_INIT(ValueError)
2492 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002493 POST_INIT(UnicodeEncodeError)
2494 POST_INIT(UnicodeDecodeError)
2495 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002496 POST_INIT(AssertionError)
2497 POST_INIT(ArithmeticError)
2498 POST_INIT(FloatingPointError)
2499 POST_INIT(OverflowError)
2500 POST_INIT(ZeroDivisionError)
2501 POST_INIT(SystemError)
2502 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002503 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002504 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002505 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002506 POST_INIT(Warning)
2507 POST_INIT(UserWarning)
2508 POST_INIT(DeprecationWarning)
2509 POST_INIT(PendingDeprecationWarning)
2510 POST_INIT(SyntaxWarning)
2511 POST_INIT(RuntimeWarning)
2512 POST_INIT(FutureWarning)
2513 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002514 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002515 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002516 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002517
Antoine Pitrouac456a12012-01-18 21:35:21 +01002518 if (!errnomap) {
2519 errnomap = PyDict_New();
2520 if (!errnomap)
2521 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2522 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002523
2524 /* OSError subclasses */
2525 POST_INIT(ConnectionError);
2526
2527 POST_INIT(BlockingIOError);
2528 ADD_ERRNO(BlockingIOError, EAGAIN);
2529 ADD_ERRNO(BlockingIOError, EALREADY);
2530 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2531 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2532 POST_INIT(BrokenPipeError);
2533 ADD_ERRNO(BrokenPipeError, EPIPE);
2534 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2535 POST_INIT(ChildProcessError);
2536 ADD_ERRNO(ChildProcessError, ECHILD);
2537 POST_INIT(ConnectionAbortedError);
2538 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2539 POST_INIT(ConnectionRefusedError);
2540 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2541 POST_INIT(ConnectionResetError);
2542 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2543 POST_INIT(FileExistsError);
2544 ADD_ERRNO(FileExistsError, EEXIST);
2545 POST_INIT(FileNotFoundError);
2546 ADD_ERRNO(FileNotFoundError, ENOENT);
2547 POST_INIT(IsADirectoryError);
2548 ADD_ERRNO(IsADirectoryError, EISDIR);
2549 POST_INIT(NotADirectoryError);
2550 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2551 POST_INIT(InterruptedError);
2552 ADD_ERRNO(InterruptedError, EINTR);
2553 POST_INIT(PermissionError);
2554 ADD_ERRNO(PermissionError, EACCES);
2555 ADD_ERRNO(PermissionError, EPERM);
2556 POST_INIT(ProcessLookupError);
2557 ADD_ERRNO(ProcessLookupError, ESRCH);
2558 POST_INIT(TimeoutError);
2559 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2560
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002561 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002562
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002563 if (!PyExc_RecursionErrorInst) {
2564 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL);
2565 if (!PyExc_RecursionErrorInst)
2566 Py_FatalError("Cannot pre-allocate RuntimeError instance for "
2567 "recursion errors");
2568 else {
2569 PyBaseExceptionObject *err_inst =
2570 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2571 PyObject *args_tuple;
2572 PyObject *exc_message;
2573 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2574 if (!exc_message)
2575 Py_FatalError("cannot allocate argument for RuntimeError "
2576 "pre-allocation");
2577 args_tuple = PyTuple_Pack(1, exc_message);
2578 if (!args_tuple)
2579 Py_FatalError("cannot allocate tuple for RuntimeError "
2580 "pre-allocation");
2581 Py_DECREF(exc_message);
2582 if (BaseException_init(err_inst, args_tuple, NULL))
2583 Py_FatalError("init of pre-allocated RuntimeError failed");
2584 Py_DECREF(args_tuple);
2585 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002586 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002587}
2588
2589void
2590_PyExc_Fini(void)
2591{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002592 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002593 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002594 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002595}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002596
2597/* Helper to do the equivalent of "raise X from Y" in C, but always using
2598 * the current exception rather than passing one in.
2599 *
2600 * We currently limit this to *only* exceptions that use the BaseException
2601 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2602 * those correctly without losing data and without losing backwards
2603 * compatibility.
2604 *
2605 * We also aim to rule out *all* exceptions that might be storing additional
2606 * state, whether by having a size difference relative to BaseException,
2607 * additional arguments passed in during construction or by having a
2608 * non-empty instance dict.
2609 *
2610 * We need to be very careful with what we wrap, since changing types to
2611 * a broader exception type would be backwards incompatible for
2612 * existing codecs, and with different init or new method implementations
2613 * may either not support instantiation with PyErr_Format or lose
2614 * information when instantiated that way.
2615 *
2616 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2617 * fact that exceptions are expected to support pickling. If more builtin
2618 * exceptions (e.g. AttributeError) start to be converted to rich
2619 * exceptions with additional attributes, that's probably a better approach
2620 * to pursue over adding special cases for particular stateful subclasses.
2621 *
2622 * Returns a borrowed reference to the new exception (if any), NULL if the
2623 * existing exception was left in place.
2624 */
2625PyObject *
2626_PyErr_TrySetFromCause(const char *format, ...)
2627{
2628 PyObject* msg_prefix;
2629 PyObject *exc, *val, *tb;
2630 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002631 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002632 PyObject *instance_args;
2633 Py_ssize_t num_args;
2634 PyObject *new_exc, *new_val, *new_tb;
2635 va_list vargs;
2636
Nick Coghlan8b097b42013-11-13 23:49:21 +10002637 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002638 caught_type = (PyTypeObject *)exc;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002639 /* Ensure type info indicates no extra state is stored at the C level */
Benjamin Peterson079c9982013-11-13 23:25:01 -05002640 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002641 caught_type->tp_new != BaseException_new ||
2642 caught_type->tp_basicsize != _PyExc_BaseException.tp_basicsize ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002643 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002644 /* We can't be sure we can wrap this safely, since it may contain
2645 * more state than just the exception type. Accordingly, we just
2646 * leave it alone.
2647 */
2648 PyErr_Restore(exc, val, tb);
2649 return NULL;
2650 }
2651
2652 /* Check the args are empty or contain a single string */
2653 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002654 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002655 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002656 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002657 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002658 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002659 /* More than 1 arg, or the one arg we do have isn't a string
2660 */
2661 PyErr_Restore(exc, val, tb);
2662 return NULL;
2663 }
2664
2665 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002666 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002667 if (dictptr != NULL && *dictptr != NULL &&
2668 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002669 /* While we could potentially copy a non-empty instance dictionary
2670 * to the replacement exception, for now we take the more
2671 * conservative path of leaving exceptions with attributes set
2672 * alone.
2673 */
2674 PyErr_Restore(exc, val, tb);
2675 return NULL;
2676 }
2677
2678 /* For exceptions that we can wrap safely, we chain the original
2679 * exception to a new one of the exact same type with an
2680 * error message that mentions the additional details and the
2681 * original exception.
2682 *
2683 * It would be nice to wrap OSError and various other exception
2684 * types as well, but that's quite a bit trickier due to the extra
2685 * state potentially stored on OSError instances.
2686 */
Christian Heimes507eabd2013-11-14 01:39:35 +01002687
Benjamin Petersone109ee82013-11-13 23:49:49 -05002688 Py_DECREF(exc);
2689 Py_XDECREF(tb);
2690
Christian Heimes507eabd2013-11-14 01:39:35 +01002691#ifdef HAVE_STDARG_PROTOTYPES
2692 va_start(vargs, format);
2693#else
2694 va_start(vargs);
2695#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002696 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002697 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002698 if (msg_prefix == NULL) {
2699 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002700 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002701 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002702
2703 PyErr_Format(exc, "%U (%s: %S)",
2704 msg_prefix, Py_TYPE(val)->tp_name, val);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002705 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002706 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2707 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2708 PyException_SetCause(new_val, val);
2709 PyErr_Restore(new_exc, new_val, new_tb);
2710 return new_val;
2711}