blob: d494995ddefd1ba20372dc815ec67ddbda421c1b [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/*
Yury Selivanov75445082015-05-11 22:57:16 -0400476 * StopAsyncIteration extends Exception
477 */
478SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
479 "Signal the end from iterator.__anext__().");
480
481
482/*
Thomas Wouters477c8d52006-05-27 19:21:47 +0000483 * StopIteration extends Exception
484 */
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000485
486static PyMemberDef StopIteration_members[] = {
487 {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
488 PyDoc_STR("generator return value")},
489 {NULL} /* Sentinel */
490};
491
492static int
493StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
494{
495 Py_ssize_t size = PyTuple_GET_SIZE(args);
496 PyObject *value;
497
498 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
499 return -1;
500 Py_CLEAR(self->value);
501 if (size > 0)
502 value = PyTuple_GET_ITEM(args, 0);
503 else
504 value = Py_None;
505 Py_INCREF(value);
506 self->value = value;
507 return 0;
508}
509
510static int
511StopIteration_clear(PyStopIterationObject *self)
512{
513 Py_CLEAR(self->value);
514 return BaseException_clear((PyBaseExceptionObject *)self);
515}
516
517static void
518StopIteration_dealloc(PyStopIterationObject *self)
519{
520 _PyObject_GC_UNTRACK(self);
521 StopIteration_clear(self);
522 Py_TYPE(self)->tp_free((PyObject *)self);
523}
524
525static int
526StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
527{
528 Py_VISIT(self->value);
529 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
530}
531
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000532ComplexExtendsException(
533 PyExc_Exception, /* base */
534 StopIteration, /* name */
535 StopIteration, /* prefix for *_init, etc */
536 0, /* new */
537 0, /* methods */
538 StopIteration_members, /* members */
539 0, /* getset */
540 0, /* str */
541 "Signal the end from iterator.__next__()."
542);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543
544
545/*
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000546 * GeneratorExit extends BaseException
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547 */
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000548SimpleExtendsException(PyExc_BaseException, GeneratorExit,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549 "Request that a generator exit.");
550
551
552/*
553 * SystemExit extends BaseException
554 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555
556static int
557SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
558{
559 Py_ssize_t size = PyTuple_GET_SIZE(args);
560
561 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
562 return -1;
563
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000564 if (size == 0)
565 return 0;
566 Py_CLEAR(self->code);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000567 if (size == 1)
568 self->code = PyTuple_GET_ITEM(args, 0);
Victor Stinner92236e52011-05-26 14:25:54 +0200569 else /* size > 1 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000570 self->code = args;
571 Py_INCREF(self->code);
572 return 0;
573}
574
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000575static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000576SystemExit_clear(PySystemExitObject *self)
577{
578 Py_CLEAR(self->code);
579 return BaseException_clear((PyBaseExceptionObject *)self);
580}
581
582static void
583SystemExit_dealloc(PySystemExitObject *self)
584{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000585 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586 SystemExit_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000587 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588}
589
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000590static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000591SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
592{
593 Py_VISIT(self->code);
594 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
595}
596
597static PyMemberDef SystemExit_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
599 PyDoc_STR("exception code")},
600 {NULL} /* Sentinel */
601};
602
603ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200604 0, 0, SystemExit_members, 0, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000605 "Request to exit from the interpreter.");
606
607/*
608 * KeyboardInterrupt extends BaseException
609 */
610SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
611 "Program interrupted by user.");
612
613
614/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000615 * ImportError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000616 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000617
Brett Cannon79ec55e2012-04-12 20:24:54 -0400618static int
619ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
620{
621 PyObject *msg = NULL;
622 PyObject *name = NULL;
623 PyObject *path = NULL;
624
625/* Macro replacement doesn't allow ## to start the first line of a macro,
626 so we move the assignment and NULL check into the if-statement. */
627#define GET_KWD(kwd) { \
628 kwd = PyDict_GetItemString(kwds, #kwd); \
629 if (kwd) { \
630 Py_CLEAR(self->kwd); \
631 self->kwd = kwd; \
632 Py_INCREF(self->kwd);\
633 if (PyDict_DelItemString(kwds, #kwd)) \
634 return -1; \
635 } \
636 }
637
638 if (kwds) {
639 GET_KWD(name);
640 GET_KWD(path);
641 }
642
643 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
644 return -1;
645 if (PyTuple_GET_SIZE(args) != 1)
646 return 0;
647 if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
648 return -1;
649
650 Py_CLEAR(self->msg); /* replacing */
651 self->msg = msg;
652 Py_INCREF(self->msg);
653
654 return 0;
655}
656
657static int
658ImportError_clear(PyImportErrorObject *self)
659{
660 Py_CLEAR(self->msg);
661 Py_CLEAR(self->name);
662 Py_CLEAR(self->path);
663 return BaseException_clear((PyBaseExceptionObject *)self);
664}
665
666static void
667ImportError_dealloc(PyImportErrorObject *self)
668{
669 _PyObject_GC_UNTRACK(self);
670 ImportError_clear(self);
671 Py_TYPE(self)->tp_free((PyObject *)self);
672}
673
674static int
675ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
676{
677 Py_VISIT(self->msg);
678 Py_VISIT(self->name);
679 Py_VISIT(self->path);
680 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
681}
682
683static PyObject *
684ImportError_str(PyImportErrorObject *self)
685{
Brett Cannon07c6e712012-08-24 13:05:09 -0400686 if (self->msg && PyUnicode_CheckExact(self->msg)) {
Brett Cannon79ec55e2012-04-12 20:24:54 -0400687 Py_INCREF(self->msg);
688 return self->msg;
689 }
690 else {
691 return BaseException_str((PyBaseExceptionObject *)self);
692 }
693}
694
695static PyMemberDef ImportError_members[] = {
696 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
697 PyDoc_STR("exception message")},
698 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
699 PyDoc_STR("module name")},
700 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
701 PyDoc_STR("module path")},
702 {NULL} /* Sentinel */
703};
704
705static PyMethodDef ImportError_methods[] = {
706 {NULL}
707};
708
709ComplexExtendsException(PyExc_Exception, ImportError,
710 ImportError, 0 /* new */,
711 ImportError_methods, ImportError_members,
712 0 /* getset */, ImportError_str,
713 "Import can't find module, or can't find name in "
714 "module.");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000715
716/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200717 * OSError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718 */
719
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200720#ifdef MS_WINDOWS
721#include "errmap.h"
722#endif
723
Thomas Wouters477c8d52006-05-27 19:21:47 +0000724/* Where a function has a single filename, such as open() or some
725 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
726 * called, giving a third argument which is the filename. But, so
727 * that old code using in-place unpacking doesn't break, e.g.:
728 *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200729 * except OSError, (errno, strerror):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730 *
731 * we hack args so that it only contains two items. This also
732 * means we need our own __str__() which prints out the filename
733 * when it was supplied.
Larry Hastingsb0827312014-02-09 22:05:19 -0800734 *
735 * (If a function has two filenames, such as rename(), symlink(),
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800736 * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
737 * which allows passing in a second filename.)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200739
Antoine Pitroue0e27352011-12-15 14:31:28 +0100740/* This function doesn't cleanup on error, the caller should */
741static int
742oserror_parse_args(PyObject **p_args,
743 PyObject **myerrno, PyObject **strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800744 PyObject **filename, PyObject **filename2
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200745#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100746 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200747#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100748 )
749{
750 Py_ssize_t nargs;
751 PyObject *args = *p_args;
Larry Hastingsb0827312014-02-09 22:05:19 -0800752#ifndef MS_WINDOWS
753 /*
754 * ignored on non-Windows platforms,
755 * but parsed so OSError has a consistent signature
756 */
757 PyObject *_winerror = NULL;
758 PyObject **winerror = &_winerror;
759#endif /* MS_WINDOWS */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000760
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200761 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000762
Larry Hastingsb0827312014-02-09 22:05:19 -0800763 if (nargs >= 2 && nargs <= 5) {
764 if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
765 myerrno, strerror,
766 filename, winerror, filename2))
Antoine Pitroue0e27352011-12-15 14:31:28 +0100767 return -1;
Larry Hastingsb0827312014-02-09 22:05:19 -0800768#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100769 if (*winerror && PyLong_Check(*winerror)) {
770 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200771 PyObject *newargs;
772 Py_ssize_t i;
773
Antoine Pitroue0e27352011-12-15 14:31:28 +0100774 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200775 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100776 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200777 /* Set errno to the corresponding POSIX errno (overriding
778 first argument). Windows Socket error codes (>= 10000)
779 have the same value as their POSIX counterparts.
780 */
781 if (winerrcode < 10000)
782 errcode = winerror_to_errno(winerrcode);
783 else
784 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100785 *myerrno = PyLong_FromLong(errcode);
786 if (!*myerrno)
787 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200788 newargs = PyTuple_New(nargs);
789 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100790 return -1;
791 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200792 for (i = 1; i < nargs; i++) {
793 PyObject *val = PyTuple_GET_ITEM(args, i);
794 Py_INCREF(val);
795 PyTuple_SET_ITEM(newargs, i, val);
796 }
797 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100798 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200799 }
Larry Hastingsb0827312014-02-09 22:05:19 -0800800#endif /* MS_WINDOWS */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200801 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000802
Antoine Pitroue0e27352011-12-15 14:31:28 +0100803 return 0;
804}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805
Antoine Pitroue0e27352011-12-15 14:31:28 +0100806static int
807oserror_init(PyOSErrorObject *self, PyObject **p_args,
808 PyObject *myerrno, PyObject *strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800809 PyObject *filename, PyObject *filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100810#ifdef MS_WINDOWS
811 , PyObject *winerror
812#endif
813 )
814{
815 PyObject *args = *p_args;
816 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000817
818 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200819 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100820 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200821 PyNumber_Check(filename)) {
822 /* BlockingIOError's 3rd argument can be the number of
823 * characters written.
824 */
825 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
826 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100827 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200828 }
829 else {
830 Py_INCREF(filename);
831 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000832
Larry Hastingsb0827312014-02-09 22:05:19 -0800833 if (filename2 && filename2 != Py_None) {
834 Py_INCREF(filename2);
835 self->filename2 = filename2;
836 }
837
838 if (nargs >= 2 && nargs <= 5) {
839 /* filename, filename2, and winerror are removed from the args tuple
840 (for compatibility purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100841 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200842 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100843 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000844
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200845 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100846 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200847 }
848 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000849 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200850 Py_XINCREF(myerrno);
851 self->myerrno = myerrno;
852
853 Py_XINCREF(strerror);
854 self->strerror = strerror;
855
856#ifdef MS_WINDOWS
857 Py_XINCREF(winerror);
858 self->winerror = winerror;
859#endif
860
Antoine Pitroue0e27352011-12-15 14:31:28 +0100861 /* Steals the reference to args */
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200862 Py_CLEAR(self->args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100863 self->args = args;
Victor Stinner46ef3192013-11-14 22:31:41 +0100864 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100865
866 return 0;
867}
868
869static PyObject *
870OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
871static int
872OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
873
874static int
875oserror_use_init(PyTypeObject *type)
876{
877 /* When __init__ is defined in a OSError subclass, we want any
878 extraneous argument to __new__ to be ignored. The only reasonable
879 solution, given __new__ takes a variable number of arguments,
880 is to defer arg parsing and initialization to __init__.
881
882 But when __new__ is overriden as well, it should call our __new__
883 with the right arguments.
884
885 (see http://bugs.python.org/issue12555#msg148829 )
886 */
887 if (type->tp_init != (initproc) OSError_init &&
888 type->tp_new == (newfunc) OSError_new) {
889 assert((PyObject *) type != PyExc_OSError);
890 return 1;
891 }
892 return 0;
893}
894
895static PyObject *
896OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
897{
898 PyOSErrorObject *self = NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800899 PyObject *myerrno = NULL, *strerror = NULL;
900 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100901#ifdef MS_WINDOWS
902 PyObject *winerror = NULL;
903#endif
904
Victor Stinner46ef3192013-11-14 22:31:41 +0100905 Py_INCREF(args);
906
Antoine Pitroue0e27352011-12-15 14:31:28 +0100907 if (!oserror_use_init(type)) {
908 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100909 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100910
Larry Hastingsb0827312014-02-09 22:05:19 -0800911 if (oserror_parse_args(&args, &myerrno, &strerror,
912 &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100913#ifdef MS_WINDOWS
914 , &winerror
915#endif
916 ))
917 goto error;
918
919 if (myerrno && PyLong_Check(myerrno) &&
920 errnomap && (PyObject *) type == PyExc_OSError) {
921 PyObject *newtype;
922 newtype = PyDict_GetItem(errnomap, myerrno);
923 if (newtype) {
924 assert(PyType_Check(newtype));
925 type = (PyTypeObject *) newtype;
926 }
927 else if (PyErr_Occurred())
928 goto error;
929 }
930 }
931
932 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
933 if (!self)
934 goto error;
935
936 self->dict = NULL;
937 self->traceback = self->cause = self->context = NULL;
938 self->written = -1;
939
940 if (!oserror_use_init(type)) {
Larry Hastingsb0827312014-02-09 22:05:19 -0800941 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100942#ifdef MS_WINDOWS
943 , winerror
944#endif
945 ))
946 goto error;
947 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200948 else {
949 self->args = PyTuple_New(0);
950 if (self->args == NULL)
951 goto error;
952 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100953
Victor Stinner46ef3192013-11-14 22:31:41 +0100954 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200955 return (PyObject *) self;
956
957error:
958 Py_XDECREF(args);
959 Py_XDECREF(self);
960 return NULL;
961}
962
963static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100964OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200965{
Larry Hastingsb0827312014-02-09 22:05:19 -0800966 PyObject *myerrno = NULL, *strerror = NULL;
967 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100968#ifdef MS_WINDOWS
969 PyObject *winerror = NULL;
970#endif
971
972 if (!oserror_use_init(Py_TYPE(self)))
973 /* Everything already done in OSError_new */
974 return 0;
975
976 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
977 return -1;
978
979 Py_INCREF(args);
Larry Hastingsb0827312014-02-09 22:05:19 -0800980 if (oserror_parse_args(&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
Larry Hastingsb0827312014-02-09 22:05:19 -0800987 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100988#ifdef MS_WINDOWS
989 , winerror
990#endif
991 ))
992 goto error;
993
Thomas Wouters477c8d52006-05-27 19:21:47 +0000994 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100995
996error:
997 Py_XDECREF(args);
998 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000999}
1000
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001001static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001002OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001003{
1004 Py_CLEAR(self->myerrno);
1005 Py_CLEAR(self->strerror);
1006 Py_CLEAR(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001007 Py_CLEAR(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001008#ifdef MS_WINDOWS
1009 Py_CLEAR(self->winerror);
1010#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001011 return BaseException_clear((PyBaseExceptionObject *)self);
1012}
1013
1014static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001015OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001016{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001017 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001018 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001019 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001020}
1021
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001022static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001023OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001024 void *arg)
1025{
1026 Py_VISIT(self->myerrno);
1027 Py_VISIT(self->strerror);
1028 Py_VISIT(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001029 Py_VISIT(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001030#ifdef MS_WINDOWS
1031 Py_VISIT(self->winerror);
1032#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1034}
1035
1036static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001037OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001038{
Larry Hastingsb0827312014-02-09 22:05:19 -08001039#define OR_NONE(x) ((x)?(x):Py_None)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001040#ifdef MS_WINDOWS
1041 /* If available, winerror has the priority over myerrno */
Larry Hastingsb0827312014-02-09 22:05:19 -08001042 if (self->winerror && self->filename) {
1043 if (self->filename2) {
1044 return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
1045 OR_NONE(self->winerror),
1046 OR_NONE(self->strerror),
1047 self->filename,
1048 self->filename2);
1049 } else {
1050 return PyUnicode_FromFormat("[WinError %S] %S: %R",
1051 OR_NONE(self->winerror),
1052 OR_NONE(self->strerror),
1053 self->filename);
1054 }
1055 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001056 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001057 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001058 self->winerror ? self->winerror: Py_None,
1059 self->strerror ? self->strerror: Py_None);
1060#endif
Larry Hastingsb0827312014-02-09 22:05:19 -08001061 if (self->filename) {
1062 if (self->filename2) {
1063 return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
1064 OR_NONE(self->myerrno),
1065 OR_NONE(self->strerror),
1066 self->filename,
1067 self->filename2);
1068 } else {
1069 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1070 OR_NONE(self->myerrno),
1071 OR_NONE(self->strerror),
1072 self->filename);
1073 }
1074 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001075 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001076 return PyUnicode_FromFormat("[Errno %S] %S",
1077 self->myerrno ? self->myerrno: Py_None,
1078 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001079 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080}
1081
Thomas Wouters477c8d52006-05-27 19:21:47 +00001082static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001083OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084{
1085 PyObject *args = self->args;
1086 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001087
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001089 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001090 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Larry Hastingsb0827312014-02-09 22:05:19 -08001091 Py_ssize_t size = self->filename2 ? 5 : 3;
1092 args = PyTuple_New(size);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001093 if (!args)
1094 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001095
1096 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001097 Py_INCREF(tmp);
1098 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001099
1100 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101 Py_INCREF(tmp);
1102 PyTuple_SET_ITEM(args, 1, tmp);
1103
1104 Py_INCREF(self->filename);
1105 PyTuple_SET_ITEM(args, 2, self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001106
1107 if (self->filename2) {
1108 /*
1109 * This tuple is essentially used as OSError(*args).
1110 * So, to recreate filename2, we need to pass in
1111 * winerror as well.
1112 */
1113 Py_INCREF(Py_None);
1114 PyTuple_SET_ITEM(args, 3, Py_None);
1115
1116 /* filename2 */
1117 Py_INCREF(self->filename2);
1118 PyTuple_SET_ITEM(args, 4, self->filename2);
1119 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001120 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001121 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001122
1123 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001124 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001125 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001126 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127 Py_DECREF(args);
1128 return res;
1129}
1130
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001131static PyObject *
1132OSError_written_get(PyOSErrorObject *self, void *context)
1133{
1134 if (self->written == -1) {
1135 PyErr_SetString(PyExc_AttributeError, "characters_written");
1136 return NULL;
1137 }
1138 return PyLong_FromSsize_t(self->written);
1139}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001140
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001141static int
1142OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1143{
1144 Py_ssize_t n;
1145 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1146 if (n == -1 && PyErr_Occurred())
1147 return -1;
1148 self->written = n;
1149 return 0;
1150}
1151
1152static PyMemberDef OSError_members[] = {
1153 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1154 PyDoc_STR("POSIX exception code")},
1155 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1156 PyDoc_STR("exception strerror")},
1157 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1158 PyDoc_STR("exception filename")},
Larry Hastingsb0827312014-02-09 22:05:19 -08001159 {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
1160 PyDoc_STR("second exception filename")},
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001161#ifdef MS_WINDOWS
1162 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1163 PyDoc_STR("Win32 exception code")},
1164#endif
1165 {NULL} /* Sentinel */
1166};
1167
1168static PyMethodDef OSError_methods[] = {
1169 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001170 {NULL}
1171};
1172
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001173static PyGetSetDef OSError_getset[] = {
1174 {"characters_written", (getter) OSError_written_get,
1175 (setter) OSError_written_set, NULL},
1176 {NULL}
1177};
1178
1179
1180ComplexExtendsException(PyExc_Exception, OSError,
1181 OSError, OSError_new,
1182 OSError_methods, OSError_members, OSError_getset,
1183 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001184 "Base class for I/O related errors.");
1185
1186
1187/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001188 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001189 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001190MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1191 "I/O operation would block.");
1192MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1193 "Connection error.");
1194MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1195 "Child process error.");
1196MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1197 "Broken pipe.");
1198MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1199 "Connection aborted.");
1200MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1201 "Connection refused.");
1202MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1203 "Connection reset.");
1204MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1205 "File already exists.");
1206MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1207 "File not found.");
1208MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1209 "Operation doesn't work on directories.");
1210MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1211 "Operation only works on directories.");
1212MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1213 "Interrupted by signal.");
1214MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1215 "Not enough permissions.");
1216MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1217 "Process not found.");
1218MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1219 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220
1221/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001222 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001223 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001224SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001225 "Read beyond end of file.");
1226
1227
1228/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001229 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001230 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001231SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001232 "Unspecified run-time error.");
1233
1234
1235/*
1236 * NotImplementedError extends RuntimeError
1237 */
1238SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1239 "Method or function hasn't been implemented yet.");
1240
1241/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001242 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001243 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001244SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001245 "Name not found globally.");
1246
1247/*
1248 * UnboundLocalError extends NameError
1249 */
1250SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1251 "Local name referenced but not bound to a value.");
1252
1253/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001254 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001255 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001256SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257 "Attribute not found.");
1258
1259
1260/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001261 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001262 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001264/* Helper function to customise error message for some syntax errors */
1265static int _report_missing_parentheses(PySyntaxErrorObject *self);
1266
Thomas Wouters477c8d52006-05-27 19:21:47 +00001267static int
1268SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1269{
1270 PyObject *info = NULL;
1271 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1272
1273 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1274 return -1;
1275
1276 if (lenargs >= 1) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001277 Py_CLEAR(self->msg);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001278 self->msg = PyTuple_GET_ITEM(args, 0);
1279 Py_INCREF(self->msg);
1280 }
1281 if (lenargs == 2) {
1282 info = PyTuple_GET_ITEM(args, 1);
1283 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001284 if (!info)
1285 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001286
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001287 if (PyTuple_GET_SIZE(info) != 4) {
1288 /* not a very good error message, but it's what Python 2.4 gives */
1289 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1290 Py_DECREF(info);
1291 return -1;
1292 }
1293
1294 Py_CLEAR(self->filename);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001295 self->filename = PyTuple_GET_ITEM(info, 0);
1296 Py_INCREF(self->filename);
1297
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001298 Py_CLEAR(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001299 self->lineno = PyTuple_GET_ITEM(info, 1);
1300 Py_INCREF(self->lineno);
1301
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001302 Py_CLEAR(self->offset);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001303 self->offset = PyTuple_GET_ITEM(info, 2);
1304 Py_INCREF(self->offset);
1305
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001306 Py_CLEAR(self->text);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001307 self->text = PyTuple_GET_ITEM(info, 3);
1308 Py_INCREF(self->text);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001309
1310 Py_DECREF(info);
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001311
1312 /* Issue #21669: Custom error for 'print' & 'exec' as statements */
1313 if (self->text && PyUnicode_Check(self->text)) {
1314 if (_report_missing_parentheses(self) < 0) {
1315 return -1;
1316 }
1317 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001318 }
1319 return 0;
1320}
1321
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001322static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001323SyntaxError_clear(PySyntaxErrorObject *self)
1324{
1325 Py_CLEAR(self->msg);
1326 Py_CLEAR(self->filename);
1327 Py_CLEAR(self->lineno);
1328 Py_CLEAR(self->offset);
1329 Py_CLEAR(self->text);
1330 Py_CLEAR(self->print_file_and_line);
1331 return BaseException_clear((PyBaseExceptionObject *)self);
1332}
1333
1334static void
1335SyntaxError_dealloc(PySyntaxErrorObject *self)
1336{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001337 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001338 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001339 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001340}
1341
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001342static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001343SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1344{
1345 Py_VISIT(self->msg);
1346 Py_VISIT(self->filename);
1347 Py_VISIT(self->lineno);
1348 Py_VISIT(self->offset);
1349 Py_VISIT(self->text);
1350 Py_VISIT(self->print_file_and_line);
1351 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1352}
1353
1354/* This is called "my_basename" instead of just "basename" to avoid name
1355 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1356 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001357static PyObject*
1358my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001359{
Victor Stinner6237daf2010-04-28 17:26:19 +00001360 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001361 int kind;
1362 void *data;
1363
1364 if (PyUnicode_READY(name))
1365 return NULL;
1366 kind = PyUnicode_KIND(name);
1367 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001369 offset = 0;
1370 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001372 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001373 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001374 if (offset != 0)
1375 return PyUnicode_Substring(name, offset, size);
1376 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001377 Py_INCREF(name);
1378 return name;
1379 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001380}
1381
1382
1383static PyObject *
1384SyntaxError_str(PySyntaxErrorObject *self)
1385{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001386 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001387 PyObject *filename;
1388 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001389 /* Below, we always ignore overflow errors, just printing -1.
1390 Still, we cannot allow an OverflowError to be raised, so
1391 we need to call PyLong_AsLongAndOverflow. */
1392 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001393
1394 /* XXX -- do all the additional formatting with filename and
1395 lineno here */
1396
Neal Norwitzed2b7392007-08-26 04:51:10 +00001397 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001398 filename = my_basename(self->filename);
1399 if (filename == NULL)
1400 return NULL;
1401 } else {
1402 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001403 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001404 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001405
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001406 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001407 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001408
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001409 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001410 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001411 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001412 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001414 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001415 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001416 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001417 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001418 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001419 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001420 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001421 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001422 Py_XDECREF(filename);
1423 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001424}
1425
1426static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001427 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1428 PyDoc_STR("exception msg")},
1429 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1430 PyDoc_STR("exception filename")},
1431 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1432 PyDoc_STR("exception lineno")},
1433 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1434 PyDoc_STR("exception offset")},
1435 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1436 PyDoc_STR("exception text")},
1437 {"print_file_and_line", T_OBJECT,
1438 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1439 PyDoc_STR("exception print_file_and_line")},
1440 {NULL} /* Sentinel */
1441};
1442
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001443ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001444 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445 SyntaxError_str, "Invalid syntax.");
1446
1447
1448/*
1449 * IndentationError extends SyntaxError
1450 */
1451MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1452 "Improper indentation.");
1453
1454
1455/*
1456 * TabError extends IndentationError
1457 */
1458MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1459 "Improper mixture of spaces and tabs.");
1460
1461
1462/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001463 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001464 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001465SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001466 "Base class for lookup errors.");
1467
1468
1469/*
1470 * IndexError extends LookupError
1471 */
1472SimpleExtendsException(PyExc_LookupError, IndexError,
1473 "Sequence index out of range.");
1474
1475
1476/*
1477 * KeyError extends LookupError
1478 */
1479static PyObject *
1480KeyError_str(PyBaseExceptionObject *self)
1481{
1482 /* If args is a tuple of exactly one item, apply repr to args[0].
1483 This is done so that e.g. the exception raised by {}[''] prints
1484 KeyError: ''
1485 rather than the confusing
1486 KeyError
1487 alone. The downside is that if KeyError is raised with an explanatory
1488 string, that string will be displayed in quotes. Too bad.
1489 If args is anything else, use the default BaseException__str__().
1490 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001491 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001492 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001493 }
1494 return BaseException_str(self);
1495}
1496
1497ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001498 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001499
1500
1501/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001502 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001503 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001504SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001505 "Inappropriate argument value (of correct type).");
1506
1507/*
1508 * UnicodeError extends ValueError
1509 */
1510
1511SimpleExtendsException(PyExc_ValueError, UnicodeError,
1512 "Unicode related error.");
1513
Thomas Wouters477c8d52006-05-27 19:21:47 +00001514static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001515get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001516{
1517 if (!attr) {
1518 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1519 return NULL;
1520 }
1521
Christian Heimes72b710a2008-05-26 13:28:38 +00001522 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001523 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1524 return NULL;
1525 }
1526 Py_INCREF(attr);
1527 return attr;
1528}
1529
1530static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001531get_unicode(PyObject *attr, const char *name)
1532{
1533 if (!attr) {
1534 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1535 return NULL;
1536 }
1537
1538 if (!PyUnicode_Check(attr)) {
1539 PyErr_Format(PyExc_TypeError,
1540 "%.200s attribute must be unicode", name);
1541 return NULL;
1542 }
1543 Py_INCREF(attr);
1544 return attr;
1545}
1546
Walter Dörwaldd2034312007-05-18 16:29:38 +00001547static int
1548set_unicodefromstring(PyObject **attr, const char *value)
1549{
1550 PyObject *obj = PyUnicode_FromString(value);
1551 if (!obj)
1552 return -1;
1553 Py_CLEAR(*attr);
1554 *attr = obj;
1555 return 0;
1556}
1557
Thomas Wouters477c8d52006-05-27 19:21:47 +00001558PyObject *
1559PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1560{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001561 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001562}
1563
1564PyObject *
1565PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1566{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001567 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001568}
1569
1570PyObject *
1571PyUnicodeEncodeError_GetObject(PyObject *exc)
1572{
1573 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1574}
1575
1576PyObject *
1577PyUnicodeDecodeError_GetObject(PyObject *exc)
1578{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001579 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001580}
1581
1582PyObject *
1583PyUnicodeTranslateError_GetObject(PyObject *exc)
1584{
1585 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1586}
1587
1588int
1589PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1590{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001591 Py_ssize_t size;
1592 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1593 "object");
1594 if (!obj)
1595 return -1;
1596 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001597 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001598 if (*start<0)
1599 *start = 0; /*XXX check for values <0*/
1600 if (*start>=size)
1601 *start = size-1;
1602 Py_DECREF(obj);
1603 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001604}
1605
1606
1607int
1608PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1609{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001610 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001611 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001612 if (!obj)
1613 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001614 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001615 *start = ((PyUnicodeErrorObject *)exc)->start;
1616 if (*start<0)
1617 *start = 0;
1618 if (*start>=size)
1619 *start = size-1;
1620 Py_DECREF(obj);
1621 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001622}
1623
1624
1625int
1626PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1627{
1628 return PyUnicodeEncodeError_GetStart(exc, start);
1629}
1630
1631
1632int
1633PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1634{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001635 ((PyUnicodeErrorObject *)exc)->start = start;
1636 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001637}
1638
1639
1640int
1641PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1642{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001643 ((PyUnicodeErrorObject *)exc)->start = start;
1644 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001645}
1646
1647
1648int
1649PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1650{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001651 ((PyUnicodeErrorObject *)exc)->start = start;
1652 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001653}
1654
1655
1656int
1657PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1658{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001659 Py_ssize_t size;
1660 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1661 "object");
1662 if (!obj)
1663 return -1;
1664 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001665 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001666 if (*end<1)
1667 *end = 1;
1668 if (*end>size)
1669 *end = size;
1670 Py_DECREF(obj);
1671 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001672}
1673
1674
1675int
1676PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1677{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001678 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001679 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001680 if (!obj)
1681 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001682 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001683 *end = ((PyUnicodeErrorObject *)exc)->end;
1684 if (*end<1)
1685 *end = 1;
1686 if (*end>size)
1687 *end = size;
1688 Py_DECREF(obj);
1689 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001690}
1691
1692
1693int
1694PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1695{
1696 return PyUnicodeEncodeError_GetEnd(exc, start);
1697}
1698
1699
1700int
1701PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1702{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001703 ((PyUnicodeErrorObject *)exc)->end = end;
1704 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001705}
1706
1707
1708int
1709PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1710{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001711 ((PyUnicodeErrorObject *)exc)->end = end;
1712 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001713}
1714
1715
1716int
1717PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1718{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001719 ((PyUnicodeErrorObject *)exc)->end = end;
1720 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001721}
1722
1723PyObject *
1724PyUnicodeEncodeError_GetReason(PyObject *exc)
1725{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001726 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001727}
1728
1729
1730PyObject *
1731PyUnicodeDecodeError_GetReason(PyObject *exc)
1732{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001733 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001734}
1735
1736
1737PyObject *
1738PyUnicodeTranslateError_GetReason(PyObject *exc)
1739{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001740 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001741}
1742
1743
1744int
1745PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1746{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001747 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1748 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001749}
1750
1751
1752int
1753PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1754{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001755 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1756 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001757}
1758
1759
1760int
1761PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1762{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001763 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1764 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001765}
1766
1767
Thomas Wouters477c8d52006-05-27 19:21:47 +00001768static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001769UnicodeError_clear(PyUnicodeErrorObject *self)
1770{
1771 Py_CLEAR(self->encoding);
1772 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001773 Py_CLEAR(self->reason);
1774 return BaseException_clear((PyBaseExceptionObject *)self);
1775}
1776
1777static void
1778UnicodeError_dealloc(PyUnicodeErrorObject *self)
1779{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001780 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001781 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001782 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001783}
1784
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001785static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001786UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1787{
1788 Py_VISIT(self->encoding);
1789 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001790 Py_VISIT(self->reason);
1791 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1792}
1793
1794static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001795 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1796 PyDoc_STR("exception encoding")},
1797 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1798 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001799 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001800 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001801 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001802 PyDoc_STR("exception end")},
1803 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1804 PyDoc_STR("exception reason")},
1805 {NULL} /* Sentinel */
1806};
1807
1808
1809/*
1810 * UnicodeEncodeError extends UnicodeError
1811 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001812
1813static int
1814UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1815{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001816 PyUnicodeErrorObject *err;
1817
Thomas Wouters477c8d52006-05-27 19:21:47 +00001818 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1819 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001820
1821 err = (PyUnicodeErrorObject *)self;
1822
1823 Py_CLEAR(err->encoding);
1824 Py_CLEAR(err->object);
1825 Py_CLEAR(err->reason);
1826
1827 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1828 &PyUnicode_Type, &err->encoding,
1829 &PyUnicode_Type, &err->object,
1830 &err->start,
1831 &err->end,
1832 &PyUnicode_Type, &err->reason)) {
1833 err->encoding = err->object = err->reason = NULL;
1834 return -1;
1835 }
1836
Martin v. Löwisb09af032011-11-04 11:16:41 +01001837 if (PyUnicode_READY(err->object) < -1) {
1838 err->encoding = NULL;
1839 return -1;
1840 }
1841
Guido van Rossum98297ee2007-11-06 21:34:58 +00001842 Py_INCREF(err->encoding);
1843 Py_INCREF(err->object);
1844 Py_INCREF(err->reason);
1845
1846 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001847}
1848
1849static PyObject *
1850UnicodeEncodeError_str(PyObject *self)
1851{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001852 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001853 PyObject *result = NULL;
1854 PyObject *reason_str = NULL;
1855 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001856
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001857 if (!uself->object)
1858 /* Not properly initialized. */
1859 return PyUnicode_FromString("");
1860
Eric Smith0facd772010-02-24 15:42:29 +00001861 /* Get reason and encoding as strings, which they might not be if
1862 they've been modified after we were contructed. */
1863 reason_str = PyObject_Str(uself->reason);
1864 if (reason_str == NULL)
1865 goto done;
1866 encoding_str = PyObject_Str(uself->encoding);
1867 if (encoding_str == NULL)
1868 goto done;
1869
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001870 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1871 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001872 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001873 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001874 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001875 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001876 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001877 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001878 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001879 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001880 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001881 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001882 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001883 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001884 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001885 }
Eric Smith0facd772010-02-24 15:42:29 +00001886 else {
1887 result = PyUnicode_FromFormat(
1888 "'%U' codec can't encode characters in position %zd-%zd: %U",
1889 encoding_str,
1890 uself->start,
1891 uself->end-1,
1892 reason_str);
1893 }
1894done:
1895 Py_XDECREF(reason_str);
1896 Py_XDECREF(encoding_str);
1897 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001898}
1899
1900static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001901 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001902 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001903 sizeof(PyUnicodeErrorObject), 0,
1904 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1905 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1906 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001907 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1908 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001909 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001910 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911};
1912PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1913
1914PyObject *
1915PyUnicodeEncodeError_Create(
1916 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1917 Py_ssize_t start, Py_ssize_t end, const char *reason)
1918{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001919 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001920 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001921}
1922
1923
1924/*
1925 * UnicodeDecodeError extends UnicodeError
1926 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001927
1928static int
1929UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1930{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001931 PyUnicodeErrorObject *ude;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001932
Thomas Wouters477c8d52006-05-27 19:21:47 +00001933 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1934 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001935
1936 ude = (PyUnicodeErrorObject *)self;
1937
1938 Py_CLEAR(ude->encoding);
1939 Py_CLEAR(ude->object);
1940 Py_CLEAR(ude->reason);
1941
1942 if (!PyArg_ParseTuple(args, "O!OnnO!",
1943 &PyUnicode_Type, &ude->encoding,
1944 &ude->object,
1945 &ude->start,
1946 &ude->end,
1947 &PyUnicode_Type, &ude->reason)) {
1948 ude->encoding = ude->object = ude->reason = NULL;
1949 return -1;
1950 }
1951
Guido van Rossum98297ee2007-11-06 21:34:58 +00001952 Py_INCREF(ude->encoding);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001953 Py_INCREF(ude->object);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001954 Py_INCREF(ude->reason);
1955
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001956 if (!PyBytes_Check(ude->object)) {
1957 Py_buffer view;
1958 if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
1959 goto error;
1960 Py_CLEAR(ude->object);
1961 ude->object = PyBytes_FromStringAndSize(view.buf, view.len);
1962 PyBuffer_Release(&view);
1963 if (!ude->object)
1964 goto error;
1965 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001966 return 0;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001967
1968error:
1969 Py_CLEAR(ude->encoding);
1970 Py_CLEAR(ude->object);
1971 Py_CLEAR(ude->reason);
1972 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001973}
1974
1975static PyObject *
1976UnicodeDecodeError_str(PyObject *self)
1977{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001978 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001979 PyObject *result = NULL;
1980 PyObject *reason_str = NULL;
1981 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001982
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001983 if (!uself->object)
1984 /* Not properly initialized. */
1985 return PyUnicode_FromString("");
1986
Eric Smith0facd772010-02-24 15:42:29 +00001987 /* Get reason and encoding as strings, which they might not be if
1988 they've been modified after we were contructed. */
1989 reason_str = PyObject_Str(uself->reason);
1990 if (reason_str == NULL)
1991 goto done;
1992 encoding_str = PyObject_Str(uself->encoding);
1993 if (encoding_str == NULL)
1994 goto done;
1995
1996 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001997 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00001998 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001999 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00002000 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002001 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002002 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002003 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002004 }
Eric Smith0facd772010-02-24 15:42:29 +00002005 else {
2006 result = PyUnicode_FromFormat(
2007 "'%U' codec can't decode bytes in position %zd-%zd: %U",
2008 encoding_str,
2009 uself->start,
2010 uself->end-1,
2011 reason_str
2012 );
2013 }
2014done:
2015 Py_XDECREF(reason_str);
2016 Py_XDECREF(encoding_str);
2017 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002018}
2019
2020static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002021 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002022 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002023 sizeof(PyUnicodeErrorObject), 0,
2024 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2025 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
2026 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002027 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
2028 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002029 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002030 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002031};
2032PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
2033
2034PyObject *
2035PyUnicodeDecodeError_Create(
2036 const char *encoding, const char *object, Py_ssize_t length,
2037 Py_ssize_t start, Py_ssize_t end, const char *reason)
2038{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00002039 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002040 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002041}
2042
2043
2044/*
2045 * UnicodeTranslateError extends UnicodeError
2046 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002047
2048static int
2049UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
2050 PyObject *kwds)
2051{
2052 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2053 return -1;
2054
2055 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002056 Py_CLEAR(self->reason);
2057
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002058 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002059 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002060 &self->start,
2061 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00002062 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002063 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002064 return -1;
2065 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002066
Thomas Wouters477c8d52006-05-27 19:21:47 +00002067 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002068 Py_INCREF(self->reason);
2069
2070 return 0;
2071}
2072
2073
2074static PyObject *
2075UnicodeTranslateError_str(PyObject *self)
2076{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002077 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00002078 PyObject *result = NULL;
2079 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002080
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04002081 if (!uself->object)
2082 /* Not properly initialized. */
2083 return PyUnicode_FromString("");
2084
Eric Smith0facd772010-02-24 15:42:29 +00002085 /* Get reason as a string, which it might not be if it's been
2086 modified after we were contructed. */
2087 reason_str = PyObject_Str(uself->reason);
2088 if (reason_str == NULL)
2089 goto done;
2090
Victor Stinner53b33e72011-11-21 01:17:27 +01002091 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2092 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002093 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002094 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002095 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002096 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002097 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002098 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002099 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002100 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002101 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002102 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002103 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002104 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002105 );
Eric Smith0facd772010-02-24 15:42:29 +00002106 } else {
2107 result = PyUnicode_FromFormat(
2108 "can't translate characters in position %zd-%zd: %U",
2109 uself->start,
2110 uself->end-1,
2111 reason_str
2112 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002113 }
Eric Smith0facd772010-02-24 15:42:29 +00002114done:
2115 Py_XDECREF(reason_str);
2116 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002117}
2118
2119static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002120 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002121 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002122 sizeof(PyUnicodeErrorObject), 0,
2123 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2124 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2125 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002126 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002127 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2128 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002129 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002130};
2131PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2132
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002133/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002134PyObject *
2135PyUnicodeTranslateError_Create(
2136 const Py_UNICODE *object, Py_ssize_t length,
2137 Py_ssize_t start, Py_ssize_t end, const char *reason)
2138{
2139 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002140 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002141}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002143PyObject *
2144_PyUnicodeTranslateError_Create(
2145 PyObject *object,
2146 Py_ssize_t start, Py_ssize_t end, const char *reason)
2147{
Victor Stinner69598d4c2014-04-04 20:59:44 +02002148 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002149 object, start, end, reason);
2150}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002151
2152/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002153 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002154 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002155SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002156 "Assertion failed.");
2157
2158
2159/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002160 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002161 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002162SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002163 "Base class for arithmetic errors.");
2164
2165
2166/*
2167 * FloatingPointError extends ArithmeticError
2168 */
2169SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2170 "Floating point operation failed.");
2171
2172
2173/*
2174 * OverflowError extends ArithmeticError
2175 */
2176SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2177 "Result too large to be represented.");
2178
2179
2180/*
2181 * ZeroDivisionError extends ArithmeticError
2182 */
2183SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2184 "Second argument to a division or modulo operation was zero.");
2185
2186
2187/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002188 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002189 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002190SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002191 "Internal error in the Python interpreter.\n"
2192 "\n"
2193 "Please report this to the Python maintainer, along with the traceback,\n"
2194 "the Python version, and the hardware/OS platform and version.");
2195
2196
2197/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002198 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002199 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002200SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002201 "Weak ref proxy used after referent went away.");
2202
2203
2204/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002205 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002206 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002207
2208#define MEMERRORS_SAVE 16
2209static PyBaseExceptionObject *memerrors_freelist = NULL;
2210static int memerrors_numfree = 0;
2211
2212static PyObject *
2213MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2214{
2215 PyBaseExceptionObject *self;
2216
2217 if (type != (PyTypeObject *) PyExc_MemoryError)
2218 return BaseException_new(type, args, kwds);
2219 if (memerrors_freelist == NULL)
2220 return BaseException_new(type, args, kwds);
2221 /* Fetch object from freelist and revive it */
2222 self = memerrors_freelist;
2223 self->args = PyTuple_New(0);
2224 /* This shouldn't happen since the empty tuple is persistent */
2225 if (self->args == NULL)
2226 return NULL;
2227 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2228 memerrors_numfree--;
2229 self->dict = NULL;
2230 _Py_NewReference((PyObject *)self);
2231 _PyObject_GC_TRACK(self);
2232 return (PyObject *)self;
2233}
2234
2235static void
2236MemoryError_dealloc(PyBaseExceptionObject *self)
2237{
2238 _PyObject_GC_UNTRACK(self);
2239 BaseException_clear(self);
2240 if (memerrors_numfree >= MEMERRORS_SAVE)
2241 Py_TYPE(self)->tp_free((PyObject *)self);
2242 else {
2243 self->dict = (PyObject *) memerrors_freelist;
2244 memerrors_freelist = self;
2245 memerrors_numfree++;
2246 }
2247}
2248
2249static void
2250preallocate_memerrors(void)
2251{
2252 /* We create enough MemoryErrors and then decref them, which will fill
2253 up the freelist. */
2254 int i;
2255 PyObject *errors[MEMERRORS_SAVE];
2256 for (i = 0; i < MEMERRORS_SAVE; i++) {
2257 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2258 NULL, NULL);
2259 if (!errors[i])
2260 Py_FatalError("Could not preallocate MemoryError object");
2261 }
2262 for (i = 0; i < MEMERRORS_SAVE; i++) {
2263 Py_DECREF(errors[i]);
2264 }
2265}
2266
2267static void
2268free_preallocated_memerrors(void)
2269{
2270 while (memerrors_freelist != NULL) {
2271 PyObject *self = (PyObject *) memerrors_freelist;
2272 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2273 Py_TYPE(self)->tp_free((PyObject *)self);
2274 }
2275}
2276
2277
2278static PyTypeObject _PyExc_MemoryError = {
2279 PyVarObject_HEAD_INIT(NULL, 0)
2280 "MemoryError",
2281 sizeof(PyBaseExceptionObject),
2282 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2283 0, 0, 0, 0, 0, 0, 0,
2284 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2285 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2286 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2287 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2288 (initproc)BaseException_init, 0, MemoryError_new
2289};
2290PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2291
Thomas Wouters477c8d52006-05-27 19:21:47 +00002292
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002293/*
2294 * BufferError extends Exception
2295 */
2296SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2297
Thomas Wouters477c8d52006-05-27 19:21:47 +00002298
2299/* Warning category docstrings */
2300
2301/*
2302 * Warning extends Exception
2303 */
2304SimpleExtendsException(PyExc_Exception, Warning,
2305 "Base class for warning categories.");
2306
2307
2308/*
2309 * UserWarning extends Warning
2310 */
2311SimpleExtendsException(PyExc_Warning, UserWarning,
2312 "Base class for warnings generated by user code.");
2313
2314
2315/*
2316 * DeprecationWarning extends Warning
2317 */
2318SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2319 "Base class for warnings about deprecated features.");
2320
2321
2322/*
2323 * PendingDeprecationWarning extends Warning
2324 */
2325SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2326 "Base class for warnings about features which will be deprecated\n"
2327 "in the future.");
2328
2329
2330/*
2331 * SyntaxWarning extends Warning
2332 */
2333SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2334 "Base class for warnings about dubious syntax.");
2335
2336
2337/*
2338 * RuntimeWarning extends Warning
2339 */
2340SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2341 "Base class for warnings about dubious runtime behavior.");
2342
2343
2344/*
2345 * FutureWarning extends Warning
2346 */
2347SimpleExtendsException(PyExc_Warning, FutureWarning,
2348 "Base class for warnings about constructs that will change semantically\n"
2349 "in the future.");
2350
2351
2352/*
2353 * ImportWarning extends Warning
2354 */
2355SimpleExtendsException(PyExc_Warning, ImportWarning,
2356 "Base class for warnings about probable mistakes in module imports");
2357
2358
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002359/*
2360 * UnicodeWarning extends Warning
2361 */
2362SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2363 "Base class for warnings about Unicode related problems, mostly\n"
2364 "related to conversion problems.");
2365
Georg Brandl08be72d2010-10-24 15:11:22 +00002366
Guido van Rossum98297ee2007-11-06 21:34:58 +00002367/*
2368 * BytesWarning extends Warning
2369 */
2370SimpleExtendsException(PyExc_Warning, BytesWarning,
2371 "Base class for warnings about bytes and buffer related problems, mostly\n"
2372 "related to conversion from str or comparing to str.");
2373
2374
Georg Brandl08be72d2010-10-24 15:11:22 +00002375/*
2376 * ResourceWarning extends Warning
2377 */
2378SimpleExtendsException(PyExc_Warning, ResourceWarning,
2379 "Base class for warnings about resource usage.");
2380
2381
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002382
Thomas Wouters89d996e2007-09-08 17:39:28 +00002383/* Pre-computed RuntimeError instance for when recursion depth is reached.
2384 Meant to be used when normalizing the exception for exceeding the recursion
2385 depth will cause its own infinite recursion.
2386*/
2387PyObject *PyExc_RecursionErrorInst = NULL;
2388
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002389#define PRE_INIT(TYPE) \
2390 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2391 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2392 Py_FatalError("exceptions bootstrapping error."); \
2393 Py_INCREF(PyExc_ ## TYPE); \
2394 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002395
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002396#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002397 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2398 Py_FatalError("Module dictionary insertion problem.");
2399
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002400#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002401 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002402 PyExc_ ## NAME = PyExc_ ## TYPE; \
2403 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2404 Py_FatalError("Module dictionary insertion problem.");
2405
2406#define ADD_ERRNO(TYPE, CODE) { \
2407 PyObject *_code = PyLong_FromLong(CODE); \
2408 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2409 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2410 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002411 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002412 }
2413
2414#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002415#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002416/* The following constants were added to errno.h in VS2010 but have
2417 preferred WSA equivalents. */
2418#undef EADDRINUSE
2419#undef EADDRNOTAVAIL
2420#undef EAFNOSUPPORT
2421#undef EALREADY
2422#undef ECONNABORTED
2423#undef ECONNREFUSED
2424#undef ECONNRESET
2425#undef EDESTADDRREQ
2426#undef EHOSTUNREACH
2427#undef EINPROGRESS
2428#undef EISCONN
2429#undef ELOOP
2430#undef EMSGSIZE
2431#undef ENETDOWN
2432#undef ENETRESET
2433#undef ENETUNREACH
2434#undef ENOBUFS
2435#undef ENOPROTOOPT
2436#undef ENOTCONN
2437#undef ENOTSOCK
2438#undef EOPNOTSUPP
2439#undef EPROTONOSUPPORT
2440#undef EPROTOTYPE
2441#undef ETIMEDOUT
2442#undef EWOULDBLOCK
2443
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002444#if defined(WSAEALREADY) && !defined(EALREADY)
2445#define EALREADY WSAEALREADY
2446#endif
2447#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2448#define ECONNABORTED WSAECONNABORTED
2449#endif
2450#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2451#define ECONNREFUSED WSAECONNREFUSED
2452#endif
2453#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2454#define ECONNRESET WSAECONNRESET
2455#endif
2456#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2457#define EINPROGRESS WSAEINPROGRESS
2458#endif
2459#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2460#define ESHUTDOWN WSAESHUTDOWN
2461#endif
2462#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2463#define ETIMEDOUT WSAETIMEDOUT
2464#endif
2465#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2466#define EWOULDBLOCK WSAEWOULDBLOCK
2467#endif
2468#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002469
Martin v. Löwis1a214512008-06-11 05:26:20 +00002470void
Brett Cannonfd074152012-04-14 14:10:13 -04002471_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002472{
Brett Cannonfd074152012-04-14 14:10:13 -04002473 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002474
2475 PRE_INIT(BaseException)
2476 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002477 PRE_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002478 PRE_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002479 PRE_INIT(StopIteration)
2480 PRE_INIT(GeneratorExit)
2481 PRE_INIT(SystemExit)
2482 PRE_INIT(KeyboardInterrupt)
2483 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002484 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002485 PRE_INIT(EOFError)
2486 PRE_INIT(RuntimeError)
2487 PRE_INIT(NotImplementedError)
2488 PRE_INIT(NameError)
2489 PRE_INIT(UnboundLocalError)
2490 PRE_INIT(AttributeError)
2491 PRE_INIT(SyntaxError)
2492 PRE_INIT(IndentationError)
2493 PRE_INIT(TabError)
2494 PRE_INIT(LookupError)
2495 PRE_INIT(IndexError)
2496 PRE_INIT(KeyError)
2497 PRE_INIT(ValueError)
2498 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002499 PRE_INIT(UnicodeEncodeError)
2500 PRE_INIT(UnicodeDecodeError)
2501 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002502 PRE_INIT(AssertionError)
2503 PRE_INIT(ArithmeticError)
2504 PRE_INIT(FloatingPointError)
2505 PRE_INIT(OverflowError)
2506 PRE_INIT(ZeroDivisionError)
2507 PRE_INIT(SystemError)
2508 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002509 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002510 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002511 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002512 PRE_INIT(Warning)
2513 PRE_INIT(UserWarning)
2514 PRE_INIT(DeprecationWarning)
2515 PRE_INIT(PendingDeprecationWarning)
2516 PRE_INIT(SyntaxWarning)
2517 PRE_INIT(RuntimeWarning)
2518 PRE_INIT(FutureWarning)
2519 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002520 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002521 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002522 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002523
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002524 /* OSError subclasses */
2525 PRE_INIT(ConnectionError);
2526
2527 PRE_INIT(BlockingIOError);
2528 PRE_INIT(BrokenPipeError);
2529 PRE_INIT(ChildProcessError);
2530 PRE_INIT(ConnectionAbortedError);
2531 PRE_INIT(ConnectionRefusedError);
2532 PRE_INIT(ConnectionResetError);
2533 PRE_INIT(FileExistsError);
2534 PRE_INIT(FileNotFoundError);
2535 PRE_INIT(IsADirectoryError);
2536 PRE_INIT(NotADirectoryError);
2537 PRE_INIT(InterruptedError);
2538 PRE_INIT(PermissionError);
2539 PRE_INIT(ProcessLookupError);
2540 PRE_INIT(TimeoutError);
2541
Thomas Wouters477c8d52006-05-27 19:21:47 +00002542 bdict = PyModule_GetDict(bltinmod);
2543 if (bdict == NULL)
2544 Py_FatalError("exceptions bootstrapping error.");
2545
2546 POST_INIT(BaseException)
2547 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002548 POST_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002549 POST_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002550 POST_INIT(StopIteration)
2551 POST_INIT(GeneratorExit)
2552 POST_INIT(SystemExit)
2553 POST_INIT(KeyboardInterrupt)
2554 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002555 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002556 INIT_ALIAS(EnvironmentError, OSError)
2557 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002558#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002559 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002560#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00002561 POST_INIT(EOFError)
2562 POST_INIT(RuntimeError)
2563 POST_INIT(NotImplementedError)
2564 POST_INIT(NameError)
2565 POST_INIT(UnboundLocalError)
2566 POST_INIT(AttributeError)
2567 POST_INIT(SyntaxError)
2568 POST_INIT(IndentationError)
2569 POST_INIT(TabError)
2570 POST_INIT(LookupError)
2571 POST_INIT(IndexError)
2572 POST_INIT(KeyError)
2573 POST_INIT(ValueError)
2574 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002575 POST_INIT(UnicodeEncodeError)
2576 POST_INIT(UnicodeDecodeError)
2577 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002578 POST_INIT(AssertionError)
2579 POST_INIT(ArithmeticError)
2580 POST_INIT(FloatingPointError)
2581 POST_INIT(OverflowError)
2582 POST_INIT(ZeroDivisionError)
2583 POST_INIT(SystemError)
2584 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002585 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002586 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002587 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002588 POST_INIT(Warning)
2589 POST_INIT(UserWarning)
2590 POST_INIT(DeprecationWarning)
2591 POST_INIT(PendingDeprecationWarning)
2592 POST_INIT(SyntaxWarning)
2593 POST_INIT(RuntimeWarning)
2594 POST_INIT(FutureWarning)
2595 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002596 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002597 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002598 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002599
Antoine Pitrouac456a12012-01-18 21:35:21 +01002600 if (!errnomap) {
2601 errnomap = PyDict_New();
2602 if (!errnomap)
2603 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2604 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002605
2606 /* OSError subclasses */
2607 POST_INIT(ConnectionError);
2608
2609 POST_INIT(BlockingIOError);
2610 ADD_ERRNO(BlockingIOError, EAGAIN);
2611 ADD_ERRNO(BlockingIOError, EALREADY);
2612 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2613 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2614 POST_INIT(BrokenPipeError);
2615 ADD_ERRNO(BrokenPipeError, EPIPE);
2616 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2617 POST_INIT(ChildProcessError);
2618 ADD_ERRNO(ChildProcessError, ECHILD);
2619 POST_INIT(ConnectionAbortedError);
2620 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2621 POST_INIT(ConnectionRefusedError);
2622 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2623 POST_INIT(ConnectionResetError);
2624 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2625 POST_INIT(FileExistsError);
2626 ADD_ERRNO(FileExistsError, EEXIST);
2627 POST_INIT(FileNotFoundError);
2628 ADD_ERRNO(FileNotFoundError, ENOENT);
2629 POST_INIT(IsADirectoryError);
2630 ADD_ERRNO(IsADirectoryError, EISDIR);
2631 POST_INIT(NotADirectoryError);
2632 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2633 POST_INIT(InterruptedError);
2634 ADD_ERRNO(InterruptedError, EINTR);
2635 POST_INIT(PermissionError);
2636 ADD_ERRNO(PermissionError, EACCES);
2637 ADD_ERRNO(PermissionError, EPERM);
2638 POST_INIT(ProcessLookupError);
2639 ADD_ERRNO(ProcessLookupError, ESRCH);
2640 POST_INIT(TimeoutError);
2641 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2642
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002643 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002644
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002645 if (!PyExc_RecursionErrorInst) {
2646 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL);
2647 if (!PyExc_RecursionErrorInst)
2648 Py_FatalError("Cannot pre-allocate RuntimeError instance for "
2649 "recursion errors");
2650 else {
2651 PyBaseExceptionObject *err_inst =
2652 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2653 PyObject *args_tuple;
2654 PyObject *exc_message;
2655 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2656 if (!exc_message)
2657 Py_FatalError("cannot allocate argument for RuntimeError "
2658 "pre-allocation");
2659 args_tuple = PyTuple_Pack(1, exc_message);
2660 if (!args_tuple)
2661 Py_FatalError("cannot allocate tuple for RuntimeError "
2662 "pre-allocation");
2663 Py_DECREF(exc_message);
2664 if (BaseException_init(err_inst, args_tuple, NULL))
2665 Py_FatalError("init of pre-allocated RuntimeError failed");
2666 Py_DECREF(args_tuple);
2667 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002668 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002669}
2670
2671void
2672_PyExc_Fini(void)
2673{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002674 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002675 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002676 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002677}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002678
2679/* Helper to do the equivalent of "raise X from Y" in C, but always using
2680 * the current exception rather than passing one in.
2681 *
2682 * We currently limit this to *only* exceptions that use the BaseException
2683 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2684 * those correctly without losing data and without losing backwards
2685 * compatibility.
2686 *
2687 * We also aim to rule out *all* exceptions that might be storing additional
2688 * state, whether by having a size difference relative to BaseException,
2689 * additional arguments passed in during construction or by having a
2690 * non-empty instance dict.
2691 *
2692 * We need to be very careful with what we wrap, since changing types to
2693 * a broader exception type would be backwards incompatible for
2694 * existing codecs, and with different init or new method implementations
2695 * may either not support instantiation with PyErr_Format or lose
2696 * information when instantiated that way.
2697 *
2698 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2699 * fact that exceptions are expected to support pickling. If more builtin
2700 * exceptions (e.g. AttributeError) start to be converted to rich
2701 * exceptions with additional attributes, that's probably a better approach
2702 * to pursue over adding special cases for particular stateful subclasses.
2703 *
2704 * Returns a borrowed reference to the new exception (if any), NULL if the
2705 * existing exception was left in place.
2706 */
2707PyObject *
2708_PyErr_TrySetFromCause(const char *format, ...)
2709{
2710 PyObject* msg_prefix;
2711 PyObject *exc, *val, *tb;
2712 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002713 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002714 PyObject *instance_args;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002715 Py_ssize_t num_args, caught_type_size, base_exc_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002716 PyObject *new_exc, *new_val, *new_tb;
2717 va_list vargs;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002718 int same_basic_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002719
Nick Coghlan8b097b42013-11-13 23:49:21 +10002720 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002721 caught_type = (PyTypeObject *)exc;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002722 /* Ensure type info indicates no extra state is stored at the C level
2723 * and that the type can be reinstantiated using PyErr_Format
2724 */
2725 caught_type_size = caught_type->tp_basicsize;
2726 base_exc_size = _PyExc_BaseException.tp_basicsize;
2727 same_basic_size = (
2728 caught_type_size == base_exc_size ||
2729 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
Victor Stinner12174a52014-08-15 23:17:38 +02002730 (caught_type_size == base_exc_size + (Py_ssize_t)sizeof(PyObject *))
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002731 )
2732 );
Benjamin Peterson079c9982013-11-13 23:25:01 -05002733 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002734 caught_type->tp_new != BaseException_new ||
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002735 !same_basic_size ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002736 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002737 /* We can't be sure we can wrap this safely, since it may contain
2738 * more state than just the exception type. Accordingly, we just
2739 * leave it alone.
2740 */
2741 PyErr_Restore(exc, val, tb);
2742 return NULL;
2743 }
2744
2745 /* Check the args are empty or contain a single string */
2746 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002747 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002748 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002749 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002750 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002751 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002752 /* More than 1 arg, or the one arg we do have isn't a string
2753 */
2754 PyErr_Restore(exc, val, tb);
2755 return NULL;
2756 }
2757
2758 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002759 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002760 if (dictptr != NULL && *dictptr != NULL &&
2761 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002762 /* While we could potentially copy a non-empty instance dictionary
2763 * to the replacement exception, for now we take the more
2764 * conservative path of leaving exceptions with attributes set
2765 * alone.
2766 */
2767 PyErr_Restore(exc, val, tb);
2768 return NULL;
2769 }
2770
2771 /* For exceptions that we can wrap safely, we chain the original
2772 * exception to a new one of the exact same type with an
2773 * error message that mentions the additional details and the
2774 * original exception.
2775 *
2776 * It would be nice to wrap OSError and various other exception
2777 * types as well, but that's quite a bit trickier due to the extra
2778 * state potentially stored on OSError instances.
2779 */
Nick Coghlan77b286b2014-01-27 00:53:38 +10002780 /* Ensure the traceback is set correctly on the existing exception */
2781 if (tb != NULL) {
2782 PyException_SetTraceback(val, tb);
2783 Py_DECREF(tb);
2784 }
Benjamin Petersone109ee82013-11-13 23:49:49 -05002785
Christian Heimes507eabd2013-11-14 01:39:35 +01002786#ifdef HAVE_STDARG_PROTOTYPES
2787 va_start(vargs, format);
2788#else
2789 va_start(vargs);
2790#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002791 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002792 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002793 if (msg_prefix == NULL) {
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002794 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002795 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002796 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002797 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002798
2799 PyErr_Format(exc, "%U (%s: %S)",
2800 msg_prefix, Py_TYPE(val)->tp_name, val);
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002801 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002802 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002803 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2804 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2805 PyException_SetCause(new_val, val);
2806 PyErr_Restore(new_exc, new_val, new_tb);
2807 return new_val;
2808}
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002809
2810
2811/* To help with migration from Python 2, SyntaxError.__init__ applies some
2812 * heuristics to try to report a more meaningful exception when print and
2813 * exec are used like statements.
2814 *
2815 * The heuristics are currently expected to detect the following cases:
2816 * - top level statement
2817 * - statement in a nested suite
2818 * - trailing section of a one line complex statement
2819 *
2820 * They're currently known not to trigger:
2821 * - after a semi-colon
2822 *
2823 * The error message can be a bit odd in cases where the "arguments" are
2824 * completely illegal syntactically, but that isn't worth the hassle of
2825 * fixing.
2826 *
2827 * We also can't do anything about cases that are legal Python 3 syntax
2828 * but mean something entirely different from what they did in Python 2
2829 * (omitting the arguments entirely, printing items preceded by a unary plus
2830 * or minus, using the stream redirection syntax).
2831 */
2832
2833static int
2834_check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start)
2835{
2836 /* Return values:
2837 * -1: an error occurred
2838 * 0: nothing happened
2839 * 1: the check triggered & the error message was changed
2840 */
2841 static PyObject *print_prefix = NULL;
2842 static PyObject *exec_prefix = NULL;
2843 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2844 int kind = PyUnicode_KIND(self->text);
2845 void *data = PyUnicode_DATA(self->text);
2846
2847 /* Ignore leading whitespace */
2848 while (start < text_len) {
2849 Py_UCS4 ch = PyUnicode_READ(kind, data, start);
2850 if (!Py_UNICODE_ISSPACE(ch))
2851 break;
2852 start++;
2853 }
2854 /* Checking against an empty or whitespace-only part of the string */
2855 if (start == text_len) {
2856 return 0;
2857 }
2858
2859 /* Check for legacy print statements */
2860 if (print_prefix == NULL) {
2861 print_prefix = PyUnicode_InternFromString("print ");
2862 if (print_prefix == NULL) {
2863 return -1;
2864 }
2865 }
2866 if (PyUnicode_Tailmatch(self->text, print_prefix,
2867 start, text_len, -1)) {
2868 Py_CLEAR(self->msg);
2869 self->msg = PyUnicode_FromString(
2870 "Missing parentheses in call to 'print'");
2871 return 1;
2872 }
2873
2874 /* Check for legacy exec statements */
2875 if (exec_prefix == NULL) {
2876 exec_prefix = PyUnicode_InternFromString("exec ");
2877 if (exec_prefix == NULL) {
2878 return -1;
2879 }
2880 }
2881 if (PyUnicode_Tailmatch(self->text, exec_prefix,
2882 start, text_len, -1)) {
2883 Py_CLEAR(self->msg);
2884 self->msg = PyUnicode_FromString(
2885 "Missing parentheses in call to 'exec'");
2886 return 1;
2887 }
2888 /* Fall back to the default error message */
2889 return 0;
2890}
2891
2892static int
2893_report_missing_parentheses(PySyntaxErrorObject *self)
2894{
2895 Py_UCS4 left_paren = 40;
2896 Py_ssize_t left_paren_index;
2897 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2898 int legacy_check_result = 0;
2899
2900 /* Skip entirely if there is an opening parenthesis */
2901 left_paren_index = PyUnicode_FindChar(self->text, left_paren,
2902 0, text_len, 1);
2903 if (left_paren_index < -1) {
2904 return -1;
2905 }
2906 if (left_paren_index != -1) {
2907 /* Use default error message for any line with an opening paren */
2908 return 0;
2909 }
2910 /* Handle the simple statement case */
2911 legacy_check_result = _check_for_legacy_statements(self, 0);
2912 if (legacy_check_result < 0) {
2913 return -1;
2914
2915 }
2916 if (legacy_check_result == 0) {
2917 /* Handle the one-line complex statement case */
2918 Py_UCS4 colon = 58;
2919 Py_ssize_t colon_index;
2920 colon_index = PyUnicode_FindChar(self->text, colon,
2921 0, text_len, 1);
2922 if (colon_index < -1) {
2923 return -1;
2924 }
2925 if (colon_index >= 0 && colon_index < text_len) {
2926 /* Check again, starting from just after the colon */
2927 if (_check_for_legacy_statements(self, colon_index+1) < 0) {
2928 return -1;
2929 }
2930 }
2931 }
2932 return 0;
2933}