blob: 44e60dd0440c3f75c47cc59e0a2390832a177902 [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.
Larry Hastingsb0827312014-02-09 22:05:19 -0800727 *
728 * (If a function has two filenames, such as rename(), symlink(),
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800729 * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
730 * which allows passing in a second filename.)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000731 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200732
Antoine Pitroue0e27352011-12-15 14:31:28 +0100733/* This function doesn't cleanup on error, the caller should */
734static int
735oserror_parse_args(PyObject **p_args,
736 PyObject **myerrno, PyObject **strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800737 PyObject **filename, PyObject **filename2
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200738#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100739 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200740#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100741 )
742{
743 Py_ssize_t nargs;
744 PyObject *args = *p_args;
Larry Hastingsb0827312014-02-09 22:05:19 -0800745#ifndef MS_WINDOWS
746 /*
747 * ignored on non-Windows platforms,
748 * but parsed so OSError has a consistent signature
749 */
750 PyObject *_winerror = NULL;
751 PyObject **winerror = &_winerror;
752#endif /* MS_WINDOWS */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000753
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200754 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000755
Larry Hastingsb0827312014-02-09 22:05:19 -0800756 if (nargs >= 2 && nargs <= 5) {
757 if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
758 myerrno, strerror,
759 filename, winerror, filename2))
Antoine Pitroue0e27352011-12-15 14:31:28 +0100760 return -1;
Larry Hastingsb0827312014-02-09 22:05:19 -0800761#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100762 if (*winerror && PyLong_Check(*winerror)) {
763 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200764 PyObject *newargs;
765 Py_ssize_t i;
766
Antoine Pitroue0e27352011-12-15 14:31:28 +0100767 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200768 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100769 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200770 /* Set errno to the corresponding POSIX errno (overriding
771 first argument). Windows Socket error codes (>= 10000)
772 have the same value as their POSIX counterparts.
773 */
774 if (winerrcode < 10000)
775 errcode = winerror_to_errno(winerrcode);
776 else
777 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100778 *myerrno = PyLong_FromLong(errcode);
779 if (!*myerrno)
780 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200781 newargs = PyTuple_New(nargs);
782 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100783 return -1;
784 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200785 for (i = 1; i < nargs; i++) {
786 PyObject *val = PyTuple_GET_ITEM(args, i);
787 Py_INCREF(val);
788 PyTuple_SET_ITEM(newargs, i, val);
789 }
790 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100791 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200792 }
Larry Hastingsb0827312014-02-09 22:05:19 -0800793#endif /* MS_WINDOWS */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200794 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000795
Antoine Pitroue0e27352011-12-15 14:31:28 +0100796 return 0;
797}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000798
Antoine Pitroue0e27352011-12-15 14:31:28 +0100799static int
800oserror_init(PyOSErrorObject *self, PyObject **p_args,
801 PyObject *myerrno, PyObject *strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800802 PyObject *filename, PyObject *filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100803#ifdef MS_WINDOWS
804 , PyObject *winerror
805#endif
806 )
807{
808 PyObject *args = *p_args;
809 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000810
811 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200812 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100813 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200814 PyNumber_Check(filename)) {
815 /* BlockingIOError's 3rd argument can be the number of
816 * characters written.
817 */
818 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
819 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100820 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200821 }
822 else {
823 Py_INCREF(filename);
824 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000825
Larry Hastingsb0827312014-02-09 22:05:19 -0800826 if (filename2 && filename2 != Py_None) {
827 Py_INCREF(filename2);
828 self->filename2 = filename2;
829 }
830
831 if (nargs >= 2 && nargs <= 5) {
832 /* filename, filename2, and winerror are removed from the args tuple
833 (for compatibility purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100834 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200835 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100836 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000837
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200838 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100839 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200840 }
841 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000842 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200843 Py_XINCREF(myerrno);
844 self->myerrno = myerrno;
845
846 Py_XINCREF(strerror);
847 self->strerror = strerror;
848
849#ifdef MS_WINDOWS
850 Py_XINCREF(winerror);
851 self->winerror = winerror;
852#endif
853
Antoine Pitroue0e27352011-12-15 14:31:28 +0100854 /* Steals the reference to args */
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200855 Py_CLEAR(self->args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100856 self->args = args;
Victor Stinner46ef3192013-11-14 22:31:41 +0100857 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100858
859 return 0;
860}
861
862static PyObject *
863OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
864static int
865OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
866
867static int
868oserror_use_init(PyTypeObject *type)
869{
870 /* When __init__ is defined in a OSError subclass, we want any
871 extraneous argument to __new__ to be ignored. The only reasonable
872 solution, given __new__ takes a variable number of arguments,
873 is to defer arg parsing and initialization to __init__.
874
875 But when __new__ is overriden as well, it should call our __new__
876 with the right arguments.
877
878 (see http://bugs.python.org/issue12555#msg148829 )
879 */
880 if (type->tp_init != (initproc) OSError_init &&
881 type->tp_new == (newfunc) OSError_new) {
882 assert((PyObject *) type != PyExc_OSError);
883 return 1;
884 }
885 return 0;
886}
887
888static PyObject *
889OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
890{
891 PyOSErrorObject *self = NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800892 PyObject *myerrno = NULL, *strerror = NULL;
893 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100894#ifdef MS_WINDOWS
895 PyObject *winerror = NULL;
896#endif
897
Victor Stinner46ef3192013-11-14 22:31:41 +0100898 Py_INCREF(args);
899
Antoine Pitroue0e27352011-12-15 14:31:28 +0100900 if (!oserror_use_init(type)) {
901 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100902 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100903
Larry Hastingsb0827312014-02-09 22:05:19 -0800904 if (oserror_parse_args(&args, &myerrno, &strerror,
905 &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100906#ifdef MS_WINDOWS
907 , &winerror
908#endif
909 ))
910 goto error;
911
912 if (myerrno && PyLong_Check(myerrno) &&
913 errnomap && (PyObject *) type == PyExc_OSError) {
914 PyObject *newtype;
915 newtype = PyDict_GetItem(errnomap, myerrno);
916 if (newtype) {
917 assert(PyType_Check(newtype));
918 type = (PyTypeObject *) newtype;
919 }
920 else if (PyErr_Occurred())
921 goto error;
922 }
923 }
924
925 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
926 if (!self)
927 goto error;
928
929 self->dict = NULL;
930 self->traceback = self->cause = self->context = NULL;
931 self->written = -1;
932
933 if (!oserror_use_init(type)) {
Larry Hastingsb0827312014-02-09 22:05:19 -0800934 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100935#ifdef MS_WINDOWS
936 , winerror
937#endif
938 ))
939 goto error;
940 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200941 else {
942 self->args = PyTuple_New(0);
943 if (self->args == NULL)
944 goto error;
945 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100946
Victor Stinner46ef3192013-11-14 22:31:41 +0100947 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200948 return (PyObject *) self;
949
950error:
951 Py_XDECREF(args);
952 Py_XDECREF(self);
953 return NULL;
954}
955
956static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100957OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200958{
Larry Hastingsb0827312014-02-09 22:05:19 -0800959 PyObject *myerrno = NULL, *strerror = NULL;
960 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100961#ifdef MS_WINDOWS
962 PyObject *winerror = NULL;
963#endif
964
965 if (!oserror_use_init(Py_TYPE(self)))
966 /* Everything already done in OSError_new */
967 return 0;
968
969 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
970 return -1;
971
972 Py_INCREF(args);
Larry Hastingsb0827312014-02-09 22:05:19 -0800973 if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100974#ifdef MS_WINDOWS
975 , &winerror
976#endif
977 ))
978 goto error;
979
Larry Hastingsb0827312014-02-09 22:05:19 -0800980 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100981#ifdef MS_WINDOWS
982 , winerror
983#endif
984 ))
985 goto error;
986
Thomas Wouters477c8d52006-05-27 19:21:47 +0000987 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100988
989error:
990 Py_XDECREF(args);
991 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000992}
993
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000994static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200995OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000996{
997 Py_CLEAR(self->myerrno);
998 Py_CLEAR(self->strerror);
999 Py_CLEAR(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001000 Py_CLEAR(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001001#ifdef MS_WINDOWS
1002 Py_CLEAR(self->winerror);
1003#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001004 return BaseException_clear((PyBaseExceptionObject *)self);
1005}
1006
1007static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001008OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001010 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001011 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001012 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001013}
1014
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001015static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001016OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001017 void *arg)
1018{
1019 Py_VISIT(self->myerrno);
1020 Py_VISIT(self->strerror);
1021 Py_VISIT(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001022 Py_VISIT(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001023#ifdef MS_WINDOWS
1024 Py_VISIT(self->winerror);
1025#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001026 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1027}
1028
1029static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001030OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001031{
Larry Hastingsb0827312014-02-09 22:05:19 -08001032#define OR_NONE(x) ((x)?(x):Py_None)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001033#ifdef MS_WINDOWS
1034 /* If available, winerror has the priority over myerrno */
Larry Hastingsb0827312014-02-09 22:05:19 -08001035 if (self->winerror && self->filename) {
1036 if (self->filename2) {
1037 return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
1038 OR_NONE(self->winerror),
1039 OR_NONE(self->strerror),
1040 self->filename,
1041 self->filename2);
1042 } else {
1043 return PyUnicode_FromFormat("[WinError %S] %S: %R",
1044 OR_NONE(self->winerror),
1045 OR_NONE(self->strerror),
1046 self->filename);
1047 }
1048 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001049 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001050 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001051 self->winerror ? self->winerror: Py_None,
1052 self->strerror ? self->strerror: Py_None);
1053#endif
Larry Hastingsb0827312014-02-09 22:05:19 -08001054 if (self->filename) {
1055 if (self->filename2) {
1056 return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
1057 OR_NONE(self->myerrno),
1058 OR_NONE(self->strerror),
1059 self->filename,
1060 self->filename2);
1061 } else {
1062 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1063 OR_NONE(self->myerrno),
1064 OR_NONE(self->strerror),
1065 self->filename);
1066 }
1067 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001068 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001069 return PyUnicode_FromFormat("[Errno %S] %S",
1070 self->myerrno ? self->myerrno: Py_None,
1071 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001072 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073}
1074
Thomas Wouters477c8d52006-05-27 19:21:47 +00001075static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001076OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001077{
1078 PyObject *args = self->args;
1079 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001080
Thomas Wouters477c8d52006-05-27 19:21:47 +00001081 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001082 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001083 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Larry Hastingsb0827312014-02-09 22:05:19 -08001084 Py_ssize_t size = self->filename2 ? 5 : 3;
1085 args = PyTuple_New(size);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001086 if (!args)
1087 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001088
1089 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001090 Py_INCREF(tmp);
1091 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001092
1093 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001094 Py_INCREF(tmp);
1095 PyTuple_SET_ITEM(args, 1, tmp);
1096
1097 Py_INCREF(self->filename);
1098 PyTuple_SET_ITEM(args, 2, self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001099
1100 if (self->filename2) {
1101 /*
1102 * This tuple is essentially used as OSError(*args).
1103 * So, to recreate filename2, we need to pass in
1104 * winerror as well.
1105 */
1106 Py_INCREF(Py_None);
1107 PyTuple_SET_ITEM(args, 3, Py_None);
1108
1109 /* filename2 */
1110 Py_INCREF(self->filename2);
1111 PyTuple_SET_ITEM(args, 4, self->filename2);
1112 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001113 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001114 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001115
1116 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001117 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001118 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001119 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120 Py_DECREF(args);
1121 return res;
1122}
1123
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001124static PyObject *
1125OSError_written_get(PyOSErrorObject *self, void *context)
1126{
1127 if (self->written == -1) {
1128 PyErr_SetString(PyExc_AttributeError, "characters_written");
1129 return NULL;
1130 }
1131 return PyLong_FromSsize_t(self->written);
1132}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001133
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001134static int
1135OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1136{
1137 Py_ssize_t n;
1138 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1139 if (n == -1 && PyErr_Occurred())
1140 return -1;
1141 self->written = n;
1142 return 0;
1143}
1144
1145static PyMemberDef OSError_members[] = {
1146 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1147 PyDoc_STR("POSIX exception code")},
1148 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1149 PyDoc_STR("exception strerror")},
1150 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1151 PyDoc_STR("exception filename")},
Larry Hastingsb0827312014-02-09 22:05:19 -08001152 {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
1153 PyDoc_STR("second exception filename")},
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001154#ifdef MS_WINDOWS
1155 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1156 PyDoc_STR("Win32 exception code")},
1157#endif
1158 {NULL} /* Sentinel */
1159};
1160
1161static PyMethodDef OSError_methods[] = {
1162 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163 {NULL}
1164};
1165
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001166static PyGetSetDef OSError_getset[] = {
1167 {"characters_written", (getter) OSError_written_get,
1168 (setter) OSError_written_set, NULL},
1169 {NULL}
1170};
1171
1172
1173ComplexExtendsException(PyExc_Exception, OSError,
1174 OSError, OSError_new,
1175 OSError_methods, OSError_members, OSError_getset,
1176 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001177 "Base class for I/O related errors.");
1178
1179
1180/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001181 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001182 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001183MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1184 "I/O operation would block.");
1185MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1186 "Connection error.");
1187MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1188 "Child process error.");
1189MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1190 "Broken pipe.");
1191MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1192 "Connection aborted.");
1193MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1194 "Connection refused.");
1195MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1196 "Connection reset.");
1197MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1198 "File already exists.");
1199MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1200 "File not found.");
1201MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1202 "Operation doesn't work on directories.");
1203MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1204 "Operation only works on directories.");
1205MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1206 "Interrupted by signal.");
1207MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1208 "Not enough permissions.");
1209MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1210 "Process not found.");
1211MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1212 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001213
1214/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001215 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001216 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001217SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001218 "Read beyond end of file.");
1219
1220
1221/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001222 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001223 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001224SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001225 "Unspecified run-time error.");
1226
1227
1228/*
1229 * NotImplementedError extends RuntimeError
1230 */
1231SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1232 "Method or function hasn't been implemented yet.");
1233
1234/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001235 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001236 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001237SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001238 "Name not found globally.");
1239
1240/*
1241 * UnboundLocalError extends NameError
1242 */
1243SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1244 "Local name referenced but not bound to a value.");
1245
1246/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001247 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001248 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001249SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001250 "Attribute not found.");
1251
1252
1253/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001254 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001255 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256
1257static int
1258SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1259{
1260 PyObject *info = NULL;
1261 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1262
1263 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1264 return -1;
1265
1266 if (lenargs >= 1) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001267 Py_CLEAR(self->msg);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001268 self->msg = PyTuple_GET_ITEM(args, 0);
1269 Py_INCREF(self->msg);
1270 }
1271 if (lenargs == 2) {
1272 info = PyTuple_GET_ITEM(args, 1);
1273 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001274 if (!info)
1275 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001276
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001277 if (PyTuple_GET_SIZE(info) != 4) {
1278 /* not a very good error message, but it's what Python 2.4 gives */
1279 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1280 Py_DECREF(info);
1281 return -1;
1282 }
1283
1284 Py_CLEAR(self->filename);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001285 self->filename = PyTuple_GET_ITEM(info, 0);
1286 Py_INCREF(self->filename);
1287
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001288 Py_CLEAR(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001289 self->lineno = PyTuple_GET_ITEM(info, 1);
1290 Py_INCREF(self->lineno);
1291
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001292 Py_CLEAR(self->offset);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001293 self->offset = PyTuple_GET_ITEM(info, 2);
1294 Py_INCREF(self->offset);
1295
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001296 Py_CLEAR(self->text);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001297 self->text = PyTuple_GET_ITEM(info, 3);
1298 Py_INCREF(self->text);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001299
1300 Py_DECREF(info);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001301 }
1302 return 0;
1303}
1304
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001305static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001306SyntaxError_clear(PySyntaxErrorObject *self)
1307{
1308 Py_CLEAR(self->msg);
1309 Py_CLEAR(self->filename);
1310 Py_CLEAR(self->lineno);
1311 Py_CLEAR(self->offset);
1312 Py_CLEAR(self->text);
1313 Py_CLEAR(self->print_file_and_line);
1314 return BaseException_clear((PyBaseExceptionObject *)self);
1315}
1316
1317static void
1318SyntaxError_dealloc(PySyntaxErrorObject *self)
1319{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001320 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001321 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001322 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001323}
1324
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001325static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001326SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1327{
1328 Py_VISIT(self->msg);
1329 Py_VISIT(self->filename);
1330 Py_VISIT(self->lineno);
1331 Py_VISIT(self->offset);
1332 Py_VISIT(self->text);
1333 Py_VISIT(self->print_file_and_line);
1334 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1335}
1336
1337/* This is called "my_basename" instead of just "basename" to avoid name
1338 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1339 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001340static PyObject*
1341my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001342{
Victor Stinner6237daf2010-04-28 17:26:19 +00001343 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001344 int kind;
1345 void *data;
1346
1347 if (PyUnicode_READY(name))
1348 return NULL;
1349 kind = PyUnicode_KIND(name);
1350 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001351 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001352 offset = 0;
1353 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001355 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001356 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001357 if (offset != 0)
1358 return PyUnicode_Substring(name, offset, size);
1359 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001360 Py_INCREF(name);
1361 return name;
1362 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363}
1364
1365
1366static PyObject *
1367SyntaxError_str(PySyntaxErrorObject *self)
1368{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001369 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001370 PyObject *filename;
1371 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001372 /* Below, we always ignore overflow errors, just printing -1.
1373 Still, we cannot allow an OverflowError to be raised, so
1374 we need to call PyLong_AsLongAndOverflow. */
1375 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001376
1377 /* XXX -- do all the additional formatting with filename and
1378 lineno here */
1379
Neal Norwitzed2b7392007-08-26 04:51:10 +00001380 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001381 filename = my_basename(self->filename);
1382 if (filename == NULL)
1383 return NULL;
1384 } else {
1385 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001386 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001387 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001388
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001389 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001390 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001391
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001392 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001393 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001394 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001395 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001397 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001398 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001399 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001400 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001401 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001402 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001403 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001404 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001405 Py_XDECREF(filename);
1406 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001407}
1408
1409static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001410 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1411 PyDoc_STR("exception msg")},
1412 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1413 PyDoc_STR("exception filename")},
1414 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1415 PyDoc_STR("exception lineno")},
1416 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1417 PyDoc_STR("exception offset")},
1418 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1419 PyDoc_STR("exception text")},
1420 {"print_file_and_line", T_OBJECT,
1421 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1422 PyDoc_STR("exception print_file_and_line")},
1423 {NULL} /* Sentinel */
1424};
1425
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001426ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001427 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001428 SyntaxError_str, "Invalid syntax.");
1429
1430
1431/*
1432 * IndentationError extends SyntaxError
1433 */
1434MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1435 "Improper indentation.");
1436
1437
1438/*
1439 * TabError extends IndentationError
1440 */
1441MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1442 "Improper mixture of spaces and tabs.");
1443
1444
1445/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001446 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001447 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001448SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001449 "Base class for lookup errors.");
1450
1451
1452/*
1453 * IndexError extends LookupError
1454 */
1455SimpleExtendsException(PyExc_LookupError, IndexError,
1456 "Sequence index out of range.");
1457
1458
1459/*
1460 * KeyError extends LookupError
1461 */
1462static PyObject *
1463KeyError_str(PyBaseExceptionObject *self)
1464{
1465 /* If args is a tuple of exactly one item, apply repr to args[0].
1466 This is done so that e.g. the exception raised by {}[''] prints
1467 KeyError: ''
1468 rather than the confusing
1469 KeyError
1470 alone. The downside is that if KeyError is raised with an explanatory
1471 string, that string will be displayed in quotes. Too bad.
1472 If args is anything else, use the default BaseException__str__().
1473 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001474 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001475 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001476 }
1477 return BaseException_str(self);
1478}
1479
1480ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001481 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001482
1483
1484/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001485 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001486 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001487SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001488 "Inappropriate argument value (of correct type).");
1489
1490/*
1491 * UnicodeError extends ValueError
1492 */
1493
1494SimpleExtendsException(PyExc_ValueError, UnicodeError,
1495 "Unicode related error.");
1496
Thomas Wouters477c8d52006-05-27 19:21:47 +00001497static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001498get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001499{
1500 if (!attr) {
1501 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1502 return NULL;
1503 }
1504
Christian Heimes72b710a2008-05-26 13:28:38 +00001505 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001506 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1507 return NULL;
1508 }
1509 Py_INCREF(attr);
1510 return attr;
1511}
1512
1513static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001514get_unicode(PyObject *attr, const char *name)
1515{
1516 if (!attr) {
1517 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1518 return NULL;
1519 }
1520
1521 if (!PyUnicode_Check(attr)) {
1522 PyErr_Format(PyExc_TypeError,
1523 "%.200s attribute must be unicode", name);
1524 return NULL;
1525 }
1526 Py_INCREF(attr);
1527 return attr;
1528}
1529
Walter Dörwaldd2034312007-05-18 16:29:38 +00001530static int
1531set_unicodefromstring(PyObject **attr, const char *value)
1532{
1533 PyObject *obj = PyUnicode_FromString(value);
1534 if (!obj)
1535 return -1;
1536 Py_CLEAR(*attr);
1537 *attr = obj;
1538 return 0;
1539}
1540
Thomas Wouters477c8d52006-05-27 19:21:47 +00001541PyObject *
1542PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1543{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001544 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001545}
1546
1547PyObject *
1548PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1549{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001550 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001551}
1552
1553PyObject *
1554PyUnicodeEncodeError_GetObject(PyObject *exc)
1555{
1556 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1557}
1558
1559PyObject *
1560PyUnicodeDecodeError_GetObject(PyObject *exc)
1561{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001562 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001563}
1564
1565PyObject *
1566PyUnicodeTranslateError_GetObject(PyObject *exc)
1567{
1568 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1569}
1570
1571int
1572PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1573{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001574 Py_ssize_t size;
1575 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1576 "object");
1577 if (!obj)
1578 return -1;
1579 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001580 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001581 if (*start<0)
1582 *start = 0; /*XXX check for values <0*/
1583 if (*start>=size)
1584 *start = size-1;
1585 Py_DECREF(obj);
1586 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001587}
1588
1589
1590int
1591PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1592{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001593 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001594 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001595 if (!obj)
1596 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001597 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001598 *start = ((PyUnicodeErrorObject *)exc)->start;
1599 if (*start<0)
1600 *start = 0;
1601 if (*start>=size)
1602 *start = size-1;
1603 Py_DECREF(obj);
1604 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001605}
1606
1607
1608int
1609PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1610{
1611 return PyUnicodeEncodeError_GetStart(exc, start);
1612}
1613
1614
1615int
1616PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1617{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001618 ((PyUnicodeErrorObject *)exc)->start = start;
1619 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001620}
1621
1622
1623int
1624PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1625{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001626 ((PyUnicodeErrorObject *)exc)->start = start;
1627 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001628}
1629
1630
1631int
1632PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1633{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001634 ((PyUnicodeErrorObject *)exc)->start = start;
1635 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001636}
1637
1638
1639int
1640PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1641{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001642 Py_ssize_t size;
1643 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1644 "object");
1645 if (!obj)
1646 return -1;
1647 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001648 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001649 if (*end<1)
1650 *end = 1;
1651 if (*end>size)
1652 *end = size;
1653 Py_DECREF(obj);
1654 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001655}
1656
1657
1658int
1659PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1660{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001661 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001662 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001663 if (!obj)
1664 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001665 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001666 *end = ((PyUnicodeErrorObject *)exc)->end;
1667 if (*end<1)
1668 *end = 1;
1669 if (*end>size)
1670 *end = size;
1671 Py_DECREF(obj);
1672 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001673}
1674
1675
1676int
1677PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1678{
1679 return PyUnicodeEncodeError_GetEnd(exc, start);
1680}
1681
1682
1683int
1684PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1685{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001686 ((PyUnicodeErrorObject *)exc)->end = end;
1687 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001688}
1689
1690
1691int
1692PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1693{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001694 ((PyUnicodeErrorObject *)exc)->end = end;
1695 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001696}
1697
1698
1699int
1700PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1701{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001702 ((PyUnicodeErrorObject *)exc)->end = end;
1703 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001704}
1705
1706PyObject *
1707PyUnicodeEncodeError_GetReason(PyObject *exc)
1708{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001709 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001710}
1711
1712
1713PyObject *
1714PyUnicodeDecodeError_GetReason(PyObject *exc)
1715{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001716 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001717}
1718
1719
1720PyObject *
1721PyUnicodeTranslateError_GetReason(PyObject *exc)
1722{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001723 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001724}
1725
1726
1727int
1728PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1729{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001730 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1731 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001732}
1733
1734
1735int
1736PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1737{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001738 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1739 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001740}
1741
1742
1743int
1744PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1745{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001746 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1747 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001748}
1749
1750
Thomas Wouters477c8d52006-05-27 19:21:47 +00001751static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001752UnicodeError_clear(PyUnicodeErrorObject *self)
1753{
1754 Py_CLEAR(self->encoding);
1755 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001756 Py_CLEAR(self->reason);
1757 return BaseException_clear((PyBaseExceptionObject *)self);
1758}
1759
1760static void
1761UnicodeError_dealloc(PyUnicodeErrorObject *self)
1762{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001763 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001764 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001765 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001766}
1767
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001768static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001769UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1770{
1771 Py_VISIT(self->encoding);
1772 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001773 Py_VISIT(self->reason);
1774 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1775}
1776
1777static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001778 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1779 PyDoc_STR("exception encoding")},
1780 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1781 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001782 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001783 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001784 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001785 PyDoc_STR("exception end")},
1786 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1787 PyDoc_STR("exception reason")},
1788 {NULL} /* Sentinel */
1789};
1790
1791
1792/*
1793 * UnicodeEncodeError extends UnicodeError
1794 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001795
1796static int
1797UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1798{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001799 PyUnicodeErrorObject *err;
1800
Thomas Wouters477c8d52006-05-27 19:21:47 +00001801 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1802 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001803
1804 err = (PyUnicodeErrorObject *)self;
1805
1806 Py_CLEAR(err->encoding);
1807 Py_CLEAR(err->object);
1808 Py_CLEAR(err->reason);
1809
1810 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1811 &PyUnicode_Type, &err->encoding,
1812 &PyUnicode_Type, &err->object,
1813 &err->start,
1814 &err->end,
1815 &PyUnicode_Type, &err->reason)) {
1816 err->encoding = err->object = err->reason = NULL;
1817 return -1;
1818 }
1819
Martin v. Löwisb09af032011-11-04 11:16:41 +01001820 if (PyUnicode_READY(err->object) < -1) {
1821 err->encoding = NULL;
1822 return -1;
1823 }
1824
Guido van Rossum98297ee2007-11-06 21:34:58 +00001825 Py_INCREF(err->encoding);
1826 Py_INCREF(err->object);
1827 Py_INCREF(err->reason);
1828
1829 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001830}
1831
1832static PyObject *
1833UnicodeEncodeError_str(PyObject *self)
1834{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001835 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001836 PyObject *result = NULL;
1837 PyObject *reason_str = NULL;
1838 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001839
Eric Smith0facd772010-02-24 15:42:29 +00001840 /* Get reason and encoding as strings, which they might not be if
1841 they've been modified after we were contructed. */
1842 reason_str = PyObject_Str(uself->reason);
1843 if (reason_str == NULL)
1844 goto done;
1845 encoding_str = PyObject_Str(uself->encoding);
1846 if (encoding_str == NULL)
1847 goto done;
1848
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001849 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1850 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001851 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001852 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001853 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001854 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001855 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001856 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001857 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001858 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001859 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001860 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001861 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001862 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001863 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001864 }
Eric Smith0facd772010-02-24 15:42:29 +00001865 else {
1866 result = PyUnicode_FromFormat(
1867 "'%U' codec can't encode characters in position %zd-%zd: %U",
1868 encoding_str,
1869 uself->start,
1870 uself->end-1,
1871 reason_str);
1872 }
1873done:
1874 Py_XDECREF(reason_str);
1875 Py_XDECREF(encoding_str);
1876 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001877}
1878
1879static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001880 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001881 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001882 sizeof(PyUnicodeErrorObject), 0,
1883 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1884 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1885 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001886 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1887 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001888 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001889 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001890};
1891PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1892
1893PyObject *
1894PyUnicodeEncodeError_Create(
1895 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1896 Py_ssize_t start, Py_ssize_t end, const char *reason)
1897{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001898 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001899 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001900}
1901
1902
1903/*
1904 * UnicodeDecodeError extends UnicodeError
1905 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001906
1907static int
1908UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1909{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001910 PyUnicodeErrorObject *ude;
1911 const char *data;
1912 Py_ssize_t size;
1913
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1915 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001916
1917 ude = (PyUnicodeErrorObject *)self;
1918
1919 Py_CLEAR(ude->encoding);
1920 Py_CLEAR(ude->object);
1921 Py_CLEAR(ude->reason);
1922
1923 if (!PyArg_ParseTuple(args, "O!OnnO!",
1924 &PyUnicode_Type, &ude->encoding,
1925 &ude->object,
1926 &ude->start,
1927 &ude->end,
1928 &PyUnicode_Type, &ude->reason)) {
1929 ude->encoding = ude->object = ude->reason = NULL;
1930 return -1;
1931 }
1932
Christian Heimes72b710a2008-05-26 13:28:38 +00001933 if (!PyBytes_Check(ude->object)) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00001934 if (PyObject_AsReadBuffer(ude->object, (const void **)&data, &size)) {
1935 ude->encoding = ude->object = ude->reason = NULL;
1936 return -1;
1937 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001938 ude->object = PyBytes_FromStringAndSize(data, size);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001939 }
1940 else {
1941 Py_INCREF(ude->object);
1942 }
1943
1944 Py_INCREF(ude->encoding);
1945 Py_INCREF(ude->reason);
1946
1947 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001948}
1949
1950static PyObject *
1951UnicodeDecodeError_str(PyObject *self)
1952{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001953 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001954 PyObject *result = NULL;
1955 PyObject *reason_str = NULL;
1956 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001957
Eric Smith0facd772010-02-24 15:42:29 +00001958 /* Get reason and encoding as strings, which they might not be if
1959 they've been modified after we were contructed. */
1960 reason_str = PyObject_Str(uself->reason);
1961 if (reason_str == NULL)
1962 goto done;
1963 encoding_str = PyObject_Str(uself->encoding);
1964 if (encoding_str == NULL)
1965 goto done;
1966
1967 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001968 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00001969 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001970 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00001971 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001972 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001973 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001974 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001975 }
Eric Smith0facd772010-02-24 15:42:29 +00001976 else {
1977 result = PyUnicode_FromFormat(
1978 "'%U' codec can't decode bytes in position %zd-%zd: %U",
1979 encoding_str,
1980 uself->start,
1981 uself->end-1,
1982 reason_str
1983 );
1984 }
1985done:
1986 Py_XDECREF(reason_str);
1987 Py_XDECREF(encoding_str);
1988 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001989}
1990
1991static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001992 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001993 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001994 sizeof(PyUnicodeErrorObject), 0,
1995 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1996 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
1997 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001998 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
1999 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002000 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002001 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002002};
2003PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
2004
2005PyObject *
2006PyUnicodeDecodeError_Create(
2007 const char *encoding, const char *object, Py_ssize_t length,
2008 Py_ssize_t start, Py_ssize_t end, const char *reason)
2009{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00002010 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002011 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002012}
2013
2014
2015/*
2016 * UnicodeTranslateError extends UnicodeError
2017 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002018
2019static int
2020UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
2021 PyObject *kwds)
2022{
2023 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2024 return -1;
2025
2026 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002027 Py_CLEAR(self->reason);
2028
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002029 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002030 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002031 &self->start,
2032 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00002033 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002034 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002035 return -1;
2036 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002037
Thomas Wouters477c8d52006-05-27 19:21:47 +00002038 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002039 Py_INCREF(self->reason);
2040
2041 return 0;
2042}
2043
2044
2045static PyObject *
2046UnicodeTranslateError_str(PyObject *self)
2047{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002048 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00002049 PyObject *result = NULL;
2050 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002051
Eric Smith0facd772010-02-24 15:42:29 +00002052 /* Get reason as a string, which it might not be if it's been
2053 modified after we were contructed. */
2054 reason_str = PyObject_Str(uself->reason);
2055 if (reason_str == NULL)
2056 goto done;
2057
Victor Stinner53b33e72011-11-21 01:17:27 +01002058 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2059 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002060 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002061 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002062 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002063 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002064 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002065 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002066 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002067 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002068 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002069 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002070 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002071 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002072 );
Eric Smith0facd772010-02-24 15:42:29 +00002073 } else {
2074 result = PyUnicode_FromFormat(
2075 "can't translate characters in position %zd-%zd: %U",
2076 uself->start,
2077 uself->end-1,
2078 reason_str
2079 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002080 }
Eric Smith0facd772010-02-24 15:42:29 +00002081done:
2082 Py_XDECREF(reason_str);
2083 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002084}
2085
2086static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002087 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002088 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002089 sizeof(PyUnicodeErrorObject), 0,
2090 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2091 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2092 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002093 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002094 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2095 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002096 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002097};
2098PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002100/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002101PyObject *
2102PyUnicodeTranslateError_Create(
2103 const Py_UNICODE *object, Py_ssize_t length,
2104 Py_ssize_t start, Py_ssize_t end, const char *reason)
2105{
2106 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002107 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002108}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002110PyObject *
2111_PyUnicodeTranslateError_Create(
2112 PyObject *object,
2113 Py_ssize_t start, Py_ssize_t end, const char *reason)
2114{
2115 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Ons",
2116 object, start, end, reason);
2117}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002118
2119/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002120 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002121 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002122SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002123 "Assertion failed.");
2124
2125
2126/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002127 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002128 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002129SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002130 "Base class for arithmetic errors.");
2131
2132
2133/*
2134 * FloatingPointError extends ArithmeticError
2135 */
2136SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2137 "Floating point operation failed.");
2138
2139
2140/*
2141 * OverflowError extends ArithmeticError
2142 */
2143SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2144 "Result too large to be represented.");
2145
2146
2147/*
2148 * ZeroDivisionError extends ArithmeticError
2149 */
2150SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2151 "Second argument to a division or modulo operation was zero.");
2152
2153
2154/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002155 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002156 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002157SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002158 "Internal error in the Python interpreter.\n"
2159 "\n"
2160 "Please report this to the Python maintainer, along with the traceback,\n"
2161 "the Python version, and the hardware/OS platform and version.");
2162
2163
2164/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002165 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002166 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002167SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002168 "Weak ref proxy used after referent went away.");
2169
2170
2171/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002172 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002173 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002174
2175#define MEMERRORS_SAVE 16
2176static PyBaseExceptionObject *memerrors_freelist = NULL;
2177static int memerrors_numfree = 0;
2178
2179static PyObject *
2180MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2181{
2182 PyBaseExceptionObject *self;
2183
2184 if (type != (PyTypeObject *) PyExc_MemoryError)
2185 return BaseException_new(type, args, kwds);
2186 if (memerrors_freelist == NULL)
2187 return BaseException_new(type, args, kwds);
2188 /* Fetch object from freelist and revive it */
2189 self = memerrors_freelist;
2190 self->args = PyTuple_New(0);
2191 /* This shouldn't happen since the empty tuple is persistent */
2192 if (self->args == NULL)
2193 return NULL;
2194 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2195 memerrors_numfree--;
2196 self->dict = NULL;
2197 _Py_NewReference((PyObject *)self);
2198 _PyObject_GC_TRACK(self);
2199 return (PyObject *)self;
2200}
2201
2202static void
2203MemoryError_dealloc(PyBaseExceptionObject *self)
2204{
2205 _PyObject_GC_UNTRACK(self);
2206 BaseException_clear(self);
2207 if (memerrors_numfree >= MEMERRORS_SAVE)
2208 Py_TYPE(self)->tp_free((PyObject *)self);
2209 else {
2210 self->dict = (PyObject *) memerrors_freelist;
2211 memerrors_freelist = self;
2212 memerrors_numfree++;
2213 }
2214}
2215
2216static void
2217preallocate_memerrors(void)
2218{
2219 /* We create enough MemoryErrors and then decref them, which will fill
2220 up the freelist. */
2221 int i;
2222 PyObject *errors[MEMERRORS_SAVE];
2223 for (i = 0; i < MEMERRORS_SAVE; i++) {
2224 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2225 NULL, NULL);
2226 if (!errors[i])
2227 Py_FatalError("Could not preallocate MemoryError object");
2228 }
2229 for (i = 0; i < MEMERRORS_SAVE; i++) {
2230 Py_DECREF(errors[i]);
2231 }
2232}
2233
2234static void
2235free_preallocated_memerrors(void)
2236{
2237 while (memerrors_freelist != NULL) {
2238 PyObject *self = (PyObject *) memerrors_freelist;
2239 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2240 Py_TYPE(self)->tp_free((PyObject *)self);
2241 }
2242}
2243
2244
2245static PyTypeObject _PyExc_MemoryError = {
2246 PyVarObject_HEAD_INIT(NULL, 0)
2247 "MemoryError",
2248 sizeof(PyBaseExceptionObject),
2249 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2250 0, 0, 0, 0, 0, 0, 0,
2251 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2252 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2253 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2254 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2255 (initproc)BaseException_init, 0, MemoryError_new
2256};
2257PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2258
Thomas Wouters477c8d52006-05-27 19:21:47 +00002259
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002260/*
2261 * BufferError extends Exception
2262 */
2263SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2264
Thomas Wouters477c8d52006-05-27 19:21:47 +00002265
2266/* Warning category docstrings */
2267
2268/*
2269 * Warning extends Exception
2270 */
2271SimpleExtendsException(PyExc_Exception, Warning,
2272 "Base class for warning categories.");
2273
2274
2275/*
2276 * UserWarning extends Warning
2277 */
2278SimpleExtendsException(PyExc_Warning, UserWarning,
2279 "Base class for warnings generated by user code.");
2280
2281
2282/*
2283 * DeprecationWarning extends Warning
2284 */
2285SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2286 "Base class for warnings about deprecated features.");
2287
2288
2289/*
2290 * PendingDeprecationWarning extends Warning
2291 */
2292SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2293 "Base class for warnings about features which will be deprecated\n"
2294 "in the future.");
2295
2296
2297/*
2298 * SyntaxWarning extends Warning
2299 */
2300SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2301 "Base class for warnings about dubious syntax.");
2302
2303
2304/*
2305 * RuntimeWarning extends Warning
2306 */
2307SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2308 "Base class for warnings about dubious runtime behavior.");
2309
2310
2311/*
2312 * FutureWarning extends Warning
2313 */
2314SimpleExtendsException(PyExc_Warning, FutureWarning,
2315 "Base class for warnings about constructs that will change semantically\n"
2316 "in the future.");
2317
2318
2319/*
2320 * ImportWarning extends Warning
2321 */
2322SimpleExtendsException(PyExc_Warning, ImportWarning,
2323 "Base class for warnings about probable mistakes in module imports");
2324
2325
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002326/*
2327 * UnicodeWarning extends Warning
2328 */
2329SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2330 "Base class for warnings about Unicode related problems, mostly\n"
2331 "related to conversion problems.");
2332
Georg Brandl08be72d2010-10-24 15:11:22 +00002333
Guido van Rossum98297ee2007-11-06 21:34:58 +00002334/*
2335 * BytesWarning extends Warning
2336 */
2337SimpleExtendsException(PyExc_Warning, BytesWarning,
2338 "Base class for warnings about bytes and buffer related problems, mostly\n"
2339 "related to conversion from str or comparing to str.");
2340
2341
Georg Brandl08be72d2010-10-24 15:11:22 +00002342/*
2343 * ResourceWarning extends Warning
2344 */
2345SimpleExtendsException(PyExc_Warning, ResourceWarning,
2346 "Base class for warnings about resource usage.");
2347
2348
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002349
Thomas Wouters89d996e2007-09-08 17:39:28 +00002350/* Pre-computed RuntimeError instance for when recursion depth is reached.
2351 Meant to be used when normalizing the exception for exceeding the recursion
2352 depth will cause its own infinite recursion.
2353*/
2354PyObject *PyExc_RecursionErrorInst = NULL;
2355
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002356#define PRE_INIT(TYPE) \
2357 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2358 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2359 Py_FatalError("exceptions bootstrapping error."); \
2360 Py_INCREF(PyExc_ ## TYPE); \
2361 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002362
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002363#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002364 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2365 Py_FatalError("Module dictionary insertion problem.");
2366
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002367#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002368 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002369 PyExc_ ## NAME = PyExc_ ## TYPE; \
2370 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2371 Py_FatalError("Module dictionary insertion problem.");
2372
2373#define ADD_ERRNO(TYPE, CODE) { \
2374 PyObject *_code = PyLong_FromLong(CODE); \
2375 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2376 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2377 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002378 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002379 }
2380
2381#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002382#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002383/* The following constants were added to errno.h in VS2010 but have
2384 preferred WSA equivalents. */
2385#undef EADDRINUSE
2386#undef EADDRNOTAVAIL
2387#undef EAFNOSUPPORT
2388#undef EALREADY
2389#undef ECONNABORTED
2390#undef ECONNREFUSED
2391#undef ECONNRESET
2392#undef EDESTADDRREQ
2393#undef EHOSTUNREACH
2394#undef EINPROGRESS
2395#undef EISCONN
2396#undef ELOOP
2397#undef EMSGSIZE
2398#undef ENETDOWN
2399#undef ENETRESET
2400#undef ENETUNREACH
2401#undef ENOBUFS
2402#undef ENOPROTOOPT
2403#undef ENOTCONN
2404#undef ENOTSOCK
2405#undef EOPNOTSUPP
2406#undef EPROTONOSUPPORT
2407#undef EPROTOTYPE
2408#undef ETIMEDOUT
2409#undef EWOULDBLOCK
2410
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002411#if defined(WSAEALREADY) && !defined(EALREADY)
2412#define EALREADY WSAEALREADY
2413#endif
2414#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2415#define ECONNABORTED WSAECONNABORTED
2416#endif
2417#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2418#define ECONNREFUSED WSAECONNREFUSED
2419#endif
2420#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2421#define ECONNRESET WSAECONNRESET
2422#endif
2423#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2424#define EINPROGRESS WSAEINPROGRESS
2425#endif
2426#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2427#define ESHUTDOWN WSAESHUTDOWN
2428#endif
2429#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2430#define ETIMEDOUT WSAETIMEDOUT
2431#endif
2432#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2433#define EWOULDBLOCK WSAEWOULDBLOCK
2434#endif
2435#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002436
Martin v. Löwis1a214512008-06-11 05:26:20 +00002437void
Brett Cannonfd074152012-04-14 14:10:13 -04002438_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002439{
Brett Cannonfd074152012-04-14 14:10:13 -04002440 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002441
2442 PRE_INIT(BaseException)
2443 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002444 PRE_INIT(TypeError)
2445 PRE_INIT(StopIteration)
2446 PRE_INIT(GeneratorExit)
2447 PRE_INIT(SystemExit)
2448 PRE_INIT(KeyboardInterrupt)
2449 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002450 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002451 PRE_INIT(EOFError)
2452 PRE_INIT(RuntimeError)
2453 PRE_INIT(NotImplementedError)
2454 PRE_INIT(NameError)
2455 PRE_INIT(UnboundLocalError)
2456 PRE_INIT(AttributeError)
2457 PRE_INIT(SyntaxError)
2458 PRE_INIT(IndentationError)
2459 PRE_INIT(TabError)
2460 PRE_INIT(LookupError)
2461 PRE_INIT(IndexError)
2462 PRE_INIT(KeyError)
2463 PRE_INIT(ValueError)
2464 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002465 PRE_INIT(UnicodeEncodeError)
2466 PRE_INIT(UnicodeDecodeError)
2467 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002468 PRE_INIT(AssertionError)
2469 PRE_INIT(ArithmeticError)
2470 PRE_INIT(FloatingPointError)
2471 PRE_INIT(OverflowError)
2472 PRE_INIT(ZeroDivisionError)
2473 PRE_INIT(SystemError)
2474 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002475 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002476 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002477 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002478 PRE_INIT(Warning)
2479 PRE_INIT(UserWarning)
2480 PRE_INIT(DeprecationWarning)
2481 PRE_INIT(PendingDeprecationWarning)
2482 PRE_INIT(SyntaxWarning)
2483 PRE_INIT(RuntimeWarning)
2484 PRE_INIT(FutureWarning)
2485 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002486 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002487 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002488 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002489
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002490 /* OSError subclasses */
2491 PRE_INIT(ConnectionError);
2492
2493 PRE_INIT(BlockingIOError);
2494 PRE_INIT(BrokenPipeError);
2495 PRE_INIT(ChildProcessError);
2496 PRE_INIT(ConnectionAbortedError);
2497 PRE_INIT(ConnectionRefusedError);
2498 PRE_INIT(ConnectionResetError);
2499 PRE_INIT(FileExistsError);
2500 PRE_INIT(FileNotFoundError);
2501 PRE_INIT(IsADirectoryError);
2502 PRE_INIT(NotADirectoryError);
2503 PRE_INIT(InterruptedError);
2504 PRE_INIT(PermissionError);
2505 PRE_INIT(ProcessLookupError);
2506 PRE_INIT(TimeoutError);
2507
Thomas Wouters477c8d52006-05-27 19:21:47 +00002508 bdict = PyModule_GetDict(bltinmod);
2509 if (bdict == NULL)
2510 Py_FatalError("exceptions bootstrapping error.");
2511
2512 POST_INIT(BaseException)
2513 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002514 POST_INIT(TypeError)
2515 POST_INIT(StopIteration)
2516 POST_INIT(GeneratorExit)
2517 POST_INIT(SystemExit)
2518 POST_INIT(KeyboardInterrupt)
2519 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002520 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002521 INIT_ALIAS(EnvironmentError, OSError)
2522 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002523#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002524 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002525#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00002526 POST_INIT(EOFError)
2527 POST_INIT(RuntimeError)
2528 POST_INIT(NotImplementedError)
2529 POST_INIT(NameError)
2530 POST_INIT(UnboundLocalError)
2531 POST_INIT(AttributeError)
2532 POST_INIT(SyntaxError)
2533 POST_INIT(IndentationError)
2534 POST_INIT(TabError)
2535 POST_INIT(LookupError)
2536 POST_INIT(IndexError)
2537 POST_INIT(KeyError)
2538 POST_INIT(ValueError)
2539 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002540 POST_INIT(UnicodeEncodeError)
2541 POST_INIT(UnicodeDecodeError)
2542 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002543 POST_INIT(AssertionError)
2544 POST_INIT(ArithmeticError)
2545 POST_INIT(FloatingPointError)
2546 POST_INIT(OverflowError)
2547 POST_INIT(ZeroDivisionError)
2548 POST_INIT(SystemError)
2549 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002550 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002551 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002552 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002553 POST_INIT(Warning)
2554 POST_INIT(UserWarning)
2555 POST_INIT(DeprecationWarning)
2556 POST_INIT(PendingDeprecationWarning)
2557 POST_INIT(SyntaxWarning)
2558 POST_INIT(RuntimeWarning)
2559 POST_INIT(FutureWarning)
2560 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002561 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002562 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002563 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002564
Antoine Pitrouac456a12012-01-18 21:35:21 +01002565 if (!errnomap) {
2566 errnomap = PyDict_New();
2567 if (!errnomap)
2568 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2569 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002570
2571 /* OSError subclasses */
2572 POST_INIT(ConnectionError);
2573
2574 POST_INIT(BlockingIOError);
2575 ADD_ERRNO(BlockingIOError, EAGAIN);
2576 ADD_ERRNO(BlockingIOError, EALREADY);
2577 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2578 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2579 POST_INIT(BrokenPipeError);
2580 ADD_ERRNO(BrokenPipeError, EPIPE);
2581 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2582 POST_INIT(ChildProcessError);
2583 ADD_ERRNO(ChildProcessError, ECHILD);
2584 POST_INIT(ConnectionAbortedError);
2585 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2586 POST_INIT(ConnectionRefusedError);
2587 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2588 POST_INIT(ConnectionResetError);
2589 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2590 POST_INIT(FileExistsError);
2591 ADD_ERRNO(FileExistsError, EEXIST);
2592 POST_INIT(FileNotFoundError);
2593 ADD_ERRNO(FileNotFoundError, ENOENT);
2594 POST_INIT(IsADirectoryError);
2595 ADD_ERRNO(IsADirectoryError, EISDIR);
2596 POST_INIT(NotADirectoryError);
2597 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2598 POST_INIT(InterruptedError);
2599 ADD_ERRNO(InterruptedError, EINTR);
2600 POST_INIT(PermissionError);
2601 ADD_ERRNO(PermissionError, EACCES);
2602 ADD_ERRNO(PermissionError, EPERM);
2603 POST_INIT(ProcessLookupError);
2604 ADD_ERRNO(ProcessLookupError, ESRCH);
2605 POST_INIT(TimeoutError);
2606 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2607
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002608 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002609
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002610 if (!PyExc_RecursionErrorInst) {
2611 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL);
2612 if (!PyExc_RecursionErrorInst)
2613 Py_FatalError("Cannot pre-allocate RuntimeError instance for "
2614 "recursion errors");
2615 else {
2616 PyBaseExceptionObject *err_inst =
2617 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2618 PyObject *args_tuple;
2619 PyObject *exc_message;
2620 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2621 if (!exc_message)
2622 Py_FatalError("cannot allocate argument for RuntimeError "
2623 "pre-allocation");
2624 args_tuple = PyTuple_Pack(1, exc_message);
2625 if (!args_tuple)
2626 Py_FatalError("cannot allocate tuple for RuntimeError "
2627 "pre-allocation");
2628 Py_DECREF(exc_message);
2629 if (BaseException_init(err_inst, args_tuple, NULL))
2630 Py_FatalError("init of pre-allocated RuntimeError failed");
2631 Py_DECREF(args_tuple);
2632 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002633 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002634}
2635
2636void
2637_PyExc_Fini(void)
2638{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002639 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002640 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002641 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002642}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002643
2644/* Helper to do the equivalent of "raise X from Y" in C, but always using
2645 * the current exception rather than passing one in.
2646 *
2647 * We currently limit this to *only* exceptions that use the BaseException
2648 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2649 * those correctly without losing data and without losing backwards
2650 * compatibility.
2651 *
2652 * We also aim to rule out *all* exceptions that might be storing additional
2653 * state, whether by having a size difference relative to BaseException,
2654 * additional arguments passed in during construction or by having a
2655 * non-empty instance dict.
2656 *
2657 * We need to be very careful with what we wrap, since changing types to
2658 * a broader exception type would be backwards incompatible for
2659 * existing codecs, and with different init or new method implementations
2660 * may either not support instantiation with PyErr_Format or lose
2661 * information when instantiated that way.
2662 *
2663 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2664 * fact that exceptions are expected to support pickling. If more builtin
2665 * exceptions (e.g. AttributeError) start to be converted to rich
2666 * exceptions with additional attributes, that's probably a better approach
2667 * to pursue over adding special cases for particular stateful subclasses.
2668 *
2669 * Returns a borrowed reference to the new exception (if any), NULL if the
2670 * existing exception was left in place.
2671 */
2672PyObject *
2673_PyErr_TrySetFromCause(const char *format, ...)
2674{
2675 PyObject* msg_prefix;
2676 PyObject *exc, *val, *tb;
2677 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002678 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002679 PyObject *instance_args;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002680 Py_ssize_t num_args, caught_type_size, base_exc_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002681 PyObject *new_exc, *new_val, *new_tb;
2682 va_list vargs;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002683 int same_basic_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002684
Nick Coghlan8b097b42013-11-13 23:49:21 +10002685 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002686 caught_type = (PyTypeObject *)exc;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002687 /* Ensure type info indicates no extra state is stored at the C level
2688 * and that the type can be reinstantiated using PyErr_Format
2689 */
2690 caught_type_size = caught_type->tp_basicsize;
2691 base_exc_size = _PyExc_BaseException.tp_basicsize;
2692 same_basic_size = (
2693 caught_type_size == base_exc_size ||
2694 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
2695 (caught_type_size == base_exc_size + sizeof(PyObject *))
2696 )
2697 );
Benjamin Peterson079c9982013-11-13 23:25:01 -05002698 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002699 caught_type->tp_new != BaseException_new ||
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002700 !same_basic_size ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002701 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002702 /* We can't be sure we can wrap this safely, since it may contain
2703 * more state than just the exception type. Accordingly, we just
2704 * leave it alone.
2705 */
2706 PyErr_Restore(exc, val, tb);
2707 return NULL;
2708 }
2709
2710 /* Check the args are empty or contain a single string */
2711 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002712 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002713 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002714 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002715 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002716 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002717 /* More than 1 arg, or the one arg we do have isn't a string
2718 */
2719 PyErr_Restore(exc, val, tb);
2720 return NULL;
2721 }
2722
2723 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002724 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002725 if (dictptr != NULL && *dictptr != NULL &&
2726 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002727 /* While we could potentially copy a non-empty instance dictionary
2728 * to the replacement exception, for now we take the more
2729 * conservative path of leaving exceptions with attributes set
2730 * alone.
2731 */
2732 PyErr_Restore(exc, val, tb);
2733 return NULL;
2734 }
2735
2736 /* For exceptions that we can wrap safely, we chain the original
2737 * exception to a new one of the exact same type with an
2738 * error message that mentions the additional details and the
2739 * original exception.
2740 *
2741 * It would be nice to wrap OSError and various other exception
2742 * types as well, but that's quite a bit trickier due to the extra
2743 * state potentially stored on OSError instances.
2744 */
Nick Coghlan77b286b2014-01-27 00:53:38 +10002745 /* Ensure the traceback is set correctly on the existing exception */
2746 if (tb != NULL) {
2747 PyException_SetTraceback(val, tb);
2748 Py_DECREF(tb);
2749 }
Benjamin Petersone109ee82013-11-13 23:49:49 -05002750
Christian Heimes507eabd2013-11-14 01:39:35 +01002751#ifdef HAVE_STDARG_PROTOTYPES
2752 va_start(vargs, format);
2753#else
2754 va_start(vargs);
2755#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002756 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002757 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002758 if (msg_prefix == NULL) {
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002759 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002760 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002761 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002762 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002763
2764 PyErr_Format(exc, "%U (%s: %S)",
2765 msg_prefix, Py_TYPE(val)->tp_name, val);
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002766 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002767 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002768 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2769 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2770 PyException_SetCause(new_val, val);
2771 PyErr_Restore(new_exc, new_val, new_tb);
2772 return new_val;
2773}