blob: 62ea3789f75767e44e69b7bd581ef8a9f877aec4 [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);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +0200239 Py_SETREF(self->traceback, tb);
Collin Winter828f04a2007-08-31 00:04:24 +0000240 return 0;
241}
242
Georg Brandlab6f2f62009-03-31 04:16:10 +0000243static PyObject *
244BaseException_get_context(PyObject *self) {
245 PyObject *res = PyException_GetContext(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500246 if (res)
247 return res; /* new reference already returned above */
Georg Brandlab6f2f62009-03-31 04:16:10 +0000248 Py_RETURN_NONE;
249}
250
251static int
252BaseException_set_context(PyObject *self, PyObject *arg) {
253 if (arg == NULL) {
254 PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
255 return -1;
256 } else if (arg == Py_None) {
257 arg = NULL;
258 } else if (!PyExceptionInstance_Check(arg)) {
259 PyErr_SetString(PyExc_TypeError, "exception context must be None "
260 "or derive from BaseException");
261 return -1;
262 } else {
263 /* PyException_SetContext steals this reference */
264 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 }
Georg Brandlab6f2f62009-03-31 04:16:10 +0000266 PyException_SetContext(self, arg);
267 return 0;
268}
269
270static PyObject *
271BaseException_get_cause(PyObject *self) {
272 PyObject *res = PyException_GetCause(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500273 if (res)
274 return res; /* new reference already returned above */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700275 Py_RETURN_NONE;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000276}
277
278static int
279BaseException_set_cause(PyObject *self, PyObject *arg) {
280 if (arg == NULL) {
281 PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
282 return -1;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700283 } else if (arg == Py_None) {
284 arg = NULL;
285 } else if (!PyExceptionInstance_Check(arg)) {
286 PyErr_SetString(PyExc_TypeError, "exception cause must be None "
287 "or derive from BaseException");
288 return -1;
289 } else {
290 /* PyException_SetCause steals this reference */
291 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700293 PyException_SetCause(self, arg);
294 return 0;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000295}
296
Guido van Rossum360e4b82007-05-14 22:51:27 +0000297
Thomas Wouters477c8d52006-05-27 19:21:47 +0000298static PyGetSetDef BaseException_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500299 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000300 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
Collin Winter828f04a2007-08-31 00:04:24 +0000301 {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
Georg Brandlab6f2f62009-03-31 04:16:10 +0000302 {"__context__", (getter)BaseException_get_context,
303 (setter)BaseException_set_context, PyDoc_STR("exception context")},
304 {"__cause__", (getter)BaseException_get_cause,
305 (setter)BaseException_set_cause, PyDoc_STR("exception cause")},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000306 {NULL},
307};
308
309
Collin Winter828f04a2007-08-31 00:04:24 +0000310PyObject *
311PyException_GetTraceback(PyObject *self) {
312 PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
313 Py_XINCREF(base_self->traceback);
314 return base_self->traceback;
315}
316
317
318int
319PyException_SetTraceback(PyObject *self, PyObject *tb) {
320 return BaseException_set_tb((PyBaseExceptionObject *)self, tb);
321}
322
323PyObject *
324PyException_GetCause(PyObject *self) {
325 PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
326 Py_XINCREF(cause);
327 return cause;
328}
329
330/* Steals a reference to cause */
331void
332PyException_SetCause(PyObject *self, PyObject *cause) {
333 PyObject *old_cause = ((PyBaseExceptionObject *)self)->cause;
334 ((PyBaseExceptionObject *)self)->cause = cause;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700335 ((PyBaseExceptionObject *)self)->suppress_context = 1;
Collin Winter828f04a2007-08-31 00:04:24 +0000336 Py_XDECREF(old_cause);
337}
338
339PyObject *
340PyException_GetContext(PyObject *self) {
341 PyObject *context = ((PyBaseExceptionObject *)self)->context;
342 Py_XINCREF(context);
343 return context;
344}
345
346/* Steals a reference to context */
347void
348PyException_SetContext(PyObject *self, PyObject *context) {
349 PyObject *old_context = ((PyBaseExceptionObject *)self)->context;
350 ((PyBaseExceptionObject *)self)->context = context;
351 Py_XDECREF(old_context);
352}
353
354
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700355static struct PyMemberDef BaseException_members[] = {
356 {"__suppress_context__", T_BOOL,
Antoine Pitrou32bc80c2012-05-16 12:51:55 +0200357 offsetof(PyBaseExceptionObject, suppress_context)},
358 {NULL}
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700359};
360
361
Thomas Wouters477c8d52006-05-27 19:21:47 +0000362static PyTypeObject _PyExc_BaseException = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000363 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +0000364 "BaseException", /*tp_name*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000365 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
366 0, /*tp_itemsize*/
367 (destructor)BaseException_dealloc, /*tp_dealloc*/
368 0, /*tp_print*/
369 0, /*tp_getattr*/
370 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000371 0, /* tp_reserved; */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000372 (reprfunc)BaseException_repr, /*tp_repr*/
373 0, /*tp_as_number*/
Brett Cannonba7bf492007-02-27 00:15:55 +0000374 0, /*tp_as_sequence*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000375 0, /*tp_as_mapping*/
376 0, /*tp_hash */
377 0, /*tp_call*/
378 (reprfunc)BaseException_str, /*tp_str*/
379 PyObject_GenericGetAttr, /*tp_getattro*/
380 PyObject_GenericSetAttr, /*tp_setattro*/
381 0, /*tp_as_buffer*/
Thomas Wouters27d517b2007-02-25 20:39:11 +0000382 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000384 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
385 (traverseproc)BaseException_traverse, /* tp_traverse */
386 (inquiry)BaseException_clear, /* tp_clear */
387 0, /* tp_richcompare */
388 0, /* tp_weaklistoffset */
389 0, /* tp_iter */
390 0, /* tp_iternext */
391 BaseException_methods, /* tp_methods */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700392 BaseException_members, /* tp_members */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000393 BaseException_getset, /* tp_getset */
394 0, /* tp_base */
395 0, /* tp_dict */
396 0, /* tp_descr_get */
397 0, /* tp_descr_set */
398 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
399 (initproc)BaseException_init, /* tp_init */
400 0, /* tp_alloc */
401 BaseException_new, /* tp_new */
402};
403/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
404from the previous implmentation and also allowing Python objects to be used
405in the API */
406PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
407
408/* note these macros omit the last semicolon so the macro invocation may
409 * include it and not look strange.
410 */
411#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
412static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000413 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000414 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415 sizeof(PyBaseExceptionObject), \
416 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
417 0, 0, 0, 0, 0, 0, 0, \
418 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
419 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
420 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
421 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
422 (initproc)BaseException_init, 0, BaseException_new,\
423}; \
424PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
425
426#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
427static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000428 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000429 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000430 sizeof(Py ## EXCSTORE ## Object), \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000431 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000432 0, 0, 0, 0, 0, \
433 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000434 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
435 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000436 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200437 (initproc)EXCSTORE ## _init, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000438}; \
439PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
440
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200441#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
442 EXCMETHODS, EXCMEMBERS, EXCGETSET, \
443 EXCSTR, EXCDOC) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000444static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000445 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000446 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447 sizeof(Py ## EXCSTORE ## Object), 0, \
448 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
449 (reprfunc)EXCSTR, 0, 0, 0, \
450 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
451 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
452 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200453 EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200455 (initproc)EXCSTORE ## _init, 0, EXCNEW,\
Thomas Wouters477c8d52006-05-27 19:21:47 +0000456}; \
457PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
458
459
460/*
461 * Exception extends BaseException
462 */
463SimpleExtendsException(PyExc_BaseException, Exception,
464 "Common base class for all non-exit exceptions.");
465
466
467/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000468 * TypeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000469 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000470SimpleExtendsException(PyExc_Exception, TypeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000471 "Inappropriate argument type.");
472
473
474/*
Yury Selivanov75445082015-05-11 22:57:16 -0400475 * StopAsyncIteration extends Exception
476 */
477SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
478 "Signal the end from iterator.__anext__().");
479
480
481/*
Thomas Wouters477c8d52006-05-27 19:21:47 +0000482 * StopIteration extends Exception
483 */
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000484
485static PyMemberDef StopIteration_members[] = {
486 {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
487 PyDoc_STR("generator return value")},
488 {NULL} /* Sentinel */
489};
490
491static int
492StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
493{
494 Py_ssize_t size = PyTuple_GET_SIZE(args);
495 PyObject *value;
496
497 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
498 return -1;
499 Py_CLEAR(self->value);
500 if (size > 0)
501 value = PyTuple_GET_ITEM(args, 0);
502 else
503 value = Py_None;
504 Py_INCREF(value);
505 self->value = value;
506 return 0;
507}
508
509static int
510StopIteration_clear(PyStopIterationObject *self)
511{
512 Py_CLEAR(self->value);
513 return BaseException_clear((PyBaseExceptionObject *)self);
514}
515
516static void
517StopIteration_dealloc(PyStopIterationObject *self)
518{
519 _PyObject_GC_UNTRACK(self);
520 StopIteration_clear(self);
521 Py_TYPE(self)->tp_free((PyObject *)self);
522}
523
524static int
525StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
526{
527 Py_VISIT(self->value);
528 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
529}
530
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000531ComplexExtendsException(
532 PyExc_Exception, /* base */
533 StopIteration, /* name */
534 StopIteration, /* prefix for *_init, etc */
535 0, /* new */
536 0, /* methods */
537 StopIteration_members, /* members */
538 0, /* getset */
539 0, /* str */
540 "Signal the end from iterator.__next__()."
541);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542
543
544/*
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000545 * GeneratorExit extends BaseException
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546 */
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000547SimpleExtendsException(PyExc_BaseException, GeneratorExit,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548 "Request that a generator exit.");
549
550
551/*
552 * SystemExit extends BaseException
553 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554
555static int
556SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
557{
558 Py_ssize_t size = PyTuple_GET_SIZE(args);
559
560 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
561 return -1;
562
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000563 if (size == 0)
564 return 0;
565 Py_CLEAR(self->code);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000566 if (size == 1)
567 self->code = PyTuple_GET_ITEM(args, 0);
Victor Stinner92236e52011-05-26 14:25:54 +0200568 else /* size > 1 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569 self->code = args;
570 Py_INCREF(self->code);
571 return 0;
572}
573
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000574static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000575SystemExit_clear(PySystemExitObject *self)
576{
577 Py_CLEAR(self->code);
578 return BaseException_clear((PyBaseExceptionObject *)self);
579}
580
581static void
582SystemExit_dealloc(PySystemExitObject *self)
583{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000584 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585 SystemExit_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000586 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587}
588
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000589static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
591{
592 Py_VISIT(self->code);
593 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
594}
595
596static PyMemberDef SystemExit_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000597 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
598 PyDoc_STR("exception code")},
599 {NULL} /* Sentinel */
600};
601
602ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200603 0, 0, SystemExit_members, 0, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000604 "Request to exit from the interpreter.");
605
606/*
607 * KeyboardInterrupt extends BaseException
608 */
609SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
610 "Program interrupted by user.");
611
612
613/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000614 * ImportError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000615 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000616
Brett Cannon79ec55e2012-04-12 20:24:54 -0400617static int
618ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
619{
620 PyObject *msg = NULL;
621 PyObject *name = NULL;
622 PyObject *path = NULL;
623
624/* Macro replacement doesn't allow ## to start the first line of a macro,
625 so we move the assignment and NULL check into the if-statement. */
626#define GET_KWD(kwd) { \
627 kwd = PyDict_GetItemString(kwds, #kwd); \
628 if (kwd) { \
629 Py_CLEAR(self->kwd); \
630 self->kwd = kwd; \
631 Py_INCREF(self->kwd);\
632 if (PyDict_DelItemString(kwds, #kwd)) \
633 return -1; \
634 } \
635 }
636
637 if (kwds) {
638 GET_KWD(name);
639 GET_KWD(path);
640 }
641
642 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
643 return -1;
644 if (PyTuple_GET_SIZE(args) != 1)
645 return 0;
646 if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
647 return -1;
648
649 Py_CLEAR(self->msg); /* replacing */
650 self->msg = msg;
651 Py_INCREF(self->msg);
652
653 return 0;
654}
655
656static int
657ImportError_clear(PyImportErrorObject *self)
658{
659 Py_CLEAR(self->msg);
660 Py_CLEAR(self->name);
661 Py_CLEAR(self->path);
662 return BaseException_clear((PyBaseExceptionObject *)self);
663}
664
665static void
666ImportError_dealloc(PyImportErrorObject *self)
667{
668 _PyObject_GC_UNTRACK(self);
669 ImportError_clear(self);
670 Py_TYPE(self)->tp_free((PyObject *)self);
671}
672
673static int
674ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
675{
676 Py_VISIT(self->msg);
677 Py_VISIT(self->name);
678 Py_VISIT(self->path);
679 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
680}
681
682static PyObject *
683ImportError_str(PyImportErrorObject *self)
684{
Brett Cannon07c6e712012-08-24 13:05:09 -0400685 if (self->msg && PyUnicode_CheckExact(self->msg)) {
Brett Cannon79ec55e2012-04-12 20:24:54 -0400686 Py_INCREF(self->msg);
687 return self->msg;
688 }
689 else {
690 return BaseException_str((PyBaseExceptionObject *)self);
691 }
692}
693
694static PyMemberDef ImportError_members[] = {
695 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
696 PyDoc_STR("exception message")},
697 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
698 PyDoc_STR("module name")},
699 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
700 PyDoc_STR("module path")},
701 {NULL} /* Sentinel */
702};
703
704static PyMethodDef ImportError_methods[] = {
705 {NULL}
706};
707
708ComplexExtendsException(PyExc_Exception, ImportError,
709 ImportError, 0 /* new */,
710 ImportError_methods, ImportError_members,
711 0 /* getset */, ImportError_str,
712 "Import can't find module, or can't find name in "
713 "module.");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000714
715/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200716 * OSError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717 */
718
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200719#ifdef MS_WINDOWS
720#include "errmap.h"
721#endif
722
Thomas Wouters477c8d52006-05-27 19:21:47 +0000723/* Where a function has a single filename, such as open() or some
724 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
725 * called, giving a third argument which is the filename. But, so
726 * that old code using in-place unpacking doesn't break, e.g.:
727 *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200728 * except OSError, (errno, strerror):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000729 *
730 * we hack args so that it only contains two items. This also
731 * means we need our own __str__() which prints out the filename
732 * when it was supplied.
Larry Hastingsb0827312014-02-09 22:05:19 -0800733 *
734 * (If a function has two filenames, such as rename(), symlink(),
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800735 * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
736 * which allows passing in a second filename.)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000737 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200738
Antoine Pitroue0e27352011-12-15 14:31:28 +0100739/* This function doesn't cleanup on error, the caller should */
740static int
741oserror_parse_args(PyObject **p_args,
742 PyObject **myerrno, PyObject **strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800743 PyObject **filename, PyObject **filename2
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200744#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100745 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200746#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100747 )
748{
749 Py_ssize_t nargs;
750 PyObject *args = *p_args;
Larry Hastingsb0827312014-02-09 22:05:19 -0800751#ifndef MS_WINDOWS
752 /*
753 * ignored on non-Windows platforms,
754 * but parsed so OSError has a consistent signature
755 */
756 PyObject *_winerror = NULL;
757 PyObject **winerror = &_winerror;
758#endif /* MS_WINDOWS */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200760 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761
Larry Hastingsb0827312014-02-09 22:05:19 -0800762 if (nargs >= 2 && nargs <= 5) {
763 if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
764 myerrno, strerror,
765 filename, winerror, filename2))
Antoine Pitroue0e27352011-12-15 14:31:28 +0100766 return -1;
Larry Hastingsb0827312014-02-09 22:05:19 -0800767#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100768 if (*winerror && PyLong_Check(*winerror)) {
769 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200770 PyObject *newargs;
771 Py_ssize_t i;
772
Antoine Pitroue0e27352011-12-15 14:31:28 +0100773 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200774 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100775 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200776 /* Set errno to the corresponding POSIX errno (overriding
777 first argument). Windows Socket error codes (>= 10000)
778 have the same value as their POSIX counterparts.
779 */
780 if (winerrcode < 10000)
781 errcode = winerror_to_errno(winerrcode);
782 else
783 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100784 *myerrno = PyLong_FromLong(errcode);
785 if (!*myerrno)
786 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200787 newargs = PyTuple_New(nargs);
788 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100789 return -1;
790 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200791 for (i = 1; i < nargs; i++) {
792 PyObject *val = PyTuple_GET_ITEM(args, i);
793 Py_INCREF(val);
794 PyTuple_SET_ITEM(newargs, i, val);
795 }
796 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100797 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200798 }
Larry Hastingsb0827312014-02-09 22:05:19 -0800799#endif /* MS_WINDOWS */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200800 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000801
Antoine Pitroue0e27352011-12-15 14:31:28 +0100802 return 0;
803}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000804
Antoine Pitroue0e27352011-12-15 14:31:28 +0100805static int
806oserror_init(PyOSErrorObject *self, PyObject **p_args,
807 PyObject *myerrno, PyObject *strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800808 PyObject *filename, PyObject *filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100809#ifdef MS_WINDOWS
810 , PyObject *winerror
811#endif
812 )
813{
814 PyObject *args = *p_args;
815 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000816
817 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200818 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100819 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200820 PyNumber_Check(filename)) {
821 /* BlockingIOError's 3rd argument can be the number of
822 * characters written.
823 */
824 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
825 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100826 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200827 }
828 else {
829 Py_INCREF(filename);
830 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000831
Larry Hastingsb0827312014-02-09 22:05:19 -0800832 if (filename2 && filename2 != Py_None) {
833 Py_INCREF(filename2);
834 self->filename2 = filename2;
835 }
836
837 if (nargs >= 2 && nargs <= 5) {
838 /* filename, filename2, and winerror are removed from the args tuple
839 (for compatibility purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100840 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200841 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100842 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000843
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200844 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100845 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200846 }
847 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000848 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200849 Py_XINCREF(myerrno);
850 self->myerrno = myerrno;
851
852 Py_XINCREF(strerror);
853 self->strerror = strerror;
854
855#ifdef MS_WINDOWS
856 Py_XINCREF(winerror);
857 self->winerror = winerror;
858#endif
859
Antoine Pitroue0e27352011-12-15 14:31:28 +0100860 /* Steals the reference to args */
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200861 Py_CLEAR(self->args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100862 self->args = args;
Victor Stinner46ef3192013-11-14 22:31:41 +0100863 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100864
865 return 0;
866}
867
868static PyObject *
869OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
870static int
871OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
872
873static int
874oserror_use_init(PyTypeObject *type)
875{
Martin Panter7462b6492015-11-02 03:37:02 +0000876 /* When __init__ is defined in an OSError subclass, we want any
Antoine Pitroue0e27352011-12-15 14:31:28 +0100877 extraneous argument to __new__ to be ignored. The only reasonable
878 solution, given __new__ takes a variable number of arguments,
879 is to defer arg parsing and initialization to __init__.
880
881 But when __new__ is overriden as well, it should call our __new__
882 with the right arguments.
883
884 (see http://bugs.python.org/issue12555#msg148829 )
885 */
886 if (type->tp_init != (initproc) OSError_init &&
887 type->tp_new == (newfunc) OSError_new) {
888 assert((PyObject *) type != PyExc_OSError);
889 return 1;
890 }
891 return 0;
892}
893
894static PyObject *
895OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
896{
897 PyOSErrorObject *self = NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800898 PyObject *myerrno = NULL, *strerror = NULL;
899 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100900#ifdef MS_WINDOWS
901 PyObject *winerror = NULL;
902#endif
903
Victor Stinner46ef3192013-11-14 22:31:41 +0100904 Py_INCREF(args);
905
Antoine Pitroue0e27352011-12-15 14:31:28 +0100906 if (!oserror_use_init(type)) {
907 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100908 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100909
Larry Hastingsb0827312014-02-09 22:05:19 -0800910 if (oserror_parse_args(&args, &myerrno, &strerror,
911 &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100912#ifdef MS_WINDOWS
913 , &winerror
914#endif
915 ))
916 goto error;
917
918 if (myerrno && PyLong_Check(myerrno) &&
919 errnomap && (PyObject *) type == PyExc_OSError) {
920 PyObject *newtype;
921 newtype = PyDict_GetItem(errnomap, myerrno);
922 if (newtype) {
923 assert(PyType_Check(newtype));
924 type = (PyTypeObject *) newtype;
925 }
926 else if (PyErr_Occurred())
927 goto error;
928 }
929 }
930
931 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
932 if (!self)
933 goto error;
934
935 self->dict = NULL;
936 self->traceback = self->cause = self->context = NULL;
937 self->written = -1;
938
939 if (!oserror_use_init(type)) {
Larry Hastingsb0827312014-02-09 22:05:19 -0800940 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100941#ifdef MS_WINDOWS
942 , winerror
943#endif
944 ))
945 goto error;
946 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200947 else {
948 self->args = PyTuple_New(0);
949 if (self->args == NULL)
950 goto error;
951 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100952
Victor Stinner46ef3192013-11-14 22:31:41 +0100953 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200954 return (PyObject *) self;
955
956error:
957 Py_XDECREF(args);
958 Py_XDECREF(self);
959 return NULL;
960}
961
962static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100963OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200964{
Larry Hastingsb0827312014-02-09 22:05:19 -0800965 PyObject *myerrno = NULL, *strerror = NULL;
966 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100967#ifdef MS_WINDOWS
968 PyObject *winerror = NULL;
969#endif
970
971 if (!oserror_use_init(Py_TYPE(self)))
972 /* Everything already done in OSError_new */
973 return 0;
974
975 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
976 return -1;
977
978 Py_INCREF(args);
Larry Hastingsb0827312014-02-09 22:05:19 -0800979 if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100980#ifdef MS_WINDOWS
981 , &winerror
982#endif
983 ))
984 goto error;
985
Larry Hastingsb0827312014-02-09 22:05:19 -0800986 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100987#ifdef MS_WINDOWS
988 , winerror
989#endif
990 ))
991 goto error;
992
Thomas Wouters477c8d52006-05-27 19:21:47 +0000993 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100994
995error:
996 Py_XDECREF(args);
997 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000998}
999
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001000static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001001OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002{
1003 Py_CLEAR(self->myerrno);
1004 Py_CLEAR(self->strerror);
1005 Py_CLEAR(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001006 Py_CLEAR(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001007#ifdef MS_WINDOWS
1008 Py_CLEAR(self->winerror);
1009#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001010 return BaseException_clear((PyBaseExceptionObject *)self);
1011}
1012
1013static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001014OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001015{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001016 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001017 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001018 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001019}
1020
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001021static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001022OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001023 void *arg)
1024{
1025 Py_VISIT(self->myerrno);
1026 Py_VISIT(self->strerror);
1027 Py_VISIT(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001028 Py_VISIT(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001029#ifdef MS_WINDOWS
1030 Py_VISIT(self->winerror);
1031#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001032 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1033}
1034
1035static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001036OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001037{
Larry Hastingsb0827312014-02-09 22:05:19 -08001038#define OR_NONE(x) ((x)?(x):Py_None)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001039#ifdef MS_WINDOWS
1040 /* If available, winerror has the priority over myerrno */
Larry Hastingsb0827312014-02-09 22:05:19 -08001041 if (self->winerror && self->filename) {
1042 if (self->filename2) {
1043 return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
1044 OR_NONE(self->winerror),
1045 OR_NONE(self->strerror),
1046 self->filename,
1047 self->filename2);
1048 } else {
1049 return PyUnicode_FromFormat("[WinError %S] %S: %R",
1050 OR_NONE(self->winerror),
1051 OR_NONE(self->strerror),
1052 self->filename);
1053 }
1054 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001055 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001056 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001057 self->winerror ? self->winerror: Py_None,
1058 self->strerror ? self->strerror: Py_None);
1059#endif
Larry Hastingsb0827312014-02-09 22:05:19 -08001060 if (self->filename) {
1061 if (self->filename2) {
1062 return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
1063 OR_NONE(self->myerrno),
1064 OR_NONE(self->strerror),
1065 self->filename,
1066 self->filename2);
1067 } else {
1068 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1069 OR_NONE(self->myerrno),
1070 OR_NONE(self->strerror),
1071 self->filename);
1072 }
1073 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001074 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001075 return PyUnicode_FromFormat("[Errno %S] %S",
1076 self->myerrno ? self->myerrno: Py_None,
1077 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001078 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079}
1080
Thomas Wouters477c8d52006-05-27 19:21:47 +00001081static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001082OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001083{
1084 PyObject *args = self->args;
1085 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001086
Thomas Wouters477c8d52006-05-27 19:21:47 +00001087 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001088 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001089 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Larry Hastingsb0827312014-02-09 22:05:19 -08001090 Py_ssize_t size = self->filename2 ? 5 : 3;
1091 args = PyTuple_New(size);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001092 if (!args)
1093 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001094
1095 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001096 Py_INCREF(tmp);
1097 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001098
1099 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100 Py_INCREF(tmp);
1101 PyTuple_SET_ITEM(args, 1, tmp);
1102
1103 Py_INCREF(self->filename);
1104 PyTuple_SET_ITEM(args, 2, self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001105
1106 if (self->filename2) {
1107 /*
1108 * This tuple is essentially used as OSError(*args).
1109 * So, to recreate filename2, we need to pass in
1110 * winerror as well.
1111 */
1112 Py_INCREF(Py_None);
1113 PyTuple_SET_ITEM(args, 3, Py_None);
1114
1115 /* filename2 */
1116 Py_INCREF(self->filename2);
1117 PyTuple_SET_ITEM(args, 4, self->filename2);
1118 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001119 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001121
1122 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001123 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001124 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001125 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001126 Py_DECREF(args);
1127 return res;
1128}
1129
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001130static PyObject *
1131OSError_written_get(PyOSErrorObject *self, void *context)
1132{
1133 if (self->written == -1) {
1134 PyErr_SetString(PyExc_AttributeError, "characters_written");
1135 return NULL;
1136 }
1137 return PyLong_FromSsize_t(self->written);
1138}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001139
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001140static int
1141OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1142{
1143 Py_ssize_t n;
1144 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1145 if (n == -1 && PyErr_Occurred())
1146 return -1;
1147 self->written = n;
1148 return 0;
1149}
1150
1151static PyMemberDef OSError_members[] = {
1152 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1153 PyDoc_STR("POSIX exception code")},
1154 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1155 PyDoc_STR("exception strerror")},
1156 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1157 PyDoc_STR("exception filename")},
Larry Hastingsb0827312014-02-09 22:05:19 -08001158 {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
1159 PyDoc_STR("second exception filename")},
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001160#ifdef MS_WINDOWS
1161 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1162 PyDoc_STR("Win32 exception code")},
1163#endif
1164 {NULL} /* Sentinel */
1165};
1166
1167static PyMethodDef OSError_methods[] = {
1168 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001169 {NULL}
1170};
1171
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001172static PyGetSetDef OSError_getset[] = {
1173 {"characters_written", (getter) OSError_written_get,
1174 (setter) OSError_written_set, NULL},
1175 {NULL}
1176};
1177
1178
1179ComplexExtendsException(PyExc_Exception, OSError,
1180 OSError, OSError_new,
1181 OSError_methods, OSError_members, OSError_getset,
1182 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001183 "Base class for I/O related errors.");
1184
1185
1186/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001187 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001188 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001189MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1190 "I/O operation would block.");
1191MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1192 "Connection error.");
1193MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1194 "Child process error.");
1195MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1196 "Broken pipe.");
1197MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1198 "Connection aborted.");
1199MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1200 "Connection refused.");
1201MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1202 "Connection reset.");
1203MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1204 "File already exists.");
1205MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1206 "File not found.");
1207MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1208 "Operation doesn't work on directories.");
1209MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1210 "Operation only works on directories.");
1211MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1212 "Interrupted by signal.");
1213MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1214 "Not enough permissions.");
1215MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1216 "Process not found.");
1217MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1218 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219
1220/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001221 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001222 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001223SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001224 "Read beyond end of file.");
1225
1226
1227/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001228 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001229 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001230SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001231 "Unspecified run-time error.");
1232
Yury Selivanovf488fb42015-07-03 01:04:23 -04001233/*
1234 * RecursionError extends RuntimeError
1235 */
1236SimpleExtendsException(PyExc_RuntimeError, RecursionError,
1237 "Recursion limit exceeded.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001238
1239/*
1240 * NotImplementedError extends RuntimeError
1241 */
1242SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1243 "Method or function hasn't been implemented yet.");
1244
1245/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001246 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001247 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001248SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001249 "Name not found globally.");
1250
1251/*
1252 * UnboundLocalError extends NameError
1253 */
1254SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1255 "Local name referenced but not bound to a value.");
1256
1257/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001258 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001259 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001260SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001261 "Attribute not found.");
1262
1263
1264/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001265 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001266 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001267
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001268/* Helper function to customise error message for some syntax errors */
1269static int _report_missing_parentheses(PySyntaxErrorObject *self);
1270
Thomas Wouters477c8d52006-05-27 19:21:47 +00001271static int
1272SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1273{
1274 PyObject *info = NULL;
1275 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1276
1277 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1278 return -1;
1279
1280 if (lenargs >= 1) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001281 Py_CLEAR(self->msg);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001282 self->msg = PyTuple_GET_ITEM(args, 0);
1283 Py_INCREF(self->msg);
1284 }
1285 if (lenargs == 2) {
1286 info = PyTuple_GET_ITEM(args, 1);
1287 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001288 if (!info)
1289 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001290
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001291 if (PyTuple_GET_SIZE(info) != 4) {
1292 /* not a very good error message, but it's what Python 2.4 gives */
1293 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1294 Py_DECREF(info);
1295 return -1;
1296 }
1297
1298 Py_CLEAR(self->filename);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001299 self->filename = PyTuple_GET_ITEM(info, 0);
1300 Py_INCREF(self->filename);
1301
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001302 Py_CLEAR(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001303 self->lineno = PyTuple_GET_ITEM(info, 1);
1304 Py_INCREF(self->lineno);
1305
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001306 Py_CLEAR(self->offset);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001307 self->offset = PyTuple_GET_ITEM(info, 2);
1308 Py_INCREF(self->offset);
1309
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001310 Py_CLEAR(self->text);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001311 self->text = PyTuple_GET_ITEM(info, 3);
1312 Py_INCREF(self->text);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001313
1314 Py_DECREF(info);
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001315
1316 /* Issue #21669: Custom error for 'print' & 'exec' as statements */
1317 if (self->text && PyUnicode_Check(self->text)) {
1318 if (_report_missing_parentheses(self) < 0) {
1319 return -1;
1320 }
1321 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001322 }
1323 return 0;
1324}
1325
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001326static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001327SyntaxError_clear(PySyntaxErrorObject *self)
1328{
1329 Py_CLEAR(self->msg);
1330 Py_CLEAR(self->filename);
1331 Py_CLEAR(self->lineno);
1332 Py_CLEAR(self->offset);
1333 Py_CLEAR(self->text);
1334 Py_CLEAR(self->print_file_and_line);
1335 return BaseException_clear((PyBaseExceptionObject *)self);
1336}
1337
1338static void
1339SyntaxError_dealloc(PySyntaxErrorObject *self)
1340{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001341 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001342 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001343 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001344}
1345
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001346static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001347SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1348{
1349 Py_VISIT(self->msg);
1350 Py_VISIT(self->filename);
1351 Py_VISIT(self->lineno);
1352 Py_VISIT(self->offset);
1353 Py_VISIT(self->text);
1354 Py_VISIT(self->print_file_and_line);
1355 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1356}
1357
1358/* This is called "my_basename" instead of just "basename" to avoid name
1359 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1360 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001361static PyObject*
1362my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363{
Victor Stinner6237daf2010-04-28 17:26:19 +00001364 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001365 int kind;
1366 void *data;
1367
1368 if (PyUnicode_READY(name))
1369 return NULL;
1370 kind = PyUnicode_KIND(name);
1371 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001372 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001373 offset = 0;
1374 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001375 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001376 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001377 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001378 if (offset != 0)
1379 return PyUnicode_Substring(name, offset, size);
1380 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001381 Py_INCREF(name);
1382 return name;
1383 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001384}
1385
1386
1387static PyObject *
1388SyntaxError_str(PySyntaxErrorObject *self)
1389{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001390 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001391 PyObject *filename;
1392 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001393 /* Below, we always ignore overflow errors, just printing -1.
1394 Still, we cannot allow an OverflowError to be raised, so
1395 we need to call PyLong_AsLongAndOverflow. */
1396 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001397
1398 /* XXX -- do all the additional formatting with filename and
1399 lineno here */
1400
Neal Norwitzed2b7392007-08-26 04:51:10 +00001401 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001402 filename = my_basename(self->filename);
1403 if (filename == NULL)
1404 return NULL;
1405 } else {
1406 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001407 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001408 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001409
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001410 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001411 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001412
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001413 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001414 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001415 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001416 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001418 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001419 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001420 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001421 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001422 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001423 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001424 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001425 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001426 Py_XDECREF(filename);
1427 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001428}
1429
1430static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001431 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1432 PyDoc_STR("exception msg")},
1433 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1434 PyDoc_STR("exception filename")},
1435 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1436 PyDoc_STR("exception lineno")},
1437 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1438 PyDoc_STR("exception offset")},
1439 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1440 PyDoc_STR("exception text")},
1441 {"print_file_and_line", T_OBJECT,
1442 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1443 PyDoc_STR("exception print_file_and_line")},
1444 {NULL} /* Sentinel */
1445};
1446
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001447ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001448 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001449 SyntaxError_str, "Invalid syntax.");
1450
1451
1452/*
1453 * IndentationError extends SyntaxError
1454 */
1455MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1456 "Improper indentation.");
1457
1458
1459/*
1460 * TabError extends IndentationError
1461 */
1462MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1463 "Improper mixture of spaces and tabs.");
1464
1465
1466/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001467 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001468 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001469SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001470 "Base class for lookup errors.");
1471
1472
1473/*
1474 * IndexError extends LookupError
1475 */
1476SimpleExtendsException(PyExc_LookupError, IndexError,
1477 "Sequence index out of range.");
1478
1479
1480/*
1481 * KeyError extends LookupError
1482 */
1483static PyObject *
1484KeyError_str(PyBaseExceptionObject *self)
1485{
1486 /* If args is a tuple of exactly one item, apply repr to args[0].
1487 This is done so that e.g. the exception raised by {}[''] prints
1488 KeyError: ''
1489 rather than the confusing
1490 KeyError
1491 alone. The downside is that if KeyError is raised with an explanatory
1492 string, that string will be displayed in quotes. Too bad.
1493 If args is anything else, use the default BaseException__str__().
1494 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001495 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001496 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001497 }
1498 return BaseException_str(self);
1499}
1500
1501ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001502 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001503
1504
1505/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001506 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001507 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001508SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001509 "Inappropriate argument value (of correct type).");
1510
1511/*
1512 * UnicodeError extends ValueError
1513 */
1514
1515SimpleExtendsException(PyExc_ValueError, UnicodeError,
1516 "Unicode related error.");
1517
Thomas Wouters477c8d52006-05-27 19:21:47 +00001518static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001519get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001520{
1521 if (!attr) {
1522 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1523 return NULL;
1524 }
1525
Christian Heimes72b710a2008-05-26 13:28:38 +00001526 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001527 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1528 return NULL;
1529 }
1530 Py_INCREF(attr);
1531 return attr;
1532}
1533
1534static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001535get_unicode(PyObject *attr, const char *name)
1536{
1537 if (!attr) {
1538 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1539 return NULL;
1540 }
1541
1542 if (!PyUnicode_Check(attr)) {
1543 PyErr_Format(PyExc_TypeError,
1544 "%.200s attribute must be unicode", name);
1545 return NULL;
1546 }
1547 Py_INCREF(attr);
1548 return attr;
1549}
1550
Walter Dörwaldd2034312007-05-18 16:29:38 +00001551static int
1552set_unicodefromstring(PyObject **attr, const char *value)
1553{
1554 PyObject *obj = PyUnicode_FromString(value);
1555 if (!obj)
1556 return -1;
1557 Py_CLEAR(*attr);
1558 *attr = obj;
1559 return 0;
1560}
1561
Thomas Wouters477c8d52006-05-27 19:21:47 +00001562PyObject *
1563PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1564{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001565 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001566}
1567
1568PyObject *
1569PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1570{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001571 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001572}
1573
1574PyObject *
1575PyUnicodeEncodeError_GetObject(PyObject *exc)
1576{
1577 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1578}
1579
1580PyObject *
1581PyUnicodeDecodeError_GetObject(PyObject *exc)
1582{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001583 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584}
1585
1586PyObject *
1587PyUnicodeTranslateError_GetObject(PyObject *exc)
1588{
1589 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1590}
1591
1592int
1593PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1594{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001595 Py_ssize_t size;
1596 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1597 "object");
1598 if (!obj)
1599 return -1;
1600 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001601 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001602 if (*start<0)
1603 *start = 0; /*XXX check for values <0*/
1604 if (*start>=size)
1605 *start = size-1;
1606 Py_DECREF(obj);
1607 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001608}
1609
1610
1611int
1612PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1613{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001614 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001615 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001616 if (!obj)
1617 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001618 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001619 *start = ((PyUnicodeErrorObject *)exc)->start;
1620 if (*start<0)
1621 *start = 0;
1622 if (*start>=size)
1623 *start = size-1;
1624 Py_DECREF(obj);
1625 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001626}
1627
1628
1629int
1630PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1631{
1632 return PyUnicodeEncodeError_GetStart(exc, start);
1633}
1634
1635
1636int
1637PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1638{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001639 ((PyUnicodeErrorObject *)exc)->start = start;
1640 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001641}
1642
1643
1644int
1645PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1646{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001647 ((PyUnicodeErrorObject *)exc)->start = start;
1648 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001649}
1650
1651
1652int
1653PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1654{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001655 ((PyUnicodeErrorObject *)exc)->start = start;
1656 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001657}
1658
1659
1660int
1661PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1662{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001663 Py_ssize_t size;
1664 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1665 "object");
1666 if (!obj)
1667 return -1;
1668 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001669 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001670 if (*end<1)
1671 *end = 1;
1672 if (*end>size)
1673 *end = size;
1674 Py_DECREF(obj);
1675 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001676}
1677
1678
1679int
1680PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1681{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001682 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001683 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001684 if (!obj)
1685 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001686 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001687 *end = ((PyUnicodeErrorObject *)exc)->end;
1688 if (*end<1)
1689 *end = 1;
1690 if (*end>size)
1691 *end = size;
1692 Py_DECREF(obj);
1693 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001694}
1695
1696
1697int
1698PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1699{
1700 return PyUnicodeEncodeError_GetEnd(exc, start);
1701}
1702
1703
1704int
1705PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1706{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001707 ((PyUnicodeErrorObject *)exc)->end = end;
1708 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001709}
1710
1711
1712int
1713PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1714{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001715 ((PyUnicodeErrorObject *)exc)->end = end;
1716 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001717}
1718
1719
1720int
1721PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1722{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001723 ((PyUnicodeErrorObject *)exc)->end = end;
1724 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001725}
1726
1727PyObject *
1728PyUnicodeEncodeError_GetReason(PyObject *exc)
1729{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001730 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001731}
1732
1733
1734PyObject *
1735PyUnicodeDecodeError_GetReason(PyObject *exc)
1736{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001737 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001738}
1739
1740
1741PyObject *
1742PyUnicodeTranslateError_GetReason(PyObject *exc)
1743{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001744 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001745}
1746
1747
1748int
1749PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1750{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001751 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1752 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001753}
1754
1755
1756int
1757PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1758{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001759 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1760 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001761}
1762
1763
1764int
1765PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1766{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001767 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1768 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001769}
1770
1771
Thomas Wouters477c8d52006-05-27 19:21:47 +00001772static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001773UnicodeError_clear(PyUnicodeErrorObject *self)
1774{
1775 Py_CLEAR(self->encoding);
1776 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001777 Py_CLEAR(self->reason);
1778 return BaseException_clear((PyBaseExceptionObject *)self);
1779}
1780
1781static void
1782UnicodeError_dealloc(PyUnicodeErrorObject *self)
1783{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001784 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001785 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001786 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001787}
1788
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001789static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001790UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1791{
1792 Py_VISIT(self->encoding);
1793 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001794 Py_VISIT(self->reason);
1795 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1796}
1797
1798static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001799 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1800 PyDoc_STR("exception encoding")},
1801 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1802 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001803 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001804 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001805 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001806 PyDoc_STR("exception end")},
1807 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1808 PyDoc_STR("exception reason")},
1809 {NULL} /* Sentinel */
1810};
1811
1812
1813/*
1814 * UnicodeEncodeError extends UnicodeError
1815 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001816
1817static int
1818UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1819{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001820 PyUnicodeErrorObject *err;
1821
Thomas Wouters477c8d52006-05-27 19:21:47 +00001822 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1823 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001824
1825 err = (PyUnicodeErrorObject *)self;
1826
1827 Py_CLEAR(err->encoding);
1828 Py_CLEAR(err->object);
1829 Py_CLEAR(err->reason);
1830
1831 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1832 &PyUnicode_Type, &err->encoding,
1833 &PyUnicode_Type, &err->object,
1834 &err->start,
1835 &err->end,
1836 &PyUnicode_Type, &err->reason)) {
1837 err->encoding = err->object = err->reason = NULL;
1838 return -1;
1839 }
1840
Martin v. Löwisb09af032011-11-04 11:16:41 +01001841 if (PyUnicode_READY(err->object) < -1) {
1842 err->encoding = NULL;
1843 return -1;
1844 }
1845
Guido van Rossum98297ee2007-11-06 21:34:58 +00001846 Py_INCREF(err->encoding);
1847 Py_INCREF(err->object);
1848 Py_INCREF(err->reason);
1849
1850 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001851}
1852
1853static PyObject *
1854UnicodeEncodeError_str(PyObject *self)
1855{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001856 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001857 PyObject *result = NULL;
1858 PyObject *reason_str = NULL;
1859 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001860
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001861 if (!uself->object)
1862 /* Not properly initialized. */
1863 return PyUnicode_FromString("");
1864
Eric Smith0facd772010-02-24 15:42:29 +00001865 /* Get reason and encoding as strings, which they might not be if
1866 they've been modified after we were contructed. */
1867 reason_str = PyObject_Str(uself->reason);
1868 if (reason_str == NULL)
1869 goto done;
1870 encoding_str = PyObject_Str(uself->encoding);
1871 if (encoding_str == NULL)
1872 goto done;
1873
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001874 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1875 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001876 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001877 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001878 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001879 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001880 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001881 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001882 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001883 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001884 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001885 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001886 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001887 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001888 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001889 }
Eric Smith0facd772010-02-24 15:42:29 +00001890 else {
1891 result = PyUnicode_FromFormat(
1892 "'%U' codec can't encode characters in position %zd-%zd: %U",
1893 encoding_str,
1894 uself->start,
1895 uself->end-1,
1896 reason_str);
1897 }
1898done:
1899 Py_XDECREF(reason_str);
1900 Py_XDECREF(encoding_str);
1901 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001902}
1903
1904static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001905 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001906 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001907 sizeof(PyUnicodeErrorObject), 0,
1908 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1909 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1910 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001911 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1912 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001913 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001914 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001915};
1916PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1917
1918PyObject *
1919PyUnicodeEncodeError_Create(
1920 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1921 Py_ssize_t start, Py_ssize_t end, const char *reason)
1922{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001923 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001924 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001925}
1926
1927
1928/*
1929 * UnicodeDecodeError extends UnicodeError
1930 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001931
1932static int
1933UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1934{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001935 PyUnicodeErrorObject *ude;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001936
Thomas Wouters477c8d52006-05-27 19:21:47 +00001937 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1938 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001939
1940 ude = (PyUnicodeErrorObject *)self;
1941
1942 Py_CLEAR(ude->encoding);
1943 Py_CLEAR(ude->object);
1944 Py_CLEAR(ude->reason);
1945
1946 if (!PyArg_ParseTuple(args, "O!OnnO!",
1947 &PyUnicode_Type, &ude->encoding,
1948 &ude->object,
1949 &ude->start,
1950 &ude->end,
1951 &PyUnicode_Type, &ude->reason)) {
1952 ude->encoding = ude->object = ude->reason = NULL;
1953 return -1;
1954 }
1955
Guido van Rossum98297ee2007-11-06 21:34:58 +00001956 Py_INCREF(ude->encoding);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001957 Py_INCREF(ude->object);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001958 Py_INCREF(ude->reason);
1959
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001960 if (!PyBytes_Check(ude->object)) {
1961 Py_buffer view;
1962 if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
1963 goto error;
1964 Py_CLEAR(ude->object);
1965 ude->object = PyBytes_FromStringAndSize(view.buf, view.len);
1966 PyBuffer_Release(&view);
1967 if (!ude->object)
1968 goto error;
1969 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001970 return 0;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001971
1972error:
1973 Py_CLEAR(ude->encoding);
1974 Py_CLEAR(ude->object);
1975 Py_CLEAR(ude->reason);
1976 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001977}
1978
1979static PyObject *
1980UnicodeDecodeError_str(PyObject *self)
1981{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001982 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001983 PyObject *result = NULL;
1984 PyObject *reason_str = NULL;
1985 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001986
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001987 if (!uself->object)
1988 /* Not properly initialized. */
1989 return PyUnicode_FromString("");
1990
Eric Smith0facd772010-02-24 15:42:29 +00001991 /* Get reason and encoding as strings, which they might not be if
1992 they've been modified after we were contructed. */
1993 reason_str = PyObject_Str(uself->reason);
1994 if (reason_str == NULL)
1995 goto done;
1996 encoding_str = PyObject_Str(uself->encoding);
1997 if (encoding_str == NULL)
1998 goto done;
1999
2000 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00002001 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00002002 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002003 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00002004 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002005 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002006 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002007 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002008 }
Eric Smith0facd772010-02-24 15:42:29 +00002009 else {
2010 result = PyUnicode_FromFormat(
2011 "'%U' codec can't decode bytes in position %zd-%zd: %U",
2012 encoding_str,
2013 uself->start,
2014 uself->end-1,
2015 reason_str
2016 );
2017 }
2018done:
2019 Py_XDECREF(reason_str);
2020 Py_XDECREF(encoding_str);
2021 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002022}
2023
2024static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002025 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002026 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002027 sizeof(PyUnicodeErrorObject), 0,
2028 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2029 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
2030 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002031 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
2032 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002033 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002034 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002035};
2036PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
2037
2038PyObject *
2039PyUnicodeDecodeError_Create(
2040 const char *encoding, const char *object, Py_ssize_t length,
2041 Py_ssize_t start, Py_ssize_t end, const char *reason)
2042{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00002043 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002044 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002045}
2046
2047
2048/*
2049 * UnicodeTranslateError extends UnicodeError
2050 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002051
2052static int
2053UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
2054 PyObject *kwds)
2055{
2056 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2057 return -1;
2058
2059 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002060 Py_CLEAR(self->reason);
2061
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002062 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002063 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002064 &self->start,
2065 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00002066 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002067 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002068 return -1;
2069 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002070
Thomas Wouters477c8d52006-05-27 19:21:47 +00002071 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002072 Py_INCREF(self->reason);
2073
2074 return 0;
2075}
2076
2077
2078static PyObject *
2079UnicodeTranslateError_str(PyObject *self)
2080{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002081 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00002082 PyObject *result = NULL;
2083 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002084
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04002085 if (!uself->object)
2086 /* Not properly initialized. */
2087 return PyUnicode_FromString("");
2088
Eric Smith0facd772010-02-24 15:42:29 +00002089 /* Get reason as a string, which it might not be if it's been
2090 modified after we were contructed. */
2091 reason_str = PyObject_Str(uself->reason);
2092 if (reason_str == NULL)
2093 goto done;
2094
Victor Stinner53b33e72011-11-21 01:17:27 +01002095 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2096 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002097 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002098 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002099 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002100 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002101 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002102 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002103 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002104 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002105 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002106 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002107 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002108 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002109 );
Eric Smith0facd772010-02-24 15:42:29 +00002110 } else {
2111 result = PyUnicode_FromFormat(
2112 "can't translate characters in position %zd-%zd: %U",
2113 uself->start,
2114 uself->end-1,
2115 reason_str
2116 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002117 }
Eric Smith0facd772010-02-24 15:42:29 +00002118done:
2119 Py_XDECREF(reason_str);
2120 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002121}
2122
2123static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002124 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002125 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002126 sizeof(PyUnicodeErrorObject), 0,
2127 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2128 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2129 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002130 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002131 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2132 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002133 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002134};
2135PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002137/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002138PyObject *
2139PyUnicodeTranslateError_Create(
2140 const Py_UNICODE *object, Py_ssize_t length,
2141 Py_ssize_t start, Py_ssize_t end, const char *reason)
2142{
2143 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002144 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002145}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002147PyObject *
2148_PyUnicodeTranslateError_Create(
2149 PyObject *object,
2150 Py_ssize_t start, Py_ssize_t end, const char *reason)
2151{
Victor Stinner69598d4c2014-04-04 20:59:44 +02002152 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002153 object, start, end, reason);
2154}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002155
2156/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002157 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002158 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002159SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002160 "Assertion failed.");
2161
2162
2163/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002164 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002165 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002166SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002167 "Base class for arithmetic errors.");
2168
2169
2170/*
2171 * FloatingPointError extends ArithmeticError
2172 */
2173SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2174 "Floating point operation failed.");
2175
2176
2177/*
2178 * OverflowError extends ArithmeticError
2179 */
2180SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2181 "Result too large to be represented.");
2182
2183
2184/*
2185 * ZeroDivisionError extends ArithmeticError
2186 */
2187SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2188 "Second argument to a division or modulo operation was zero.");
2189
2190
2191/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002192 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002193 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002194SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002195 "Internal error in the Python interpreter.\n"
2196 "\n"
2197 "Please report this to the Python maintainer, along with the traceback,\n"
2198 "the Python version, and the hardware/OS platform and version.");
2199
2200
2201/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002202 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002203 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002204SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002205 "Weak ref proxy used after referent went away.");
2206
2207
2208/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002209 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002210 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002211
2212#define MEMERRORS_SAVE 16
2213static PyBaseExceptionObject *memerrors_freelist = NULL;
2214static int memerrors_numfree = 0;
2215
2216static PyObject *
2217MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2218{
2219 PyBaseExceptionObject *self;
2220
2221 if (type != (PyTypeObject *) PyExc_MemoryError)
2222 return BaseException_new(type, args, kwds);
2223 if (memerrors_freelist == NULL)
2224 return BaseException_new(type, args, kwds);
2225 /* Fetch object from freelist and revive it */
2226 self = memerrors_freelist;
2227 self->args = PyTuple_New(0);
2228 /* This shouldn't happen since the empty tuple is persistent */
2229 if (self->args == NULL)
2230 return NULL;
2231 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2232 memerrors_numfree--;
2233 self->dict = NULL;
2234 _Py_NewReference((PyObject *)self);
2235 _PyObject_GC_TRACK(self);
2236 return (PyObject *)self;
2237}
2238
2239static void
2240MemoryError_dealloc(PyBaseExceptionObject *self)
2241{
2242 _PyObject_GC_UNTRACK(self);
2243 BaseException_clear(self);
2244 if (memerrors_numfree >= MEMERRORS_SAVE)
2245 Py_TYPE(self)->tp_free((PyObject *)self);
2246 else {
2247 self->dict = (PyObject *) memerrors_freelist;
2248 memerrors_freelist = self;
2249 memerrors_numfree++;
2250 }
2251}
2252
2253static void
2254preallocate_memerrors(void)
2255{
2256 /* We create enough MemoryErrors and then decref them, which will fill
2257 up the freelist. */
2258 int i;
2259 PyObject *errors[MEMERRORS_SAVE];
2260 for (i = 0; i < MEMERRORS_SAVE; i++) {
2261 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2262 NULL, NULL);
2263 if (!errors[i])
2264 Py_FatalError("Could not preallocate MemoryError object");
2265 }
2266 for (i = 0; i < MEMERRORS_SAVE; i++) {
2267 Py_DECREF(errors[i]);
2268 }
2269}
2270
2271static void
2272free_preallocated_memerrors(void)
2273{
2274 while (memerrors_freelist != NULL) {
2275 PyObject *self = (PyObject *) memerrors_freelist;
2276 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2277 Py_TYPE(self)->tp_free((PyObject *)self);
2278 }
2279}
2280
2281
2282static PyTypeObject _PyExc_MemoryError = {
2283 PyVarObject_HEAD_INIT(NULL, 0)
2284 "MemoryError",
2285 sizeof(PyBaseExceptionObject),
2286 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2287 0, 0, 0, 0, 0, 0, 0,
2288 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2289 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2290 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2291 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2292 (initproc)BaseException_init, 0, MemoryError_new
2293};
2294PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2295
Thomas Wouters477c8d52006-05-27 19:21:47 +00002296
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002297/*
2298 * BufferError extends Exception
2299 */
2300SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2301
Thomas Wouters477c8d52006-05-27 19:21:47 +00002302
2303/* Warning category docstrings */
2304
2305/*
2306 * Warning extends Exception
2307 */
2308SimpleExtendsException(PyExc_Exception, Warning,
2309 "Base class for warning categories.");
2310
2311
2312/*
2313 * UserWarning extends Warning
2314 */
2315SimpleExtendsException(PyExc_Warning, UserWarning,
2316 "Base class for warnings generated by user code.");
2317
2318
2319/*
2320 * DeprecationWarning extends Warning
2321 */
2322SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2323 "Base class for warnings about deprecated features.");
2324
2325
2326/*
2327 * PendingDeprecationWarning extends Warning
2328 */
2329SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2330 "Base class for warnings about features which will be deprecated\n"
2331 "in the future.");
2332
2333
2334/*
2335 * SyntaxWarning extends Warning
2336 */
2337SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2338 "Base class for warnings about dubious syntax.");
2339
2340
2341/*
2342 * RuntimeWarning extends Warning
2343 */
2344SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2345 "Base class for warnings about dubious runtime behavior.");
2346
2347
2348/*
2349 * FutureWarning extends Warning
2350 */
2351SimpleExtendsException(PyExc_Warning, FutureWarning,
2352 "Base class for warnings about constructs that will change semantically\n"
2353 "in the future.");
2354
2355
2356/*
2357 * ImportWarning extends Warning
2358 */
2359SimpleExtendsException(PyExc_Warning, ImportWarning,
2360 "Base class for warnings about probable mistakes in module imports");
2361
2362
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002363/*
2364 * UnicodeWarning extends Warning
2365 */
2366SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2367 "Base class for warnings about Unicode related problems, mostly\n"
2368 "related to conversion problems.");
2369
Georg Brandl08be72d2010-10-24 15:11:22 +00002370
Guido van Rossum98297ee2007-11-06 21:34:58 +00002371/*
2372 * BytesWarning extends Warning
2373 */
2374SimpleExtendsException(PyExc_Warning, BytesWarning,
2375 "Base class for warnings about bytes and buffer related problems, mostly\n"
2376 "related to conversion from str or comparing to str.");
2377
2378
Georg Brandl08be72d2010-10-24 15:11:22 +00002379/*
2380 * ResourceWarning extends Warning
2381 */
2382SimpleExtendsException(PyExc_Warning, ResourceWarning,
2383 "Base class for warnings about resource usage.");
2384
2385
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002386
Yury Selivanovf488fb42015-07-03 01:04:23 -04002387/* Pre-computed RecursionError instance for when recursion depth is reached.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002388 Meant to be used when normalizing the exception for exceeding the recursion
2389 depth will cause its own infinite recursion.
2390*/
2391PyObject *PyExc_RecursionErrorInst = NULL;
2392
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002393#define PRE_INIT(TYPE) \
2394 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2395 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2396 Py_FatalError("exceptions bootstrapping error."); \
2397 Py_INCREF(PyExc_ ## TYPE); \
2398 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002399
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002400#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002401 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2402 Py_FatalError("Module dictionary insertion problem.");
2403
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002404#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002405 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002406 PyExc_ ## NAME = PyExc_ ## TYPE; \
2407 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2408 Py_FatalError("Module dictionary insertion problem.");
2409
2410#define ADD_ERRNO(TYPE, CODE) { \
2411 PyObject *_code = PyLong_FromLong(CODE); \
2412 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2413 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2414 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002415 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002416 }
2417
2418#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002419#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002420/* The following constants were added to errno.h in VS2010 but have
2421 preferred WSA equivalents. */
2422#undef EADDRINUSE
2423#undef EADDRNOTAVAIL
2424#undef EAFNOSUPPORT
2425#undef EALREADY
2426#undef ECONNABORTED
2427#undef ECONNREFUSED
2428#undef ECONNRESET
2429#undef EDESTADDRREQ
2430#undef EHOSTUNREACH
2431#undef EINPROGRESS
2432#undef EISCONN
2433#undef ELOOP
2434#undef EMSGSIZE
2435#undef ENETDOWN
2436#undef ENETRESET
2437#undef ENETUNREACH
2438#undef ENOBUFS
2439#undef ENOPROTOOPT
2440#undef ENOTCONN
2441#undef ENOTSOCK
2442#undef EOPNOTSUPP
2443#undef EPROTONOSUPPORT
2444#undef EPROTOTYPE
2445#undef ETIMEDOUT
2446#undef EWOULDBLOCK
2447
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002448#if defined(WSAEALREADY) && !defined(EALREADY)
2449#define EALREADY WSAEALREADY
2450#endif
2451#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2452#define ECONNABORTED WSAECONNABORTED
2453#endif
2454#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2455#define ECONNREFUSED WSAECONNREFUSED
2456#endif
2457#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2458#define ECONNRESET WSAECONNRESET
2459#endif
2460#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2461#define EINPROGRESS WSAEINPROGRESS
2462#endif
2463#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2464#define ESHUTDOWN WSAESHUTDOWN
2465#endif
2466#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2467#define ETIMEDOUT WSAETIMEDOUT
2468#endif
2469#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2470#define EWOULDBLOCK WSAEWOULDBLOCK
2471#endif
2472#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002473
Martin v. Löwis1a214512008-06-11 05:26:20 +00002474void
Brett Cannonfd074152012-04-14 14:10:13 -04002475_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002476{
Brett Cannonfd074152012-04-14 14:10:13 -04002477 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002478
2479 PRE_INIT(BaseException)
2480 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002481 PRE_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002482 PRE_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002483 PRE_INIT(StopIteration)
2484 PRE_INIT(GeneratorExit)
2485 PRE_INIT(SystemExit)
2486 PRE_INIT(KeyboardInterrupt)
2487 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002488 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002489 PRE_INIT(EOFError)
2490 PRE_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002491 PRE_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002492 PRE_INIT(NotImplementedError)
2493 PRE_INIT(NameError)
2494 PRE_INIT(UnboundLocalError)
2495 PRE_INIT(AttributeError)
2496 PRE_INIT(SyntaxError)
2497 PRE_INIT(IndentationError)
2498 PRE_INIT(TabError)
2499 PRE_INIT(LookupError)
2500 PRE_INIT(IndexError)
2501 PRE_INIT(KeyError)
2502 PRE_INIT(ValueError)
2503 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002504 PRE_INIT(UnicodeEncodeError)
2505 PRE_INIT(UnicodeDecodeError)
2506 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002507 PRE_INIT(AssertionError)
2508 PRE_INIT(ArithmeticError)
2509 PRE_INIT(FloatingPointError)
2510 PRE_INIT(OverflowError)
2511 PRE_INIT(ZeroDivisionError)
2512 PRE_INIT(SystemError)
2513 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002514 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002515 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002516 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002517 PRE_INIT(Warning)
2518 PRE_INIT(UserWarning)
2519 PRE_INIT(DeprecationWarning)
2520 PRE_INIT(PendingDeprecationWarning)
2521 PRE_INIT(SyntaxWarning)
2522 PRE_INIT(RuntimeWarning)
2523 PRE_INIT(FutureWarning)
2524 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002525 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002526 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002527 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002528
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002529 /* OSError subclasses */
2530 PRE_INIT(ConnectionError);
2531
2532 PRE_INIT(BlockingIOError);
2533 PRE_INIT(BrokenPipeError);
2534 PRE_INIT(ChildProcessError);
2535 PRE_INIT(ConnectionAbortedError);
2536 PRE_INIT(ConnectionRefusedError);
2537 PRE_INIT(ConnectionResetError);
2538 PRE_INIT(FileExistsError);
2539 PRE_INIT(FileNotFoundError);
2540 PRE_INIT(IsADirectoryError);
2541 PRE_INIT(NotADirectoryError);
2542 PRE_INIT(InterruptedError);
2543 PRE_INIT(PermissionError);
2544 PRE_INIT(ProcessLookupError);
2545 PRE_INIT(TimeoutError);
2546
Thomas Wouters477c8d52006-05-27 19:21:47 +00002547 bdict = PyModule_GetDict(bltinmod);
2548 if (bdict == NULL)
2549 Py_FatalError("exceptions bootstrapping error.");
2550
2551 POST_INIT(BaseException)
2552 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002553 POST_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002554 POST_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002555 POST_INIT(StopIteration)
2556 POST_INIT(GeneratorExit)
2557 POST_INIT(SystemExit)
2558 POST_INIT(KeyboardInterrupt)
2559 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002560 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002561 INIT_ALIAS(EnvironmentError, OSError)
2562 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002563#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002564 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002565#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00002566 POST_INIT(EOFError)
2567 POST_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002568 POST_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002569 POST_INIT(NotImplementedError)
2570 POST_INIT(NameError)
2571 POST_INIT(UnboundLocalError)
2572 POST_INIT(AttributeError)
2573 POST_INIT(SyntaxError)
2574 POST_INIT(IndentationError)
2575 POST_INIT(TabError)
2576 POST_INIT(LookupError)
2577 POST_INIT(IndexError)
2578 POST_INIT(KeyError)
2579 POST_INIT(ValueError)
2580 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002581 POST_INIT(UnicodeEncodeError)
2582 POST_INIT(UnicodeDecodeError)
2583 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002584 POST_INIT(AssertionError)
2585 POST_INIT(ArithmeticError)
2586 POST_INIT(FloatingPointError)
2587 POST_INIT(OverflowError)
2588 POST_INIT(ZeroDivisionError)
2589 POST_INIT(SystemError)
2590 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002591 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002592 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002593 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002594 POST_INIT(Warning)
2595 POST_INIT(UserWarning)
2596 POST_INIT(DeprecationWarning)
2597 POST_INIT(PendingDeprecationWarning)
2598 POST_INIT(SyntaxWarning)
2599 POST_INIT(RuntimeWarning)
2600 POST_INIT(FutureWarning)
2601 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002602 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002603 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002604 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002605
Antoine Pitrouac456a12012-01-18 21:35:21 +01002606 if (!errnomap) {
2607 errnomap = PyDict_New();
2608 if (!errnomap)
2609 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2610 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002611
2612 /* OSError subclasses */
2613 POST_INIT(ConnectionError);
2614
2615 POST_INIT(BlockingIOError);
2616 ADD_ERRNO(BlockingIOError, EAGAIN);
2617 ADD_ERRNO(BlockingIOError, EALREADY);
2618 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2619 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2620 POST_INIT(BrokenPipeError);
2621 ADD_ERRNO(BrokenPipeError, EPIPE);
2622 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2623 POST_INIT(ChildProcessError);
2624 ADD_ERRNO(ChildProcessError, ECHILD);
2625 POST_INIT(ConnectionAbortedError);
2626 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2627 POST_INIT(ConnectionRefusedError);
2628 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2629 POST_INIT(ConnectionResetError);
2630 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2631 POST_INIT(FileExistsError);
2632 ADD_ERRNO(FileExistsError, EEXIST);
2633 POST_INIT(FileNotFoundError);
2634 ADD_ERRNO(FileNotFoundError, ENOENT);
2635 POST_INIT(IsADirectoryError);
2636 ADD_ERRNO(IsADirectoryError, EISDIR);
2637 POST_INIT(NotADirectoryError);
2638 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2639 POST_INIT(InterruptedError);
2640 ADD_ERRNO(InterruptedError, EINTR);
2641 POST_INIT(PermissionError);
2642 ADD_ERRNO(PermissionError, EACCES);
2643 ADD_ERRNO(PermissionError, EPERM);
2644 POST_INIT(ProcessLookupError);
2645 ADD_ERRNO(ProcessLookupError, ESRCH);
2646 POST_INIT(TimeoutError);
2647 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2648
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002649 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002650
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002651 if (!PyExc_RecursionErrorInst) {
Yury Selivanovf488fb42015-07-03 01:04:23 -04002652 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RecursionError, NULL, NULL);
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002653 if (!PyExc_RecursionErrorInst)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002654 Py_FatalError("Cannot pre-allocate RecursionError instance for "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002655 "recursion errors");
2656 else {
2657 PyBaseExceptionObject *err_inst =
2658 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2659 PyObject *args_tuple;
2660 PyObject *exc_message;
2661 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2662 if (!exc_message)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002663 Py_FatalError("cannot allocate argument for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002664 "pre-allocation");
2665 args_tuple = PyTuple_Pack(1, exc_message);
2666 if (!args_tuple)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002667 Py_FatalError("cannot allocate tuple for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002668 "pre-allocation");
2669 Py_DECREF(exc_message);
2670 if (BaseException_init(err_inst, args_tuple, NULL))
Yury Selivanovf488fb42015-07-03 01:04:23 -04002671 Py_FatalError("init of pre-allocated RecursionError failed");
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002672 Py_DECREF(args_tuple);
2673 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002674 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002675}
2676
2677void
2678_PyExc_Fini(void)
2679{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002680 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002681 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002682 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002683}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002684
2685/* Helper to do the equivalent of "raise X from Y" in C, but always using
2686 * the current exception rather than passing one in.
2687 *
2688 * We currently limit this to *only* exceptions that use the BaseException
2689 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2690 * those correctly without losing data and without losing backwards
2691 * compatibility.
2692 *
2693 * We also aim to rule out *all* exceptions that might be storing additional
2694 * state, whether by having a size difference relative to BaseException,
2695 * additional arguments passed in during construction or by having a
2696 * non-empty instance dict.
2697 *
2698 * We need to be very careful with what we wrap, since changing types to
2699 * a broader exception type would be backwards incompatible for
2700 * existing codecs, and with different init or new method implementations
2701 * may either not support instantiation with PyErr_Format or lose
2702 * information when instantiated that way.
2703 *
2704 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2705 * fact that exceptions are expected to support pickling. If more builtin
2706 * exceptions (e.g. AttributeError) start to be converted to rich
2707 * exceptions with additional attributes, that's probably a better approach
2708 * to pursue over adding special cases for particular stateful subclasses.
2709 *
2710 * Returns a borrowed reference to the new exception (if any), NULL if the
2711 * existing exception was left in place.
2712 */
2713PyObject *
2714_PyErr_TrySetFromCause(const char *format, ...)
2715{
2716 PyObject* msg_prefix;
2717 PyObject *exc, *val, *tb;
2718 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002719 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002720 PyObject *instance_args;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002721 Py_ssize_t num_args, caught_type_size, base_exc_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002722 PyObject *new_exc, *new_val, *new_tb;
2723 va_list vargs;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002724 int same_basic_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002725
Nick Coghlan8b097b42013-11-13 23:49:21 +10002726 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002727 caught_type = (PyTypeObject *)exc;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002728 /* Ensure type info indicates no extra state is stored at the C level
2729 * and that the type can be reinstantiated using PyErr_Format
2730 */
2731 caught_type_size = caught_type->tp_basicsize;
2732 base_exc_size = _PyExc_BaseException.tp_basicsize;
2733 same_basic_size = (
2734 caught_type_size == base_exc_size ||
2735 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
Victor Stinner12174a52014-08-15 23:17:38 +02002736 (caught_type_size == base_exc_size + (Py_ssize_t)sizeof(PyObject *))
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002737 )
2738 );
Benjamin Peterson079c9982013-11-13 23:25:01 -05002739 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002740 caught_type->tp_new != BaseException_new ||
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002741 !same_basic_size ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002742 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002743 /* We can't be sure we can wrap this safely, since it may contain
2744 * more state than just the exception type. Accordingly, we just
2745 * leave it alone.
2746 */
2747 PyErr_Restore(exc, val, tb);
2748 return NULL;
2749 }
2750
2751 /* Check the args are empty or contain a single string */
2752 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002753 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002754 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002755 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002756 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002757 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002758 /* More than 1 arg, or the one arg we do have isn't a string
2759 */
2760 PyErr_Restore(exc, val, tb);
2761 return NULL;
2762 }
2763
2764 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002765 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002766 if (dictptr != NULL && *dictptr != NULL &&
2767 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002768 /* While we could potentially copy a non-empty instance dictionary
2769 * to the replacement exception, for now we take the more
2770 * conservative path of leaving exceptions with attributes set
2771 * alone.
2772 */
2773 PyErr_Restore(exc, val, tb);
2774 return NULL;
2775 }
2776
2777 /* For exceptions that we can wrap safely, we chain the original
2778 * exception to a new one of the exact same type with an
2779 * error message that mentions the additional details and the
2780 * original exception.
2781 *
2782 * It would be nice to wrap OSError and various other exception
2783 * types as well, but that's quite a bit trickier due to the extra
2784 * state potentially stored on OSError instances.
2785 */
Nick Coghlan77b286b2014-01-27 00:53:38 +10002786 /* Ensure the traceback is set correctly on the existing exception */
2787 if (tb != NULL) {
2788 PyException_SetTraceback(val, tb);
2789 Py_DECREF(tb);
2790 }
Benjamin Petersone109ee82013-11-13 23:49:49 -05002791
Christian Heimes507eabd2013-11-14 01:39:35 +01002792#ifdef HAVE_STDARG_PROTOTYPES
2793 va_start(vargs, format);
2794#else
2795 va_start(vargs);
2796#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002797 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002798 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002799 if (msg_prefix == NULL) {
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002800 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002801 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002802 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002803 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002804
2805 PyErr_Format(exc, "%U (%s: %S)",
2806 msg_prefix, Py_TYPE(val)->tp_name, val);
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002807 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002808 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002809 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2810 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2811 PyException_SetCause(new_val, val);
2812 PyErr_Restore(new_exc, new_val, new_tb);
2813 return new_val;
2814}
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002815
2816
2817/* To help with migration from Python 2, SyntaxError.__init__ applies some
2818 * heuristics to try to report a more meaningful exception when print and
2819 * exec are used like statements.
2820 *
2821 * The heuristics are currently expected to detect the following cases:
2822 * - top level statement
2823 * - statement in a nested suite
2824 * - trailing section of a one line complex statement
2825 *
2826 * They're currently known not to trigger:
2827 * - after a semi-colon
2828 *
2829 * The error message can be a bit odd in cases where the "arguments" are
2830 * completely illegal syntactically, but that isn't worth the hassle of
2831 * fixing.
2832 *
2833 * We also can't do anything about cases that are legal Python 3 syntax
2834 * but mean something entirely different from what they did in Python 2
2835 * (omitting the arguments entirely, printing items preceded by a unary plus
2836 * or minus, using the stream redirection syntax).
2837 */
2838
2839static int
2840_check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start)
2841{
2842 /* Return values:
2843 * -1: an error occurred
2844 * 0: nothing happened
2845 * 1: the check triggered & the error message was changed
2846 */
2847 static PyObject *print_prefix = NULL;
2848 static PyObject *exec_prefix = NULL;
2849 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2850 int kind = PyUnicode_KIND(self->text);
2851 void *data = PyUnicode_DATA(self->text);
2852
2853 /* Ignore leading whitespace */
2854 while (start < text_len) {
2855 Py_UCS4 ch = PyUnicode_READ(kind, data, start);
2856 if (!Py_UNICODE_ISSPACE(ch))
2857 break;
2858 start++;
2859 }
2860 /* Checking against an empty or whitespace-only part of the string */
2861 if (start == text_len) {
2862 return 0;
2863 }
2864
2865 /* Check for legacy print statements */
2866 if (print_prefix == NULL) {
2867 print_prefix = PyUnicode_InternFromString("print ");
2868 if (print_prefix == NULL) {
2869 return -1;
2870 }
2871 }
2872 if (PyUnicode_Tailmatch(self->text, print_prefix,
2873 start, text_len, -1)) {
2874 Py_CLEAR(self->msg);
2875 self->msg = PyUnicode_FromString(
2876 "Missing parentheses in call to 'print'");
2877 return 1;
2878 }
2879
2880 /* Check for legacy exec statements */
2881 if (exec_prefix == NULL) {
2882 exec_prefix = PyUnicode_InternFromString("exec ");
2883 if (exec_prefix == NULL) {
2884 return -1;
2885 }
2886 }
2887 if (PyUnicode_Tailmatch(self->text, exec_prefix,
2888 start, text_len, -1)) {
2889 Py_CLEAR(self->msg);
2890 self->msg = PyUnicode_FromString(
2891 "Missing parentheses in call to 'exec'");
2892 return 1;
2893 }
2894 /* Fall back to the default error message */
2895 return 0;
2896}
2897
2898static int
2899_report_missing_parentheses(PySyntaxErrorObject *self)
2900{
2901 Py_UCS4 left_paren = 40;
2902 Py_ssize_t left_paren_index;
2903 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2904 int legacy_check_result = 0;
2905
2906 /* Skip entirely if there is an opening parenthesis */
2907 left_paren_index = PyUnicode_FindChar(self->text, left_paren,
2908 0, text_len, 1);
2909 if (left_paren_index < -1) {
2910 return -1;
2911 }
2912 if (left_paren_index != -1) {
2913 /* Use default error message for any line with an opening paren */
2914 return 0;
2915 }
2916 /* Handle the simple statement case */
2917 legacy_check_result = _check_for_legacy_statements(self, 0);
2918 if (legacy_check_result < 0) {
2919 return -1;
2920
2921 }
2922 if (legacy_check_result == 0) {
2923 /* Handle the one-line complex statement case */
2924 Py_UCS4 colon = 58;
2925 Py_ssize_t colon_index;
2926 colon_index = PyUnicode_FindChar(self->text, colon,
2927 0, text_len, 1);
2928 if (colon_index < -1) {
2929 return -1;
2930 }
2931 if (colon_index >= 0 && colon_index < text_len) {
2932 /* Check again, starting from just after the colon */
2933 if (_check_for_legacy_statements(self, colon_index+1) < 0) {
2934 return -1;
2935 }
2936 }
2937 }
2938 return 0;
2939}