blob: a27599781071c4b3fb94085ba5c11efef9bf557d [file] [log] [blame]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001/*
2 * New exceptions.c written in Iceland by Richard Jones and Georg Brandl.
3 *
4 * Thanks go to Tim Peters and Michael Hudson for debugging.
5 */
6
Thomas Wouters477c8d52006-05-27 19:21:47 +00007#define PY_SSIZE_T_CLEAN
8#include <Python.h>
9#include "structmember.h"
10#include "osdefs.h"
11
Thomas Wouters477c8d52006-05-27 19:21:47 +000012
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020013/* Compatibility aliases */
14PyObject *PyExc_EnvironmentError = NULL;
15PyObject *PyExc_IOError = NULL;
16#ifdef MS_WINDOWS
17PyObject *PyExc_WindowsError = NULL;
18#endif
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020019
20/* The dict map from errno codes to OSError subclasses */
21static PyObject *errnomap = NULL;
22
23
Thomas Wouters477c8d52006-05-27 19:21:47 +000024/* NOTE: If the exception class hierarchy changes, don't forget to update
25 * Lib/test/exception_hierarchy.txt
26 */
27
Thomas Wouters477c8d52006-05-27 19:21:47 +000028/*
29 * BaseException
30 */
31static PyObject *
32BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
33{
34 PyBaseExceptionObject *self;
35
36 self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +000037 if (!self)
38 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000039 /* the dict is created on the fly in PyObject_GenericSetAttr */
Guido van Rossumebe3e162007-05-17 18:20:34 +000040 self->dict = NULL;
Collin Winter1966f1c2007-09-01 20:26:44 +000041 self->traceback = self->cause = self->context = NULL;
Benjamin Petersond5a1c442012-05-14 22:09:31 -070042 self->suppress_context = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000043
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010044 if (args) {
45 self->args = args;
46 Py_INCREF(args);
47 return (PyObject *)self;
48 }
49
Thomas Wouters477c8d52006-05-27 19:21:47 +000050 self->args = PyTuple_New(0);
51 if (!self->args) {
52 Py_DECREF(self);
53 return NULL;
54 }
55
Thomas Wouters477c8d52006-05-27 19:21:47 +000056 return (PyObject *)self;
57}
58
59static int
60BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
61{
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010062 PyObject *tmp;
63
Christian Heimes90aa7642007-12-19 02:45:37 +000064 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000065 return -1;
66
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010067 tmp = self->args;
Thomas Wouters477c8d52006-05-27 19:21:47 +000068 self->args = args;
69 Py_INCREF(self->args);
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010070 Py_XDECREF(tmp);
Thomas Wouters477c8d52006-05-27 19:21:47 +000071
Thomas Wouters477c8d52006-05-27 19:21:47 +000072 return 0;
73}
74
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000075static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000076BaseException_clear(PyBaseExceptionObject *self)
77{
78 Py_CLEAR(self->dict);
79 Py_CLEAR(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +000080 Py_CLEAR(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +000081 Py_CLEAR(self->cause);
82 Py_CLEAR(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +000083 return 0;
84}
85
86static void
87BaseException_dealloc(PyBaseExceptionObject *self)
88{
Thomas Wouters89f507f2006-12-13 04:49:30 +000089 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000090 BaseException_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +000091 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000092}
93
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000094static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000095BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
96{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000097 Py_VISIT(self->dict);
Thomas Wouters477c8d52006-05-27 19:21:47 +000098 Py_VISIT(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +000099 Py_VISIT(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +0000100 Py_VISIT(self->cause);
101 Py_VISIT(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000102 return 0;
103}
104
105static PyObject *
106BaseException_str(PyBaseExceptionObject *self)
107{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000108 switch (PyTuple_GET_SIZE(self->args)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 case 0:
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +0000110 return PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000111 case 1:
Thomas Heller519a0422007-11-15 20:48:54 +0000112 return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000113 default:
Thomas Heller519a0422007-11-15 20:48:54 +0000114 return PyObject_Str(self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000115 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000116}
117
118static PyObject *
119BaseException_repr(PyBaseExceptionObject *self)
120{
Serhiy Storchakac6792272013-10-19 21:03:34 +0300121 const char *name;
122 const char *dot;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123
Serhiy Storchakac6792272013-10-19 21:03:34 +0300124 name = Py_TYPE(self)->tp_name;
125 dot = (const char *) strrchr(name, '.');
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126 if (dot != NULL) name = dot+1;
127
Walter Dörwald7569dfe2007-05-19 21:49:49 +0000128 return PyUnicode_FromFormat("%s%R", name, self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000129}
130
131/* Pickling support */
132static PyObject *
133BaseException_reduce(PyBaseExceptionObject *self)
134{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000135 if (self->args && self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +0000136 return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000137 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000138 return PyTuple_Pack(2, Py_TYPE(self), self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000139}
140
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000141/*
142 * Needed for backward compatibility, since exceptions used to store
143 * all their attributes in the __dict__. Code is taken from cPickle's
144 * load_build function.
145 */
146static PyObject *
147BaseException_setstate(PyObject *self, PyObject *state)
148{
149 PyObject *d_key, *d_value;
150 Py_ssize_t i = 0;
151
152 if (state != Py_None) {
153 if (!PyDict_Check(state)) {
154 PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
155 return NULL;
156 }
157 while (PyDict_Next(state, &i, &d_key, &d_value)) {
158 if (PyObject_SetAttr(self, d_key, d_value) < 0)
159 return NULL;
160 }
161 }
162 Py_RETURN_NONE;
163}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000164
Collin Winter828f04a2007-08-31 00:04:24 +0000165static PyObject *
166BaseException_with_traceback(PyObject *self, PyObject *tb) {
167 if (PyException_SetTraceback(self, tb))
168 return NULL;
169
170 Py_INCREF(self);
171 return self;
172}
173
Georg Brandl76941002008-05-05 21:38:47 +0000174PyDoc_STRVAR(with_traceback_doc,
175"Exception.with_traceback(tb) --\n\
176 set self.__traceback__ to tb and return self.");
177
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178
179static PyMethodDef BaseException_methods[] = {
180 {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000181 {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
Georg Brandl76941002008-05-05 21:38:47 +0000182 {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
183 with_traceback_doc},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000184 {NULL, NULL, 0, NULL},
185};
186
Thomas Wouters477c8d52006-05-27 19:21:47 +0000187static PyObject *
188BaseException_get_args(PyBaseExceptionObject *self)
189{
190 if (self->args == NULL) {
191 Py_INCREF(Py_None);
192 return Py_None;
193 }
194 Py_INCREF(self->args);
195 return self->args;
196}
197
198static int
199BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
200{
201 PyObject *seq;
202 if (val == NULL) {
203 PyErr_SetString(PyExc_TypeError, "args may not be deleted");
204 return -1;
205 }
206 seq = PySequence_Tuple(val);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500207 if (!seq)
208 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000209 Py_CLEAR(self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000210 self->args = seq;
211 return 0;
212}
213
Collin Winter828f04a2007-08-31 00:04:24 +0000214static PyObject *
215BaseException_get_tb(PyBaseExceptionObject *self)
216{
217 if (self->traceback == NULL) {
218 Py_INCREF(Py_None);
219 return Py_None;
220 }
221 Py_INCREF(self->traceback);
222 return self->traceback;
223}
224
225static int
226BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb)
227{
228 if (tb == NULL) {
229 PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
230 return -1;
231 }
232 else if (!(tb == Py_None || PyTraceBack_Check(tb))) {
233 PyErr_SetString(PyExc_TypeError,
234 "__traceback__ must be a traceback or None");
235 return -1;
236 }
237
238 Py_XINCREF(tb);
239 Py_XDECREF(self->traceback);
240 self->traceback = tb;
241 return 0;
242}
243
Georg Brandlab6f2f62009-03-31 04:16:10 +0000244static PyObject *
245BaseException_get_context(PyObject *self) {
246 PyObject *res = PyException_GetContext(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500247 if (res)
248 return res; /* new reference already returned above */
Georg Brandlab6f2f62009-03-31 04:16:10 +0000249 Py_RETURN_NONE;
250}
251
252static int
253BaseException_set_context(PyObject *self, PyObject *arg) {
254 if (arg == NULL) {
255 PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
256 return -1;
257 } else if (arg == Py_None) {
258 arg = NULL;
259 } else if (!PyExceptionInstance_Check(arg)) {
260 PyErr_SetString(PyExc_TypeError, "exception context must be None "
261 "or derive from BaseException");
262 return -1;
263 } else {
264 /* PyException_SetContext steals this reference */
265 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 }
Georg Brandlab6f2f62009-03-31 04:16:10 +0000267 PyException_SetContext(self, arg);
268 return 0;
269}
270
271static PyObject *
272BaseException_get_cause(PyObject *self) {
273 PyObject *res = PyException_GetCause(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500274 if (res)
275 return res; /* new reference already returned above */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700276 Py_RETURN_NONE;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000277}
278
279static int
280BaseException_set_cause(PyObject *self, PyObject *arg) {
281 if (arg == NULL) {
282 PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
283 return -1;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700284 } else if (arg == Py_None) {
285 arg = NULL;
286 } else if (!PyExceptionInstance_Check(arg)) {
287 PyErr_SetString(PyExc_TypeError, "exception cause must be None "
288 "or derive from BaseException");
289 return -1;
290 } else {
291 /* PyException_SetCause steals this reference */
292 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700294 PyException_SetCause(self, arg);
295 return 0;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000296}
297
Guido van Rossum360e4b82007-05-14 22:51:27 +0000298
Thomas Wouters477c8d52006-05-27 19:21:47 +0000299static PyGetSetDef BaseException_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500300 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000301 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
Collin Winter828f04a2007-08-31 00:04:24 +0000302 {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
Georg Brandlab6f2f62009-03-31 04:16:10 +0000303 {"__context__", (getter)BaseException_get_context,
304 (setter)BaseException_set_context, PyDoc_STR("exception context")},
305 {"__cause__", (getter)BaseException_get_cause,
306 (setter)BaseException_set_cause, PyDoc_STR("exception cause")},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000307 {NULL},
308};
309
310
Collin Winter828f04a2007-08-31 00:04:24 +0000311PyObject *
312PyException_GetTraceback(PyObject *self) {
313 PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
314 Py_XINCREF(base_self->traceback);
315 return base_self->traceback;
316}
317
318
319int
320PyException_SetTraceback(PyObject *self, PyObject *tb) {
321 return BaseException_set_tb((PyBaseExceptionObject *)self, tb);
322}
323
324PyObject *
325PyException_GetCause(PyObject *self) {
326 PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
327 Py_XINCREF(cause);
328 return cause;
329}
330
331/* Steals a reference to cause */
332void
333PyException_SetCause(PyObject *self, PyObject *cause) {
334 PyObject *old_cause = ((PyBaseExceptionObject *)self)->cause;
335 ((PyBaseExceptionObject *)self)->cause = cause;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700336 ((PyBaseExceptionObject *)self)->suppress_context = 1;
Collin Winter828f04a2007-08-31 00:04:24 +0000337 Py_XDECREF(old_cause);
338}
339
340PyObject *
341PyException_GetContext(PyObject *self) {
342 PyObject *context = ((PyBaseExceptionObject *)self)->context;
343 Py_XINCREF(context);
344 return context;
345}
346
347/* Steals a reference to context */
348void
349PyException_SetContext(PyObject *self, PyObject *context) {
350 PyObject *old_context = ((PyBaseExceptionObject *)self)->context;
351 ((PyBaseExceptionObject *)self)->context = context;
352 Py_XDECREF(old_context);
353}
354
355
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700356static struct PyMemberDef BaseException_members[] = {
357 {"__suppress_context__", T_BOOL,
Antoine Pitrou32bc80c2012-05-16 12:51:55 +0200358 offsetof(PyBaseExceptionObject, suppress_context)},
359 {NULL}
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700360};
361
362
Thomas Wouters477c8d52006-05-27 19:21:47 +0000363static PyTypeObject _PyExc_BaseException = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000364 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +0000365 "BaseException", /*tp_name*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000366 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
367 0, /*tp_itemsize*/
368 (destructor)BaseException_dealloc, /*tp_dealloc*/
369 0, /*tp_print*/
370 0, /*tp_getattr*/
371 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000372 0, /* tp_reserved; */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373 (reprfunc)BaseException_repr, /*tp_repr*/
374 0, /*tp_as_number*/
Brett Cannonba7bf492007-02-27 00:15:55 +0000375 0, /*tp_as_sequence*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000376 0, /*tp_as_mapping*/
377 0, /*tp_hash */
378 0, /*tp_call*/
379 (reprfunc)BaseException_str, /*tp_str*/
380 PyObject_GenericGetAttr, /*tp_getattro*/
381 PyObject_GenericSetAttr, /*tp_setattro*/
382 0, /*tp_as_buffer*/
Thomas Wouters27d517b2007-02-25 20:39:11 +0000383 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000385 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
386 (traverseproc)BaseException_traverse, /* tp_traverse */
387 (inquiry)BaseException_clear, /* tp_clear */
388 0, /* tp_richcompare */
389 0, /* tp_weaklistoffset */
390 0, /* tp_iter */
391 0, /* tp_iternext */
392 BaseException_methods, /* tp_methods */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700393 BaseException_members, /* tp_members */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000394 BaseException_getset, /* tp_getset */
395 0, /* tp_base */
396 0, /* tp_dict */
397 0, /* tp_descr_get */
398 0, /* tp_descr_set */
399 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
400 (initproc)BaseException_init, /* tp_init */
401 0, /* tp_alloc */
402 BaseException_new, /* tp_new */
403};
404/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
405from the previous implmentation and also allowing Python objects to be used
406in the API */
407PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
408
409/* note these macros omit the last semicolon so the macro invocation may
410 * include it and not look strange.
411 */
412#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
413static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000414 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000415 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000416 sizeof(PyBaseExceptionObject), \
417 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
418 0, 0, 0, 0, 0, 0, 0, \
419 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
420 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
421 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
422 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
423 (initproc)BaseException_init, 0, BaseException_new,\
424}; \
425PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
426
427#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
428static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000429 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000430 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431 sizeof(Py ## EXCSTORE ## Object), \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000432 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433 0, 0, 0, 0, 0, \
434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000435 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
436 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200438 (initproc)EXCSTORE ## _init, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439}; \
440PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
441
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200442#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
443 EXCMETHODS, EXCMEMBERS, EXCGETSET, \
444 EXCSTR, EXCDOC) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000445static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000446 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000447 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000448 sizeof(Py ## EXCSTORE ## Object), 0, \
449 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
450 (reprfunc)EXCSTR, 0, 0, 0, \
451 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
452 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
453 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200454 EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200456 (initproc)EXCSTORE ## _init, 0, EXCNEW,\
Thomas Wouters477c8d52006-05-27 19:21:47 +0000457}; \
458PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
459
460
461/*
462 * Exception extends BaseException
463 */
464SimpleExtendsException(PyExc_BaseException, Exception,
465 "Common base class for all non-exit exceptions.");
466
467
468/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000469 * TypeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000470 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000471SimpleExtendsException(PyExc_Exception, TypeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000472 "Inappropriate argument type.");
473
474
475/*
Yury Selivanov75445082015-05-11 22:57:16 -0400476 * StopAsyncIteration extends Exception
477 */
478SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
479 "Signal the end from iterator.__anext__().");
480
481
482/*
Thomas Wouters477c8d52006-05-27 19:21:47 +0000483 * StopIteration extends Exception
484 */
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000485
486static PyMemberDef StopIteration_members[] = {
487 {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
488 PyDoc_STR("generator return value")},
489 {NULL} /* Sentinel */
490};
491
492static int
493StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
494{
495 Py_ssize_t size = PyTuple_GET_SIZE(args);
496 PyObject *value;
497
498 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
499 return -1;
500 Py_CLEAR(self->value);
501 if (size > 0)
502 value = PyTuple_GET_ITEM(args, 0);
503 else
504 value = Py_None;
505 Py_INCREF(value);
506 self->value = value;
507 return 0;
508}
509
510static int
511StopIteration_clear(PyStopIterationObject *self)
512{
513 Py_CLEAR(self->value);
514 return BaseException_clear((PyBaseExceptionObject *)self);
515}
516
517static void
518StopIteration_dealloc(PyStopIterationObject *self)
519{
520 _PyObject_GC_UNTRACK(self);
521 StopIteration_clear(self);
522 Py_TYPE(self)->tp_free((PyObject *)self);
523}
524
525static int
526StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
527{
528 Py_VISIT(self->value);
529 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
530}
531
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000532ComplexExtendsException(
533 PyExc_Exception, /* base */
534 StopIteration, /* name */
535 StopIteration, /* prefix for *_init, etc */
536 0, /* new */
537 0, /* methods */
538 StopIteration_members, /* members */
539 0, /* getset */
540 0, /* str */
541 "Signal the end from iterator.__next__()."
542);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543
544
545/*
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000546 * GeneratorExit extends BaseException
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547 */
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000548SimpleExtendsException(PyExc_BaseException, GeneratorExit,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549 "Request that a generator exit.");
550
551
552/*
553 * SystemExit extends BaseException
554 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555
556static int
557SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
558{
559 Py_ssize_t size = PyTuple_GET_SIZE(args);
560
561 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
562 return -1;
563
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000564 if (size == 0)
565 return 0;
566 Py_CLEAR(self->code);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000567 if (size == 1)
568 self->code = PyTuple_GET_ITEM(args, 0);
Victor Stinner92236e52011-05-26 14:25:54 +0200569 else /* size > 1 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000570 self->code = args;
571 Py_INCREF(self->code);
572 return 0;
573}
574
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000575static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000576SystemExit_clear(PySystemExitObject *self)
577{
578 Py_CLEAR(self->code);
579 return BaseException_clear((PyBaseExceptionObject *)self);
580}
581
582static void
583SystemExit_dealloc(PySystemExitObject *self)
584{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000585 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586 SystemExit_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000587 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588}
589
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000590static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000591SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
592{
593 Py_VISIT(self->code);
594 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
595}
596
597static PyMemberDef SystemExit_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
599 PyDoc_STR("exception code")},
600 {NULL} /* Sentinel */
601};
602
603ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200604 0, 0, SystemExit_members, 0, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000605 "Request to exit from the interpreter.");
606
607/*
608 * KeyboardInterrupt extends BaseException
609 */
610SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
611 "Program interrupted by user.");
612
613
614/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000615 * ImportError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000616 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000617
Brett Cannon79ec55e2012-04-12 20:24:54 -0400618static int
619ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
620{
621 PyObject *msg = NULL;
622 PyObject *name = NULL;
623 PyObject *path = NULL;
624
625/* Macro replacement doesn't allow ## to start the first line of a macro,
626 so we move the assignment and NULL check into the if-statement. */
627#define GET_KWD(kwd) { \
628 kwd = PyDict_GetItemString(kwds, #kwd); \
629 if (kwd) { \
630 Py_CLEAR(self->kwd); \
631 self->kwd = kwd; \
632 Py_INCREF(self->kwd);\
633 if (PyDict_DelItemString(kwds, #kwd)) \
634 return -1; \
635 } \
636 }
637
638 if (kwds) {
639 GET_KWD(name);
640 GET_KWD(path);
641 }
642
643 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
644 return -1;
645 if (PyTuple_GET_SIZE(args) != 1)
646 return 0;
647 if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
648 return -1;
649
650 Py_CLEAR(self->msg); /* replacing */
651 self->msg = msg;
652 Py_INCREF(self->msg);
653
654 return 0;
655}
656
657static int
658ImportError_clear(PyImportErrorObject *self)
659{
660 Py_CLEAR(self->msg);
661 Py_CLEAR(self->name);
662 Py_CLEAR(self->path);
663 return BaseException_clear((PyBaseExceptionObject *)self);
664}
665
666static void
667ImportError_dealloc(PyImportErrorObject *self)
668{
669 _PyObject_GC_UNTRACK(self);
670 ImportError_clear(self);
671 Py_TYPE(self)->tp_free((PyObject *)self);
672}
673
674static int
675ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
676{
677 Py_VISIT(self->msg);
678 Py_VISIT(self->name);
679 Py_VISIT(self->path);
680 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
681}
682
683static PyObject *
684ImportError_str(PyImportErrorObject *self)
685{
Brett Cannon07c6e712012-08-24 13:05:09 -0400686 if (self->msg && PyUnicode_CheckExact(self->msg)) {
Brett Cannon79ec55e2012-04-12 20:24:54 -0400687 Py_INCREF(self->msg);
688 return self->msg;
689 }
690 else {
691 return BaseException_str((PyBaseExceptionObject *)self);
692 }
693}
694
695static PyMemberDef ImportError_members[] = {
696 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
697 PyDoc_STR("exception message")},
698 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
699 PyDoc_STR("module name")},
700 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
701 PyDoc_STR("module path")},
702 {NULL} /* Sentinel */
703};
704
705static PyMethodDef ImportError_methods[] = {
706 {NULL}
707};
708
709ComplexExtendsException(PyExc_Exception, ImportError,
710 ImportError, 0 /* new */,
711 ImportError_methods, ImportError_members,
712 0 /* getset */, ImportError_str,
713 "Import can't find module, or can't find name in "
714 "module.");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000715
716/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200717 * OSError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718 */
719
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200720#ifdef MS_WINDOWS
721#include "errmap.h"
722#endif
723
Thomas Wouters477c8d52006-05-27 19:21:47 +0000724/* Where a function has a single filename, such as open() or some
725 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
726 * called, giving a third argument which is the filename. But, so
727 * that old code using in-place unpacking doesn't break, e.g.:
728 *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200729 * except OSError, (errno, strerror):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730 *
731 * we hack args so that it only contains two items. This also
732 * means we need our own __str__() which prints out the filename
733 * when it was supplied.
Larry Hastingsb0827312014-02-09 22:05:19 -0800734 *
735 * (If a function has two filenames, such as rename(), symlink(),
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800736 * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
737 * which allows passing in a second filename.)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200739
Antoine Pitroue0e27352011-12-15 14:31:28 +0100740/* This function doesn't cleanup on error, the caller should */
741static int
742oserror_parse_args(PyObject **p_args,
743 PyObject **myerrno, PyObject **strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800744 PyObject **filename, PyObject **filename2
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200745#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100746 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200747#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100748 )
749{
750 Py_ssize_t nargs;
751 PyObject *args = *p_args;
Larry Hastingsb0827312014-02-09 22:05:19 -0800752#ifndef MS_WINDOWS
753 /*
754 * ignored on non-Windows platforms,
755 * but parsed so OSError has a consistent signature
756 */
757 PyObject *_winerror = NULL;
758 PyObject **winerror = &_winerror;
759#endif /* MS_WINDOWS */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000760
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200761 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000762
Larry Hastingsb0827312014-02-09 22:05:19 -0800763 if (nargs >= 2 && nargs <= 5) {
764 if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
765 myerrno, strerror,
766 filename, winerror, filename2))
Antoine Pitroue0e27352011-12-15 14:31:28 +0100767 return -1;
Larry Hastingsb0827312014-02-09 22:05:19 -0800768#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100769 if (*winerror && PyLong_Check(*winerror)) {
770 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200771 PyObject *newargs;
772 Py_ssize_t i;
773
Antoine Pitroue0e27352011-12-15 14:31:28 +0100774 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200775 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100776 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200777 /* Set errno to the corresponding POSIX errno (overriding
778 first argument). Windows Socket error codes (>= 10000)
779 have the same value as their POSIX counterparts.
780 */
781 if (winerrcode < 10000)
782 errcode = winerror_to_errno(winerrcode);
783 else
784 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100785 *myerrno = PyLong_FromLong(errcode);
786 if (!*myerrno)
787 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200788 newargs = PyTuple_New(nargs);
789 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100790 return -1;
791 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200792 for (i = 1; i < nargs; i++) {
793 PyObject *val = PyTuple_GET_ITEM(args, i);
794 Py_INCREF(val);
795 PyTuple_SET_ITEM(newargs, i, val);
796 }
797 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100798 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200799 }
Larry Hastingsb0827312014-02-09 22:05:19 -0800800#endif /* MS_WINDOWS */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200801 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000802
Antoine Pitroue0e27352011-12-15 14:31:28 +0100803 return 0;
804}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805
Antoine Pitroue0e27352011-12-15 14:31:28 +0100806static int
807oserror_init(PyOSErrorObject *self, PyObject **p_args,
808 PyObject *myerrno, PyObject *strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800809 PyObject *filename, PyObject *filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100810#ifdef MS_WINDOWS
811 , PyObject *winerror
812#endif
813 )
814{
815 PyObject *args = *p_args;
816 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000817
818 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200819 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100820 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200821 PyNumber_Check(filename)) {
822 /* BlockingIOError's 3rd argument can be the number of
823 * characters written.
824 */
825 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
826 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100827 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200828 }
829 else {
830 Py_INCREF(filename);
831 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000832
Larry Hastingsb0827312014-02-09 22:05:19 -0800833 if (filename2 && filename2 != Py_None) {
834 Py_INCREF(filename2);
835 self->filename2 = filename2;
836 }
837
838 if (nargs >= 2 && nargs <= 5) {
839 /* filename, filename2, and winerror are removed from the args tuple
840 (for compatibility purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100841 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200842 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100843 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000844
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200845 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100846 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200847 }
848 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000849 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200850 Py_XINCREF(myerrno);
851 self->myerrno = myerrno;
852
853 Py_XINCREF(strerror);
854 self->strerror = strerror;
855
856#ifdef MS_WINDOWS
857 Py_XINCREF(winerror);
858 self->winerror = winerror;
859#endif
860
Antoine Pitroue0e27352011-12-15 14:31:28 +0100861 /* Steals the reference to args */
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200862 Py_CLEAR(self->args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100863 self->args = args;
Victor Stinner46ef3192013-11-14 22:31:41 +0100864 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100865
866 return 0;
867}
868
869static PyObject *
870OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
871static int
872OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
873
874static int
875oserror_use_init(PyTypeObject *type)
876{
877 /* When __init__ is defined in a OSError subclass, we want any
878 extraneous argument to __new__ to be ignored. The only reasonable
879 solution, given __new__ takes a variable number of arguments,
880 is to defer arg parsing and initialization to __init__.
881
882 But when __new__ is overriden as well, it should call our __new__
883 with the right arguments.
884
885 (see http://bugs.python.org/issue12555#msg148829 )
886 */
887 if (type->tp_init != (initproc) OSError_init &&
888 type->tp_new == (newfunc) OSError_new) {
889 assert((PyObject *) type != PyExc_OSError);
890 return 1;
891 }
892 return 0;
893}
894
895static PyObject *
896OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
897{
898 PyOSErrorObject *self = NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800899 PyObject *myerrno = NULL, *strerror = NULL;
900 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100901#ifdef MS_WINDOWS
902 PyObject *winerror = NULL;
903#endif
904
Victor Stinner46ef3192013-11-14 22:31:41 +0100905 Py_INCREF(args);
906
Antoine Pitroue0e27352011-12-15 14:31:28 +0100907 if (!oserror_use_init(type)) {
908 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100909 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100910
Larry Hastingsb0827312014-02-09 22:05:19 -0800911 if (oserror_parse_args(&args, &myerrno, &strerror,
912 &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100913#ifdef MS_WINDOWS
914 , &winerror
915#endif
916 ))
917 goto error;
918
919 if (myerrno && PyLong_Check(myerrno) &&
920 errnomap && (PyObject *) type == PyExc_OSError) {
921 PyObject *newtype;
922 newtype = PyDict_GetItem(errnomap, myerrno);
923 if (newtype) {
924 assert(PyType_Check(newtype));
925 type = (PyTypeObject *) newtype;
926 }
927 else if (PyErr_Occurred())
928 goto error;
929 }
930 }
931
932 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
933 if (!self)
934 goto error;
935
936 self->dict = NULL;
937 self->traceback = self->cause = self->context = NULL;
938 self->written = -1;
939
940 if (!oserror_use_init(type)) {
Larry Hastingsb0827312014-02-09 22:05:19 -0800941 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100942#ifdef MS_WINDOWS
943 , winerror
944#endif
945 ))
946 goto error;
947 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200948 else {
949 self->args = PyTuple_New(0);
950 if (self->args == NULL)
951 goto error;
952 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100953
Victor Stinner46ef3192013-11-14 22:31:41 +0100954 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200955 return (PyObject *) self;
956
957error:
958 Py_XDECREF(args);
959 Py_XDECREF(self);
960 return NULL;
961}
962
963static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100964OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200965{
Larry Hastingsb0827312014-02-09 22:05:19 -0800966 PyObject *myerrno = NULL, *strerror = NULL;
967 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100968#ifdef MS_WINDOWS
969 PyObject *winerror = NULL;
970#endif
971
972 if (!oserror_use_init(Py_TYPE(self)))
973 /* Everything already done in OSError_new */
974 return 0;
975
976 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
977 return -1;
978
979 Py_INCREF(args);
Larry Hastingsb0827312014-02-09 22:05:19 -0800980 if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100981#ifdef MS_WINDOWS
982 , &winerror
983#endif
984 ))
985 goto error;
986
Larry Hastingsb0827312014-02-09 22:05:19 -0800987 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100988#ifdef MS_WINDOWS
989 , winerror
990#endif
991 ))
992 goto error;
993
Thomas Wouters477c8d52006-05-27 19:21:47 +0000994 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100995
996error:
997 Py_XDECREF(args);
998 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000999}
1000
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001001static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001002OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001003{
1004 Py_CLEAR(self->myerrno);
1005 Py_CLEAR(self->strerror);
1006 Py_CLEAR(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001007 Py_CLEAR(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001008#ifdef MS_WINDOWS
1009 Py_CLEAR(self->winerror);
1010#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001011 return BaseException_clear((PyBaseExceptionObject *)self);
1012}
1013
1014static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001015OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001016{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001017 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001018 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001019 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001020}
1021
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001022static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001023OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001024 void *arg)
1025{
1026 Py_VISIT(self->myerrno);
1027 Py_VISIT(self->strerror);
1028 Py_VISIT(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001029 Py_VISIT(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001030#ifdef MS_WINDOWS
1031 Py_VISIT(self->winerror);
1032#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1034}
1035
1036static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001037OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001038{
Larry Hastingsb0827312014-02-09 22:05:19 -08001039#define OR_NONE(x) ((x)?(x):Py_None)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001040#ifdef MS_WINDOWS
1041 /* If available, winerror has the priority over myerrno */
Larry Hastingsb0827312014-02-09 22:05:19 -08001042 if (self->winerror && self->filename) {
1043 if (self->filename2) {
1044 return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
1045 OR_NONE(self->winerror),
1046 OR_NONE(self->strerror),
1047 self->filename,
1048 self->filename2);
1049 } else {
1050 return PyUnicode_FromFormat("[WinError %S] %S: %R",
1051 OR_NONE(self->winerror),
1052 OR_NONE(self->strerror),
1053 self->filename);
1054 }
1055 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001056 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001057 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001058 self->winerror ? self->winerror: Py_None,
1059 self->strerror ? self->strerror: Py_None);
1060#endif
Larry Hastingsb0827312014-02-09 22:05:19 -08001061 if (self->filename) {
1062 if (self->filename2) {
1063 return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
1064 OR_NONE(self->myerrno),
1065 OR_NONE(self->strerror),
1066 self->filename,
1067 self->filename2);
1068 } else {
1069 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1070 OR_NONE(self->myerrno),
1071 OR_NONE(self->strerror),
1072 self->filename);
1073 }
1074 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001075 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001076 return PyUnicode_FromFormat("[Errno %S] %S",
1077 self->myerrno ? self->myerrno: Py_None,
1078 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001079 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080}
1081
Thomas Wouters477c8d52006-05-27 19:21:47 +00001082static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001083OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084{
1085 PyObject *args = self->args;
1086 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001087
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001089 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001090 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Larry Hastingsb0827312014-02-09 22:05:19 -08001091 Py_ssize_t size = self->filename2 ? 5 : 3;
1092 args = PyTuple_New(size);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001093 if (!args)
1094 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001095
1096 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001097 Py_INCREF(tmp);
1098 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001099
1100 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101 Py_INCREF(tmp);
1102 PyTuple_SET_ITEM(args, 1, tmp);
1103
1104 Py_INCREF(self->filename);
1105 PyTuple_SET_ITEM(args, 2, self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001106
1107 if (self->filename2) {
1108 /*
1109 * This tuple is essentially used as OSError(*args).
1110 * So, to recreate filename2, we need to pass in
1111 * winerror as well.
1112 */
1113 Py_INCREF(Py_None);
1114 PyTuple_SET_ITEM(args, 3, Py_None);
1115
1116 /* filename2 */
1117 Py_INCREF(self->filename2);
1118 PyTuple_SET_ITEM(args, 4, self->filename2);
1119 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001120 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001121 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001122
1123 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001124 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001125 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001126 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127 Py_DECREF(args);
1128 return res;
1129}
1130
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001131static PyObject *
1132OSError_written_get(PyOSErrorObject *self, void *context)
1133{
1134 if (self->written == -1) {
1135 PyErr_SetString(PyExc_AttributeError, "characters_written");
1136 return NULL;
1137 }
1138 return PyLong_FromSsize_t(self->written);
1139}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001140
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001141static int
1142OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1143{
1144 Py_ssize_t n;
1145 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1146 if (n == -1 && PyErr_Occurred())
1147 return -1;
1148 self->written = n;
1149 return 0;
1150}
1151
1152static PyMemberDef OSError_members[] = {
1153 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1154 PyDoc_STR("POSIX exception code")},
1155 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1156 PyDoc_STR("exception strerror")},
1157 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1158 PyDoc_STR("exception filename")},
Larry Hastingsb0827312014-02-09 22:05:19 -08001159 {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
1160 PyDoc_STR("second exception filename")},
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001161#ifdef MS_WINDOWS
1162 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1163 PyDoc_STR("Win32 exception code")},
1164#endif
1165 {NULL} /* Sentinel */
1166};
1167
1168static PyMethodDef OSError_methods[] = {
1169 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001170 {NULL}
1171};
1172
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001173static PyGetSetDef OSError_getset[] = {
1174 {"characters_written", (getter) OSError_written_get,
1175 (setter) OSError_written_set, NULL},
1176 {NULL}
1177};
1178
1179
1180ComplexExtendsException(PyExc_Exception, OSError,
1181 OSError, OSError_new,
1182 OSError_methods, OSError_members, OSError_getset,
1183 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001184 "Base class for I/O related errors.");
1185
1186
1187/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001188 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001189 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001190MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1191 "I/O operation would block.");
1192MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1193 "Connection error.");
1194MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1195 "Child process error.");
1196MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1197 "Broken pipe.");
1198MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1199 "Connection aborted.");
1200MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1201 "Connection refused.");
1202MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1203 "Connection reset.");
1204MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1205 "File already exists.");
1206MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1207 "File not found.");
1208MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1209 "Operation doesn't work on directories.");
1210MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1211 "Operation only works on directories.");
1212MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1213 "Interrupted by signal.");
1214MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1215 "Not enough permissions.");
1216MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1217 "Process not found.");
1218MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1219 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220
1221/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001222 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001223 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001224SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001225 "Read beyond end of file.");
1226
1227
1228/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001229 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001230 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001231SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001232 "Unspecified run-time error.");
1233
Yury Selivanovf488fb42015-07-03 01:04:23 -04001234/*
1235 * RecursionError extends RuntimeError
1236 */
1237SimpleExtendsException(PyExc_RuntimeError, RecursionError,
1238 "Recursion limit exceeded.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001239
1240/*
1241 * NotImplementedError extends RuntimeError
1242 */
1243SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1244 "Method or function hasn't been implemented yet.");
1245
1246/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001247 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001248 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001249SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001250 "Name not found globally.");
1251
1252/*
1253 * UnboundLocalError extends NameError
1254 */
1255SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1256 "Local name referenced but not bound to a value.");
1257
1258/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001259 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001260 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001261SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001262 "Attribute not found.");
1263
1264
1265/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001266 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001267 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001268
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001269/* Helper function to customise error message for some syntax errors */
1270static int _report_missing_parentheses(PySyntaxErrorObject *self);
1271
Thomas Wouters477c8d52006-05-27 19:21:47 +00001272static int
1273SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1274{
1275 PyObject *info = NULL;
1276 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1277
1278 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1279 return -1;
1280
1281 if (lenargs >= 1) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001282 Py_CLEAR(self->msg);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001283 self->msg = PyTuple_GET_ITEM(args, 0);
1284 Py_INCREF(self->msg);
1285 }
1286 if (lenargs == 2) {
1287 info = PyTuple_GET_ITEM(args, 1);
1288 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001289 if (!info)
1290 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001291
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001292 if (PyTuple_GET_SIZE(info) != 4) {
1293 /* not a very good error message, but it's what Python 2.4 gives */
1294 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1295 Py_DECREF(info);
1296 return -1;
1297 }
1298
1299 Py_CLEAR(self->filename);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001300 self->filename = PyTuple_GET_ITEM(info, 0);
1301 Py_INCREF(self->filename);
1302
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001303 Py_CLEAR(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001304 self->lineno = PyTuple_GET_ITEM(info, 1);
1305 Py_INCREF(self->lineno);
1306
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001307 Py_CLEAR(self->offset);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001308 self->offset = PyTuple_GET_ITEM(info, 2);
1309 Py_INCREF(self->offset);
1310
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001311 Py_CLEAR(self->text);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001312 self->text = PyTuple_GET_ITEM(info, 3);
1313 Py_INCREF(self->text);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001314
1315 Py_DECREF(info);
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001316
1317 /* Issue #21669: Custom error for 'print' & 'exec' as statements */
1318 if (self->text && PyUnicode_Check(self->text)) {
1319 if (_report_missing_parentheses(self) < 0) {
1320 return -1;
1321 }
1322 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001323 }
1324 return 0;
1325}
1326
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001327static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001328SyntaxError_clear(PySyntaxErrorObject *self)
1329{
1330 Py_CLEAR(self->msg);
1331 Py_CLEAR(self->filename);
1332 Py_CLEAR(self->lineno);
1333 Py_CLEAR(self->offset);
1334 Py_CLEAR(self->text);
1335 Py_CLEAR(self->print_file_and_line);
1336 return BaseException_clear((PyBaseExceptionObject *)self);
1337}
1338
1339static void
1340SyntaxError_dealloc(PySyntaxErrorObject *self)
1341{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001342 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001343 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001344 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001345}
1346
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001347static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001348SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1349{
1350 Py_VISIT(self->msg);
1351 Py_VISIT(self->filename);
1352 Py_VISIT(self->lineno);
1353 Py_VISIT(self->offset);
1354 Py_VISIT(self->text);
1355 Py_VISIT(self->print_file_and_line);
1356 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1357}
1358
1359/* This is called "my_basename" instead of just "basename" to avoid name
1360 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1361 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001362static PyObject*
1363my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001364{
Victor Stinner6237daf2010-04-28 17:26:19 +00001365 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001366 int kind;
1367 void *data;
1368
1369 if (PyUnicode_READY(name))
1370 return NULL;
1371 kind = PyUnicode_KIND(name);
1372 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001374 offset = 0;
1375 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001377 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001379 if (offset != 0)
1380 return PyUnicode_Substring(name, offset, size);
1381 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001382 Py_INCREF(name);
1383 return name;
1384 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001385}
1386
1387
1388static PyObject *
1389SyntaxError_str(PySyntaxErrorObject *self)
1390{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001391 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001392 PyObject *filename;
1393 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001394 /* Below, we always ignore overflow errors, just printing -1.
1395 Still, we cannot allow an OverflowError to be raised, so
1396 we need to call PyLong_AsLongAndOverflow. */
1397 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001398
1399 /* XXX -- do all the additional formatting with filename and
1400 lineno here */
1401
Neal Norwitzed2b7392007-08-26 04:51:10 +00001402 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001403 filename = my_basename(self->filename);
1404 if (filename == NULL)
1405 return NULL;
1406 } else {
1407 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001408 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001409 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001410
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001411 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001412 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001413
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001414 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001415 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001416 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001417 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001419 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001420 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001421 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001422 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001423 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001424 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001425 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001426 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001427 Py_XDECREF(filename);
1428 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001429}
1430
1431static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001432 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1433 PyDoc_STR("exception msg")},
1434 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1435 PyDoc_STR("exception filename")},
1436 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1437 PyDoc_STR("exception lineno")},
1438 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1439 PyDoc_STR("exception offset")},
1440 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1441 PyDoc_STR("exception text")},
1442 {"print_file_and_line", T_OBJECT,
1443 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1444 PyDoc_STR("exception print_file_and_line")},
1445 {NULL} /* Sentinel */
1446};
1447
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001448ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001449 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001450 SyntaxError_str, "Invalid syntax.");
1451
1452
1453/*
1454 * IndentationError extends SyntaxError
1455 */
1456MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1457 "Improper indentation.");
1458
1459
1460/*
1461 * TabError extends IndentationError
1462 */
1463MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1464 "Improper mixture of spaces and tabs.");
1465
1466
1467/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001468 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001469 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001470SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001471 "Base class for lookup errors.");
1472
1473
1474/*
1475 * IndexError extends LookupError
1476 */
1477SimpleExtendsException(PyExc_LookupError, IndexError,
1478 "Sequence index out of range.");
1479
1480
1481/*
1482 * KeyError extends LookupError
1483 */
1484static PyObject *
1485KeyError_str(PyBaseExceptionObject *self)
1486{
1487 /* If args is a tuple of exactly one item, apply repr to args[0].
1488 This is done so that e.g. the exception raised by {}[''] prints
1489 KeyError: ''
1490 rather than the confusing
1491 KeyError
1492 alone. The downside is that if KeyError is raised with an explanatory
1493 string, that string will be displayed in quotes. Too bad.
1494 If args is anything else, use the default BaseException__str__().
1495 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001496 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001497 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001498 }
1499 return BaseException_str(self);
1500}
1501
1502ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001503 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001504
1505
1506/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001507 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001508 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001509SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001510 "Inappropriate argument value (of correct type).");
1511
1512/*
1513 * UnicodeError extends ValueError
1514 */
1515
1516SimpleExtendsException(PyExc_ValueError, UnicodeError,
1517 "Unicode related error.");
1518
Thomas Wouters477c8d52006-05-27 19:21:47 +00001519static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001520get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001521{
1522 if (!attr) {
1523 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1524 return NULL;
1525 }
1526
Christian Heimes72b710a2008-05-26 13:28:38 +00001527 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001528 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1529 return NULL;
1530 }
1531 Py_INCREF(attr);
1532 return attr;
1533}
1534
1535static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001536get_unicode(PyObject *attr, const char *name)
1537{
1538 if (!attr) {
1539 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1540 return NULL;
1541 }
1542
1543 if (!PyUnicode_Check(attr)) {
1544 PyErr_Format(PyExc_TypeError,
1545 "%.200s attribute must be unicode", name);
1546 return NULL;
1547 }
1548 Py_INCREF(attr);
1549 return attr;
1550}
1551
Walter Dörwaldd2034312007-05-18 16:29:38 +00001552static int
1553set_unicodefromstring(PyObject **attr, const char *value)
1554{
1555 PyObject *obj = PyUnicode_FromString(value);
1556 if (!obj)
1557 return -1;
1558 Py_CLEAR(*attr);
1559 *attr = obj;
1560 return 0;
1561}
1562
Thomas Wouters477c8d52006-05-27 19:21:47 +00001563PyObject *
1564PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1565{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001566 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001567}
1568
1569PyObject *
1570PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1571{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001572 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001573}
1574
1575PyObject *
1576PyUnicodeEncodeError_GetObject(PyObject *exc)
1577{
1578 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1579}
1580
1581PyObject *
1582PyUnicodeDecodeError_GetObject(PyObject *exc)
1583{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001584 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001585}
1586
1587PyObject *
1588PyUnicodeTranslateError_GetObject(PyObject *exc)
1589{
1590 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1591}
1592
1593int
1594PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1595{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001596 Py_ssize_t size;
1597 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1598 "object");
1599 if (!obj)
1600 return -1;
1601 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001602 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001603 if (*start<0)
1604 *start = 0; /*XXX check for values <0*/
1605 if (*start>=size)
1606 *start = size-1;
1607 Py_DECREF(obj);
1608 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001609}
1610
1611
1612int
1613PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1614{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001615 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001616 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001617 if (!obj)
1618 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001619 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001620 *start = ((PyUnicodeErrorObject *)exc)->start;
1621 if (*start<0)
1622 *start = 0;
1623 if (*start>=size)
1624 *start = size-1;
1625 Py_DECREF(obj);
1626 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001627}
1628
1629
1630int
1631PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1632{
1633 return PyUnicodeEncodeError_GetStart(exc, start);
1634}
1635
1636
1637int
1638PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1639{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001640 ((PyUnicodeErrorObject *)exc)->start = start;
1641 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001642}
1643
1644
1645int
1646PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1647{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001648 ((PyUnicodeErrorObject *)exc)->start = start;
1649 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001650}
1651
1652
1653int
1654PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1655{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001656 ((PyUnicodeErrorObject *)exc)->start = start;
1657 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001658}
1659
1660
1661int
1662PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1663{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001664 Py_ssize_t size;
1665 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1666 "object");
1667 if (!obj)
1668 return -1;
1669 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001670 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001671 if (*end<1)
1672 *end = 1;
1673 if (*end>size)
1674 *end = size;
1675 Py_DECREF(obj);
1676 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001677}
1678
1679
1680int
1681PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1682{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001683 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001684 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001685 if (!obj)
1686 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001687 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001688 *end = ((PyUnicodeErrorObject *)exc)->end;
1689 if (*end<1)
1690 *end = 1;
1691 if (*end>size)
1692 *end = size;
1693 Py_DECREF(obj);
1694 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001695}
1696
1697
1698int
1699PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1700{
1701 return PyUnicodeEncodeError_GetEnd(exc, start);
1702}
1703
1704
1705int
1706PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1707{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001708 ((PyUnicodeErrorObject *)exc)->end = end;
1709 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001710}
1711
1712
1713int
1714PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1715{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001716 ((PyUnicodeErrorObject *)exc)->end = end;
1717 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001718}
1719
1720
1721int
1722PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1723{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001724 ((PyUnicodeErrorObject *)exc)->end = end;
1725 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001726}
1727
1728PyObject *
1729PyUnicodeEncodeError_GetReason(PyObject *exc)
1730{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001731 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001732}
1733
1734
1735PyObject *
1736PyUnicodeDecodeError_GetReason(PyObject *exc)
1737{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001738 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001739}
1740
1741
1742PyObject *
1743PyUnicodeTranslateError_GetReason(PyObject *exc)
1744{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001745 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001746}
1747
1748
1749int
1750PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1751{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001752 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1753 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001754}
1755
1756
1757int
1758PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1759{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001760 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1761 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001762}
1763
1764
1765int
1766PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1767{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001768 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1769 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001770}
1771
1772
Thomas Wouters477c8d52006-05-27 19:21:47 +00001773static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001774UnicodeError_clear(PyUnicodeErrorObject *self)
1775{
1776 Py_CLEAR(self->encoding);
1777 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001778 Py_CLEAR(self->reason);
1779 return BaseException_clear((PyBaseExceptionObject *)self);
1780}
1781
1782static void
1783UnicodeError_dealloc(PyUnicodeErrorObject *self)
1784{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001785 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001786 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001787 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001788}
1789
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001790static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001791UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1792{
1793 Py_VISIT(self->encoding);
1794 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001795 Py_VISIT(self->reason);
1796 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1797}
1798
1799static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001800 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1801 PyDoc_STR("exception encoding")},
1802 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1803 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001804 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001805 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001806 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001807 PyDoc_STR("exception end")},
1808 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1809 PyDoc_STR("exception reason")},
1810 {NULL} /* Sentinel */
1811};
1812
1813
1814/*
1815 * UnicodeEncodeError extends UnicodeError
1816 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001817
1818static int
1819UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1820{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001821 PyUnicodeErrorObject *err;
1822
Thomas Wouters477c8d52006-05-27 19:21:47 +00001823 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1824 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001825
1826 err = (PyUnicodeErrorObject *)self;
1827
1828 Py_CLEAR(err->encoding);
1829 Py_CLEAR(err->object);
1830 Py_CLEAR(err->reason);
1831
1832 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1833 &PyUnicode_Type, &err->encoding,
1834 &PyUnicode_Type, &err->object,
1835 &err->start,
1836 &err->end,
1837 &PyUnicode_Type, &err->reason)) {
1838 err->encoding = err->object = err->reason = NULL;
1839 return -1;
1840 }
1841
Martin v. Löwisb09af032011-11-04 11:16:41 +01001842 if (PyUnicode_READY(err->object) < -1) {
1843 err->encoding = NULL;
1844 return -1;
1845 }
1846
Guido van Rossum98297ee2007-11-06 21:34:58 +00001847 Py_INCREF(err->encoding);
1848 Py_INCREF(err->object);
1849 Py_INCREF(err->reason);
1850
1851 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001852}
1853
1854static PyObject *
1855UnicodeEncodeError_str(PyObject *self)
1856{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001857 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001858 PyObject *result = NULL;
1859 PyObject *reason_str = NULL;
1860 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001861
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001862 if (!uself->object)
1863 /* Not properly initialized. */
1864 return PyUnicode_FromString("");
1865
Eric Smith0facd772010-02-24 15:42:29 +00001866 /* Get reason and encoding as strings, which they might not be if
1867 they've been modified after we were contructed. */
1868 reason_str = PyObject_Str(uself->reason);
1869 if (reason_str == NULL)
1870 goto done;
1871 encoding_str = PyObject_Str(uself->encoding);
1872 if (encoding_str == NULL)
1873 goto done;
1874
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001875 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1876 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001877 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001878 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001879 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001880 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001881 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001882 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001883 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001884 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001885 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001886 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001887 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001888 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001889 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001890 }
Eric Smith0facd772010-02-24 15:42:29 +00001891 else {
1892 result = PyUnicode_FromFormat(
1893 "'%U' codec can't encode characters in position %zd-%zd: %U",
1894 encoding_str,
1895 uself->start,
1896 uself->end-1,
1897 reason_str);
1898 }
1899done:
1900 Py_XDECREF(reason_str);
1901 Py_XDECREF(encoding_str);
1902 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001903}
1904
1905static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001906 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001907 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001908 sizeof(PyUnicodeErrorObject), 0,
1909 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1910 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1911 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001912 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1913 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001915 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916};
1917PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1918
1919PyObject *
1920PyUnicodeEncodeError_Create(
1921 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1922 Py_ssize_t start, Py_ssize_t end, const char *reason)
1923{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001924 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001925 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001926}
1927
1928
1929/*
1930 * UnicodeDecodeError extends UnicodeError
1931 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001932
1933static int
1934UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1935{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001936 PyUnicodeErrorObject *ude;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001937
Thomas Wouters477c8d52006-05-27 19:21:47 +00001938 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1939 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001940
1941 ude = (PyUnicodeErrorObject *)self;
1942
1943 Py_CLEAR(ude->encoding);
1944 Py_CLEAR(ude->object);
1945 Py_CLEAR(ude->reason);
1946
1947 if (!PyArg_ParseTuple(args, "O!OnnO!",
1948 &PyUnicode_Type, &ude->encoding,
1949 &ude->object,
1950 &ude->start,
1951 &ude->end,
1952 &PyUnicode_Type, &ude->reason)) {
1953 ude->encoding = ude->object = ude->reason = NULL;
1954 return -1;
1955 }
1956
Guido van Rossum98297ee2007-11-06 21:34:58 +00001957 Py_INCREF(ude->encoding);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001958 Py_INCREF(ude->object);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001959 Py_INCREF(ude->reason);
1960
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001961 if (!PyBytes_Check(ude->object)) {
1962 Py_buffer view;
1963 if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
1964 goto error;
1965 Py_CLEAR(ude->object);
1966 ude->object = PyBytes_FromStringAndSize(view.buf, view.len);
1967 PyBuffer_Release(&view);
1968 if (!ude->object)
1969 goto error;
1970 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001971 return 0;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001972
1973error:
1974 Py_CLEAR(ude->encoding);
1975 Py_CLEAR(ude->object);
1976 Py_CLEAR(ude->reason);
1977 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001978}
1979
1980static PyObject *
1981UnicodeDecodeError_str(PyObject *self)
1982{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001983 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001984 PyObject *result = NULL;
1985 PyObject *reason_str = NULL;
1986 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001987
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001988 if (!uself->object)
1989 /* Not properly initialized. */
1990 return PyUnicode_FromString("");
1991
Eric Smith0facd772010-02-24 15:42:29 +00001992 /* Get reason and encoding as strings, which they might not be if
1993 they've been modified after we were contructed. */
1994 reason_str = PyObject_Str(uself->reason);
1995 if (reason_str == NULL)
1996 goto done;
1997 encoding_str = PyObject_Str(uself->encoding);
1998 if (encoding_str == NULL)
1999 goto done;
2000
2001 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00002002 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00002003 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002004 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00002005 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002006 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002007 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002008 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002009 }
Eric Smith0facd772010-02-24 15:42:29 +00002010 else {
2011 result = PyUnicode_FromFormat(
2012 "'%U' codec can't decode bytes in position %zd-%zd: %U",
2013 encoding_str,
2014 uself->start,
2015 uself->end-1,
2016 reason_str
2017 );
2018 }
2019done:
2020 Py_XDECREF(reason_str);
2021 Py_XDECREF(encoding_str);
2022 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002023}
2024
2025static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002026 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002027 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002028 sizeof(PyUnicodeErrorObject), 0,
2029 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2030 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
2031 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002032 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
2033 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002034 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002035 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002036};
2037PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
2038
2039PyObject *
2040PyUnicodeDecodeError_Create(
2041 const char *encoding, const char *object, Py_ssize_t length,
2042 Py_ssize_t start, Py_ssize_t end, const char *reason)
2043{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00002044 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002045 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002046}
2047
2048
2049/*
2050 * UnicodeTranslateError extends UnicodeError
2051 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002052
2053static int
2054UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
2055 PyObject *kwds)
2056{
2057 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2058 return -1;
2059
2060 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002061 Py_CLEAR(self->reason);
2062
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002063 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002064 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002065 &self->start,
2066 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00002067 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002068 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002069 return -1;
2070 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002071
Thomas Wouters477c8d52006-05-27 19:21:47 +00002072 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002073 Py_INCREF(self->reason);
2074
2075 return 0;
2076}
2077
2078
2079static PyObject *
2080UnicodeTranslateError_str(PyObject *self)
2081{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002082 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00002083 PyObject *result = NULL;
2084 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002085
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04002086 if (!uself->object)
2087 /* Not properly initialized. */
2088 return PyUnicode_FromString("");
2089
Eric Smith0facd772010-02-24 15:42:29 +00002090 /* Get reason as a string, which it might not be if it's been
2091 modified after we were contructed. */
2092 reason_str = PyObject_Str(uself->reason);
2093 if (reason_str == NULL)
2094 goto done;
2095
Victor Stinner53b33e72011-11-21 01:17:27 +01002096 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2097 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002098 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002099 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002100 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002101 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002102 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002103 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002104 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002105 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002106 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002107 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002108 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002109 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002110 );
Eric Smith0facd772010-02-24 15:42:29 +00002111 } else {
2112 result = PyUnicode_FromFormat(
2113 "can't translate characters in position %zd-%zd: %U",
2114 uself->start,
2115 uself->end-1,
2116 reason_str
2117 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002118 }
Eric Smith0facd772010-02-24 15:42:29 +00002119done:
2120 Py_XDECREF(reason_str);
2121 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002122}
2123
2124static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002125 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002126 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002127 sizeof(PyUnicodeErrorObject), 0,
2128 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2129 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2130 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002131 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002132 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2133 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002134 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002135};
2136PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002138/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002139PyObject *
2140PyUnicodeTranslateError_Create(
2141 const Py_UNICODE *object, Py_ssize_t length,
2142 Py_ssize_t start, Py_ssize_t end, const char *reason)
2143{
2144 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002145 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002146}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002148PyObject *
2149_PyUnicodeTranslateError_Create(
2150 PyObject *object,
2151 Py_ssize_t start, Py_ssize_t end, const char *reason)
2152{
Victor Stinner69598d42014-04-04 20:59:44 +02002153 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002154 object, start, end, reason);
2155}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002156
2157/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002158 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002159 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002160SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002161 "Assertion failed.");
2162
2163
2164/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002165 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002166 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002167SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002168 "Base class for arithmetic errors.");
2169
2170
2171/*
2172 * FloatingPointError extends ArithmeticError
2173 */
2174SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2175 "Floating point operation failed.");
2176
2177
2178/*
2179 * OverflowError extends ArithmeticError
2180 */
2181SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2182 "Result too large to be represented.");
2183
2184
2185/*
2186 * ZeroDivisionError extends ArithmeticError
2187 */
2188SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2189 "Second argument to a division or modulo operation was zero.");
2190
2191
2192/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002193 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002194 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002195SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002196 "Internal error in the Python interpreter.\n"
2197 "\n"
2198 "Please report this to the Python maintainer, along with the traceback,\n"
2199 "the Python version, and the hardware/OS platform and version.");
2200
2201
2202/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002203 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002204 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002205SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002206 "Weak ref proxy used after referent went away.");
2207
2208
2209/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002210 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002211 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002212
2213#define MEMERRORS_SAVE 16
2214static PyBaseExceptionObject *memerrors_freelist = NULL;
2215static int memerrors_numfree = 0;
2216
2217static PyObject *
2218MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2219{
2220 PyBaseExceptionObject *self;
2221
2222 if (type != (PyTypeObject *) PyExc_MemoryError)
2223 return BaseException_new(type, args, kwds);
2224 if (memerrors_freelist == NULL)
2225 return BaseException_new(type, args, kwds);
2226 /* Fetch object from freelist and revive it */
2227 self = memerrors_freelist;
2228 self->args = PyTuple_New(0);
2229 /* This shouldn't happen since the empty tuple is persistent */
2230 if (self->args == NULL)
2231 return NULL;
2232 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2233 memerrors_numfree--;
2234 self->dict = NULL;
2235 _Py_NewReference((PyObject *)self);
2236 _PyObject_GC_TRACK(self);
2237 return (PyObject *)self;
2238}
2239
2240static void
2241MemoryError_dealloc(PyBaseExceptionObject *self)
2242{
2243 _PyObject_GC_UNTRACK(self);
2244 BaseException_clear(self);
2245 if (memerrors_numfree >= MEMERRORS_SAVE)
2246 Py_TYPE(self)->tp_free((PyObject *)self);
2247 else {
2248 self->dict = (PyObject *) memerrors_freelist;
2249 memerrors_freelist = self;
2250 memerrors_numfree++;
2251 }
2252}
2253
2254static void
2255preallocate_memerrors(void)
2256{
2257 /* We create enough MemoryErrors and then decref them, which will fill
2258 up the freelist. */
2259 int i;
2260 PyObject *errors[MEMERRORS_SAVE];
2261 for (i = 0; i < MEMERRORS_SAVE; i++) {
2262 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2263 NULL, NULL);
2264 if (!errors[i])
2265 Py_FatalError("Could not preallocate MemoryError object");
2266 }
2267 for (i = 0; i < MEMERRORS_SAVE; i++) {
2268 Py_DECREF(errors[i]);
2269 }
2270}
2271
2272static void
2273free_preallocated_memerrors(void)
2274{
2275 while (memerrors_freelist != NULL) {
2276 PyObject *self = (PyObject *) memerrors_freelist;
2277 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2278 Py_TYPE(self)->tp_free((PyObject *)self);
2279 }
2280}
2281
2282
2283static PyTypeObject _PyExc_MemoryError = {
2284 PyVarObject_HEAD_INIT(NULL, 0)
2285 "MemoryError",
2286 sizeof(PyBaseExceptionObject),
2287 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2288 0, 0, 0, 0, 0, 0, 0,
2289 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2290 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2291 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2292 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2293 (initproc)BaseException_init, 0, MemoryError_new
2294};
2295PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2296
Thomas Wouters477c8d52006-05-27 19:21:47 +00002297
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002298/*
2299 * BufferError extends Exception
2300 */
2301SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2302
Thomas Wouters477c8d52006-05-27 19:21:47 +00002303
2304/* Warning category docstrings */
2305
2306/*
2307 * Warning extends Exception
2308 */
2309SimpleExtendsException(PyExc_Exception, Warning,
2310 "Base class for warning categories.");
2311
2312
2313/*
2314 * UserWarning extends Warning
2315 */
2316SimpleExtendsException(PyExc_Warning, UserWarning,
2317 "Base class for warnings generated by user code.");
2318
2319
2320/*
2321 * DeprecationWarning extends Warning
2322 */
2323SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2324 "Base class for warnings about deprecated features.");
2325
2326
2327/*
2328 * PendingDeprecationWarning extends Warning
2329 */
2330SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2331 "Base class for warnings about features which will be deprecated\n"
2332 "in the future.");
2333
2334
2335/*
2336 * SyntaxWarning extends Warning
2337 */
2338SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2339 "Base class for warnings about dubious syntax.");
2340
2341
2342/*
2343 * RuntimeWarning extends Warning
2344 */
2345SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2346 "Base class for warnings about dubious runtime behavior.");
2347
2348
2349/*
2350 * FutureWarning extends Warning
2351 */
2352SimpleExtendsException(PyExc_Warning, FutureWarning,
2353 "Base class for warnings about constructs that will change semantically\n"
2354 "in the future.");
2355
2356
2357/*
2358 * ImportWarning extends Warning
2359 */
2360SimpleExtendsException(PyExc_Warning, ImportWarning,
2361 "Base class for warnings about probable mistakes in module imports");
2362
2363
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002364/*
2365 * UnicodeWarning extends Warning
2366 */
2367SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2368 "Base class for warnings about Unicode related problems, mostly\n"
2369 "related to conversion problems.");
2370
Georg Brandl08be72d2010-10-24 15:11:22 +00002371
Guido van Rossum98297ee2007-11-06 21:34:58 +00002372/*
2373 * BytesWarning extends Warning
2374 */
2375SimpleExtendsException(PyExc_Warning, BytesWarning,
2376 "Base class for warnings about bytes and buffer related problems, mostly\n"
2377 "related to conversion from str or comparing to str.");
2378
2379
Georg Brandl08be72d2010-10-24 15:11:22 +00002380/*
2381 * ResourceWarning extends Warning
2382 */
2383SimpleExtendsException(PyExc_Warning, ResourceWarning,
2384 "Base class for warnings about resource usage.");
2385
2386
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002387
Yury Selivanovf488fb42015-07-03 01:04:23 -04002388/* Pre-computed RecursionError instance for when recursion depth is reached.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002389 Meant to be used when normalizing the exception for exceeding the recursion
2390 depth will cause its own infinite recursion.
2391*/
2392PyObject *PyExc_RecursionErrorInst = NULL;
2393
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002394#define PRE_INIT(TYPE) \
2395 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2396 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2397 Py_FatalError("exceptions bootstrapping error."); \
2398 Py_INCREF(PyExc_ ## TYPE); \
2399 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002400
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002401#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002402 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2403 Py_FatalError("Module dictionary insertion problem.");
2404
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002405#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002406 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002407 PyExc_ ## NAME = PyExc_ ## TYPE; \
2408 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2409 Py_FatalError("Module dictionary insertion problem.");
2410
2411#define ADD_ERRNO(TYPE, CODE) { \
2412 PyObject *_code = PyLong_FromLong(CODE); \
2413 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2414 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2415 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002416 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002417 }
2418
2419#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002420#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002421/* The following constants were added to errno.h in VS2010 but have
2422 preferred WSA equivalents. */
2423#undef EADDRINUSE
2424#undef EADDRNOTAVAIL
2425#undef EAFNOSUPPORT
2426#undef EALREADY
2427#undef ECONNABORTED
2428#undef ECONNREFUSED
2429#undef ECONNRESET
2430#undef EDESTADDRREQ
2431#undef EHOSTUNREACH
2432#undef EINPROGRESS
2433#undef EISCONN
2434#undef ELOOP
2435#undef EMSGSIZE
2436#undef ENETDOWN
2437#undef ENETRESET
2438#undef ENETUNREACH
2439#undef ENOBUFS
2440#undef ENOPROTOOPT
2441#undef ENOTCONN
2442#undef ENOTSOCK
2443#undef EOPNOTSUPP
2444#undef EPROTONOSUPPORT
2445#undef EPROTOTYPE
2446#undef ETIMEDOUT
2447#undef EWOULDBLOCK
2448
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002449#if defined(WSAEALREADY) && !defined(EALREADY)
2450#define EALREADY WSAEALREADY
2451#endif
2452#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2453#define ECONNABORTED WSAECONNABORTED
2454#endif
2455#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2456#define ECONNREFUSED WSAECONNREFUSED
2457#endif
2458#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2459#define ECONNRESET WSAECONNRESET
2460#endif
2461#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2462#define EINPROGRESS WSAEINPROGRESS
2463#endif
2464#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2465#define ESHUTDOWN WSAESHUTDOWN
2466#endif
2467#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2468#define ETIMEDOUT WSAETIMEDOUT
2469#endif
2470#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2471#define EWOULDBLOCK WSAEWOULDBLOCK
2472#endif
2473#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002474
Martin v. Löwis1a214512008-06-11 05:26:20 +00002475void
Brett Cannonfd074152012-04-14 14:10:13 -04002476_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002477{
Brett Cannonfd074152012-04-14 14:10:13 -04002478 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002479
2480 PRE_INIT(BaseException)
2481 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002482 PRE_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002483 PRE_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002484 PRE_INIT(StopIteration)
2485 PRE_INIT(GeneratorExit)
2486 PRE_INIT(SystemExit)
2487 PRE_INIT(KeyboardInterrupt)
2488 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002489 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002490 PRE_INIT(EOFError)
2491 PRE_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002492 PRE_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002493 PRE_INIT(NotImplementedError)
2494 PRE_INIT(NameError)
2495 PRE_INIT(UnboundLocalError)
2496 PRE_INIT(AttributeError)
2497 PRE_INIT(SyntaxError)
2498 PRE_INIT(IndentationError)
2499 PRE_INIT(TabError)
2500 PRE_INIT(LookupError)
2501 PRE_INIT(IndexError)
2502 PRE_INIT(KeyError)
2503 PRE_INIT(ValueError)
2504 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002505 PRE_INIT(UnicodeEncodeError)
2506 PRE_INIT(UnicodeDecodeError)
2507 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002508 PRE_INIT(AssertionError)
2509 PRE_INIT(ArithmeticError)
2510 PRE_INIT(FloatingPointError)
2511 PRE_INIT(OverflowError)
2512 PRE_INIT(ZeroDivisionError)
2513 PRE_INIT(SystemError)
2514 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002515 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002516 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002517 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002518 PRE_INIT(Warning)
2519 PRE_INIT(UserWarning)
2520 PRE_INIT(DeprecationWarning)
2521 PRE_INIT(PendingDeprecationWarning)
2522 PRE_INIT(SyntaxWarning)
2523 PRE_INIT(RuntimeWarning)
2524 PRE_INIT(FutureWarning)
2525 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002526 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002527 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002528 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002529
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002530 /* OSError subclasses */
2531 PRE_INIT(ConnectionError);
2532
2533 PRE_INIT(BlockingIOError);
2534 PRE_INIT(BrokenPipeError);
2535 PRE_INIT(ChildProcessError);
2536 PRE_INIT(ConnectionAbortedError);
2537 PRE_INIT(ConnectionRefusedError);
2538 PRE_INIT(ConnectionResetError);
2539 PRE_INIT(FileExistsError);
2540 PRE_INIT(FileNotFoundError);
2541 PRE_INIT(IsADirectoryError);
2542 PRE_INIT(NotADirectoryError);
2543 PRE_INIT(InterruptedError);
2544 PRE_INIT(PermissionError);
2545 PRE_INIT(ProcessLookupError);
2546 PRE_INIT(TimeoutError);
2547
Thomas Wouters477c8d52006-05-27 19:21:47 +00002548 bdict = PyModule_GetDict(bltinmod);
2549 if (bdict == NULL)
2550 Py_FatalError("exceptions bootstrapping error.");
2551
2552 POST_INIT(BaseException)
2553 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002554 POST_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002555 POST_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002556 POST_INIT(StopIteration)
2557 POST_INIT(GeneratorExit)
2558 POST_INIT(SystemExit)
2559 POST_INIT(KeyboardInterrupt)
2560 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002561 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002562 INIT_ALIAS(EnvironmentError, OSError)
2563 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002564#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002565 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002566#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00002567 POST_INIT(EOFError)
2568 POST_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002569 POST_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002570 POST_INIT(NotImplementedError)
2571 POST_INIT(NameError)
2572 POST_INIT(UnboundLocalError)
2573 POST_INIT(AttributeError)
2574 POST_INIT(SyntaxError)
2575 POST_INIT(IndentationError)
2576 POST_INIT(TabError)
2577 POST_INIT(LookupError)
2578 POST_INIT(IndexError)
2579 POST_INIT(KeyError)
2580 POST_INIT(ValueError)
2581 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002582 POST_INIT(UnicodeEncodeError)
2583 POST_INIT(UnicodeDecodeError)
2584 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002585 POST_INIT(AssertionError)
2586 POST_INIT(ArithmeticError)
2587 POST_INIT(FloatingPointError)
2588 POST_INIT(OverflowError)
2589 POST_INIT(ZeroDivisionError)
2590 POST_INIT(SystemError)
2591 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002592 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002593 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002594 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002595 POST_INIT(Warning)
2596 POST_INIT(UserWarning)
2597 POST_INIT(DeprecationWarning)
2598 POST_INIT(PendingDeprecationWarning)
2599 POST_INIT(SyntaxWarning)
2600 POST_INIT(RuntimeWarning)
2601 POST_INIT(FutureWarning)
2602 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002603 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002604 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002605 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002606
Antoine Pitrouac456a12012-01-18 21:35:21 +01002607 if (!errnomap) {
2608 errnomap = PyDict_New();
2609 if (!errnomap)
2610 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2611 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002612
2613 /* OSError subclasses */
2614 POST_INIT(ConnectionError);
2615
2616 POST_INIT(BlockingIOError);
2617 ADD_ERRNO(BlockingIOError, EAGAIN);
2618 ADD_ERRNO(BlockingIOError, EALREADY);
2619 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2620 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2621 POST_INIT(BrokenPipeError);
2622 ADD_ERRNO(BrokenPipeError, EPIPE);
2623 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2624 POST_INIT(ChildProcessError);
2625 ADD_ERRNO(ChildProcessError, ECHILD);
2626 POST_INIT(ConnectionAbortedError);
2627 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2628 POST_INIT(ConnectionRefusedError);
2629 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2630 POST_INIT(ConnectionResetError);
2631 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2632 POST_INIT(FileExistsError);
2633 ADD_ERRNO(FileExistsError, EEXIST);
2634 POST_INIT(FileNotFoundError);
2635 ADD_ERRNO(FileNotFoundError, ENOENT);
2636 POST_INIT(IsADirectoryError);
2637 ADD_ERRNO(IsADirectoryError, EISDIR);
2638 POST_INIT(NotADirectoryError);
2639 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2640 POST_INIT(InterruptedError);
2641 ADD_ERRNO(InterruptedError, EINTR);
2642 POST_INIT(PermissionError);
2643 ADD_ERRNO(PermissionError, EACCES);
2644 ADD_ERRNO(PermissionError, EPERM);
2645 POST_INIT(ProcessLookupError);
2646 ADD_ERRNO(ProcessLookupError, ESRCH);
2647 POST_INIT(TimeoutError);
2648 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2649
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002650 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002651
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002652 if (!PyExc_RecursionErrorInst) {
Yury Selivanovf488fb42015-07-03 01:04:23 -04002653 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RecursionError, NULL, NULL);
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002654 if (!PyExc_RecursionErrorInst)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002655 Py_FatalError("Cannot pre-allocate RecursionError instance for "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002656 "recursion errors");
2657 else {
2658 PyBaseExceptionObject *err_inst =
2659 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2660 PyObject *args_tuple;
2661 PyObject *exc_message;
2662 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2663 if (!exc_message)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002664 Py_FatalError("cannot allocate argument for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002665 "pre-allocation");
2666 args_tuple = PyTuple_Pack(1, exc_message);
2667 if (!args_tuple)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002668 Py_FatalError("cannot allocate tuple for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002669 "pre-allocation");
2670 Py_DECREF(exc_message);
2671 if (BaseException_init(err_inst, args_tuple, NULL))
Yury Selivanovf488fb42015-07-03 01:04:23 -04002672 Py_FatalError("init of pre-allocated RecursionError failed");
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002673 Py_DECREF(args_tuple);
2674 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002675 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002676}
2677
2678void
2679_PyExc_Fini(void)
2680{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002681 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002682 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002683 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002684}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002685
2686/* Helper to do the equivalent of "raise X from Y" in C, but always using
2687 * the current exception rather than passing one in.
2688 *
2689 * We currently limit this to *only* exceptions that use the BaseException
2690 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2691 * those correctly without losing data and without losing backwards
2692 * compatibility.
2693 *
2694 * We also aim to rule out *all* exceptions that might be storing additional
2695 * state, whether by having a size difference relative to BaseException,
2696 * additional arguments passed in during construction or by having a
2697 * non-empty instance dict.
2698 *
2699 * We need to be very careful with what we wrap, since changing types to
2700 * a broader exception type would be backwards incompatible for
2701 * existing codecs, and with different init or new method implementations
2702 * may either not support instantiation with PyErr_Format or lose
2703 * information when instantiated that way.
2704 *
2705 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2706 * fact that exceptions are expected to support pickling. If more builtin
2707 * exceptions (e.g. AttributeError) start to be converted to rich
2708 * exceptions with additional attributes, that's probably a better approach
2709 * to pursue over adding special cases for particular stateful subclasses.
2710 *
2711 * Returns a borrowed reference to the new exception (if any), NULL if the
2712 * existing exception was left in place.
2713 */
2714PyObject *
2715_PyErr_TrySetFromCause(const char *format, ...)
2716{
2717 PyObject* msg_prefix;
2718 PyObject *exc, *val, *tb;
2719 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002720 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002721 PyObject *instance_args;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002722 Py_ssize_t num_args, caught_type_size, base_exc_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002723 PyObject *new_exc, *new_val, *new_tb;
2724 va_list vargs;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002725 int same_basic_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002726
Nick Coghlan8b097b42013-11-13 23:49:21 +10002727 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002728 caught_type = (PyTypeObject *)exc;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002729 /* Ensure type info indicates no extra state is stored at the C level
2730 * and that the type can be reinstantiated using PyErr_Format
2731 */
2732 caught_type_size = caught_type->tp_basicsize;
2733 base_exc_size = _PyExc_BaseException.tp_basicsize;
2734 same_basic_size = (
2735 caught_type_size == base_exc_size ||
2736 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
Victor Stinner12174a52014-08-15 23:17:38 +02002737 (caught_type_size == base_exc_size + (Py_ssize_t)sizeof(PyObject *))
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002738 )
2739 );
Benjamin Peterson079c9982013-11-13 23:25:01 -05002740 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002741 caught_type->tp_new != BaseException_new ||
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002742 !same_basic_size ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002743 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002744 /* We can't be sure we can wrap this safely, since it may contain
2745 * more state than just the exception type. Accordingly, we just
2746 * leave it alone.
2747 */
2748 PyErr_Restore(exc, val, tb);
2749 return NULL;
2750 }
2751
2752 /* Check the args are empty or contain a single string */
2753 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002754 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002755 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002756 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002757 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002758 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002759 /* More than 1 arg, or the one arg we do have isn't a string
2760 */
2761 PyErr_Restore(exc, val, tb);
2762 return NULL;
2763 }
2764
2765 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002766 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002767 if (dictptr != NULL && *dictptr != NULL &&
2768 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002769 /* While we could potentially copy a non-empty instance dictionary
2770 * to the replacement exception, for now we take the more
2771 * conservative path of leaving exceptions with attributes set
2772 * alone.
2773 */
2774 PyErr_Restore(exc, val, tb);
2775 return NULL;
2776 }
2777
2778 /* For exceptions that we can wrap safely, we chain the original
2779 * exception to a new one of the exact same type with an
2780 * error message that mentions the additional details and the
2781 * original exception.
2782 *
2783 * It would be nice to wrap OSError and various other exception
2784 * types as well, but that's quite a bit trickier due to the extra
2785 * state potentially stored on OSError instances.
2786 */
Nick Coghlan77b286b2014-01-27 00:53:38 +10002787 /* Ensure the traceback is set correctly on the existing exception */
2788 if (tb != NULL) {
2789 PyException_SetTraceback(val, tb);
2790 Py_DECREF(tb);
2791 }
Benjamin Petersone109ee82013-11-13 23:49:49 -05002792
Christian Heimes507eabd2013-11-14 01:39:35 +01002793#ifdef HAVE_STDARG_PROTOTYPES
2794 va_start(vargs, format);
2795#else
2796 va_start(vargs);
2797#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002798 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002799 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002800 if (msg_prefix == NULL) {
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002801 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002802 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002803 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002804 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002805
2806 PyErr_Format(exc, "%U (%s: %S)",
2807 msg_prefix, Py_TYPE(val)->tp_name, val);
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002808 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002809 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002810 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2811 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2812 PyException_SetCause(new_val, val);
2813 PyErr_Restore(new_exc, new_val, new_tb);
2814 return new_val;
2815}
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002816
2817
2818/* To help with migration from Python 2, SyntaxError.__init__ applies some
2819 * heuristics to try to report a more meaningful exception when print and
2820 * exec are used like statements.
2821 *
2822 * The heuristics are currently expected to detect the following cases:
2823 * - top level statement
2824 * - statement in a nested suite
2825 * - trailing section of a one line complex statement
2826 *
2827 * They're currently known not to trigger:
2828 * - after a semi-colon
2829 *
2830 * The error message can be a bit odd in cases where the "arguments" are
2831 * completely illegal syntactically, but that isn't worth the hassle of
2832 * fixing.
2833 *
2834 * We also can't do anything about cases that are legal Python 3 syntax
2835 * but mean something entirely different from what they did in Python 2
2836 * (omitting the arguments entirely, printing items preceded by a unary plus
2837 * or minus, using the stream redirection syntax).
2838 */
2839
2840static int
2841_check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start)
2842{
2843 /* Return values:
2844 * -1: an error occurred
2845 * 0: nothing happened
2846 * 1: the check triggered & the error message was changed
2847 */
2848 static PyObject *print_prefix = NULL;
2849 static PyObject *exec_prefix = NULL;
2850 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2851 int kind = PyUnicode_KIND(self->text);
2852 void *data = PyUnicode_DATA(self->text);
2853
2854 /* Ignore leading whitespace */
2855 while (start < text_len) {
2856 Py_UCS4 ch = PyUnicode_READ(kind, data, start);
2857 if (!Py_UNICODE_ISSPACE(ch))
2858 break;
2859 start++;
2860 }
2861 /* Checking against an empty or whitespace-only part of the string */
2862 if (start == text_len) {
2863 return 0;
2864 }
2865
2866 /* Check for legacy print statements */
2867 if (print_prefix == NULL) {
2868 print_prefix = PyUnicode_InternFromString("print ");
2869 if (print_prefix == NULL) {
2870 return -1;
2871 }
2872 }
2873 if (PyUnicode_Tailmatch(self->text, print_prefix,
2874 start, text_len, -1)) {
2875 Py_CLEAR(self->msg);
2876 self->msg = PyUnicode_FromString(
2877 "Missing parentheses in call to 'print'");
2878 return 1;
2879 }
2880
2881 /* Check for legacy exec statements */
2882 if (exec_prefix == NULL) {
2883 exec_prefix = PyUnicode_InternFromString("exec ");
2884 if (exec_prefix == NULL) {
2885 return -1;
2886 }
2887 }
2888 if (PyUnicode_Tailmatch(self->text, exec_prefix,
2889 start, text_len, -1)) {
2890 Py_CLEAR(self->msg);
2891 self->msg = PyUnicode_FromString(
2892 "Missing parentheses in call to 'exec'");
2893 return 1;
2894 }
2895 /* Fall back to the default error message */
2896 return 0;
2897}
2898
2899static int
2900_report_missing_parentheses(PySyntaxErrorObject *self)
2901{
2902 Py_UCS4 left_paren = 40;
2903 Py_ssize_t left_paren_index;
2904 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2905 int legacy_check_result = 0;
2906
2907 /* Skip entirely if there is an opening parenthesis */
2908 left_paren_index = PyUnicode_FindChar(self->text, left_paren,
2909 0, text_len, 1);
2910 if (left_paren_index < -1) {
2911 return -1;
2912 }
2913 if (left_paren_index != -1) {
2914 /* Use default error message for any line with an opening paren */
2915 return 0;
2916 }
2917 /* Handle the simple statement case */
2918 legacy_check_result = _check_for_legacy_statements(self, 0);
2919 if (legacy_check_result < 0) {
2920 return -1;
2921
2922 }
2923 if (legacy_check_result == 0) {
2924 /* Handle the one-line complex statement case */
2925 Py_UCS4 colon = 58;
2926 Py_ssize_t colon_index;
2927 colon_index = PyUnicode_FindChar(self->text, colon,
2928 0, text_len, 1);
2929 if (colon_index < -1) {
2930 return -1;
2931 }
2932 if (colon_index >= 0 && colon_index < text_len) {
2933 /* Check again, starting from just after the colon */
2934 if (_check_for_legacy_statements(self, colon_index+1) < 0) {
2935 return -1;
2936 }
2937 }
2938 }
2939 return 0;
2940}