blob: 8b109703f7d5b01d475afb33b5135d843381c9bc [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;
848 args = NULL;
849
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
888 if (!oserror_use_init(type)) {
889 if (!_PyArg_NoKeywords(type->tp_name, kwds))
890 return NULL;
891
892 Py_INCREF(args);
893 if (oserror_parse_args(&args, &myerrno, &strerror, &filename
894#ifdef MS_WINDOWS
895 , &winerror
896#endif
897 ))
898 goto error;
899
900 if (myerrno && PyLong_Check(myerrno) &&
901 errnomap && (PyObject *) type == PyExc_OSError) {
902 PyObject *newtype;
903 newtype = PyDict_GetItem(errnomap, myerrno);
904 if (newtype) {
905 assert(PyType_Check(newtype));
906 type = (PyTypeObject *) newtype;
907 }
908 else if (PyErr_Occurred())
909 goto error;
910 }
911 }
912
913 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
914 if (!self)
915 goto error;
916
917 self->dict = NULL;
918 self->traceback = self->cause = self->context = NULL;
919 self->written = -1;
920
921 if (!oserror_use_init(type)) {
922 if (oserror_init(self, &args, myerrno, strerror, filename
923#ifdef MS_WINDOWS
924 , winerror
925#endif
926 ))
927 goto error;
928 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200929 else {
930 self->args = PyTuple_New(0);
931 if (self->args == NULL)
932 goto error;
933 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100934
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200935 return (PyObject *) self;
936
937error:
938 Py_XDECREF(args);
939 Py_XDECREF(self);
940 return NULL;
941}
942
943static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100944OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200945{
Antoine Pitroue0e27352011-12-15 14:31:28 +0100946 PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL;
947#ifdef MS_WINDOWS
948 PyObject *winerror = NULL;
949#endif
950
951 if (!oserror_use_init(Py_TYPE(self)))
952 /* Everything already done in OSError_new */
953 return 0;
954
955 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
956 return -1;
957
958 Py_INCREF(args);
959 if (oserror_parse_args(&args, &myerrno, &strerror, &filename
960#ifdef MS_WINDOWS
961 , &winerror
962#endif
963 ))
964 goto error;
965
966 if (oserror_init(self, &args, myerrno, strerror, filename
967#ifdef MS_WINDOWS
968 , winerror
969#endif
970 ))
971 goto error;
972
Thomas Wouters477c8d52006-05-27 19:21:47 +0000973 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100974
975error:
976 Py_XDECREF(args);
977 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000978}
979
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000980static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200981OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000982{
983 Py_CLEAR(self->myerrno);
984 Py_CLEAR(self->strerror);
985 Py_CLEAR(self->filename);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200986#ifdef MS_WINDOWS
987 Py_CLEAR(self->winerror);
988#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +0000989 return BaseException_clear((PyBaseExceptionObject *)self);
990}
991
992static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200993OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000994{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000995 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200996 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000997 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000998}
999
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001000static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001001OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002 void *arg)
1003{
1004 Py_VISIT(self->myerrno);
1005 Py_VISIT(self->strerror);
1006 Py_VISIT(self->filename);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001007#ifdef MS_WINDOWS
1008 Py_VISIT(self->winerror);
1009#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001010 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1011}
1012
1013static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001014OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001015{
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001016#ifdef MS_WINDOWS
1017 /* If available, winerror has the priority over myerrno */
1018 if (self->winerror && self->filename)
Richard Oudkerk30147712012-08-28 19:33:26 +01001019 return PyUnicode_FromFormat("[WinError %S] %S: %R",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001020 self->winerror ? self->winerror: Py_None,
1021 self->strerror ? self->strerror: Py_None,
1022 self->filename);
1023 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001024 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001025 self->winerror ? self->winerror: Py_None,
1026 self->strerror ? self->strerror: Py_None);
1027#endif
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001028 if (self->filename)
1029 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1030 self->myerrno ? self->myerrno: Py_None,
1031 self->strerror ? self->strerror: Py_None,
1032 self->filename);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001033 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001034 return PyUnicode_FromFormat("[Errno %S] %S",
1035 self->myerrno ? self->myerrno: Py_None,
1036 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001037 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001038}
1039
Thomas Wouters477c8d52006-05-27 19:21:47 +00001040static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001041OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001042{
1043 PyObject *args = self->args;
1044 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001045
Thomas Wouters477c8d52006-05-27 19:21:47 +00001046 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001047 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001048 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049 args = PyTuple_New(3);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001050 if (!args)
1051 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001052
1053 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001054 Py_INCREF(tmp);
1055 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001056
1057 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001058 Py_INCREF(tmp);
1059 PyTuple_SET_ITEM(args, 1, tmp);
1060
1061 Py_INCREF(self->filename);
1062 PyTuple_SET_ITEM(args, 2, self->filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001063 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001064 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001065
1066 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001067 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001068 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001069 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001070 Py_DECREF(args);
1071 return res;
1072}
1073
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001074static PyObject *
1075OSError_written_get(PyOSErrorObject *self, void *context)
1076{
1077 if (self->written == -1) {
1078 PyErr_SetString(PyExc_AttributeError, "characters_written");
1079 return NULL;
1080 }
1081 return PyLong_FromSsize_t(self->written);
1082}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001083
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001084static int
1085OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1086{
1087 Py_ssize_t n;
1088 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1089 if (n == -1 && PyErr_Occurred())
1090 return -1;
1091 self->written = n;
1092 return 0;
1093}
1094
1095static PyMemberDef OSError_members[] = {
1096 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1097 PyDoc_STR("POSIX exception code")},
1098 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1099 PyDoc_STR("exception strerror")},
1100 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1101 PyDoc_STR("exception filename")},
1102#ifdef MS_WINDOWS
1103 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1104 PyDoc_STR("Win32 exception code")},
1105#endif
1106 {NULL} /* Sentinel */
1107};
1108
1109static PyMethodDef OSError_methods[] = {
1110 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001111 {NULL}
1112};
1113
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001114static PyGetSetDef OSError_getset[] = {
1115 {"characters_written", (getter) OSError_written_get,
1116 (setter) OSError_written_set, NULL},
1117 {NULL}
1118};
1119
1120
1121ComplexExtendsException(PyExc_Exception, OSError,
1122 OSError, OSError_new,
1123 OSError_methods, OSError_members, OSError_getset,
1124 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001125 "Base class for I/O related errors.");
1126
1127
1128/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001129 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001130 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001131MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1132 "I/O operation would block.");
1133MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1134 "Connection error.");
1135MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1136 "Child process error.");
1137MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1138 "Broken pipe.");
1139MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1140 "Connection aborted.");
1141MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1142 "Connection refused.");
1143MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1144 "Connection reset.");
1145MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1146 "File already exists.");
1147MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1148 "File not found.");
1149MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1150 "Operation doesn't work on directories.");
1151MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1152 "Operation only works on directories.");
1153MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1154 "Interrupted by signal.");
1155MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1156 "Not enough permissions.");
1157MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1158 "Process not found.");
1159MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1160 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001161
1162/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001163 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001164 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001165SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166 "Read beyond end of file.");
1167
1168
1169/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001170 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001171 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001172SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001173 "Unspecified run-time error.");
1174
1175
1176/*
1177 * NotImplementedError extends RuntimeError
1178 */
1179SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1180 "Method or function hasn't been implemented yet.");
1181
1182/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001183 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001184 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001185SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001186 "Name not found globally.");
1187
1188/*
1189 * UnboundLocalError extends NameError
1190 */
1191SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1192 "Local name referenced but not bound to a value.");
1193
1194/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001195 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001196 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001197SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001198 "Attribute not found.");
1199
1200
1201/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001202 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001203 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001204
1205static int
1206SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1207{
1208 PyObject *info = NULL;
1209 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1210
1211 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1212 return -1;
1213
1214 if (lenargs >= 1) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001215 Py_CLEAR(self->msg);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001216 self->msg = PyTuple_GET_ITEM(args, 0);
1217 Py_INCREF(self->msg);
1218 }
1219 if (lenargs == 2) {
1220 info = PyTuple_GET_ITEM(args, 1);
1221 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001222 if (!info)
1223 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001224
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001225 if (PyTuple_GET_SIZE(info) != 4) {
1226 /* not a very good error message, but it's what Python 2.4 gives */
1227 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1228 Py_DECREF(info);
1229 return -1;
1230 }
1231
1232 Py_CLEAR(self->filename);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001233 self->filename = PyTuple_GET_ITEM(info, 0);
1234 Py_INCREF(self->filename);
1235
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001236 Py_CLEAR(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001237 self->lineno = PyTuple_GET_ITEM(info, 1);
1238 Py_INCREF(self->lineno);
1239
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001240 Py_CLEAR(self->offset);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001241 self->offset = PyTuple_GET_ITEM(info, 2);
1242 Py_INCREF(self->offset);
1243
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001244 Py_CLEAR(self->text);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001245 self->text = PyTuple_GET_ITEM(info, 3);
1246 Py_INCREF(self->text);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001247
1248 Py_DECREF(info);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001249 }
1250 return 0;
1251}
1252
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001253static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001254SyntaxError_clear(PySyntaxErrorObject *self)
1255{
1256 Py_CLEAR(self->msg);
1257 Py_CLEAR(self->filename);
1258 Py_CLEAR(self->lineno);
1259 Py_CLEAR(self->offset);
1260 Py_CLEAR(self->text);
1261 Py_CLEAR(self->print_file_and_line);
1262 return BaseException_clear((PyBaseExceptionObject *)self);
1263}
1264
1265static void
1266SyntaxError_dealloc(PySyntaxErrorObject *self)
1267{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001268 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001269 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001270 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001271}
1272
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001273static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001274SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1275{
1276 Py_VISIT(self->msg);
1277 Py_VISIT(self->filename);
1278 Py_VISIT(self->lineno);
1279 Py_VISIT(self->offset);
1280 Py_VISIT(self->text);
1281 Py_VISIT(self->print_file_and_line);
1282 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1283}
1284
1285/* This is called "my_basename" instead of just "basename" to avoid name
1286 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1287 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001288static PyObject*
1289my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001290{
Victor Stinner6237daf2010-04-28 17:26:19 +00001291 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001292 int kind;
1293 void *data;
1294
1295 if (PyUnicode_READY(name))
1296 return NULL;
1297 kind = PyUnicode_KIND(name);
1298 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001299 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001300 offset = 0;
1301 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001302 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001303 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001304 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305 if (offset != 0)
1306 return PyUnicode_Substring(name, offset, size);
1307 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001308 Py_INCREF(name);
1309 return name;
1310 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001311}
1312
1313
1314static PyObject *
1315SyntaxError_str(PySyntaxErrorObject *self)
1316{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001317 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001318 PyObject *filename;
1319 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001320 /* Below, we always ignore overflow errors, just printing -1.
1321 Still, we cannot allow an OverflowError to be raised, so
1322 we need to call PyLong_AsLongAndOverflow. */
1323 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001324
1325 /* XXX -- do all the additional formatting with filename and
1326 lineno here */
1327
Neal Norwitzed2b7392007-08-26 04:51:10 +00001328 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001329 filename = my_basename(self->filename);
1330 if (filename == NULL)
1331 return NULL;
1332 } else {
1333 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001334 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001335 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001336
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001337 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001338 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001339
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001340 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001341 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001342 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001343 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001345 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001346 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001347 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001348 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001349 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001350 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001351 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001352 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001353 Py_XDECREF(filename);
1354 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001355}
1356
1357static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001358 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1359 PyDoc_STR("exception msg")},
1360 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1361 PyDoc_STR("exception filename")},
1362 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1363 PyDoc_STR("exception lineno")},
1364 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1365 PyDoc_STR("exception offset")},
1366 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1367 PyDoc_STR("exception text")},
1368 {"print_file_and_line", T_OBJECT,
1369 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1370 PyDoc_STR("exception print_file_and_line")},
1371 {NULL} /* Sentinel */
1372};
1373
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001374ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001375 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001376 SyntaxError_str, "Invalid syntax.");
1377
1378
1379/*
1380 * IndentationError extends SyntaxError
1381 */
1382MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1383 "Improper indentation.");
1384
1385
1386/*
1387 * TabError extends IndentationError
1388 */
1389MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1390 "Improper mixture of spaces and tabs.");
1391
1392
1393/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001394 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001396SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001397 "Base class for lookup errors.");
1398
1399
1400/*
1401 * IndexError extends LookupError
1402 */
1403SimpleExtendsException(PyExc_LookupError, IndexError,
1404 "Sequence index out of range.");
1405
1406
1407/*
1408 * KeyError extends LookupError
1409 */
1410static PyObject *
1411KeyError_str(PyBaseExceptionObject *self)
1412{
1413 /* If args is a tuple of exactly one item, apply repr to args[0].
1414 This is done so that e.g. the exception raised by {}[''] prints
1415 KeyError: ''
1416 rather than the confusing
1417 KeyError
1418 alone. The downside is that if KeyError is raised with an explanatory
1419 string, that string will be displayed in quotes. Too bad.
1420 If args is anything else, use the default BaseException__str__().
1421 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001422 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001423 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001424 }
1425 return BaseException_str(self);
1426}
1427
1428ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001429 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001430
1431
1432/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001433 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001434 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001435SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001436 "Inappropriate argument value (of correct type).");
1437
1438/*
1439 * UnicodeError extends ValueError
1440 */
1441
1442SimpleExtendsException(PyExc_ValueError, UnicodeError,
1443 "Unicode related error.");
1444
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001446get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001447{
1448 if (!attr) {
1449 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1450 return NULL;
1451 }
1452
Christian Heimes72b710a2008-05-26 13:28:38 +00001453 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001454 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1455 return NULL;
1456 }
1457 Py_INCREF(attr);
1458 return attr;
1459}
1460
1461static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001462get_unicode(PyObject *attr, const char *name)
1463{
1464 if (!attr) {
1465 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1466 return NULL;
1467 }
1468
1469 if (!PyUnicode_Check(attr)) {
1470 PyErr_Format(PyExc_TypeError,
1471 "%.200s attribute must be unicode", name);
1472 return NULL;
1473 }
1474 Py_INCREF(attr);
1475 return attr;
1476}
1477
Walter Dörwaldd2034312007-05-18 16:29:38 +00001478static int
1479set_unicodefromstring(PyObject **attr, const char *value)
1480{
1481 PyObject *obj = PyUnicode_FromString(value);
1482 if (!obj)
1483 return -1;
1484 Py_CLEAR(*attr);
1485 *attr = obj;
1486 return 0;
1487}
1488
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489PyObject *
1490PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1491{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001492 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001493}
1494
1495PyObject *
1496PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1497{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001498 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001499}
1500
1501PyObject *
1502PyUnicodeEncodeError_GetObject(PyObject *exc)
1503{
1504 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1505}
1506
1507PyObject *
1508PyUnicodeDecodeError_GetObject(PyObject *exc)
1509{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001510 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001511}
1512
1513PyObject *
1514PyUnicodeTranslateError_GetObject(PyObject *exc)
1515{
1516 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1517}
1518
1519int
1520PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1521{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001522 Py_ssize_t size;
1523 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1524 "object");
1525 if (!obj)
1526 return -1;
1527 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001528 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001529 if (*start<0)
1530 *start = 0; /*XXX check for values <0*/
1531 if (*start>=size)
1532 *start = size-1;
1533 Py_DECREF(obj);
1534 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001535}
1536
1537
1538int
1539PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1540{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001541 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001542 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001543 if (!obj)
1544 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001545 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001546 *start = ((PyUnicodeErrorObject *)exc)->start;
1547 if (*start<0)
1548 *start = 0;
1549 if (*start>=size)
1550 *start = size-1;
1551 Py_DECREF(obj);
1552 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001553}
1554
1555
1556int
1557PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1558{
1559 return PyUnicodeEncodeError_GetStart(exc, start);
1560}
1561
1562
1563int
1564PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1565{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001566 ((PyUnicodeErrorObject *)exc)->start = start;
1567 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001568}
1569
1570
1571int
1572PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1573{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001574 ((PyUnicodeErrorObject *)exc)->start = start;
1575 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001576}
1577
1578
1579int
1580PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1581{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001582 ((PyUnicodeErrorObject *)exc)->start = start;
1583 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584}
1585
1586
1587int
1588PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1589{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001590 Py_ssize_t size;
1591 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1592 "object");
1593 if (!obj)
1594 return -1;
1595 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001596 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001597 if (*end<1)
1598 *end = 1;
1599 if (*end>size)
1600 *end = size;
1601 Py_DECREF(obj);
1602 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001603}
1604
1605
1606int
1607PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1608{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001609 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001610 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001611 if (!obj)
1612 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001613 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001614 *end = ((PyUnicodeErrorObject *)exc)->end;
1615 if (*end<1)
1616 *end = 1;
1617 if (*end>size)
1618 *end = size;
1619 Py_DECREF(obj);
1620 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001621}
1622
1623
1624int
1625PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1626{
1627 return PyUnicodeEncodeError_GetEnd(exc, start);
1628}
1629
1630
1631int
1632PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1633{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001634 ((PyUnicodeErrorObject *)exc)->end = end;
1635 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001636}
1637
1638
1639int
1640PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1641{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001642 ((PyUnicodeErrorObject *)exc)->end = end;
1643 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001644}
1645
1646
1647int
1648PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1649{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001650 ((PyUnicodeErrorObject *)exc)->end = end;
1651 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001652}
1653
1654PyObject *
1655PyUnicodeEncodeError_GetReason(PyObject *exc)
1656{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001657 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001658}
1659
1660
1661PyObject *
1662PyUnicodeDecodeError_GetReason(PyObject *exc)
1663{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001664 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001665}
1666
1667
1668PyObject *
1669PyUnicodeTranslateError_GetReason(PyObject *exc)
1670{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001671 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001672}
1673
1674
1675int
1676PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1677{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001678 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1679 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001680}
1681
1682
1683int
1684PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1685{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001686 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1687 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001688}
1689
1690
1691int
1692PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1693{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001694 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1695 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001696}
1697
1698
Thomas Wouters477c8d52006-05-27 19:21:47 +00001699static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001700UnicodeError_clear(PyUnicodeErrorObject *self)
1701{
1702 Py_CLEAR(self->encoding);
1703 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001704 Py_CLEAR(self->reason);
1705 return BaseException_clear((PyBaseExceptionObject *)self);
1706}
1707
1708static void
1709UnicodeError_dealloc(PyUnicodeErrorObject *self)
1710{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001711 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001712 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001713 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001714}
1715
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001716static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001717UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1718{
1719 Py_VISIT(self->encoding);
1720 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001721 Py_VISIT(self->reason);
1722 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1723}
1724
1725static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001726 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1727 PyDoc_STR("exception encoding")},
1728 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1729 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001730 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001731 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001732 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001733 PyDoc_STR("exception end")},
1734 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1735 PyDoc_STR("exception reason")},
1736 {NULL} /* Sentinel */
1737};
1738
1739
1740/*
1741 * UnicodeEncodeError extends UnicodeError
1742 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001743
1744static int
1745UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1746{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001747 PyUnicodeErrorObject *err;
1748
Thomas Wouters477c8d52006-05-27 19:21:47 +00001749 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1750 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001751
1752 err = (PyUnicodeErrorObject *)self;
1753
1754 Py_CLEAR(err->encoding);
1755 Py_CLEAR(err->object);
1756 Py_CLEAR(err->reason);
1757
1758 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1759 &PyUnicode_Type, &err->encoding,
1760 &PyUnicode_Type, &err->object,
1761 &err->start,
1762 &err->end,
1763 &PyUnicode_Type, &err->reason)) {
1764 err->encoding = err->object = err->reason = NULL;
1765 return -1;
1766 }
1767
Martin v. Löwisb09af032011-11-04 11:16:41 +01001768 if (PyUnicode_READY(err->object) < -1) {
1769 err->encoding = NULL;
1770 return -1;
1771 }
1772
Guido van Rossum98297ee2007-11-06 21:34:58 +00001773 Py_INCREF(err->encoding);
1774 Py_INCREF(err->object);
1775 Py_INCREF(err->reason);
1776
1777 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001778}
1779
1780static PyObject *
1781UnicodeEncodeError_str(PyObject *self)
1782{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001783 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001784 PyObject *result = NULL;
1785 PyObject *reason_str = NULL;
1786 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001787
Eric Smith0facd772010-02-24 15:42:29 +00001788 /* Get reason and encoding as strings, which they might not be if
1789 they've been modified after we were contructed. */
1790 reason_str = PyObject_Str(uself->reason);
1791 if (reason_str == NULL)
1792 goto done;
1793 encoding_str = PyObject_Str(uself->encoding);
1794 if (encoding_str == NULL)
1795 goto done;
1796
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001797 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1798 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001799 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001800 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001801 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001802 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001803 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001804 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001805 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001806 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001807 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001808 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001809 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001810 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001811 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001812 }
Eric Smith0facd772010-02-24 15:42:29 +00001813 else {
1814 result = PyUnicode_FromFormat(
1815 "'%U' codec can't encode characters in position %zd-%zd: %U",
1816 encoding_str,
1817 uself->start,
1818 uself->end-1,
1819 reason_str);
1820 }
1821done:
1822 Py_XDECREF(reason_str);
1823 Py_XDECREF(encoding_str);
1824 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001825}
1826
1827static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001828 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001829 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001830 sizeof(PyUnicodeErrorObject), 0,
1831 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1832 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1833 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001834 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1835 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001836 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001837 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001838};
1839PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1840
1841PyObject *
1842PyUnicodeEncodeError_Create(
1843 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1844 Py_ssize_t start, Py_ssize_t end, const char *reason)
1845{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001846 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001847 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001848}
1849
1850
1851/*
1852 * UnicodeDecodeError extends UnicodeError
1853 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001854
1855static int
1856UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1857{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001858 PyUnicodeErrorObject *ude;
1859 const char *data;
1860 Py_ssize_t size;
1861
Thomas Wouters477c8d52006-05-27 19:21:47 +00001862 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1863 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001864
1865 ude = (PyUnicodeErrorObject *)self;
1866
1867 Py_CLEAR(ude->encoding);
1868 Py_CLEAR(ude->object);
1869 Py_CLEAR(ude->reason);
1870
1871 if (!PyArg_ParseTuple(args, "O!OnnO!",
1872 &PyUnicode_Type, &ude->encoding,
1873 &ude->object,
1874 &ude->start,
1875 &ude->end,
1876 &PyUnicode_Type, &ude->reason)) {
1877 ude->encoding = ude->object = ude->reason = NULL;
1878 return -1;
1879 }
1880
Christian Heimes72b710a2008-05-26 13:28:38 +00001881 if (!PyBytes_Check(ude->object)) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00001882 if (PyObject_AsReadBuffer(ude->object, (const void **)&data, &size)) {
1883 ude->encoding = ude->object = ude->reason = NULL;
1884 return -1;
1885 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001886 ude->object = PyBytes_FromStringAndSize(data, size);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001887 }
1888 else {
1889 Py_INCREF(ude->object);
1890 }
1891
1892 Py_INCREF(ude->encoding);
1893 Py_INCREF(ude->reason);
1894
1895 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001896}
1897
1898static PyObject *
1899UnicodeDecodeError_str(PyObject *self)
1900{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001901 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001902 PyObject *result = NULL;
1903 PyObject *reason_str = NULL;
1904 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001905
Eric Smith0facd772010-02-24 15:42:29 +00001906 /* Get reason and encoding as strings, which they might not be if
1907 they've been modified after we were contructed. */
1908 reason_str = PyObject_Str(uself->reason);
1909 if (reason_str == NULL)
1910 goto done;
1911 encoding_str = PyObject_Str(uself->encoding);
1912 if (encoding_str == NULL)
1913 goto done;
1914
1915 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001916 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00001917 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001918 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00001919 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001920 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001921 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001922 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001923 }
Eric Smith0facd772010-02-24 15:42:29 +00001924 else {
1925 result = PyUnicode_FromFormat(
1926 "'%U' codec can't decode bytes in position %zd-%zd: %U",
1927 encoding_str,
1928 uself->start,
1929 uself->end-1,
1930 reason_str
1931 );
1932 }
1933done:
1934 Py_XDECREF(reason_str);
1935 Py_XDECREF(encoding_str);
1936 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001937}
1938
1939static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001940 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001941 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001942 sizeof(PyUnicodeErrorObject), 0,
1943 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1944 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
1945 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001946 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
1947 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001948 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001949 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001950};
1951PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
1952
1953PyObject *
1954PyUnicodeDecodeError_Create(
1955 const char *encoding, const char *object, Py_ssize_t length,
1956 Py_ssize_t start, Py_ssize_t end, const char *reason)
1957{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001958 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001959 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001960}
1961
1962
1963/*
1964 * UnicodeTranslateError extends UnicodeError
1965 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001966
1967static int
1968UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
1969 PyObject *kwds)
1970{
1971 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1972 return -1;
1973
1974 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001975 Py_CLEAR(self->reason);
1976
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001977 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001978 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001979 &self->start,
1980 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00001981 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001982 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001983 return -1;
1984 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001985
Thomas Wouters477c8d52006-05-27 19:21:47 +00001986 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001987 Py_INCREF(self->reason);
1988
1989 return 0;
1990}
1991
1992
1993static PyObject *
1994UnicodeTranslateError_str(PyObject *self)
1995{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001996 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001997 PyObject *result = NULL;
1998 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001999
Eric Smith0facd772010-02-24 15:42:29 +00002000 /* Get reason as a string, which it might not be if it's been
2001 modified after we were contructed. */
2002 reason_str = PyObject_Str(uself->reason);
2003 if (reason_str == NULL)
2004 goto done;
2005
Victor Stinner53b33e72011-11-21 01:17:27 +01002006 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2007 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002008 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002009 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002010 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002011 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002012 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002013 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002014 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002015 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002016 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002017 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002018 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002019 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002020 );
Eric Smith0facd772010-02-24 15:42:29 +00002021 } else {
2022 result = PyUnicode_FromFormat(
2023 "can't translate characters in position %zd-%zd: %U",
2024 uself->start,
2025 uself->end-1,
2026 reason_str
2027 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002028 }
Eric Smith0facd772010-02-24 15:42:29 +00002029done:
2030 Py_XDECREF(reason_str);
2031 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002032}
2033
2034static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002035 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002036 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002037 sizeof(PyUnicodeErrorObject), 0,
2038 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2039 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2040 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002041 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002042 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2043 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002044 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002045};
2046PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002049PyObject *
2050PyUnicodeTranslateError_Create(
2051 const Py_UNICODE *object, Py_ssize_t length,
2052 Py_ssize_t start, Py_ssize_t end, const char *reason)
2053{
2054 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002055 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002056}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058PyObject *
2059_PyUnicodeTranslateError_Create(
2060 PyObject *object,
2061 Py_ssize_t start, Py_ssize_t end, const char *reason)
2062{
2063 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Ons",
2064 object, start, end, reason);
2065}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002066
2067/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002068 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002069 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002070SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002071 "Assertion failed.");
2072
2073
2074/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002075 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002076 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002077SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002078 "Base class for arithmetic errors.");
2079
2080
2081/*
2082 * FloatingPointError extends ArithmeticError
2083 */
2084SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2085 "Floating point operation failed.");
2086
2087
2088/*
2089 * OverflowError extends ArithmeticError
2090 */
2091SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2092 "Result too large to be represented.");
2093
2094
2095/*
2096 * ZeroDivisionError extends ArithmeticError
2097 */
2098SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2099 "Second argument to a division or modulo operation was zero.");
2100
2101
2102/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002103 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002104 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002105SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002106 "Internal error in the Python interpreter.\n"
2107 "\n"
2108 "Please report this to the Python maintainer, along with the traceback,\n"
2109 "the Python version, and the hardware/OS platform and version.");
2110
2111
2112/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002113 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002114 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002115SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002116 "Weak ref proxy used after referent went away.");
2117
2118
2119/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002120 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002121 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002122
2123#define MEMERRORS_SAVE 16
2124static PyBaseExceptionObject *memerrors_freelist = NULL;
2125static int memerrors_numfree = 0;
2126
2127static PyObject *
2128MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2129{
2130 PyBaseExceptionObject *self;
2131
2132 if (type != (PyTypeObject *) PyExc_MemoryError)
2133 return BaseException_new(type, args, kwds);
2134 if (memerrors_freelist == NULL)
2135 return BaseException_new(type, args, kwds);
2136 /* Fetch object from freelist and revive it */
2137 self = memerrors_freelist;
2138 self->args = PyTuple_New(0);
2139 /* This shouldn't happen since the empty tuple is persistent */
2140 if (self->args == NULL)
2141 return NULL;
2142 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2143 memerrors_numfree--;
2144 self->dict = NULL;
2145 _Py_NewReference((PyObject *)self);
2146 _PyObject_GC_TRACK(self);
2147 return (PyObject *)self;
2148}
2149
2150static void
2151MemoryError_dealloc(PyBaseExceptionObject *self)
2152{
2153 _PyObject_GC_UNTRACK(self);
2154 BaseException_clear(self);
2155 if (memerrors_numfree >= MEMERRORS_SAVE)
2156 Py_TYPE(self)->tp_free((PyObject *)self);
2157 else {
2158 self->dict = (PyObject *) memerrors_freelist;
2159 memerrors_freelist = self;
2160 memerrors_numfree++;
2161 }
2162}
2163
2164static void
2165preallocate_memerrors(void)
2166{
2167 /* We create enough MemoryErrors and then decref them, which will fill
2168 up the freelist. */
2169 int i;
2170 PyObject *errors[MEMERRORS_SAVE];
2171 for (i = 0; i < MEMERRORS_SAVE; i++) {
2172 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2173 NULL, NULL);
2174 if (!errors[i])
2175 Py_FatalError("Could not preallocate MemoryError object");
2176 }
2177 for (i = 0; i < MEMERRORS_SAVE; i++) {
2178 Py_DECREF(errors[i]);
2179 }
2180}
2181
2182static void
2183free_preallocated_memerrors(void)
2184{
2185 while (memerrors_freelist != NULL) {
2186 PyObject *self = (PyObject *) memerrors_freelist;
2187 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2188 Py_TYPE(self)->tp_free((PyObject *)self);
2189 }
2190}
2191
2192
2193static PyTypeObject _PyExc_MemoryError = {
2194 PyVarObject_HEAD_INIT(NULL, 0)
2195 "MemoryError",
2196 sizeof(PyBaseExceptionObject),
2197 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2198 0, 0, 0, 0, 0, 0, 0,
2199 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2200 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2201 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2202 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2203 (initproc)BaseException_init, 0, MemoryError_new
2204};
2205PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2206
Thomas Wouters477c8d52006-05-27 19:21:47 +00002207
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002208/*
2209 * BufferError extends Exception
2210 */
2211SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2212
Thomas Wouters477c8d52006-05-27 19:21:47 +00002213
2214/* Warning category docstrings */
2215
2216/*
2217 * Warning extends Exception
2218 */
2219SimpleExtendsException(PyExc_Exception, Warning,
2220 "Base class for warning categories.");
2221
2222
2223/*
2224 * UserWarning extends Warning
2225 */
2226SimpleExtendsException(PyExc_Warning, UserWarning,
2227 "Base class for warnings generated by user code.");
2228
2229
2230/*
2231 * DeprecationWarning extends Warning
2232 */
2233SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2234 "Base class for warnings about deprecated features.");
2235
2236
2237/*
2238 * PendingDeprecationWarning extends Warning
2239 */
2240SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2241 "Base class for warnings about features which will be deprecated\n"
2242 "in the future.");
2243
2244
2245/*
2246 * SyntaxWarning extends Warning
2247 */
2248SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2249 "Base class for warnings about dubious syntax.");
2250
2251
2252/*
2253 * RuntimeWarning extends Warning
2254 */
2255SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2256 "Base class for warnings about dubious runtime behavior.");
2257
2258
2259/*
2260 * FutureWarning extends Warning
2261 */
2262SimpleExtendsException(PyExc_Warning, FutureWarning,
2263 "Base class for warnings about constructs that will change semantically\n"
2264 "in the future.");
2265
2266
2267/*
2268 * ImportWarning extends Warning
2269 */
2270SimpleExtendsException(PyExc_Warning, ImportWarning,
2271 "Base class for warnings about probable mistakes in module imports");
2272
2273
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002274/*
2275 * UnicodeWarning extends Warning
2276 */
2277SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2278 "Base class for warnings about Unicode related problems, mostly\n"
2279 "related to conversion problems.");
2280
Georg Brandl08be72d2010-10-24 15:11:22 +00002281
Guido van Rossum98297ee2007-11-06 21:34:58 +00002282/*
2283 * BytesWarning extends Warning
2284 */
2285SimpleExtendsException(PyExc_Warning, BytesWarning,
2286 "Base class for warnings about bytes and buffer related problems, mostly\n"
2287 "related to conversion from str or comparing to str.");
2288
2289
Georg Brandl08be72d2010-10-24 15:11:22 +00002290/*
2291 * ResourceWarning extends Warning
2292 */
2293SimpleExtendsException(PyExc_Warning, ResourceWarning,
2294 "Base class for warnings about resource usage.");
2295
2296
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002297
Thomas Wouters89d996e2007-09-08 17:39:28 +00002298/* Pre-computed RuntimeError instance for when recursion depth is reached.
2299 Meant to be used when normalizing the exception for exceeding the recursion
2300 depth will cause its own infinite recursion.
2301*/
2302PyObject *PyExc_RecursionErrorInst = NULL;
2303
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002304#define PRE_INIT(TYPE) \
2305 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2306 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2307 Py_FatalError("exceptions bootstrapping error."); \
2308 Py_INCREF(PyExc_ ## TYPE); \
2309 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002310
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002311#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002312 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2313 Py_FatalError("Module dictionary insertion problem.");
2314
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002315#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002316 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002317 PyExc_ ## NAME = PyExc_ ## TYPE; \
2318 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2319 Py_FatalError("Module dictionary insertion problem.");
2320
2321#define ADD_ERRNO(TYPE, CODE) { \
2322 PyObject *_code = PyLong_FromLong(CODE); \
2323 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2324 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2325 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002326 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002327 }
2328
2329#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002330#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002331/* The following constants were added to errno.h in VS2010 but have
2332 preferred WSA equivalents. */
2333#undef EADDRINUSE
2334#undef EADDRNOTAVAIL
2335#undef EAFNOSUPPORT
2336#undef EALREADY
2337#undef ECONNABORTED
2338#undef ECONNREFUSED
2339#undef ECONNRESET
2340#undef EDESTADDRREQ
2341#undef EHOSTUNREACH
2342#undef EINPROGRESS
2343#undef EISCONN
2344#undef ELOOP
2345#undef EMSGSIZE
2346#undef ENETDOWN
2347#undef ENETRESET
2348#undef ENETUNREACH
2349#undef ENOBUFS
2350#undef ENOPROTOOPT
2351#undef ENOTCONN
2352#undef ENOTSOCK
2353#undef EOPNOTSUPP
2354#undef EPROTONOSUPPORT
2355#undef EPROTOTYPE
2356#undef ETIMEDOUT
2357#undef EWOULDBLOCK
2358
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002359#if defined(WSAEALREADY) && !defined(EALREADY)
2360#define EALREADY WSAEALREADY
2361#endif
2362#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2363#define ECONNABORTED WSAECONNABORTED
2364#endif
2365#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2366#define ECONNREFUSED WSAECONNREFUSED
2367#endif
2368#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2369#define ECONNRESET WSAECONNRESET
2370#endif
2371#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2372#define EINPROGRESS WSAEINPROGRESS
2373#endif
2374#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2375#define ESHUTDOWN WSAESHUTDOWN
2376#endif
2377#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2378#define ETIMEDOUT WSAETIMEDOUT
2379#endif
2380#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2381#define EWOULDBLOCK WSAEWOULDBLOCK
2382#endif
2383#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002384
Martin v. Löwis1a214512008-06-11 05:26:20 +00002385void
Brett Cannonfd074152012-04-14 14:10:13 -04002386_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002387{
Brett Cannonfd074152012-04-14 14:10:13 -04002388 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002389
2390 PRE_INIT(BaseException)
2391 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002392 PRE_INIT(TypeError)
2393 PRE_INIT(StopIteration)
2394 PRE_INIT(GeneratorExit)
2395 PRE_INIT(SystemExit)
2396 PRE_INIT(KeyboardInterrupt)
2397 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002398 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002399 PRE_INIT(EOFError)
2400 PRE_INIT(RuntimeError)
2401 PRE_INIT(NotImplementedError)
2402 PRE_INIT(NameError)
2403 PRE_INIT(UnboundLocalError)
2404 PRE_INIT(AttributeError)
2405 PRE_INIT(SyntaxError)
2406 PRE_INIT(IndentationError)
2407 PRE_INIT(TabError)
2408 PRE_INIT(LookupError)
2409 PRE_INIT(IndexError)
2410 PRE_INIT(KeyError)
2411 PRE_INIT(ValueError)
2412 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002413 PRE_INIT(UnicodeEncodeError)
2414 PRE_INIT(UnicodeDecodeError)
2415 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002416 PRE_INIT(AssertionError)
2417 PRE_INIT(ArithmeticError)
2418 PRE_INIT(FloatingPointError)
2419 PRE_INIT(OverflowError)
2420 PRE_INIT(ZeroDivisionError)
2421 PRE_INIT(SystemError)
2422 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002423 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002424 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002425 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002426 PRE_INIT(Warning)
2427 PRE_INIT(UserWarning)
2428 PRE_INIT(DeprecationWarning)
2429 PRE_INIT(PendingDeprecationWarning)
2430 PRE_INIT(SyntaxWarning)
2431 PRE_INIT(RuntimeWarning)
2432 PRE_INIT(FutureWarning)
2433 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002434 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002435 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002436 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002437
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002438 /* OSError subclasses */
2439 PRE_INIT(ConnectionError);
2440
2441 PRE_INIT(BlockingIOError);
2442 PRE_INIT(BrokenPipeError);
2443 PRE_INIT(ChildProcessError);
2444 PRE_INIT(ConnectionAbortedError);
2445 PRE_INIT(ConnectionRefusedError);
2446 PRE_INIT(ConnectionResetError);
2447 PRE_INIT(FileExistsError);
2448 PRE_INIT(FileNotFoundError);
2449 PRE_INIT(IsADirectoryError);
2450 PRE_INIT(NotADirectoryError);
2451 PRE_INIT(InterruptedError);
2452 PRE_INIT(PermissionError);
2453 PRE_INIT(ProcessLookupError);
2454 PRE_INIT(TimeoutError);
2455
Thomas Wouters477c8d52006-05-27 19:21:47 +00002456 bdict = PyModule_GetDict(bltinmod);
2457 if (bdict == NULL)
2458 Py_FatalError("exceptions bootstrapping error.");
2459
2460 POST_INIT(BaseException)
2461 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002462 POST_INIT(TypeError)
2463 POST_INIT(StopIteration)
2464 POST_INIT(GeneratorExit)
2465 POST_INIT(SystemExit)
2466 POST_INIT(KeyboardInterrupt)
2467 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002468 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002469 INIT_ALIAS(EnvironmentError, OSError)
2470 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002471#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002472 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002473#endif
2474#ifdef __VMS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002475 INIT_ALIAS(VMSError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002476#endif
2477 POST_INIT(EOFError)
2478 POST_INIT(RuntimeError)
2479 POST_INIT(NotImplementedError)
2480 POST_INIT(NameError)
2481 POST_INIT(UnboundLocalError)
2482 POST_INIT(AttributeError)
2483 POST_INIT(SyntaxError)
2484 POST_INIT(IndentationError)
2485 POST_INIT(TabError)
2486 POST_INIT(LookupError)
2487 POST_INIT(IndexError)
2488 POST_INIT(KeyError)
2489 POST_INIT(ValueError)
2490 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002491 POST_INIT(UnicodeEncodeError)
2492 POST_INIT(UnicodeDecodeError)
2493 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002494 POST_INIT(AssertionError)
2495 POST_INIT(ArithmeticError)
2496 POST_INIT(FloatingPointError)
2497 POST_INIT(OverflowError)
2498 POST_INIT(ZeroDivisionError)
2499 POST_INIT(SystemError)
2500 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002501 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002502 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002503 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002504 POST_INIT(Warning)
2505 POST_INIT(UserWarning)
2506 POST_INIT(DeprecationWarning)
2507 POST_INIT(PendingDeprecationWarning)
2508 POST_INIT(SyntaxWarning)
2509 POST_INIT(RuntimeWarning)
2510 POST_INIT(FutureWarning)
2511 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002512 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002513 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002514 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002515
Antoine Pitrouac456a12012-01-18 21:35:21 +01002516 if (!errnomap) {
2517 errnomap = PyDict_New();
2518 if (!errnomap)
2519 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2520 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002521
2522 /* OSError subclasses */
2523 POST_INIT(ConnectionError);
2524
2525 POST_INIT(BlockingIOError);
2526 ADD_ERRNO(BlockingIOError, EAGAIN);
2527 ADD_ERRNO(BlockingIOError, EALREADY);
2528 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2529 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2530 POST_INIT(BrokenPipeError);
2531 ADD_ERRNO(BrokenPipeError, EPIPE);
2532 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2533 POST_INIT(ChildProcessError);
2534 ADD_ERRNO(ChildProcessError, ECHILD);
2535 POST_INIT(ConnectionAbortedError);
2536 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2537 POST_INIT(ConnectionRefusedError);
2538 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2539 POST_INIT(ConnectionResetError);
2540 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2541 POST_INIT(FileExistsError);
2542 ADD_ERRNO(FileExistsError, EEXIST);
2543 POST_INIT(FileNotFoundError);
2544 ADD_ERRNO(FileNotFoundError, ENOENT);
2545 POST_INIT(IsADirectoryError);
2546 ADD_ERRNO(IsADirectoryError, EISDIR);
2547 POST_INIT(NotADirectoryError);
2548 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2549 POST_INIT(InterruptedError);
2550 ADD_ERRNO(InterruptedError, EINTR);
2551 POST_INIT(PermissionError);
2552 ADD_ERRNO(PermissionError, EACCES);
2553 ADD_ERRNO(PermissionError, EPERM);
2554 POST_INIT(ProcessLookupError);
2555 ADD_ERRNO(ProcessLookupError, ESRCH);
2556 POST_INIT(TimeoutError);
2557 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2558
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002559 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002560
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002561 if (!PyExc_RecursionErrorInst) {
2562 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL);
2563 if (!PyExc_RecursionErrorInst)
2564 Py_FatalError("Cannot pre-allocate RuntimeError instance for "
2565 "recursion errors");
2566 else {
2567 PyBaseExceptionObject *err_inst =
2568 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2569 PyObject *args_tuple;
2570 PyObject *exc_message;
2571 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2572 if (!exc_message)
2573 Py_FatalError("cannot allocate argument for RuntimeError "
2574 "pre-allocation");
2575 args_tuple = PyTuple_Pack(1, exc_message);
2576 if (!args_tuple)
2577 Py_FatalError("cannot allocate tuple for RuntimeError "
2578 "pre-allocation");
2579 Py_DECREF(exc_message);
2580 if (BaseException_init(err_inst, args_tuple, NULL))
2581 Py_FatalError("init of pre-allocated RuntimeError failed");
2582 Py_DECREF(args_tuple);
2583 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002584 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002585}
2586
2587void
2588_PyExc_Fini(void)
2589{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002590 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002591 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002592 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002593}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002594
2595/* Helper to do the equivalent of "raise X from Y" in C, but always using
2596 * the current exception rather than passing one in.
2597 *
2598 * We currently limit this to *only* exceptions that use the BaseException
2599 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2600 * those correctly without losing data and without losing backwards
2601 * compatibility.
2602 *
2603 * We also aim to rule out *all* exceptions that might be storing additional
2604 * state, whether by having a size difference relative to BaseException,
2605 * additional arguments passed in during construction or by having a
2606 * non-empty instance dict.
2607 *
2608 * We need to be very careful with what we wrap, since changing types to
2609 * a broader exception type would be backwards incompatible for
2610 * existing codecs, and with different init or new method implementations
2611 * may either not support instantiation with PyErr_Format or lose
2612 * information when instantiated that way.
2613 *
2614 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2615 * fact that exceptions are expected to support pickling. If more builtin
2616 * exceptions (e.g. AttributeError) start to be converted to rich
2617 * exceptions with additional attributes, that's probably a better approach
2618 * to pursue over adding special cases for particular stateful subclasses.
2619 *
2620 * Returns a borrowed reference to the new exception (if any), NULL if the
2621 * existing exception was left in place.
2622 */
2623PyObject *
2624_PyErr_TrySetFromCause(const char *format, ...)
2625{
2626 PyObject* msg_prefix;
2627 PyObject *exc, *val, *tb;
2628 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002629 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002630 PyObject *instance_args;
2631 Py_ssize_t num_args;
2632 PyObject *new_exc, *new_val, *new_tb;
2633 va_list vargs;
2634
Nick Coghlan8b097b42013-11-13 23:49:21 +10002635 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002636 caught_type = (PyTypeObject *)exc;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002637 /* Ensure type info indicates no extra state is stored at the C level */
Benjamin Peterson079c9982013-11-13 23:25:01 -05002638 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002639 caught_type->tp_new != BaseException_new ||
2640 caught_type->tp_basicsize != _PyExc_BaseException.tp_basicsize ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002641 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002642 /* We can't be sure we can wrap this safely, since it may contain
2643 * more state than just the exception type. Accordingly, we just
2644 * leave it alone.
2645 */
2646 PyErr_Restore(exc, val, tb);
2647 return NULL;
2648 }
2649
2650 /* Check the args are empty or contain a single string */
2651 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002652 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002653 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002654 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002655 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002656 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002657 /* More than 1 arg, or the one arg we do have isn't a string
2658 */
2659 PyErr_Restore(exc, val, tb);
2660 return NULL;
2661 }
2662
2663 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002664 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002665 if (dictptr != NULL && *dictptr != NULL &&
2666 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002667 /* While we could potentially copy a non-empty instance dictionary
2668 * to the replacement exception, for now we take the more
2669 * conservative path of leaving exceptions with attributes set
2670 * alone.
2671 */
2672 PyErr_Restore(exc, val, tb);
2673 return NULL;
2674 }
2675
2676 /* For exceptions that we can wrap safely, we chain the original
2677 * exception to a new one of the exact same type with an
2678 * error message that mentions the additional details and the
2679 * original exception.
2680 *
2681 * It would be nice to wrap OSError and various other exception
2682 * types as well, but that's quite a bit trickier due to the extra
2683 * state potentially stored on OSError instances.
2684 */
Christian Heimes507eabd2013-11-14 01:39:35 +01002685
Benjamin Petersone109ee82013-11-13 23:49:49 -05002686 Py_DECREF(exc);
2687 Py_XDECREF(tb);
2688
Christian Heimes507eabd2013-11-14 01:39:35 +01002689#ifdef HAVE_STDARG_PROTOTYPES
2690 va_start(vargs, format);
2691#else
2692 va_start(vargs);
2693#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002694 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002695 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002696 if (msg_prefix == NULL) {
2697 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002698 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002699 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002700
2701 PyErr_Format(exc, "%U (%s: %S)",
2702 msg_prefix, Py_TYPE(val)->tp_name, val);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002703 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002704 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2705 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2706 PyException_SetCause(new_val, val);
2707 PyErr_Restore(new_exc, new_val, new_tb);
2708 return new_val;
2709}