blob: 2531ead50fbda1294e623f88ad071d17c2fbea62 [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
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020019
20/* The dict map from errno codes to OSError subclasses */
21static PyObject *errnomap = NULL;
22
23
Thomas Wouters477c8d52006-05-27 19:21:47 +000024/* NOTE: If the exception class hierarchy changes, don't forget to update
25 * Lib/test/exception_hierarchy.txt
26 */
27
Thomas Wouters477c8d52006-05-27 19:21:47 +000028/*
29 * BaseException
30 */
31static PyObject *
32BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
33{
34 PyBaseExceptionObject *self;
35
36 self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +000037 if (!self)
38 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000039 /* the dict is created on the fly in PyObject_GenericSetAttr */
Guido van Rossumebe3e162007-05-17 18:20:34 +000040 self->dict = NULL;
Collin Winter1966f1c2007-09-01 20:26:44 +000041 self->traceback = self->cause = self->context = NULL;
Benjamin Petersond5a1c442012-05-14 22:09:31 -070042 self->suppress_context = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000043
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010044 if (args) {
45 self->args = args;
46 Py_INCREF(args);
47 return (PyObject *)self;
48 }
49
Thomas Wouters477c8d52006-05-27 19:21:47 +000050 self->args = PyTuple_New(0);
51 if (!self->args) {
52 Py_DECREF(self);
53 return NULL;
54 }
55
Thomas Wouters477c8d52006-05-27 19:21:47 +000056 return (PyObject *)self;
57}
58
59static int
60BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
61{
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010062 PyObject *tmp;
63
Christian Heimes90aa7642007-12-19 02:45:37 +000064 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000065 return -1;
66
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010067 tmp = self->args;
Thomas Wouters477c8d52006-05-27 19:21:47 +000068 self->args = args;
69 Py_INCREF(self->args);
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010070 Py_XDECREF(tmp);
Thomas Wouters477c8d52006-05-27 19:21:47 +000071
Thomas Wouters477c8d52006-05-27 19:21:47 +000072 return 0;
73}
74
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000075static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000076BaseException_clear(PyBaseExceptionObject *self)
77{
78 Py_CLEAR(self->dict);
79 Py_CLEAR(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +000080 Py_CLEAR(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +000081 Py_CLEAR(self->cause);
82 Py_CLEAR(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +000083 return 0;
84}
85
86static void
87BaseException_dealloc(PyBaseExceptionObject *self)
88{
Thomas Wouters89f507f2006-12-13 04:49:30 +000089 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000090 BaseException_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +000091 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000092}
93
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000094static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000095BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
96{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000097 Py_VISIT(self->dict);
Thomas Wouters477c8d52006-05-27 19:21:47 +000098 Py_VISIT(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +000099 Py_VISIT(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +0000100 Py_VISIT(self->cause);
101 Py_VISIT(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000102 return 0;
103}
104
105static PyObject *
106BaseException_str(PyBaseExceptionObject *self)
107{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000108 switch (PyTuple_GET_SIZE(self->args)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 case 0:
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +0000110 return PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000111 case 1:
Thomas Heller519a0422007-11-15 20:48:54 +0000112 return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000113 default:
Thomas Heller519a0422007-11-15 20:48:54 +0000114 return PyObject_Str(self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000115 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000116}
117
118static PyObject *
119BaseException_repr(PyBaseExceptionObject *self)
120{
Serhiy Storchakac6792272013-10-19 21:03:34 +0300121 const char *name;
122 const char *dot;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123
Serhiy Storchakac6792272013-10-19 21:03:34 +0300124 name = Py_TYPE(self)->tp_name;
125 dot = (const char *) strrchr(name, '.');
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126 if (dot != NULL) name = dot+1;
127
Walter Dörwald7569dfe2007-05-19 21:49:49 +0000128 return PyUnicode_FromFormat("%s%R", name, self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000129}
130
131/* Pickling support */
132static PyObject *
133BaseException_reduce(PyBaseExceptionObject *self)
134{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000135 if (self->args && self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +0000136 return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000137 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000138 return PyTuple_Pack(2, Py_TYPE(self), self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000139}
140
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000141/*
142 * Needed for backward compatibility, since exceptions used to store
143 * all their attributes in the __dict__. Code is taken from cPickle's
144 * load_build function.
145 */
146static PyObject *
147BaseException_setstate(PyObject *self, PyObject *state)
148{
149 PyObject *d_key, *d_value;
150 Py_ssize_t i = 0;
151
152 if (state != Py_None) {
153 if (!PyDict_Check(state)) {
154 PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
155 return NULL;
156 }
157 while (PyDict_Next(state, &i, &d_key, &d_value)) {
158 if (PyObject_SetAttr(self, d_key, d_value) < 0)
159 return NULL;
160 }
161 }
162 Py_RETURN_NONE;
163}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000164
Collin Winter828f04a2007-08-31 00:04:24 +0000165static PyObject *
166BaseException_with_traceback(PyObject *self, PyObject *tb) {
167 if (PyException_SetTraceback(self, tb))
168 return NULL;
169
170 Py_INCREF(self);
171 return self;
172}
173
Georg Brandl76941002008-05-05 21:38:47 +0000174PyDoc_STRVAR(with_traceback_doc,
175"Exception.with_traceback(tb) --\n\
176 set self.__traceback__ to tb and return self.");
177
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178
179static PyMethodDef BaseException_methods[] = {
180 {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000181 {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
Georg Brandl76941002008-05-05 21:38:47 +0000182 {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
183 with_traceback_doc},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000184 {NULL, NULL, 0, NULL},
185};
186
Thomas Wouters477c8d52006-05-27 19:21:47 +0000187static PyObject *
188BaseException_get_args(PyBaseExceptionObject *self)
189{
190 if (self->args == NULL) {
191 Py_INCREF(Py_None);
192 return Py_None;
193 }
194 Py_INCREF(self->args);
195 return self->args;
196}
197
198static int
199BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
200{
201 PyObject *seq;
202 if (val == NULL) {
203 PyErr_SetString(PyExc_TypeError, "args may not be deleted");
204 return -1;
205 }
206 seq = PySequence_Tuple(val);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500207 if (!seq)
208 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000209 Py_CLEAR(self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000210 self->args = seq;
211 return 0;
212}
213
Collin Winter828f04a2007-08-31 00:04:24 +0000214static PyObject *
215BaseException_get_tb(PyBaseExceptionObject *self)
216{
217 if (self->traceback == NULL) {
218 Py_INCREF(Py_None);
219 return Py_None;
220 }
221 Py_INCREF(self->traceback);
222 return self->traceback;
223}
224
225static int
226BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb)
227{
228 if (tb == NULL) {
229 PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
230 return -1;
231 }
232 else if (!(tb == Py_None || PyTraceBack_Check(tb))) {
233 PyErr_SetString(PyExc_TypeError,
234 "__traceback__ must be a traceback or None");
235 return -1;
236 }
237
238 Py_XINCREF(tb);
239 Py_XDECREF(self->traceback);
240 self->traceback = tb;
241 return 0;
242}
243
Georg Brandlab6f2f62009-03-31 04:16:10 +0000244static PyObject *
245BaseException_get_context(PyObject *self) {
246 PyObject *res = PyException_GetContext(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500247 if (res)
248 return res; /* new reference already returned above */
Georg Brandlab6f2f62009-03-31 04:16:10 +0000249 Py_RETURN_NONE;
250}
251
252static int
253BaseException_set_context(PyObject *self, PyObject *arg) {
254 if (arg == NULL) {
255 PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
256 return -1;
257 } else if (arg == Py_None) {
258 arg = NULL;
259 } else if (!PyExceptionInstance_Check(arg)) {
260 PyErr_SetString(PyExc_TypeError, "exception context must be None "
261 "or derive from BaseException");
262 return -1;
263 } else {
264 /* PyException_SetContext steals this reference */
265 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 }
Georg Brandlab6f2f62009-03-31 04:16:10 +0000267 PyException_SetContext(self, arg);
268 return 0;
269}
270
271static PyObject *
272BaseException_get_cause(PyObject *self) {
273 PyObject *res = PyException_GetCause(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500274 if (res)
275 return res; /* new reference already returned above */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700276 Py_RETURN_NONE;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000277}
278
279static int
280BaseException_set_cause(PyObject *self, PyObject *arg) {
281 if (arg == NULL) {
282 PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
283 return -1;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700284 } else if (arg == Py_None) {
285 arg = NULL;
286 } else if (!PyExceptionInstance_Check(arg)) {
287 PyErr_SetString(PyExc_TypeError, "exception cause must be None "
288 "or derive from BaseException");
289 return -1;
290 } else {
291 /* PyException_SetCause steals this reference */
292 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700294 PyException_SetCause(self, arg);
295 return 0;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000296}
297
Guido van Rossum360e4b82007-05-14 22:51:27 +0000298
Thomas Wouters477c8d52006-05-27 19:21:47 +0000299static PyGetSetDef BaseException_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500300 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000301 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
Collin Winter828f04a2007-08-31 00:04:24 +0000302 {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
Georg Brandlab6f2f62009-03-31 04:16:10 +0000303 {"__context__", (getter)BaseException_get_context,
304 (setter)BaseException_set_context, PyDoc_STR("exception context")},
305 {"__cause__", (getter)BaseException_get_cause,
306 (setter)BaseException_set_cause, PyDoc_STR("exception cause")},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000307 {NULL},
308};
309
310
Collin Winter828f04a2007-08-31 00:04:24 +0000311PyObject *
312PyException_GetTraceback(PyObject *self) {
313 PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
314 Py_XINCREF(base_self->traceback);
315 return base_self->traceback;
316}
317
318
319int
320PyException_SetTraceback(PyObject *self, PyObject *tb) {
321 return BaseException_set_tb((PyBaseExceptionObject *)self, tb);
322}
323
324PyObject *
325PyException_GetCause(PyObject *self) {
326 PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
327 Py_XINCREF(cause);
328 return cause;
329}
330
331/* Steals a reference to cause */
332void
333PyException_SetCause(PyObject *self, PyObject *cause) {
334 PyObject *old_cause = ((PyBaseExceptionObject *)self)->cause;
335 ((PyBaseExceptionObject *)self)->cause = cause;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700336 ((PyBaseExceptionObject *)self)->suppress_context = 1;
Collin Winter828f04a2007-08-31 00:04:24 +0000337 Py_XDECREF(old_cause);
338}
339
340PyObject *
341PyException_GetContext(PyObject *self) {
342 PyObject *context = ((PyBaseExceptionObject *)self)->context;
343 Py_XINCREF(context);
344 return context;
345}
346
347/* Steals a reference to context */
348void
349PyException_SetContext(PyObject *self, PyObject *context) {
350 PyObject *old_context = ((PyBaseExceptionObject *)self)->context;
351 ((PyBaseExceptionObject *)self)->context = context;
352 Py_XDECREF(old_context);
353}
354
355
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700356static struct PyMemberDef BaseException_members[] = {
357 {"__suppress_context__", T_BOOL,
Antoine Pitrou32bc80c2012-05-16 12:51:55 +0200358 offsetof(PyBaseExceptionObject, suppress_context)},
359 {NULL}
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700360};
361
362
Thomas Wouters477c8d52006-05-27 19:21:47 +0000363static PyTypeObject _PyExc_BaseException = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000364 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +0000365 "BaseException", /*tp_name*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000366 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
367 0, /*tp_itemsize*/
368 (destructor)BaseException_dealloc, /*tp_dealloc*/
369 0, /*tp_print*/
370 0, /*tp_getattr*/
371 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000372 0, /* tp_reserved; */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373 (reprfunc)BaseException_repr, /*tp_repr*/
374 0, /*tp_as_number*/
Brett Cannonba7bf492007-02-27 00:15:55 +0000375 0, /*tp_as_sequence*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000376 0, /*tp_as_mapping*/
377 0, /*tp_hash */
378 0, /*tp_call*/
379 (reprfunc)BaseException_str, /*tp_str*/
380 PyObject_GenericGetAttr, /*tp_getattro*/
381 PyObject_GenericSetAttr, /*tp_setattro*/
382 0, /*tp_as_buffer*/
Thomas Wouters27d517b2007-02-25 20:39:11 +0000383 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000385 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
386 (traverseproc)BaseException_traverse, /* tp_traverse */
387 (inquiry)BaseException_clear, /* tp_clear */
388 0, /* tp_richcompare */
389 0, /* tp_weaklistoffset */
390 0, /* tp_iter */
391 0, /* tp_iternext */
392 BaseException_methods, /* tp_methods */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700393 BaseException_members, /* tp_members */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000394 BaseException_getset, /* tp_getset */
395 0, /* tp_base */
396 0, /* tp_dict */
397 0, /* tp_descr_get */
398 0, /* tp_descr_set */
399 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
400 (initproc)BaseException_init, /* tp_init */
401 0, /* tp_alloc */
402 BaseException_new, /* tp_new */
403};
404/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
405from the previous implmentation and also allowing Python objects to be used
406in the API */
407PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
408
409/* note these macros omit the last semicolon so the macro invocation may
410 * include it and not look strange.
411 */
412#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
413static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000414 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000415 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000416 sizeof(PyBaseExceptionObject), \
417 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
418 0, 0, 0, 0, 0, 0, 0, \
419 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
420 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
421 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
422 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
423 (initproc)BaseException_init, 0, BaseException_new,\
424}; \
425PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
426
427#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
428static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000429 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000430 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431 sizeof(Py ## EXCSTORE ## Object), \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000432 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433 0, 0, 0, 0, 0, \
434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000435 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
436 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200438 (initproc)EXCSTORE ## _init, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439}; \
440PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
441
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200442#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
443 EXCMETHODS, EXCMEMBERS, EXCGETSET, \
444 EXCSTR, EXCDOC) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000445static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000446 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000447 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000448 sizeof(Py ## EXCSTORE ## Object), 0, \
449 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
450 (reprfunc)EXCSTR, 0, 0, 0, \
451 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
452 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
453 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200454 EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200456 (initproc)EXCSTORE ## _init, 0, EXCNEW,\
Thomas Wouters477c8d52006-05-27 19:21:47 +0000457}; \
458PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
459
460
461/*
462 * Exception extends BaseException
463 */
464SimpleExtendsException(PyExc_BaseException, Exception,
465 "Common base class for all non-exit exceptions.");
466
467
468/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000469 * TypeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000470 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000471SimpleExtendsException(PyExc_Exception, TypeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000472 "Inappropriate argument type.");
473
474
475/*
476 * StopIteration extends Exception
477 */
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000478
479static PyMemberDef StopIteration_members[] = {
480 {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
481 PyDoc_STR("generator return value")},
482 {NULL} /* Sentinel */
483};
484
485static int
486StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
487{
488 Py_ssize_t size = PyTuple_GET_SIZE(args);
489 PyObject *value;
490
491 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
492 return -1;
493 Py_CLEAR(self->value);
494 if (size > 0)
495 value = PyTuple_GET_ITEM(args, 0);
496 else
497 value = Py_None;
498 Py_INCREF(value);
499 self->value = value;
500 return 0;
501}
502
503static int
504StopIteration_clear(PyStopIterationObject *self)
505{
506 Py_CLEAR(self->value);
507 return BaseException_clear((PyBaseExceptionObject *)self);
508}
509
510static void
511StopIteration_dealloc(PyStopIterationObject *self)
512{
513 _PyObject_GC_UNTRACK(self);
514 StopIteration_clear(self);
515 Py_TYPE(self)->tp_free((PyObject *)self);
516}
517
518static int
519StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
520{
521 Py_VISIT(self->value);
522 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
523}
524
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000525ComplexExtendsException(
526 PyExc_Exception, /* base */
527 StopIteration, /* name */
528 StopIteration, /* prefix for *_init, etc */
529 0, /* new */
530 0, /* methods */
531 StopIteration_members, /* members */
532 0, /* getset */
533 0, /* str */
534 "Signal the end from iterator.__next__()."
535);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536
537
538/*
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000539 * GeneratorExit extends BaseException
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540 */
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000541SimpleExtendsException(PyExc_BaseException, GeneratorExit,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542 "Request that a generator exit.");
543
544
545/*
546 * SystemExit extends BaseException
547 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
549static int
550SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
551{
552 Py_ssize_t size = PyTuple_GET_SIZE(args);
553
554 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
555 return -1;
556
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000557 if (size == 0)
558 return 0;
559 Py_CLEAR(self->code);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000560 if (size == 1)
561 self->code = PyTuple_GET_ITEM(args, 0);
Victor Stinner92236e52011-05-26 14:25:54 +0200562 else /* size > 1 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000563 self->code = args;
564 Py_INCREF(self->code);
565 return 0;
566}
567
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000568static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569SystemExit_clear(PySystemExitObject *self)
570{
571 Py_CLEAR(self->code);
572 return BaseException_clear((PyBaseExceptionObject *)self);
573}
574
575static void
576SystemExit_dealloc(PySystemExitObject *self)
577{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000578 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000579 SystemExit_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000580 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581}
582
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000583static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000584SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
585{
586 Py_VISIT(self->code);
587 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
588}
589
590static PyMemberDef SystemExit_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000591 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
592 PyDoc_STR("exception code")},
593 {NULL} /* Sentinel */
594};
595
596ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200597 0, 0, SystemExit_members, 0, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598 "Request to exit from the interpreter.");
599
600/*
601 * KeyboardInterrupt extends BaseException
602 */
603SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
604 "Program interrupted by user.");
605
606
607/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000608 * ImportError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000609 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000610
Brett Cannon79ec55e2012-04-12 20:24:54 -0400611static int
612ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
613{
614 PyObject *msg = NULL;
615 PyObject *name = NULL;
616 PyObject *path = NULL;
617
618/* Macro replacement doesn't allow ## to start the first line of a macro,
619 so we move the assignment and NULL check into the if-statement. */
620#define GET_KWD(kwd) { \
621 kwd = PyDict_GetItemString(kwds, #kwd); \
622 if (kwd) { \
623 Py_CLEAR(self->kwd); \
624 self->kwd = kwd; \
625 Py_INCREF(self->kwd);\
626 if (PyDict_DelItemString(kwds, #kwd)) \
627 return -1; \
628 } \
629 }
630
631 if (kwds) {
632 GET_KWD(name);
633 GET_KWD(path);
634 }
635
636 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
637 return -1;
638 if (PyTuple_GET_SIZE(args) != 1)
639 return 0;
640 if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
641 return -1;
642
643 Py_CLEAR(self->msg); /* replacing */
644 self->msg = msg;
645 Py_INCREF(self->msg);
646
647 return 0;
648}
649
650static int
651ImportError_clear(PyImportErrorObject *self)
652{
653 Py_CLEAR(self->msg);
654 Py_CLEAR(self->name);
655 Py_CLEAR(self->path);
656 return BaseException_clear((PyBaseExceptionObject *)self);
657}
658
659static void
660ImportError_dealloc(PyImportErrorObject *self)
661{
662 _PyObject_GC_UNTRACK(self);
663 ImportError_clear(self);
664 Py_TYPE(self)->tp_free((PyObject *)self);
665}
666
667static int
668ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
669{
670 Py_VISIT(self->msg);
671 Py_VISIT(self->name);
672 Py_VISIT(self->path);
673 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
674}
675
676static PyObject *
677ImportError_str(PyImportErrorObject *self)
678{
Brett Cannon07c6e712012-08-24 13:05:09 -0400679 if (self->msg && PyUnicode_CheckExact(self->msg)) {
Brett Cannon79ec55e2012-04-12 20:24:54 -0400680 Py_INCREF(self->msg);
681 return self->msg;
682 }
683 else {
684 return BaseException_str((PyBaseExceptionObject *)self);
685 }
686}
687
688static PyMemberDef ImportError_members[] = {
689 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
690 PyDoc_STR("exception message")},
691 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
692 PyDoc_STR("module name")},
693 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
694 PyDoc_STR("module path")},
695 {NULL} /* Sentinel */
696};
697
698static PyMethodDef ImportError_methods[] = {
699 {NULL}
700};
701
702ComplexExtendsException(PyExc_Exception, ImportError,
703 ImportError, 0 /* new */,
704 ImportError_methods, ImportError_members,
705 0 /* getset */, ImportError_str,
706 "Import can't find module, or can't find name in "
707 "module.");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000708
709/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200710 * OSError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711 */
712
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200713#ifdef MS_WINDOWS
714#include "errmap.h"
715#endif
716
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717/* Where a function has a single filename, such as open() or some
718 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
719 * called, giving a third argument which is the filename. But, so
720 * that old code using in-place unpacking doesn't break, e.g.:
721 *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200722 * except OSError, (errno, strerror):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000723 *
724 * we hack args so that it only contains two items. This also
725 * means we need our own __str__() which prints out the filename
726 * when it was supplied.
727 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200728
Antoine Pitroue0e27352011-12-15 14:31:28 +0100729/* This function doesn't cleanup on error, the caller should */
730static int
731oserror_parse_args(PyObject **p_args,
732 PyObject **myerrno, PyObject **strerror,
733 PyObject **filename
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200734#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100735 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200736#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100737 )
738{
739 Py_ssize_t nargs;
740 PyObject *args = *p_args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200742 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000743
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200744#ifdef MS_WINDOWS
745 if (nargs >= 2 && nargs <= 4) {
746 if (!PyArg_UnpackTuple(args, "OSError", 2, 4,
Antoine Pitroue0e27352011-12-15 14:31:28 +0100747 myerrno, strerror, filename, winerror))
748 return -1;
749 if (*winerror && PyLong_Check(*winerror)) {
750 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200751 PyObject *newargs;
752 Py_ssize_t i;
753
Antoine Pitroue0e27352011-12-15 14:31:28 +0100754 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200755 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100756 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200757 /* Set errno to the corresponding POSIX errno (overriding
758 first argument). Windows Socket error codes (>= 10000)
759 have the same value as their POSIX counterparts.
760 */
761 if (winerrcode < 10000)
762 errcode = winerror_to_errno(winerrcode);
763 else
764 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100765 *myerrno = PyLong_FromLong(errcode);
766 if (!*myerrno)
767 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200768 newargs = PyTuple_New(nargs);
769 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100770 return -1;
771 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200772 for (i = 1; i < nargs; i++) {
773 PyObject *val = PyTuple_GET_ITEM(args, i);
774 Py_INCREF(val);
775 PyTuple_SET_ITEM(newargs, i, val);
776 }
777 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100778 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200779 }
780 }
781#else
782 if (nargs >= 2 && nargs <= 3) {
783 if (!PyArg_UnpackTuple(args, "OSError", 2, 3,
Antoine Pitroue0e27352011-12-15 14:31:28 +0100784 myerrno, strerror, filename))
785 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200786 }
787#endif
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000788
Antoine Pitroue0e27352011-12-15 14:31:28 +0100789 return 0;
790}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000791
Antoine Pitroue0e27352011-12-15 14:31:28 +0100792static int
793oserror_init(PyOSErrorObject *self, PyObject **p_args,
794 PyObject *myerrno, PyObject *strerror,
795 PyObject *filename
796#ifdef MS_WINDOWS
797 , PyObject *winerror
798#endif
799 )
800{
801 PyObject *args = *p_args;
802 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000803
804 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200805 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100806 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200807 PyNumber_Check(filename)) {
808 /* BlockingIOError's 3rd argument can be the number of
809 * characters written.
810 */
811 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
812 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100813 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200814 }
815 else {
816 Py_INCREF(filename);
817 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000818
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200819 if (nargs >= 2 && nargs <= 3) {
820 /* filename is removed from the args tuple (for compatibility
821 purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100822 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200823 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100824 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000825
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200826 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100827 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200828 }
829 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000830 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200831 Py_XINCREF(myerrno);
832 self->myerrno = myerrno;
833
834 Py_XINCREF(strerror);
835 self->strerror = strerror;
836
837#ifdef MS_WINDOWS
838 Py_XINCREF(winerror);
839 self->winerror = winerror;
840#endif
841
Antoine Pitroue0e27352011-12-15 14:31:28 +0100842 /* Steals the reference to args */
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200843 Py_CLEAR(self->args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100844 self->args = args;
Victor Stinner46ef3192013-11-14 22:31:41 +0100845 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100846
847 return 0;
848}
849
850static PyObject *
851OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
852static int
853OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
854
855static int
856oserror_use_init(PyTypeObject *type)
857{
858 /* When __init__ is defined in a OSError subclass, we want any
859 extraneous argument to __new__ to be ignored. The only reasonable
860 solution, given __new__ takes a variable number of arguments,
861 is to defer arg parsing and initialization to __init__.
862
863 But when __new__ is overriden as well, it should call our __new__
864 with the right arguments.
865
866 (see http://bugs.python.org/issue12555#msg148829 )
867 */
868 if (type->tp_init != (initproc) OSError_init &&
869 type->tp_new == (newfunc) OSError_new) {
870 assert((PyObject *) type != PyExc_OSError);
871 return 1;
872 }
873 return 0;
874}
875
876static PyObject *
877OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
878{
879 PyOSErrorObject *self = NULL;
880 PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL;
881#ifdef MS_WINDOWS
882 PyObject *winerror = NULL;
883#endif
884
Victor Stinner46ef3192013-11-14 22:31:41 +0100885 Py_INCREF(args);
886
Antoine Pitroue0e27352011-12-15 14:31:28 +0100887 if (!oserror_use_init(type)) {
888 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100889 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100890
Antoine Pitroue0e27352011-12-15 14:31:28 +0100891 if (oserror_parse_args(&args, &myerrno, &strerror, &filename
892#ifdef MS_WINDOWS
893 , &winerror
894#endif
895 ))
896 goto error;
897
898 if (myerrno && PyLong_Check(myerrno) &&
899 errnomap && (PyObject *) type == PyExc_OSError) {
900 PyObject *newtype;
901 newtype = PyDict_GetItem(errnomap, myerrno);
902 if (newtype) {
903 assert(PyType_Check(newtype));
904 type = (PyTypeObject *) newtype;
905 }
906 else if (PyErr_Occurred())
907 goto error;
908 }
909 }
910
911 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
912 if (!self)
913 goto error;
914
915 self->dict = NULL;
916 self->traceback = self->cause = self->context = NULL;
917 self->written = -1;
918
919 if (!oserror_use_init(type)) {
920 if (oserror_init(self, &args, myerrno, strerror, filename
921#ifdef MS_WINDOWS
922 , winerror
923#endif
924 ))
925 goto error;
926 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200927 else {
928 self->args = PyTuple_New(0);
929 if (self->args == NULL)
930 goto error;
931 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100932
Victor Stinner46ef3192013-11-14 22:31:41 +0100933 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200934 return (PyObject *) self;
935
936error:
937 Py_XDECREF(args);
938 Py_XDECREF(self);
939 return NULL;
940}
941
942static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100943OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200944{
Antoine Pitroue0e27352011-12-15 14:31:28 +0100945 PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL;
946#ifdef MS_WINDOWS
947 PyObject *winerror = NULL;
948#endif
949
950 if (!oserror_use_init(Py_TYPE(self)))
951 /* Everything already done in OSError_new */
952 return 0;
953
954 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
955 return -1;
956
957 Py_INCREF(args);
958 if (oserror_parse_args(&args, &myerrno, &strerror, &filename
959#ifdef MS_WINDOWS
960 , &winerror
961#endif
962 ))
963 goto error;
964
965 if (oserror_init(self, &args, myerrno, strerror, filename
966#ifdef MS_WINDOWS
967 , winerror
968#endif
969 ))
970 goto error;
971
Thomas Wouters477c8d52006-05-27 19:21:47 +0000972 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100973
974error:
975 Py_XDECREF(args);
976 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000977}
978
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000979static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200980OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000981{
982 Py_CLEAR(self->myerrno);
983 Py_CLEAR(self->strerror);
984 Py_CLEAR(self->filename);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200985#ifdef MS_WINDOWS
986 Py_CLEAR(self->winerror);
987#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +0000988 return BaseException_clear((PyBaseExceptionObject *)self);
989}
990
991static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200992OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000993{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000994 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200995 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000996 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000997}
998
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000999static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001000OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001001 void *arg)
1002{
1003 Py_VISIT(self->myerrno);
1004 Py_VISIT(self->strerror);
1005 Py_VISIT(self->filename);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001006#ifdef MS_WINDOWS
1007 Py_VISIT(self->winerror);
1008#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1010}
1011
1012static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001013OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001014{
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001015#ifdef MS_WINDOWS
1016 /* If available, winerror has the priority over myerrno */
1017 if (self->winerror && self->filename)
Richard Oudkerk30147712012-08-28 19:33:26 +01001018 return PyUnicode_FromFormat("[WinError %S] %S: %R",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001019 self->winerror ? self->winerror: Py_None,
1020 self->strerror ? self->strerror: Py_None,
1021 self->filename);
1022 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001023 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001024 self->winerror ? self->winerror: Py_None,
1025 self->strerror ? self->strerror: Py_None);
1026#endif
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001027 if (self->filename)
1028 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1029 self->myerrno ? self->myerrno: Py_None,
1030 self->strerror ? self->strerror: Py_None,
1031 self->filename);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001032 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001033 return PyUnicode_FromFormat("[Errno %S] %S",
1034 self->myerrno ? self->myerrno: Py_None,
1035 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001036 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001037}
1038
Thomas Wouters477c8d52006-05-27 19:21:47 +00001039static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001040OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041{
1042 PyObject *args = self->args;
1043 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001044
Thomas Wouters477c8d52006-05-27 19:21:47 +00001045 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001046 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001047 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001048 args = PyTuple_New(3);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001049 if (!args)
1050 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001051
1052 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001053 Py_INCREF(tmp);
1054 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001055
1056 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001057 Py_INCREF(tmp);
1058 PyTuple_SET_ITEM(args, 1, tmp);
1059
1060 Py_INCREF(self->filename);
1061 PyTuple_SET_ITEM(args, 2, self->filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001062 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001063 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001064
1065 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001066 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001067 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001068 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001069 Py_DECREF(args);
1070 return res;
1071}
1072
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001073static PyObject *
1074OSError_written_get(PyOSErrorObject *self, void *context)
1075{
1076 if (self->written == -1) {
1077 PyErr_SetString(PyExc_AttributeError, "characters_written");
1078 return NULL;
1079 }
1080 return PyLong_FromSsize_t(self->written);
1081}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001082
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001083static int
1084OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1085{
1086 Py_ssize_t n;
1087 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1088 if (n == -1 && PyErr_Occurred())
1089 return -1;
1090 self->written = n;
1091 return 0;
1092}
1093
1094static PyMemberDef OSError_members[] = {
1095 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1096 PyDoc_STR("POSIX exception code")},
1097 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1098 PyDoc_STR("exception strerror")},
1099 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1100 PyDoc_STR("exception filename")},
1101#ifdef MS_WINDOWS
1102 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1103 PyDoc_STR("Win32 exception code")},
1104#endif
1105 {NULL} /* Sentinel */
1106};
1107
1108static PyMethodDef OSError_methods[] = {
1109 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001110 {NULL}
1111};
1112
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001113static PyGetSetDef OSError_getset[] = {
1114 {"characters_written", (getter) OSError_written_get,
1115 (setter) OSError_written_set, NULL},
1116 {NULL}
1117};
1118
1119
1120ComplexExtendsException(PyExc_Exception, OSError,
1121 OSError, OSError_new,
1122 OSError_methods, OSError_members, OSError_getset,
1123 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001124 "Base class for I/O related errors.");
1125
1126
1127/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001128 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001129 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001130MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1131 "I/O operation would block.");
1132MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1133 "Connection error.");
1134MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1135 "Child process error.");
1136MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1137 "Broken pipe.");
1138MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1139 "Connection aborted.");
1140MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1141 "Connection refused.");
1142MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1143 "Connection reset.");
1144MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1145 "File already exists.");
1146MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1147 "File not found.");
1148MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1149 "Operation doesn't work on directories.");
1150MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1151 "Operation only works on directories.");
1152MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1153 "Interrupted by signal.");
1154MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1155 "Not enough permissions.");
1156MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1157 "Process not found.");
1158MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1159 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001160
1161/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001162 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001164SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001165 "Read beyond end of file.");
1166
1167
1168/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001169 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001170 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001171SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001172 "Unspecified run-time error.");
1173
1174
1175/*
1176 * NotImplementedError extends RuntimeError
1177 */
1178SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1179 "Method or function hasn't been implemented yet.");
1180
1181/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001182 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001183 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001184SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001185 "Name not found globally.");
1186
1187/*
1188 * UnboundLocalError extends NameError
1189 */
1190SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1191 "Local name referenced but not bound to a value.");
1192
1193/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001194 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001195 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001196SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001197 "Attribute not found.");
1198
1199
1200/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001201 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001202 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001203
1204static int
1205SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1206{
1207 PyObject *info = NULL;
1208 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1209
1210 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1211 return -1;
1212
1213 if (lenargs >= 1) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001214 Py_CLEAR(self->msg);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001215 self->msg = PyTuple_GET_ITEM(args, 0);
1216 Py_INCREF(self->msg);
1217 }
1218 if (lenargs == 2) {
1219 info = PyTuple_GET_ITEM(args, 1);
1220 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001221 if (!info)
1222 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001223
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001224 if (PyTuple_GET_SIZE(info) != 4) {
1225 /* not a very good error message, but it's what Python 2.4 gives */
1226 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1227 Py_DECREF(info);
1228 return -1;
1229 }
1230
1231 Py_CLEAR(self->filename);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001232 self->filename = PyTuple_GET_ITEM(info, 0);
1233 Py_INCREF(self->filename);
1234
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001235 Py_CLEAR(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001236 self->lineno = PyTuple_GET_ITEM(info, 1);
1237 Py_INCREF(self->lineno);
1238
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001239 Py_CLEAR(self->offset);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240 self->offset = PyTuple_GET_ITEM(info, 2);
1241 Py_INCREF(self->offset);
1242
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001243 Py_CLEAR(self->text);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001244 self->text = PyTuple_GET_ITEM(info, 3);
1245 Py_INCREF(self->text);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001246
1247 Py_DECREF(info);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001248 }
1249 return 0;
1250}
1251
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001252static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001253SyntaxError_clear(PySyntaxErrorObject *self)
1254{
1255 Py_CLEAR(self->msg);
1256 Py_CLEAR(self->filename);
1257 Py_CLEAR(self->lineno);
1258 Py_CLEAR(self->offset);
1259 Py_CLEAR(self->text);
1260 Py_CLEAR(self->print_file_and_line);
1261 return BaseException_clear((PyBaseExceptionObject *)self);
1262}
1263
1264static void
1265SyntaxError_dealloc(PySyntaxErrorObject *self)
1266{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001267 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001268 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001269 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001270}
1271
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001272static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001273SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1274{
1275 Py_VISIT(self->msg);
1276 Py_VISIT(self->filename);
1277 Py_VISIT(self->lineno);
1278 Py_VISIT(self->offset);
1279 Py_VISIT(self->text);
1280 Py_VISIT(self->print_file_and_line);
1281 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1282}
1283
1284/* This is called "my_basename" instead of just "basename" to avoid name
1285 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1286 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001287static PyObject*
1288my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001289{
Victor Stinner6237daf2010-04-28 17:26:19 +00001290 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001291 int kind;
1292 void *data;
1293
1294 if (PyUnicode_READY(name))
1295 return NULL;
1296 kind = PyUnicode_KIND(name);
1297 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001298 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001299 offset = 0;
1300 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001301 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001302 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001303 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001304 if (offset != 0)
1305 return PyUnicode_Substring(name, offset, size);
1306 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001307 Py_INCREF(name);
1308 return name;
1309 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001310}
1311
1312
1313static PyObject *
1314SyntaxError_str(PySyntaxErrorObject *self)
1315{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001316 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001317 PyObject *filename;
1318 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001319 /* Below, we always ignore overflow errors, just printing -1.
1320 Still, we cannot allow an OverflowError to be raised, so
1321 we need to call PyLong_AsLongAndOverflow. */
1322 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001323
1324 /* XXX -- do all the additional formatting with filename and
1325 lineno here */
1326
Neal Norwitzed2b7392007-08-26 04:51:10 +00001327 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001328 filename = my_basename(self->filename);
1329 if (filename == NULL)
1330 return NULL;
1331 } else {
1332 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001333 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001334 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001335
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001336 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001337 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001338
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001339 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001340 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001341 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001342 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001344 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001345 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001346 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001347 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001348 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001349 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001350 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001351 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001352 Py_XDECREF(filename);
1353 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001354}
1355
1356static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001357 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1358 PyDoc_STR("exception msg")},
1359 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1360 PyDoc_STR("exception filename")},
1361 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1362 PyDoc_STR("exception lineno")},
1363 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1364 PyDoc_STR("exception offset")},
1365 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1366 PyDoc_STR("exception text")},
1367 {"print_file_and_line", T_OBJECT,
1368 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1369 PyDoc_STR("exception print_file_and_line")},
1370 {NULL} /* Sentinel */
1371};
1372
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001373ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001374 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001375 SyntaxError_str, "Invalid syntax.");
1376
1377
1378/*
1379 * IndentationError extends SyntaxError
1380 */
1381MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1382 "Improper indentation.");
1383
1384
1385/*
1386 * TabError extends IndentationError
1387 */
1388MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1389 "Improper mixture of spaces and tabs.");
1390
1391
1392/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001393 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001394 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001395SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001396 "Base class for lookup errors.");
1397
1398
1399/*
1400 * IndexError extends LookupError
1401 */
1402SimpleExtendsException(PyExc_LookupError, IndexError,
1403 "Sequence index out of range.");
1404
1405
1406/*
1407 * KeyError extends LookupError
1408 */
1409static PyObject *
1410KeyError_str(PyBaseExceptionObject *self)
1411{
1412 /* If args is a tuple of exactly one item, apply repr to args[0].
1413 This is done so that e.g. the exception raised by {}[''] prints
1414 KeyError: ''
1415 rather than the confusing
1416 KeyError
1417 alone. The downside is that if KeyError is raised with an explanatory
1418 string, that string will be displayed in quotes. Too bad.
1419 If args is anything else, use the default BaseException__str__().
1420 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001421 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001422 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001423 }
1424 return BaseException_str(self);
1425}
1426
1427ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001428 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001429
1430
1431/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001432 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001433 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001434SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001435 "Inappropriate argument value (of correct type).");
1436
1437/*
1438 * UnicodeError extends ValueError
1439 */
1440
1441SimpleExtendsException(PyExc_ValueError, UnicodeError,
1442 "Unicode related error.");
1443
Thomas Wouters477c8d52006-05-27 19:21:47 +00001444static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001445get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001446{
1447 if (!attr) {
1448 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1449 return NULL;
1450 }
1451
Christian Heimes72b710a2008-05-26 13:28:38 +00001452 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001453 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1454 return NULL;
1455 }
1456 Py_INCREF(attr);
1457 return attr;
1458}
1459
1460static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001461get_unicode(PyObject *attr, const char *name)
1462{
1463 if (!attr) {
1464 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1465 return NULL;
1466 }
1467
1468 if (!PyUnicode_Check(attr)) {
1469 PyErr_Format(PyExc_TypeError,
1470 "%.200s attribute must be unicode", name);
1471 return NULL;
1472 }
1473 Py_INCREF(attr);
1474 return attr;
1475}
1476
Walter Dörwaldd2034312007-05-18 16:29:38 +00001477static int
1478set_unicodefromstring(PyObject **attr, const char *value)
1479{
1480 PyObject *obj = PyUnicode_FromString(value);
1481 if (!obj)
1482 return -1;
1483 Py_CLEAR(*attr);
1484 *attr = obj;
1485 return 0;
1486}
1487
Thomas Wouters477c8d52006-05-27 19:21:47 +00001488PyObject *
1489PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1490{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001491 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001492}
1493
1494PyObject *
1495PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1496{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001497 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001498}
1499
1500PyObject *
1501PyUnicodeEncodeError_GetObject(PyObject *exc)
1502{
1503 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1504}
1505
1506PyObject *
1507PyUnicodeDecodeError_GetObject(PyObject *exc)
1508{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001509 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001510}
1511
1512PyObject *
1513PyUnicodeTranslateError_GetObject(PyObject *exc)
1514{
1515 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1516}
1517
1518int
1519PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1520{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001521 Py_ssize_t size;
1522 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1523 "object");
1524 if (!obj)
1525 return -1;
1526 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001527 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001528 if (*start<0)
1529 *start = 0; /*XXX check for values <0*/
1530 if (*start>=size)
1531 *start = size-1;
1532 Py_DECREF(obj);
1533 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001534}
1535
1536
1537int
1538PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1539{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001540 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001541 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001542 if (!obj)
1543 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001544 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001545 *start = ((PyUnicodeErrorObject *)exc)->start;
1546 if (*start<0)
1547 *start = 0;
1548 if (*start>=size)
1549 *start = size-1;
1550 Py_DECREF(obj);
1551 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001552}
1553
1554
1555int
1556PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1557{
1558 return PyUnicodeEncodeError_GetStart(exc, start);
1559}
1560
1561
1562int
1563PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1564{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001565 ((PyUnicodeErrorObject *)exc)->start = start;
1566 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001567}
1568
1569
1570int
1571PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1572{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001573 ((PyUnicodeErrorObject *)exc)->start = start;
1574 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001575}
1576
1577
1578int
1579PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1580{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001581 ((PyUnicodeErrorObject *)exc)->start = start;
1582 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001583}
1584
1585
1586int
1587PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1588{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001589 Py_ssize_t size;
1590 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1591 "object");
1592 if (!obj)
1593 return -1;
1594 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001595 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001596 if (*end<1)
1597 *end = 1;
1598 if (*end>size)
1599 *end = size;
1600 Py_DECREF(obj);
1601 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001602}
1603
1604
1605int
1606PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1607{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001608 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001609 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001610 if (!obj)
1611 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001612 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001613 *end = ((PyUnicodeErrorObject *)exc)->end;
1614 if (*end<1)
1615 *end = 1;
1616 if (*end>size)
1617 *end = size;
1618 Py_DECREF(obj);
1619 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001620}
1621
1622
1623int
1624PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1625{
1626 return PyUnicodeEncodeError_GetEnd(exc, start);
1627}
1628
1629
1630int
1631PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1632{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001633 ((PyUnicodeErrorObject *)exc)->end = end;
1634 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001635}
1636
1637
1638int
1639PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1640{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001641 ((PyUnicodeErrorObject *)exc)->end = end;
1642 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001643}
1644
1645
1646int
1647PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1648{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001649 ((PyUnicodeErrorObject *)exc)->end = end;
1650 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001651}
1652
1653PyObject *
1654PyUnicodeEncodeError_GetReason(PyObject *exc)
1655{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001656 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001657}
1658
1659
1660PyObject *
1661PyUnicodeDecodeError_GetReason(PyObject *exc)
1662{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001663 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001664}
1665
1666
1667PyObject *
1668PyUnicodeTranslateError_GetReason(PyObject *exc)
1669{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001670 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001671}
1672
1673
1674int
1675PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1676{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001677 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1678 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001679}
1680
1681
1682int
1683PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1684{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001685 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1686 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001687}
1688
1689
1690int
1691PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1692{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001693 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1694 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001695}
1696
1697
Thomas Wouters477c8d52006-05-27 19:21:47 +00001698static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001699UnicodeError_clear(PyUnicodeErrorObject *self)
1700{
1701 Py_CLEAR(self->encoding);
1702 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001703 Py_CLEAR(self->reason);
1704 return BaseException_clear((PyBaseExceptionObject *)self);
1705}
1706
1707static void
1708UnicodeError_dealloc(PyUnicodeErrorObject *self)
1709{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001710 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001711 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001712 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001713}
1714
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001715static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1717{
1718 Py_VISIT(self->encoding);
1719 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001720 Py_VISIT(self->reason);
1721 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1722}
1723
1724static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001725 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1726 PyDoc_STR("exception encoding")},
1727 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1728 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001729 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001730 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001731 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001732 PyDoc_STR("exception end")},
1733 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1734 PyDoc_STR("exception reason")},
1735 {NULL} /* Sentinel */
1736};
1737
1738
1739/*
1740 * UnicodeEncodeError extends UnicodeError
1741 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001742
1743static int
1744UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1745{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001746 PyUnicodeErrorObject *err;
1747
Thomas Wouters477c8d52006-05-27 19:21:47 +00001748 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1749 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001750
1751 err = (PyUnicodeErrorObject *)self;
1752
1753 Py_CLEAR(err->encoding);
1754 Py_CLEAR(err->object);
1755 Py_CLEAR(err->reason);
1756
1757 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1758 &PyUnicode_Type, &err->encoding,
1759 &PyUnicode_Type, &err->object,
1760 &err->start,
1761 &err->end,
1762 &PyUnicode_Type, &err->reason)) {
1763 err->encoding = err->object = err->reason = NULL;
1764 return -1;
1765 }
1766
Martin v. Löwisb09af032011-11-04 11:16:41 +01001767 if (PyUnicode_READY(err->object) < -1) {
1768 err->encoding = NULL;
1769 return -1;
1770 }
1771
Guido van Rossum98297ee2007-11-06 21:34:58 +00001772 Py_INCREF(err->encoding);
1773 Py_INCREF(err->object);
1774 Py_INCREF(err->reason);
1775
1776 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001777}
1778
1779static PyObject *
1780UnicodeEncodeError_str(PyObject *self)
1781{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001782 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001783 PyObject *result = NULL;
1784 PyObject *reason_str = NULL;
1785 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001786
Eric Smith0facd772010-02-24 15:42:29 +00001787 /* Get reason and encoding as strings, which they might not be if
1788 they've been modified after we were contructed. */
1789 reason_str = PyObject_Str(uself->reason);
1790 if (reason_str == NULL)
1791 goto done;
1792 encoding_str = PyObject_Str(uself->encoding);
1793 if (encoding_str == NULL)
1794 goto done;
1795
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001796 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1797 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001798 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001799 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001800 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001801 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001802 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001803 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001804 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001805 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001806 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001807 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001808 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001809 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001810 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001811 }
Eric Smith0facd772010-02-24 15:42:29 +00001812 else {
1813 result = PyUnicode_FromFormat(
1814 "'%U' codec can't encode characters in position %zd-%zd: %U",
1815 encoding_str,
1816 uself->start,
1817 uself->end-1,
1818 reason_str);
1819 }
1820done:
1821 Py_XDECREF(reason_str);
1822 Py_XDECREF(encoding_str);
1823 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001824}
1825
1826static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001827 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001828 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001829 sizeof(PyUnicodeErrorObject), 0,
1830 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1831 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1832 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001833 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1834 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001835 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001836 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001837};
1838PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1839
1840PyObject *
1841PyUnicodeEncodeError_Create(
1842 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1843 Py_ssize_t start, Py_ssize_t end, const char *reason)
1844{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001845 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001846 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001847}
1848
1849
1850/*
1851 * UnicodeDecodeError extends UnicodeError
1852 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001853
1854static int
1855UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1856{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001857 PyUnicodeErrorObject *ude;
1858 const char *data;
1859 Py_ssize_t size;
1860
Thomas Wouters477c8d52006-05-27 19:21:47 +00001861 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1862 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001863
1864 ude = (PyUnicodeErrorObject *)self;
1865
1866 Py_CLEAR(ude->encoding);
1867 Py_CLEAR(ude->object);
1868 Py_CLEAR(ude->reason);
1869
1870 if (!PyArg_ParseTuple(args, "O!OnnO!",
1871 &PyUnicode_Type, &ude->encoding,
1872 &ude->object,
1873 &ude->start,
1874 &ude->end,
1875 &PyUnicode_Type, &ude->reason)) {
1876 ude->encoding = ude->object = ude->reason = NULL;
1877 return -1;
1878 }
1879
Christian Heimes72b710a2008-05-26 13:28:38 +00001880 if (!PyBytes_Check(ude->object)) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00001881 if (PyObject_AsReadBuffer(ude->object, (const void **)&data, &size)) {
1882 ude->encoding = ude->object = ude->reason = NULL;
1883 return -1;
1884 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001885 ude->object = PyBytes_FromStringAndSize(data, size);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001886 }
1887 else {
1888 Py_INCREF(ude->object);
1889 }
1890
1891 Py_INCREF(ude->encoding);
1892 Py_INCREF(ude->reason);
1893
1894 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001895}
1896
1897static PyObject *
1898UnicodeDecodeError_str(PyObject *self)
1899{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001900 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001901 PyObject *result = NULL;
1902 PyObject *reason_str = NULL;
1903 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904
Eric Smith0facd772010-02-24 15:42:29 +00001905 /* Get reason and encoding as strings, which they might not be if
1906 they've been modified after we were contructed. */
1907 reason_str = PyObject_Str(uself->reason);
1908 if (reason_str == NULL)
1909 goto done;
1910 encoding_str = PyObject_Str(uself->encoding);
1911 if (encoding_str == NULL)
1912 goto done;
1913
1914 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001915 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00001916 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001917 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00001918 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001919 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001920 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001921 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922 }
Eric Smith0facd772010-02-24 15:42:29 +00001923 else {
1924 result = PyUnicode_FromFormat(
1925 "'%U' codec can't decode bytes in position %zd-%zd: %U",
1926 encoding_str,
1927 uself->start,
1928 uself->end-1,
1929 reason_str
1930 );
1931 }
1932done:
1933 Py_XDECREF(reason_str);
1934 Py_XDECREF(encoding_str);
1935 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001936}
1937
1938static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001939 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001940 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001941 sizeof(PyUnicodeErrorObject), 0,
1942 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1943 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
1944 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001945 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
1946 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001947 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001948 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001949};
1950PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
1951
1952PyObject *
1953PyUnicodeDecodeError_Create(
1954 const char *encoding, const char *object, Py_ssize_t length,
1955 Py_ssize_t start, Py_ssize_t end, const char *reason)
1956{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001957 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001958 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001959}
1960
1961
1962/*
1963 * UnicodeTranslateError extends UnicodeError
1964 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001965
1966static int
1967UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
1968 PyObject *kwds)
1969{
1970 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1971 return -1;
1972
1973 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001974 Py_CLEAR(self->reason);
1975
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001976 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001977 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001978 &self->start,
1979 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00001980 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001981 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001982 return -1;
1983 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001984
Thomas Wouters477c8d52006-05-27 19:21:47 +00001985 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001986 Py_INCREF(self->reason);
1987
1988 return 0;
1989}
1990
1991
1992static PyObject *
1993UnicodeTranslateError_str(PyObject *self)
1994{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001995 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001996 PyObject *result = NULL;
1997 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001998
Eric Smith0facd772010-02-24 15:42:29 +00001999 /* Get reason as a string, which it might not be if it's been
2000 modified after we were contructed. */
2001 reason_str = PyObject_Str(uself->reason);
2002 if (reason_str == NULL)
2003 goto done;
2004
Victor Stinner53b33e72011-11-21 01:17:27 +01002005 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2006 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002007 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002008 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002009 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002010 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002011 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002012 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002013 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002014 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002015 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002016 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002017 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002018 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002019 );
Eric Smith0facd772010-02-24 15:42:29 +00002020 } else {
2021 result = PyUnicode_FromFormat(
2022 "can't translate characters in position %zd-%zd: %U",
2023 uself->start,
2024 uself->end-1,
2025 reason_str
2026 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002027 }
Eric Smith0facd772010-02-24 15:42:29 +00002028done:
2029 Py_XDECREF(reason_str);
2030 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002031}
2032
2033static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002034 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002035 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002036 sizeof(PyUnicodeErrorObject), 0,
2037 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2038 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2039 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002040 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002041 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2042 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002043 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002044};
2045PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002048PyObject *
2049PyUnicodeTranslateError_Create(
2050 const Py_UNICODE *object, Py_ssize_t length,
2051 Py_ssize_t start, Py_ssize_t end, const char *reason)
2052{
2053 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002054 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002055}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002056
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002057PyObject *
2058_PyUnicodeTranslateError_Create(
2059 PyObject *object,
2060 Py_ssize_t start, Py_ssize_t end, const char *reason)
2061{
2062 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Ons",
2063 object, start, end, reason);
2064}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002065
2066/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002067 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002068 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002069SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002070 "Assertion failed.");
2071
2072
2073/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002074 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002075 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002076SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002077 "Base class for arithmetic errors.");
2078
2079
2080/*
2081 * FloatingPointError extends ArithmeticError
2082 */
2083SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2084 "Floating point operation failed.");
2085
2086
2087/*
2088 * OverflowError extends ArithmeticError
2089 */
2090SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2091 "Result too large to be represented.");
2092
2093
2094/*
2095 * ZeroDivisionError extends ArithmeticError
2096 */
2097SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2098 "Second argument to a division or modulo operation was zero.");
2099
2100
2101/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002102 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002103 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002104SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002105 "Internal error in the Python interpreter.\n"
2106 "\n"
2107 "Please report this to the Python maintainer, along with the traceback,\n"
2108 "the Python version, and the hardware/OS platform and version.");
2109
2110
2111/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002112 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002113 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002114SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002115 "Weak ref proxy used after referent went away.");
2116
2117
2118/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002119 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002120 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002121
2122#define MEMERRORS_SAVE 16
2123static PyBaseExceptionObject *memerrors_freelist = NULL;
2124static int memerrors_numfree = 0;
2125
2126static PyObject *
2127MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2128{
2129 PyBaseExceptionObject *self;
2130
2131 if (type != (PyTypeObject *) PyExc_MemoryError)
2132 return BaseException_new(type, args, kwds);
2133 if (memerrors_freelist == NULL)
2134 return BaseException_new(type, args, kwds);
2135 /* Fetch object from freelist and revive it */
2136 self = memerrors_freelist;
2137 self->args = PyTuple_New(0);
2138 /* This shouldn't happen since the empty tuple is persistent */
2139 if (self->args == NULL)
2140 return NULL;
2141 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2142 memerrors_numfree--;
2143 self->dict = NULL;
2144 _Py_NewReference((PyObject *)self);
2145 _PyObject_GC_TRACK(self);
2146 return (PyObject *)self;
2147}
2148
2149static void
2150MemoryError_dealloc(PyBaseExceptionObject *self)
2151{
2152 _PyObject_GC_UNTRACK(self);
2153 BaseException_clear(self);
2154 if (memerrors_numfree >= MEMERRORS_SAVE)
2155 Py_TYPE(self)->tp_free((PyObject *)self);
2156 else {
2157 self->dict = (PyObject *) memerrors_freelist;
2158 memerrors_freelist = self;
2159 memerrors_numfree++;
2160 }
2161}
2162
2163static void
2164preallocate_memerrors(void)
2165{
2166 /* We create enough MemoryErrors and then decref them, which will fill
2167 up the freelist. */
2168 int i;
2169 PyObject *errors[MEMERRORS_SAVE];
2170 for (i = 0; i < MEMERRORS_SAVE; i++) {
2171 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2172 NULL, NULL);
2173 if (!errors[i])
2174 Py_FatalError("Could not preallocate MemoryError object");
2175 }
2176 for (i = 0; i < MEMERRORS_SAVE; i++) {
2177 Py_DECREF(errors[i]);
2178 }
2179}
2180
2181static void
2182free_preallocated_memerrors(void)
2183{
2184 while (memerrors_freelist != NULL) {
2185 PyObject *self = (PyObject *) memerrors_freelist;
2186 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2187 Py_TYPE(self)->tp_free((PyObject *)self);
2188 }
2189}
2190
2191
2192static PyTypeObject _PyExc_MemoryError = {
2193 PyVarObject_HEAD_INIT(NULL, 0)
2194 "MemoryError",
2195 sizeof(PyBaseExceptionObject),
2196 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2197 0, 0, 0, 0, 0, 0, 0,
2198 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2199 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2200 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2201 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2202 (initproc)BaseException_init, 0, MemoryError_new
2203};
2204PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2205
Thomas Wouters477c8d52006-05-27 19:21:47 +00002206
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002207/*
2208 * BufferError extends Exception
2209 */
2210SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2211
Thomas Wouters477c8d52006-05-27 19:21:47 +00002212
2213/* Warning category docstrings */
2214
2215/*
2216 * Warning extends Exception
2217 */
2218SimpleExtendsException(PyExc_Exception, Warning,
2219 "Base class for warning categories.");
2220
2221
2222/*
2223 * UserWarning extends Warning
2224 */
2225SimpleExtendsException(PyExc_Warning, UserWarning,
2226 "Base class for warnings generated by user code.");
2227
2228
2229/*
2230 * DeprecationWarning extends Warning
2231 */
2232SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2233 "Base class for warnings about deprecated features.");
2234
2235
2236/*
2237 * PendingDeprecationWarning extends Warning
2238 */
2239SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2240 "Base class for warnings about features which will be deprecated\n"
2241 "in the future.");
2242
2243
2244/*
2245 * SyntaxWarning extends Warning
2246 */
2247SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2248 "Base class for warnings about dubious syntax.");
2249
2250
2251/*
2252 * RuntimeWarning extends Warning
2253 */
2254SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2255 "Base class for warnings about dubious runtime behavior.");
2256
2257
2258/*
2259 * FutureWarning extends Warning
2260 */
2261SimpleExtendsException(PyExc_Warning, FutureWarning,
2262 "Base class for warnings about constructs that will change semantically\n"
2263 "in the future.");
2264
2265
2266/*
2267 * ImportWarning extends Warning
2268 */
2269SimpleExtendsException(PyExc_Warning, ImportWarning,
2270 "Base class for warnings about probable mistakes in module imports");
2271
2272
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002273/*
2274 * UnicodeWarning extends Warning
2275 */
2276SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2277 "Base class for warnings about Unicode related problems, mostly\n"
2278 "related to conversion problems.");
2279
Georg Brandl08be72d2010-10-24 15:11:22 +00002280
Guido van Rossum98297ee2007-11-06 21:34:58 +00002281/*
2282 * BytesWarning extends Warning
2283 */
2284SimpleExtendsException(PyExc_Warning, BytesWarning,
2285 "Base class for warnings about bytes and buffer related problems, mostly\n"
2286 "related to conversion from str or comparing to str.");
2287
2288
Georg Brandl08be72d2010-10-24 15:11:22 +00002289/*
2290 * ResourceWarning extends Warning
2291 */
2292SimpleExtendsException(PyExc_Warning, ResourceWarning,
2293 "Base class for warnings about resource usage.");
2294
2295
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002296
Thomas Wouters89d996e2007-09-08 17:39:28 +00002297/* Pre-computed RuntimeError instance for when recursion depth is reached.
2298 Meant to be used when normalizing the exception for exceeding the recursion
2299 depth will cause its own infinite recursion.
2300*/
2301PyObject *PyExc_RecursionErrorInst = NULL;
2302
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002303#define PRE_INIT(TYPE) \
2304 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2305 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2306 Py_FatalError("exceptions bootstrapping error."); \
2307 Py_INCREF(PyExc_ ## TYPE); \
2308 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002309
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002310#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002311 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2312 Py_FatalError("Module dictionary insertion problem.");
2313
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002314#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002315 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002316 PyExc_ ## NAME = PyExc_ ## TYPE; \
2317 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2318 Py_FatalError("Module dictionary insertion problem.");
2319
2320#define ADD_ERRNO(TYPE, CODE) { \
2321 PyObject *_code = PyLong_FromLong(CODE); \
2322 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2323 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2324 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002325 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002326 }
2327
2328#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002329#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002330/* The following constants were added to errno.h in VS2010 but have
2331 preferred WSA equivalents. */
2332#undef EADDRINUSE
2333#undef EADDRNOTAVAIL
2334#undef EAFNOSUPPORT
2335#undef EALREADY
2336#undef ECONNABORTED
2337#undef ECONNREFUSED
2338#undef ECONNRESET
2339#undef EDESTADDRREQ
2340#undef EHOSTUNREACH
2341#undef EINPROGRESS
2342#undef EISCONN
2343#undef ELOOP
2344#undef EMSGSIZE
2345#undef ENETDOWN
2346#undef ENETRESET
2347#undef ENETUNREACH
2348#undef ENOBUFS
2349#undef ENOPROTOOPT
2350#undef ENOTCONN
2351#undef ENOTSOCK
2352#undef EOPNOTSUPP
2353#undef EPROTONOSUPPORT
2354#undef EPROTOTYPE
2355#undef ETIMEDOUT
2356#undef EWOULDBLOCK
2357
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002358#if defined(WSAEALREADY) && !defined(EALREADY)
2359#define EALREADY WSAEALREADY
2360#endif
2361#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2362#define ECONNABORTED WSAECONNABORTED
2363#endif
2364#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2365#define ECONNREFUSED WSAECONNREFUSED
2366#endif
2367#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2368#define ECONNRESET WSAECONNRESET
2369#endif
2370#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2371#define EINPROGRESS WSAEINPROGRESS
2372#endif
2373#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2374#define ESHUTDOWN WSAESHUTDOWN
2375#endif
2376#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2377#define ETIMEDOUT WSAETIMEDOUT
2378#endif
2379#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2380#define EWOULDBLOCK WSAEWOULDBLOCK
2381#endif
2382#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002383
Martin v. Löwis1a214512008-06-11 05:26:20 +00002384void
Brett Cannonfd074152012-04-14 14:10:13 -04002385_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002386{
Brett Cannonfd074152012-04-14 14:10:13 -04002387 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002388
2389 PRE_INIT(BaseException)
2390 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002391 PRE_INIT(TypeError)
2392 PRE_INIT(StopIteration)
2393 PRE_INIT(GeneratorExit)
2394 PRE_INIT(SystemExit)
2395 PRE_INIT(KeyboardInterrupt)
2396 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002397 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002398 PRE_INIT(EOFError)
2399 PRE_INIT(RuntimeError)
2400 PRE_INIT(NotImplementedError)
2401 PRE_INIT(NameError)
2402 PRE_INIT(UnboundLocalError)
2403 PRE_INIT(AttributeError)
2404 PRE_INIT(SyntaxError)
2405 PRE_INIT(IndentationError)
2406 PRE_INIT(TabError)
2407 PRE_INIT(LookupError)
2408 PRE_INIT(IndexError)
2409 PRE_INIT(KeyError)
2410 PRE_INIT(ValueError)
2411 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002412 PRE_INIT(UnicodeEncodeError)
2413 PRE_INIT(UnicodeDecodeError)
2414 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002415 PRE_INIT(AssertionError)
2416 PRE_INIT(ArithmeticError)
2417 PRE_INIT(FloatingPointError)
2418 PRE_INIT(OverflowError)
2419 PRE_INIT(ZeroDivisionError)
2420 PRE_INIT(SystemError)
2421 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002422 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002423 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002424 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002425 PRE_INIT(Warning)
2426 PRE_INIT(UserWarning)
2427 PRE_INIT(DeprecationWarning)
2428 PRE_INIT(PendingDeprecationWarning)
2429 PRE_INIT(SyntaxWarning)
2430 PRE_INIT(RuntimeWarning)
2431 PRE_INIT(FutureWarning)
2432 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002433 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002434 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002435 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002436
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002437 /* OSError subclasses */
2438 PRE_INIT(ConnectionError);
2439
2440 PRE_INIT(BlockingIOError);
2441 PRE_INIT(BrokenPipeError);
2442 PRE_INIT(ChildProcessError);
2443 PRE_INIT(ConnectionAbortedError);
2444 PRE_INIT(ConnectionRefusedError);
2445 PRE_INIT(ConnectionResetError);
2446 PRE_INIT(FileExistsError);
2447 PRE_INIT(FileNotFoundError);
2448 PRE_INIT(IsADirectoryError);
2449 PRE_INIT(NotADirectoryError);
2450 PRE_INIT(InterruptedError);
2451 PRE_INIT(PermissionError);
2452 PRE_INIT(ProcessLookupError);
2453 PRE_INIT(TimeoutError);
2454
Thomas Wouters477c8d52006-05-27 19:21:47 +00002455 bdict = PyModule_GetDict(bltinmod);
2456 if (bdict == NULL)
2457 Py_FatalError("exceptions bootstrapping error.");
2458
2459 POST_INIT(BaseException)
2460 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002461 POST_INIT(TypeError)
2462 POST_INIT(StopIteration)
2463 POST_INIT(GeneratorExit)
2464 POST_INIT(SystemExit)
2465 POST_INIT(KeyboardInterrupt)
2466 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002467 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002468 INIT_ALIAS(EnvironmentError, OSError)
2469 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002470#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002471 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002472#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00002473 POST_INIT(EOFError)
2474 POST_INIT(RuntimeError)
2475 POST_INIT(NotImplementedError)
2476 POST_INIT(NameError)
2477 POST_INIT(UnboundLocalError)
2478 POST_INIT(AttributeError)
2479 POST_INIT(SyntaxError)
2480 POST_INIT(IndentationError)
2481 POST_INIT(TabError)
2482 POST_INIT(LookupError)
2483 POST_INIT(IndexError)
2484 POST_INIT(KeyError)
2485 POST_INIT(ValueError)
2486 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002487 POST_INIT(UnicodeEncodeError)
2488 POST_INIT(UnicodeDecodeError)
2489 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002490 POST_INIT(AssertionError)
2491 POST_INIT(ArithmeticError)
2492 POST_INIT(FloatingPointError)
2493 POST_INIT(OverflowError)
2494 POST_INIT(ZeroDivisionError)
2495 POST_INIT(SystemError)
2496 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002497 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002498 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002499 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002500 POST_INIT(Warning)
2501 POST_INIT(UserWarning)
2502 POST_INIT(DeprecationWarning)
2503 POST_INIT(PendingDeprecationWarning)
2504 POST_INIT(SyntaxWarning)
2505 POST_INIT(RuntimeWarning)
2506 POST_INIT(FutureWarning)
2507 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002508 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002509 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002510 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002511
Antoine Pitrouac456a12012-01-18 21:35:21 +01002512 if (!errnomap) {
2513 errnomap = PyDict_New();
2514 if (!errnomap)
2515 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2516 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002517
2518 /* OSError subclasses */
2519 POST_INIT(ConnectionError);
2520
2521 POST_INIT(BlockingIOError);
2522 ADD_ERRNO(BlockingIOError, EAGAIN);
2523 ADD_ERRNO(BlockingIOError, EALREADY);
2524 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2525 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2526 POST_INIT(BrokenPipeError);
2527 ADD_ERRNO(BrokenPipeError, EPIPE);
2528 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2529 POST_INIT(ChildProcessError);
2530 ADD_ERRNO(ChildProcessError, ECHILD);
2531 POST_INIT(ConnectionAbortedError);
2532 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2533 POST_INIT(ConnectionRefusedError);
2534 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2535 POST_INIT(ConnectionResetError);
2536 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2537 POST_INIT(FileExistsError);
2538 ADD_ERRNO(FileExistsError, EEXIST);
2539 POST_INIT(FileNotFoundError);
2540 ADD_ERRNO(FileNotFoundError, ENOENT);
2541 POST_INIT(IsADirectoryError);
2542 ADD_ERRNO(IsADirectoryError, EISDIR);
2543 POST_INIT(NotADirectoryError);
2544 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2545 POST_INIT(InterruptedError);
2546 ADD_ERRNO(InterruptedError, EINTR);
2547 POST_INIT(PermissionError);
2548 ADD_ERRNO(PermissionError, EACCES);
2549 ADD_ERRNO(PermissionError, EPERM);
2550 POST_INIT(ProcessLookupError);
2551 ADD_ERRNO(ProcessLookupError, ESRCH);
2552 POST_INIT(TimeoutError);
2553 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2554
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002555 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002556
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002557 if (!PyExc_RecursionErrorInst) {
2558 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL);
2559 if (!PyExc_RecursionErrorInst)
2560 Py_FatalError("Cannot pre-allocate RuntimeError instance for "
2561 "recursion errors");
2562 else {
2563 PyBaseExceptionObject *err_inst =
2564 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2565 PyObject *args_tuple;
2566 PyObject *exc_message;
2567 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2568 if (!exc_message)
2569 Py_FatalError("cannot allocate argument for RuntimeError "
2570 "pre-allocation");
2571 args_tuple = PyTuple_Pack(1, exc_message);
2572 if (!args_tuple)
2573 Py_FatalError("cannot allocate tuple for RuntimeError "
2574 "pre-allocation");
2575 Py_DECREF(exc_message);
2576 if (BaseException_init(err_inst, args_tuple, NULL))
2577 Py_FatalError("init of pre-allocated RuntimeError failed");
2578 Py_DECREF(args_tuple);
2579 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002580 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002581}
2582
2583void
2584_PyExc_Fini(void)
2585{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002586 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002587 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002588 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002589}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002590
2591/* Helper to do the equivalent of "raise X from Y" in C, but always using
2592 * the current exception rather than passing one in.
2593 *
2594 * We currently limit this to *only* exceptions that use the BaseException
2595 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2596 * those correctly without losing data and without losing backwards
2597 * compatibility.
2598 *
2599 * We also aim to rule out *all* exceptions that might be storing additional
2600 * state, whether by having a size difference relative to BaseException,
2601 * additional arguments passed in during construction or by having a
2602 * non-empty instance dict.
2603 *
2604 * We need to be very careful with what we wrap, since changing types to
2605 * a broader exception type would be backwards incompatible for
2606 * existing codecs, and with different init or new method implementations
2607 * may either not support instantiation with PyErr_Format or lose
2608 * information when instantiated that way.
2609 *
2610 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2611 * fact that exceptions are expected to support pickling. If more builtin
2612 * exceptions (e.g. AttributeError) start to be converted to rich
2613 * exceptions with additional attributes, that's probably a better approach
2614 * to pursue over adding special cases for particular stateful subclasses.
2615 *
2616 * Returns a borrowed reference to the new exception (if any), NULL if the
2617 * existing exception was left in place.
2618 */
2619PyObject *
2620_PyErr_TrySetFromCause(const char *format, ...)
2621{
2622 PyObject* msg_prefix;
2623 PyObject *exc, *val, *tb;
2624 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002625 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002626 PyObject *instance_args;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002627 Py_ssize_t num_args, caught_type_size, base_exc_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002628 PyObject *new_exc, *new_val, *new_tb;
2629 va_list vargs;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002630 int same_basic_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002631
Nick Coghlan8b097b42013-11-13 23:49:21 +10002632 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002633 caught_type = (PyTypeObject *)exc;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002634 /* Ensure type info indicates no extra state is stored at the C level
2635 * and that the type can be reinstantiated using PyErr_Format
2636 */
2637 caught_type_size = caught_type->tp_basicsize;
2638 base_exc_size = _PyExc_BaseException.tp_basicsize;
2639 same_basic_size = (
2640 caught_type_size == base_exc_size ||
2641 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
2642 (caught_type_size == base_exc_size + sizeof(PyObject *))
2643 )
2644 );
Benjamin Peterson079c9982013-11-13 23:25:01 -05002645 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002646 caught_type->tp_new != BaseException_new ||
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002647 !same_basic_size ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002648 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002649 /* We can't be sure we can wrap this safely, since it may contain
2650 * more state than just the exception type. Accordingly, we just
2651 * leave it alone.
2652 */
2653 PyErr_Restore(exc, val, tb);
2654 return NULL;
2655 }
2656
2657 /* Check the args are empty or contain a single string */
2658 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002659 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002660 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002661 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002662 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002663 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002664 /* More than 1 arg, or the one arg we do have isn't a string
2665 */
2666 PyErr_Restore(exc, val, tb);
2667 return NULL;
2668 }
2669
2670 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002671 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002672 if (dictptr != NULL && *dictptr != NULL &&
2673 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002674 /* While we could potentially copy a non-empty instance dictionary
2675 * to the replacement exception, for now we take the more
2676 * conservative path of leaving exceptions with attributes set
2677 * alone.
2678 */
2679 PyErr_Restore(exc, val, tb);
2680 return NULL;
2681 }
2682
2683 /* For exceptions that we can wrap safely, we chain the original
2684 * exception to a new one of the exact same type with an
2685 * error message that mentions the additional details and the
2686 * original exception.
2687 *
2688 * It would be nice to wrap OSError and various other exception
2689 * types as well, but that's quite a bit trickier due to the extra
2690 * state potentially stored on OSError instances.
2691 */
Nick Coghlan77b286b2014-01-27 00:53:38 +10002692 /* Ensure the traceback is set correctly on the existing exception */
2693 if (tb != NULL) {
2694 PyException_SetTraceback(val, tb);
2695 Py_DECREF(tb);
2696 }
Benjamin Petersone109ee82013-11-13 23:49:49 -05002697
Christian Heimes507eabd2013-11-14 01:39:35 +01002698#ifdef HAVE_STDARG_PROTOTYPES
2699 va_start(vargs, format);
2700#else
2701 va_start(vargs);
2702#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002703 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002704 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002705 if (msg_prefix == NULL) {
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002706 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002707 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002708 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002709 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002710
2711 PyErr_Format(exc, "%U (%s: %S)",
2712 msg_prefix, Py_TYPE(val)->tp_name, val);
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002713 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002714 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002715 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2716 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2717 PyException_SetCause(new_val, val);
2718 PyErr_Restore(new_exc, new_val, new_tb);
2719 return new_val;
2720}