blob: 351304fe433ef23142f8d8dab80c7b7af80cbab2 [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;
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +0200209 Py_SETREF(self->args, seq);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000210 return 0;
211}
212
Collin Winter828f04a2007-08-31 00:04:24 +0000213static PyObject *
214BaseException_get_tb(PyBaseExceptionObject *self)
215{
216 if (self->traceback == NULL) {
217 Py_INCREF(Py_None);
218 return Py_None;
219 }
220 Py_INCREF(self->traceback);
221 return self->traceback;
222}
223
224static int
225BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb)
226{
227 if (tb == NULL) {
228 PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
229 return -1;
230 }
231 else if (!(tb == Py_None || PyTraceBack_Check(tb))) {
232 PyErr_SetString(PyExc_TypeError,
233 "__traceback__ must be a traceback or None");
234 return -1;
235 }
236
237 Py_XINCREF(tb);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +0200238 Py_SETREF(self->traceback, tb);
Collin Winter828f04a2007-08-31 00:04:24 +0000239 return 0;
240}
241
Georg Brandlab6f2f62009-03-31 04:16:10 +0000242static PyObject *
243BaseException_get_context(PyObject *self) {
244 PyObject *res = PyException_GetContext(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500245 if (res)
246 return res; /* new reference already returned above */
Georg Brandlab6f2f62009-03-31 04:16:10 +0000247 Py_RETURN_NONE;
248}
249
250static int
251BaseException_set_context(PyObject *self, PyObject *arg) {
252 if (arg == NULL) {
253 PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
254 return -1;
255 } else if (arg == Py_None) {
256 arg = NULL;
257 } else if (!PyExceptionInstance_Check(arg)) {
258 PyErr_SetString(PyExc_TypeError, "exception context must be None "
259 "or derive from BaseException");
260 return -1;
261 } else {
262 /* PyException_SetContext steals this reference */
263 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 }
Georg Brandlab6f2f62009-03-31 04:16:10 +0000265 PyException_SetContext(self, arg);
266 return 0;
267}
268
269static PyObject *
270BaseException_get_cause(PyObject *self) {
271 PyObject *res = PyException_GetCause(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500272 if (res)
273 return res; /* new reference already returned above */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700274 Py_RETURN_NONE;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000275}
276
277static int
278BaseException_set_cause(PyObject *self, PyObject *arg) {
279 if (arg == NULL) {
280 PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
281 return -1;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700282 } else if (arg == Py_None) {
283 arg = NULL;
284 } else if (!PyExceptionInstance_Check(arg)) {
285 PyErr_SetString(PyExc_TypeError, "exception cause must be None "
286 "or derive from BaseException");
287 return -1;
288 } else {
289 /* PyException_SetCause steals this reference */
290 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700292 PyException_SetCause(self, arg);
293 return 0;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000294}
295
Guido van Rossum360e4b82007-05-14 22:51:27 +0000296
Thomas Wouters477c8d52006-05-27 19:21:47 +0000297static PyGetSetDef BaseException_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500298 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000299 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
Collin Winter828f04a2007-08-31 00:04:24 +0000300 {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
Georg Brandlab6f2f62009-03-31 04:16:10 +0000301 {"__context__", (getter)BaseException_get_context,
302 (setter)BaseException_set_context, PyDoc_STR("exception context")},
303 {"__cause__", (getter)BaseException_get_cause,
304 (setter)BaseException_set_cause, PyDoc_STR("exception cause")},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000305 {NULL},
306};
307
308
Collin Winter828f04a2007-08-31 00:04:24 +0000309PyObject *
310PyException_GetTraceback(PyObject *self) {
311 PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
312 Py_XINCREF(base_self->traceback);
313 return base_self->traceback;
314}
315
316
317int
318PyException_SetTraceback(PyObject *self, PyObject *tb) {
319 return BaseException_set_tb((PyBaseExceptionObject *)self, tb);
320}
321
322PyObject *
323PyException_GetCause(PyObject *self) {
324 PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
325 Py_XINCREF(cause);
326 return cause;
327}
328
329/* Steals a reference to cause */
330void
331PyException_SetCause(PyObject *self, PyObject *cause) {
332 PyObject *old_cause = ((PyBaseExceptionObject *)self)->cause;
333 ((PyBaseExceptionObject *)self)->cause = cause;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700334 ((PyBaseExceptionObject *)self)->suppress_context = 1;
Collin Winter828f04a2007-08-31 00:04:24 +0000335 Py_XDECREF(old_cause);
336}
337
338PyObject *
339PyException_GetContext(PyObject *self) {
340 PyObject *context = ((PyBaseExceptionObject *)self)->context;
341 Py_XINCREF(context);
342 return context;
343}
344
345/* Steals a reference to context */
346void
347PyException_SetContext(PyObject *self, PyObject *context) {
348 PyObject *old_context = ((PyBaseExceptionObject *)self)->context;
349 ((PyBaseExceptionObject *)self)->context = context;
350 Py_XDECREF(old_context);
351}
352
353
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700354static struct PyMemberDef BaseException_members[] = {
355 {"__suppress_context__", T_BOOL,
Antoine Pitrou32bc80c2012-05-16 12:51:55 +0200356 offsetof(PyBaseExceptionObject, suppress_context)},
357 {NULL}
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700358};
359
360
Thomas Wouters477c8d52006-05-27 19:21:47 +0000361static PyTypeObject _PyExc_BaseException = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000362 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +0000363 "BaseException", /*tp_name*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000364 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
365 0, /*tp_itemsize*/
366 (destructor)BaseException_dealloc, /*tp_dealloc*/
367 0, /*tp_print*/
368 0, /*tp_getattr*/
369 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000370 0, /* tp_reserved; */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000371 (reprfunc)BaseException_repr, /*tp_repr*/
372 0, /*tp_as_number*/
Brett Cannonba7bf492007-02-27 00:15:55 +0000373 0, /*tp_as_sequence*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000374 0, /*tp_as_mapping*/
375 0, /*tp_hash */
376 0, /*tp_call*/
377 (reprfunc)BaseException_str, /*tp_str*/
378 PyObject_GenericGetAttr, /*tp_getattro*/
379 PyObject_GenericSetAttr, /*tp_setattro*/
380 0, /*tp_as_buffer*/
Thomas Wouters27d517b2007-02-25 20:39:11 +0000381 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000383 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
384 (traverseproc)BaseException_traverse, /* tp_traverse */
385 (inquiry)BaseException_clear, /* tp_clear */
386 0, /* tp_richcompare */
387 0, /* tp_weaklistoffset */
388 0, /* tp_iter */
389 0, /* tp_iternext */
390 BaseException_methods, /* tp_methods */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700391 BaseException_members, /* tp_members */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000392 BaseException_getset, /* tp_getset */
393 0, /* tp_base */
394 0, /* tp_dict */
395 0, /* tp_descr_get */
396 0, /* tp_descr_set */
397 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
398 (initproc)BaseException_init, /* tp_init */
399 0, /* tp_alloc */
400 BaseException_new, /* tp_new */
401};
402/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
403from the previous implmentation and also allowing Python objects to be used
404in the API */
405PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
406
407/* note these macros omit the last semicolon so the macro invocation may
408 * include it and not look strange.
409 */
410#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
411static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000412 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000413 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000414 sizeof(PyBaseExceptionObject), \
415 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
416 0, 0, 0, 0, 0, 0, 0, \
417 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
418 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
419 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
420 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
421 (initproc)BaseException_init, 0, BaseException_new,\
422}; \
423PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
424
425#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
426static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000427 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000428 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000429 sizeof(Py ## EXCSTORE ## Object), \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000430 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431 0, 0, 0, 0, 0, \
432 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000433 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
434 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000435 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200436 (initproc)EXCSTORE ## _init, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437}; \
438PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
439
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200440#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
441 EXCMETHODS, EXCMEMBERS, EXCGETSET, \
442 EXCSTR, EXCDOC) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000444 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000445 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446 sizeof(Py ## EXCSTORE ## Object), 0, \
447 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
448 (reprfunc)EXCSTR, 0, 0, 0, \
449 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
450 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
451 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200452 EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000453 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200454 (initproc)EXCSTORE ## _init, 0, EXCNEW,\
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455}; \
456PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
457
458
459/*
460 * Exception extends BaseException
461 */
462SimpleExtendsException(PyExc_BaseException, Exception,
463 "Common base class for all non-exit exceptions.");
464
465
466/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000467 * TypeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000468 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000469SimpleExtendsException(PyExc_Exception, TypeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000470 "Inappropriate argument type.");
471
472
473/*
Yury Selivanov75445082015-05-11 22:57:16 -0400474 * StopAsyncIteration extends Exception
475 */
476SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
477 "Signal the end from iterator.__anext__().");
478
479
480/*
Thomas Wouters477c8d52006-05-27 19:21:47 +0000481 * StopIteration extends Exception
482 */
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000483
484static PyMemberDef StopIteration_members[] = {
485 {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
486 PyDoc_STR("generator return value")},
487 {NULL} /* Sentinel */
488};
489
490static int
491StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
492{
493 Py_ssize_t size = PyTuple_GET_SIZE(args);
494 PyObject *value;
495
496 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
497 return -1;
498 Py_CLEAR(self->value);
499 if (size > 0)
500 value = PyTuple_GET_ITEM(args, 0);
501 else
502 value = Py_None;
503 Py_INCREF(value);
504 self->value = value;
505 return 0;
506}
507
508static int
509StopIteration_clear(PyStopIterationObject *self)
510{
511 Py_CLEAR(self->value);
512 return BaseException_clear((PyBaseExceptionObject *)self);
513}
514
515static void
516StopIteration_dealloc(PyStopIterationObject *self)
517{
518 _PyObject_GC_UNTRACK(self);
519 StopIteration_clear(self);
520 Py_TYPE(self)->tp_free((PyObject *)self);
521}
522
523static int
524StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
525{
526 Py_VISIT(self->value);
527 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
528}
529
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000530ComplexExtendsException(
531 PyExc_Exception, /* base */
532 StopIteration, /* name */
533 StopIteration, /* prefix for *_init, etc */
534 0, /* new */
535 0, /* methods */
536 StopIteration_members, /* members */
537 0, /* getset */
538 0, /* str */
539 "Signal the end from iterator.__next__()."
540);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000541
542
543/*
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000544 * GeneratorExit extends BaseException
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545 */
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000546SimpleExtendsException(PyExc_BaseException, GeneratorExit,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547 "Request that a generator exit.");
548
549
550/*
551 * SystemExit extends BaseException
552 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000553
554static int
555SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
556{
557 Py_ssize_t size = PyTuple_GET_SIZE(args);
558
559 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
560 return -1;
561
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000562 if (size == 0)
563 return 0;
564 Py_CLEAR(self->code);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000565 if (size == 1)
566 self->code = PyTuple_GET_ITEM(args, 0);
Victor Stinner92236e52011-05-26 14:25:54 +0200567 else /* size > 1 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568 self->code = args;
569 Py_INCREF(self->code);
570 return 0;
571}
572
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000573static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000574SystemExit_clear(PySystemExitObject *self)
575{
576 Py_CLEAR(self->code);
577 return BaseException_clear((PyBaseExceptionObject *)self);
578}
579
580static void
581SystemExit_dealloc(PySystemExitObject *self)
582{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000583 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000584 SystemExit_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000585 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586}
587
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000588static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000589SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
590{
591 Py_VISIT(self->code);
592 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
593}
594
595static PyMemberDef SystemExit_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000596 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
597 PyDoc_STR("exception code")},
598 {NULL} /* Sentinel */
599};
600
601ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200602 0, 0, SystemExit_members, 0, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000603 "Request to exit from the interpreter.");
604
605/*
606 * KeyboardInterrupt extends BaseException
607 */
608SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
609 "Program interrupted by user.");
610
611
612/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000613 * ImportError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000614 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000615
Brett Cannon79ec55e2012-04-12 20:24:54 -0400616static int
617ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
618{
619 PyObject *msg = NULL;
620 PyObject *name = NULL;
621 PyObject *path = NULL;
622
623/* Macro replacement doesn't allow ## to start the first line of a macro,
624 so we move the assignment and NULL check into the if-statement. */
625#define GET_KWD(kwd) { \
626 kwd = PyDict_GetItemString(kwds, #kwd); \
627 if (kwd) { \
628 Py_CLEAR(self->kwd); \
629 self->kwd = kwd; \
630 Py_INCREF(self->kwd);\
631 if (PyDict_DelItemString(kwds, #kwd)) \
632 return -1; \
633 } \
634 }
635
636 if (kwds) {
637 GET_KWD(name);
638 GET_KWD(path);
639 }
640
641 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
642 return -1;
643 if (PyTuple_GET_SIZE(args) != 1)
644 return 0;
645 if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
646 return -1;
647
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +0200648 Py_INCREF(msg);
649 Py_SETREF(self->msg, msg);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400650
651 return 0;
652}
653
654static int
655ImportError_clear(PyImportErrorObject *self)
656{
657 Py_CLEAR(self->msg);
658 Py_CLEAR(self->name);
659 Py_CLEAR(self->path);
660 return BaseException_clear((PyBaseExceptionObject *)self);
661}
662
663static void
664ImportError_dealloc(PyImportErrorObject *self)
665{
666 _PyObject_GC_UNTRACK(self);
667 ImportError_clear(self);
668 Py_TYPE(self)->tp_free((PyObject *)self);
669}
670
671static int
672ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
673{
674 Py_VISIT(self->msg);
675 Py_VISIT(self->name);
676 Py_VISIT(self->path);
677 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
678}
679
680static PyObject *
681ImportError_str(PyImportErrorObject *self)
682{
Brett Cannon07c6e712012-08-24 13:05:09 -0400683 if (self->msg && PyUnicode_CheckExact(self->msg)) {
Brett Cannon79ec55e2012-04-12 20:24:54 -0400684 Py_INCREF(self->msg);
685 return self->msg;
686 }
687 else {
688 return BaseException_str((PyBaseExceptionObject *)self);
689 }
690}
691
692static PyMemberDef ImportError_members[] = {
693 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
694 PyDoc_STR("exception message")},
695 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
696 PyDoc_STR("module name")},
697 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
698 PyDoc_STR("module path")},
699 {NULL} /* Sentinel */
700};
701
702static PyMethodDef ImportError_methods[] = {
703 {NULL}
704};
705
706ComplexExtendsException(PyExc_Exception, ImportError,
707 ImportError, 0 /* new */,
708 ImportError_methods, ImportError_members,
709 0 /* getset */, ImportError_str,
710 "Import can't find module, or can't find name in "
711 "module.");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712
713/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200714 * OSError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000715 */
716
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200717#ifdef MS_WINDOWS
718#include "errmap.h"
719#endif
720
Thomas Wouters477c8d52006-05-27 19:21:47 +0000721/* Where a function has a single filename, such as open() or some
722 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
723 * called, giving a third argument which is the filename. But, so
724 * that old code using in-place unpacking doesn't break, e.g.:
725 *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200726 * except OSError, (errno, strerror):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000727 *
728 * we hack args so that it only contains two items. This also
729 * means we need our own __str__() which prints out the filename
730 * when it was supplied.
Larry Hastingsb0827312014-02-09 22:05:19 -0800731 *
732 * (If a function has two filenames, such as rename(), symlink(),
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800733 * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
734 * which allows passing in a second filename.)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200736
Antoine Pitroue0e27352011-12-15 14:31:28 +0100737/* This function doesn't cleanup on error, the caller should */
738static int
739oserror_parse_args(PyObject **p_args,
740 PyObject **myerrno, PyObject **strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800741 PyObject **filename, PyObject **filename2
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200742#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100743 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200744#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100745 )
746{
747 Py_ssize_t nargs;
748 PyObject *args = *p_args;
Larry Hastingsb0827312014-02-09 22:05:19 -0800749#ifndef MS_WINDOWS
750 /*
751 * ignored on non-Windows platforms,
752 * but parsed so OSError has a consistent signature
753 */
754 PyObject *_winerror = NULL;
755 PyObject **winerror = &_winerror;
756#endif /* MS_WINDOWS */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000757
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200758 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759
Larry Hastingsb0827312014-02-09 22:05:19 -0800760 if (nargs >= 2 && nargs <= 5) {
761 if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
762 myerrno, strerror,
763 filename, winerror, filename2))
Antoine Pitroue0e27352011-12-15 14:31:28 +0100764 return -1;
Larry Hastingsb0827312014-02-09 22:05:19 -0800765#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100766 if (*winerror && PyLong_Check(*winerror)) {
767 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200768 PyObject *newargs;
769 Py_ssize_t i;
770
Antoine Pitroue0e27352011-12-15 14:31:28 +0100771 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200772 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100773 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200774 /* Set errno to the corresponding POSIX errno (overriding
775 first argument). Windows Socket error codes (>= 10000)
776 have the same value as their POSIX counterparts.
777 */
778 if (winerrcode < 10000)
779 errcode = winerror_to_errno(winerrcode);
780 else
781 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100782 *myerrno = PyLong_FromLong(errcode);
783 if (!*myerrno)
784 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200785 newargs = PyTuple_New(nargs);
786 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100787 return -1;
788 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200789 for (i = 1; i < nargs; i++) {
790 PyObject *val = PyTuple_GET_ITEM(args, i);
791 Py_INCREF(val);
792 PyTuple_SET_ITEM(newargs, i, val);
793 }
794 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100795 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200796 }
Larry Hastingsb0827312014-02-09 22:05:19 -0800797#endif /* MS_WINDOWS */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200798 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000799
Antoine Pitroue0e27352011-12-15 14:31:28 +0100800 return 0;
801}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000802
Antoine Pitroue0e27352011-12-15 14:31:28 +0100803static int
804oserror_init(PyOSErrorObject *self, PyObject **p_args,
805 PyObject *myerrno, PyObject *strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800806 PyObject *filename, PyObject *filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100807#ifdef MS_WINDOWS
808 , PyObject *winerror
809#endif
810 )
811{
812 PyObject *args = *p_args;
813 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000814
815 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200816 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100817 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200818 PyNumber_Check(filename)) {
819 /* BlockingIOError's 3rd argument can be the number of
820 * characters written.
821 */
822 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
823 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100824 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200825 }
826 else {
827 Py_INCREF(filename);
828 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000829
Larry Hastingsb0827312014-02-09 22:05:19 -0800830 if (filename2 && filename2 != Py_None) {
831 Py_INCREF(filename2);
832 self->filename2 = filename2;
833 }
834
835 if (nargs >= 2 && nargs <= 5) {
836 /* filename, filename2, and winerror are removed from the args tuple
837 (for compatibility purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100838 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200839 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100840 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000841
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200842 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100843 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200844 }
845 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000846 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200847 Py_XINCREF(myerrno);
848 self->myerrno = myerrno;
849
850 Py_XINCREF(strerror);
851 self->strerror = strerror;
852
853#ifdef MS_WINDOWS
854 Py_XINCREF(winerror);
855 self->winerror = winerror;
856#endif
857
Antoine Pitroue0e27352011-12-15 14:31:28 +0100858 /* Steals the reference to args */
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +0200859 Py_SETREF(self->args, args);
Victor Stinner46ef3192013-11-14 22:31:41 +0100860 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100861
862 return 0;
863}
864
865static PyObject *
866OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
867static int
868OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
869
870static int
871oserror_use_init(PyTypeObject *type)
872{
Martin Panter7462b6492015-11-02 03:37:02 +0000873 /* When __init__ is defined in an OSError subclass, we want any
Antoine Pitroue0e27352011-12-15 14:31:28 +0100874 extraneous argument to __new__ to be ignored. The only reasonable
875 solution, given __new__ takes a variable number of arguments,
876 is to defer arg parsing and initialization to __init__.
877
878 But when __new__ is overriden as well, it should call our __new__
879 with the right arguments.
880
881 (see http://bugs.python.org/issue12555#msg148829 )
882 */
883 if (type->tp_init != (initproc) OSError_init &&
884 type->tp_new == (newfunc) OSError_new) {
885 assert((PyObject *) type != PyExc_OSError);
886 return 1;
887 }
888 return 0;
889}
890
891static PyObject *
892OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
893{
894 PyOSErrorObject *self = NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800895 PyObject *myerrno = NULL, *strerror = NULL;
896 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100897#ifdef MS_WINDOWS
898 PyObject *winerror = NULL;
899#endif
900
Victor Stinner46ef3192013-11-14 22:31:41 +0100901 Py_INCREF(args);
902
Antoine Pitroue0e27352011-12-15 14:31:28 +0100903 if (!oserror_use_init(type)) {
904 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100905 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100906
Larry Hastingsb0827312014-02-09 22:05:19 -0800907 if (oserror_parse_args(&args, &myerrno, &strerror,
908 &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100909#ifdef MS_WINDOWS
910 , &winerror
911#endif
912 ))
913 goto error;
914
915 if (myerrno && PyLong_Check(myerrno) &&
916 errnomap && (PyObject *) type == PyExc_OSError) {
917 PyObject *newtype;
918 newtype = PyDict_GetItem(errnomap, myerrno);
919 if (newtype) {
920 assert(PyType_Check(newtype));
921 type = (PyTypeObject *) newtype;
922 }
923 else if (PyErr_Occurred())
924 goto error;
925 }
926 }
927
928 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
929 if (!self)
930 goto error;
931
932 self->dict = NULL;
933 self->traceback = self->cause = self->context = NULL;
934 self->written = -1;
935
936 if (!oserror_use_init(type)) {
Larry Hastingsb0827312014-02-09 22:05:19 -0800937 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100938#ifdef MS_WINDOWS
939 , winerror
940#endif
941 ))
942 goto error;
943 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200944 else {
945 self->args = PyTuple_New(0);
946 if (self->args == NULL)
947 goto error;
948 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100949
Victor Stinner46ef3192013-11-14 22:31:41 +0100950 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200951 return (PyObject *) self;
952
953error:
954 Py_XDECREF(args);
955 Py_XDECREF(self);
956 return NULL;
957}
958
959static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100960OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200961{
Larry Hastingsb0827312014-02-09 22:05:19 -0800962 PyObject *myerrno = NULL, *strerror = NULL;
963 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100964#ifdef MS_WINDOWS
965 PyObject *winerror = NULL;
966#endif
967
968 if (!oserror_use_init(Py_TYPE(self)))
969 /* Everything already done in OSError_new */
970 return 0;
971
972 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
973 return -1;
974
975 Py_INCREF(args);
Larry Hastingsb0827312014-02-09 22:05:19 -0800976 if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100977#ifdef MS_WINDOWS
978 , &winerror
979#endif
980 ))
981 goto error;
982
Larry Hastingsb0827312014-02-09 22:05:19 -0800983 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100984#ifdef MS_WINDOWS
985 , winerror
986#endif
987 ))
988 goto error;
989
Thomas Wouters477c8d52006-05-27 19:21:47 +0000990 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100991
992error:
993 Py_XDECREF(args);
994 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000995}
996
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000997static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200998OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000999{
1000 Py_CLEAR(self->myerrno);
1001 Py_CLEAR(self->strerror);
1002 Py_CLEAR(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001003 Py_CLEAR(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001004#ifdef MS_WINDOWS
1005 Py_CLEAR(self->winerror);
1006#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001007 return BaseException_clear((PyBaseExceptionObject *)self);
1008}
1009
1010static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001011OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001012{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001013 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001014 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001015 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001016}
1017
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001018static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001019OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001020 void *arg)
1021{
1022 Py_VISIT(self->myerrno);
1023 Py_VISIT(self->strerror);
1024 Py_VISIT(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001025 Py_VISIT(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001026#ifdef MS_WINDOWS
1027 Py_VISIT(self->winerror);
1028#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001029 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1030}
1031
1032static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001033OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001034{
Larry Hastingsb0827312014-02-09 22:05:19 -08001035#define OR_NONE(x) ((x)?(x):Py_None)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001036#ifdef MS_WINDOWS
1037 /* If available, winerror has the priority over myerrno */
Larry Hastingsb0827312014-02-09 22:05:19 -08001038 if (self->winerror && self->filename) {
1039 if (self->filename2) {
1040 return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
1041 OR_NONE(self->winerror),
1042 OR_NONE(self->strerror),
1043 self->filename,
1044 self->filename2);
1045 } else {
1046 return PyUnicode_FromFormat("[WinError %S] %S: %R",
1047 OR_NONE(self->winerror),
1048 OR_NONE(self->strerror),
1049 self->filename);
1050 }
1051 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001052 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001053 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001054 self->winerror ? self->winerror: Py_None,
1055 self->strerror ? self->strerror: Py_None);
1056#endif
Larry Hastingsb0827312014-02-09 22:05:19 -08001057 if (self->filename) {
1058 if (self->filename2) {
1059 return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
1060 OR_NONE(self->myerrno),
1061 OR_NONE(self->strerror),
1062 self->filename,
1063 self->filename2);
1064 } else {
1065 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1066 OR_NONE(self->myerrno),
1067 OR_NONE(self->strerror),
1068 self->filename);
1069 }
1070 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001071 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001072 return PyUnicode_FromFormat("[Errno %S] %S",
1073 self->myerrno ? self->myerrno: Py_None,
1074 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001075 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001076}
1077
Thomas Wouters477c8d52006-05-27 19:21:47 +00001078static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001079OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080{
1081 PyObject *args = self->args;
1082 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001083
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001085 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001086 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Larry Hastingsb0827312014-02-09 22:05:19 -08001087 Py_ssize_t size = self->filename2 ? 5 : 3;
1088 args = PyTuple_New(size);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001089 if (!args)
1090 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001091
1092 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001093 Py_INCREF(tmp);
1094 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001095
1096 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001097 Py_INCREF(tmp);
1098 PyTuple_SET_ITEM(args, 1, tmp);
1099
1100 Py_INCREF(self->filename);
1101 PyTuple_SET_ITEM(args, 2, self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001102
1103 if (self->filename2) {
1104 /*
1105 * This tuple is essentially used as OSError(*args).
1106 * So, to recreate filename2, we need to pass in
1107 * winerror as well.
1108 */
1109 Py_INCREF(Py_None);
1110 PyTuple_SET_ITEM(args, 3, Py_None);
1111
1112 /* filename2 */
1113 Py_INCREF(self->filename2);
1114 PyTuple_SET_ITEM(args, 4, self->filename2);
1115 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001116 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001117 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001118
1119 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001120 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001121 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001122 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123 Py_DECREF(args);
1124 return res;
1125}
1126
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001127static PyObject *
1128OSError_written_get(PyOSErrorObject *self, void *context)
1129{
1130 if (self->written == -1) {
1131 PyErr_SetString(PyExc_AttributeError, "characters_written");
1132 return NULL;
1133 }
1134 return PyLong_FromSsize_t(self->written);
1135}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001136
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001137static int
1138OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1139{
1140 Py_ssize_t n;
1141 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1142 if (n == -1 && PyErr_Occurred())
1143 return -1;
1144 self->written = n;
1145 return 0;
1146}
1147
1148static PyMemberDef OSError_members[] = {
1149 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1150 PyDoc_STR("POSIX exception code")},
1151 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1152 PyDoc_STR("exception strerror")},
1153 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1154 PyDoc_STR("exception filename")},
Larry Hastingsb0827312014-02-09 22:05:19 -08001155 {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
1156 PyDoc_STR("second exception filename")},
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001157#ifdef MS_WINDOWS
1158 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1159 PyDoc_STR("Win32 exception code")},
1160#endif
1161 {NULL} /* Sentinel */
1162};
1163
1164static PyMethodDef OSError_methods[] = {
1165 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166 {NULL}
1167};
1168
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001169static PyGetSetDef OSError_getset[] = {
1170 {"characters_written", (getter) OSError_written_get,
1171 (setter) OSError_written_set, NULL},
1172 {NULL}
1173};
1174
1175
1176ComplexExtendsException(PyExc_Exception, OSError,
1177 OSError, OSError_new,
1178 OSError_methods, OSError_members, OSError_getset,
1179 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001180 "Base class for I/O related errors.");
1181
1182
1183/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001184 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001185 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001186MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1187 "I/O operation would block.");
1188MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1189 "Connection error.");
1190MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1191 "Child process error.");
1192MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1193 "Broken pipe.");
1194MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1195 "Connection aborted.");
1196MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1197 "Connection refused.");
1198MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1199 "Connection reset.");
1200MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1201 "File already exists.");
1202MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1203 "File not found.");
1204MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1205 "Operation doesn't work on directories.");
1206MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1207 "Operation only works on directories.");
1208MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1209 "Interrupted by signal.");
1210MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1211 "Not enough permissions.");
1212MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1213 "Process not found.");
1214MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1215 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001216
1217/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001218 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001220SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001221 "Read beyond end of file.");
1222
1223
1224/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001225 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001226 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001227SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001228 "Unspecified run-time error.");
1229
Yury Selivanovf488fb42015-07-03 01:04:23 -04001230/*
1231 * RecursionError extends RuntimeError
1232 */
1233SimpleExtendsException(PyExc_RuntimeError, RecursionError,
1234 "Recursion limit exceeded.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001235
1236/*
1237 * NotImplementedError extends RuntimeError
1238 */
1239SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1240 "Method or function hasn't been implemented yet.");
1241
1242/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001243 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001244 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001245SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001246 "Name not found globally.");
1247
1248/*
1249 * UnboundLocalError extends NameError
1250 */
1251SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1252 "Local name referenced but not bound to a value.");
1253
1254/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001255 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001257SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001258 "Attribute not found.");
1259
1260
1261/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001262 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001264
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001265/* Helper function to customise error message for some syntax errors */
1266static int _report_missing_parentheses(PySyntaxErrorObject *self);
1267
Thomas Wouters477c8d52006-05-27 19:21:47 +00001268static int
1269SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1270{
1271 PyObject *info = NULL;
1272 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1273
1274 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1275 return -1;
1276
1277 if (lenargs >= 1) {
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001278 Py_INCREF(PyTuple_GET_ITEM(args, 0));
1279 Py_SETREF(self->msg, PyTuple_GET_ITEM(args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001280 }
1281 if (lenargs == 2) {
1282 info = PyTuple_GET_ITEM(args, 1);
1283 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001284 if (!info)
1285 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001286
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001287 if (PyTuple_GET_SIZE(info) != 4) {
1288 /* not a very good error message, but it's what Python 2.4 gives */
1289 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1290 Py_DECREF(info);
1291 return -1;
1292 }
1293
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001294 Py_INCREF(PyTuple_GET_ITEM(info, 0));
1295 Py_SETREF(self->filename, PyTuple_GET_ITEM(info, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001296
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001297 Py_INCREF(PyTuple_GET_ITEM(info, 1));
1298 Py_SETREF(self->lineno, PyTuple_GET_ITEM(info, 1));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001299
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001300 Py_INCREF(PyTuple_GET_ITEM(info, 2));
1301 Py_SETREF(self->offset, PyTuple_GET_ITEM(info, 2));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001302
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001303 Py_INCREF(PyTuple_GET_ITEM(info, 3));
1304 Py_SETREF(self->text, PyTuple_GET_ITEM(info, 3));
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001305
1306 Py_DECREF(info);
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001307
1308 /* Issue #21669: Custom error for 'print' & 'exec' as statements */
1309 if (self->text && PyUnicode_Check(self->text)) {
1310 if (_report_missing_parentheses(self) < 0) {
1311 return -1;
1312 }
1313 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001314 }
1315 return 0;
1316}
1317
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001318static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319SyntaxError_clear(PySyntaxErrorObject *self)
1320{
1321 Py_CLEAR(self->msg);
1322 Py_CLEAR(self->filename);
1323 Py_CLEAR(self->lineno);
1324 Py_CLEAR(self->offset);
1325 Py_CLEAR(self->text);
1326 Py_CLEAR(self->print_file_and_line);
1327 return BaseException_clear((PyBaseExceptionObject *)self);
1328}
1329
1330static void
1331SyntaxError_dealloc(PySyntaxErrorObject *self)
1332{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001333 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001334 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001335 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001336}
1337
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001338static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001339SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1340{
1341 Py_VISIT(self->msg);
1342 Py_VISIT(self->filename);
1343 Py_VISIT(self->lineno);
1344 Py_VISIT(self->offset);
1345 Py_VISIT(self->text);
1346 Py_VISIT(self->print_file_and_line);
1347 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1348}
1349
1350/* This is called "my_basename" instead of just "basename" to avoid name
1351 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1352 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001353static PyObject*
1354my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001355{
Victor Stinner6237daf2010-04-28 17:26:19 +00001356 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001357 int kind;
1358 void *data;
1359
1360 if (PyUnicode_READY(name))
1361 return NULL;
1362 kind = PyUnicode_KIND(name);
1363 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001365 offset = 0;
1366 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001368 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001369 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001370 if (offset != 0)
1371 return PyUnicode_Substring(name, offset, size);
1372 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001373 Py_INCREF(name);
1374 return name;
1375 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001376}
1377
1378
1379static PyObject *
1380SyntaxError_str(PySyntaxErrorObject *self)
1381{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001382 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001383 PyObject *filename;
1384 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001385 /* Below, we always ignore overflow errors, just printing -1.
1386 Still, we cannot allow an OverflowError to be raised, so
1387 we need to call PyLong_AsLongAndOverflow. */
1388 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001389
1390 /* XXX -- do all the additional formatting with filename and
1391 lineno here */
1392
Neal Norwitzed2b7392007-08-26 04:51:10 +00001393 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001394 filename = my_basename(self->filename);
1395 if (filename == NULL)
1396 return NULL;
1397 } else {
1398 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001399 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001400 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001401
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001402 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001403 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001404
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001405 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001406 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001407 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001408 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001410 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001411 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001412 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001413 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001414 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001415 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001416 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001417 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001418 Py_XDECREF(filename);
1419 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001420}
1421
1422static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001423 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1424 PyDoc_STR("exception msg")},
1425 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1426 PyDoc_STR("exception filename")},
1427 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1428 PyDoc_STR("exception lineno")},
1429 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1430 PyDoc_STR("exception offset")},
1431 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1432 PyDoc_STR("exception text")},
1433 {"print_file_and_line", T_OBJECT,
1434 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1435 PyDoc_STR("exception print_file_and_line")},
1436 {NULL} /* Sentinel */
1437};
1438
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001439ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001440 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001441 SyntaxError_str, "Invalid syntax.");
1442
1443
1444/*
1445 * IndentationError extends SyntaxError
1446 */
1447MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1448 "Improper indentation.");
1449
1450
1451/*
1452 * TabError extends IndentationError
1453 */
1454MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1455 "Improper mixture of spaces and tabs.");
1456
1457
1458/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001459 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001460 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001461SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001462 "Base class for lookup errors.");
1463
1464
1465/*
1466 * IndexError extends LookupError
1467 */
1468SimpleExtendsException(PyExc_LookupError, IndexError,
1469 "Sequence index out of range.");
1470
1471
1472/*
1473 * KeyError extends LookupError
1474 */
1475static PyObject *
1476KeyError_str(PyBaseExceptionObject *self)
1477{
1478 /* If args is a tuple of exactly one item, apply repr to args[0].
1479 This is done so that e.g. the exception raised by {}[''] prints
1480 KeyError: ''
1481 rather than the confusing
1482 KeyError
1483 alone. The downside is that if KeyError is raised with an explanatory
1484 string, that string will be displayed in quotes. Too bad.
1485 If args is anything else, use the default BaseException__str__().
1486 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001487 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001488 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489 }
1490 return BaseException_str(self);
1491}
1492
1493ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001494 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001495
1496
1497/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001498 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001499 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001500SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001501 "Inappropriate argument value (of correct type).");
1502
1503/*
1504 * UnicodeError extends ValueError
1505 */
1506
1507SimpleExtendsException(PyExc_ValueError, UnicodeError,
1508 "Unicode related error.");
1509
Thomas Wouters477c8d52006-05-27 19:21:47 +00001510static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001511get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001512{
1513 if (!attr) {
1514 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1515 return NULL;
1516 }
1517
Christian Heimes72b710a2008-05-26 13:28:38 +00001518 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001519 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1520 return NULL;
1521 }
1522 Py_INCREF(attr);
1523 return attr;
1524}
1525
1526static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001527get_unicode(PyObject *attr, const char *name)
1528{
1529 if (!attr) {
1530 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1531 return NULL;
1532 }
1533
1534 if (!PyUnicode_Check(attr)) {
1535 PyErr_Format(PyExc_TypeError,
1536 "%.200s attribute must be unicode", name);
1537 return NULL;
1538 }
1539 Py_INCREF(attr);
1540 return attr;
1541}
1542
Walter Dörwaldd2034312007-05-18 16:29:38 +00001543static int
1544set_unicodefromstring(PyObject **attr, const char *value)
1545{
1546 PyObject *obj = PyUnicode_FromString(value);
1547 if (!obj)
1548 return -1;
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001549 Py_SETREF(*attr, obj);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001550 return 0;
1551}
1552
Thomas Wouters477c8d52006-05-27 19:21:47 +00001553PyObject *
1554PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1555{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001556 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001557}
1558
1559PyObject *
1560PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1561{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001562 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001563}
1564
1565PyObject *
1566PyUnicodeEncodeError_GetObject(PyObject *exc)
1567{
1568 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1569}
1570
1571PyObject *
1572PyUnicodeDecodeError_GetObject(PyObject *exc)
1573{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001574 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001575}
1576
1577PyObject *
1578PyUnicodeTranslateError_GetObject(PyObject *exc)
1579{
1580 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1581}
1582
1583int
1584PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1585{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001586 Py_ssize_t size;
1587 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1588 "object");
1589 if (!obj)
1590 return -1;
1591 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001592 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001593 if (*start<0)
1594 *start = 0; /*XXX check for values <0*/
1595 if (*start>=size)
1596 *start = size-1;
1597 Py_DECREF(obj);
1598 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001599}
1600
1601
1602int
1603PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1604{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001605 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001606 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001607 if (!obj)
1608 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001609 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001610 *start = ((PyUnicodeErrorObject *)exc)->start;
1611 if (*start<0)
1612 *start = 0;
1613 if (*start>=size)
1614 *start = size-1;
1615 Py_DECREF(obj);
1616 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001617}
1618
1619
1620int
1621PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1622{
1623 return PyUnicodeEncodeError_GetStart(exc, start);
1624}
1625
1626
1627int
1628PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1629{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001630 ((PyUnicodeErrorObject *)exc)->start = start;
1631 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001632}
1633
1634
1635int
1636PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1637{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001638 ((PyUnicodeErrorObject *)exc)->start = start;
1639 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001640}
1641
1642
1643int
1644PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1645{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001646 ((PyUnicodeErrorObject *)exc)->start = start;
1647 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001648}
1649
1650
1651int
1652PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1653{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001654 Py_ssize_t size;
1655 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1656 "object");
1657 if (!obj)
1658 return -1;
1659 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001660 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001661 if (*end<1)
1662 *end = 1;
1663 if (*end>size)
1664 *end = size;
1665 Py_DECREF(obj);
1666 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001667}
1668
1669
1670int
1671PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1672{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001673 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001674 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001675 if (!obj)
1676 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001677 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001678 *end = ((PyUnicodeErrorObject *)exc)->end;
1679 if (*end<1)
1680 *end = 1;
1681 if (*end>size)
1682 *end = size;
1683 Py_DECREF(obj);
1684 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001685}
1686
1687
1688int
1689PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1690{
1691 return PyUnicodeEncodeError_GetEnd(exc, start);
1692}
1693
1694
1695int
1696PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1697{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001698 ((PyUnicodeErrorObject *)exc)->end = end;
1699 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001700}
1701
1702
1703int
1704PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1705{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001706 ((PyUnicodeErrorObject *)exc)->end = end;
1707 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001708}
1709
1710
1711int
1712PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1713{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001714 ((PyUnicodeErrorObject *)exc)->end = end;
1715 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716}
1717
1718PyObject *
1719PyUnicodeEncodeError_GetReason(PyObject *exc)
1720{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001721 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001722}
1723
1724
1725PyObject *
1726PyUnicodeDecodeError_GetReason(PyObject *exc)
1727{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001728 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001729}
1730
1731
1732PyObject *
1733PyUnicodeTranslateError_GetReason(PyObject *exc)
1734{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001735 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001736}
1737
1738
1739int
1740PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1741{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001742 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1743 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001744}
1745
1746
1747int
1748PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1749{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001750 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1751 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001752}
1753
1754
1755int
1756PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1757{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001758 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1759 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001760}
1761
1762
Thomas Wouters477c8d52006-05-27 19:21:47 +00001763static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001764UnicodeError_clear(PyUnicodeErrorObject *self)
1765{
1766 Py_CLEAR(self->encoding);
1767 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001768 Py_CLEAR(self->reason);
1769 return BaseException_clear((PyBaseExceptionObject *)self);
1770}
1771
1772static void
1773UnicodeError_dealloc(PyUnicodeErrorObject *self)
1774{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001775 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001776 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001777 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001778}
1779
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001780static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001781UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1782{
1783 Py_VISIT(self->encoding);
1784 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001785 Py_VISIT(self->reason);
1786 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1787}
1788
1789static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001790 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1791 PyDoc_STR("exception encoding")},
1792 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1793 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001794 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001795 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001796 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001797 PyDoc_STR("exception end")},
1798 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1799 PyDoc_STR("exception reason")},
1800 {NULL} /* Sentinel */
1801};
1802
1803
1804/*
1805 * UnicodeEncodeError extends UnicodeError
1806 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001807
1808static int
1809UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1810{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001811 PyUnicodeErrorObject *err;
1812
Thomas Wouters477c8d52006-05-27 19:21:47 +00001813 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1814 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001815
1816 err = (PyUnicodeErrorObject *)self;
1817
1818 Py_CLEAR(err->encoding);
1819 Py_CLEAR(err->object);
1820 Py_CLEAR(err->reason);
1821
1822 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1823 &PyUnicode_Type, &err->encoding,
1824 &PyUnicode_Type, &err->object,
1825 &err->start,
1826 &err->end,
1827 &PyUnicode_Type, &err->reason)) {
1828 err->encoding = err->object = err->reason = NULL;
1829 return -1;
1830 }
1831
Martin v. Löwisb09af032011-11-04 11:16:41 +01001832 if (PyUnicode_READY(err->object) < -1) {
1833 err->encoding = NULL;
1834 return -1;
1835 }
1836
Guido van Rossum98297ee2007-11-06 21:34:58 +00001837 Py_INCREF(err->encoding);
1838 Py_INCREF(err->object);
1839 Py_INCREF(err->reason);
1840
1841 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001842}
1843
1844static PyObject *
1845UnicodeEncodeError_str(PyObject *self)
1846{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001847 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001848 PyObject *result = NULL;
1849 PyObject *reason_str = NULL;
1850 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001851
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001852 if (!uself->object)
1853 /* Not properly initialized. */
1854 return PyUnicode_FromString("");
1855
Eric Smith0facd772010-02-24 15:42:29 +00001856 /* Get reason and encoding as strings, which they might not be if
1857 they've been modified after we were contructed. */
1858 reason_str = PyObject_Str(uself->reason);
1859 if (reason_str == NULL)
1860 goto done;
1861 encoding_str = PyObject_Str(uself->encoding);
1862 if (encoding_str == NULL)
1863 goto done;
1864
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001865 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1866 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001867 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001868 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001869 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001870 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001871 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001872 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001873 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001874 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001875 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001876 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001877 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001878 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001879 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001880 }
Eric Smith0facd772010-02-24 15:42:29 +00001881 else {
1882 result = PyUnicode_FromFormat(
1883 "'%U' codec can't encode characters in position %zd-%zd: %U",
1884 encoding_str,
1885 uself->start,
1886 uself->end-1,
1887 reason_str);
1888 }
1889done:
1890 Py_XDECREF(reason_str);
1891 Py_XDECREF(encoding_str);
1892 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001893}
1894
1895static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001896 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001897 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001898 sizeof(PyUnicodeErrorObject), 0,
1899 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1900 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1901 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001902 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1903 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001905 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001906};
1907PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1908
1909PyObject *
1910PyUnicodeEncodeError_Create(
1911 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1912 Py_ssize_t start, Py_ssize_t end, const char *reason)
1913{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001914 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001915 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916}
1917
1918
1919/*
1920 * UnicodeDecodeError extends UnicodeError
1921 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922
1923static int
1924UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1925{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001926 PyUnicodeErrorObject *ude;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001927
Thomas Wouters477c8d52006-05-27 19:21:47 +00001928 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1929 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001930
1931 ude = (PyUnicodeErrorObject *)self;
1932
1933 Py_CLEAR(ude->encoding);
1934 Py_CLEAR(ude->object);
1935 Py_CLEAR(ude->reason);
1936
1937 if (!PyArg_ParseTuple(args, "O!OnnO!",
1938 &PyUnicode_Type, &ude->encoding,
1939 &ude->object,
1940 &ude->start,
1941 &ude->end,
1942 &PyUnicode_Type, &ude->reason)) {
1943 ude->encoding = ude->object = ude->reason = NULL;
1944 return -1;
1945 }
1946
Guido van Rossum98297ee2007-11-06 21:34:58 +00001947 Py_INCREF(ude->encoding);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001948 Py_INCREF(ude->object);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001949 Py_INCREF(ude->reason);
1950
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001951 if (!PyBytes_Check(ude->object)) {
1952 Py_buffer view;
1953 if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
1954 goto error;
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001955 Py_SETREF(ude->object, PyBytes_FromStringAndSize(view.buf, view.len));
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001956 PyBuffer_Release(&view);
1957 if (!ude->object)
1958 goto error;
1959 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001960 return 0;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001961
1962error:
1963 Py_CLEAR(ude->encoding);
1964 Py_CLEAR(ude->object);
1965 Py_CLEAR(ude->reason);
1966 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001967}
1968
1969static PyObject *
1970UnicodeDecodeError_str(PyObject *self)
1971{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001972 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001973 PyObject *result = NULL;
1974 PyObject *reason_str = NULL;
1975 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001976
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001977 if (!uself->object)
1978 /* Not properly initialized. */
1979 return PyUnicode_FromString("");
1980
Eric Smith0facd772010-02-24 15:42:29 +00001981 /* Get reason and encoding as strings, which they might not be if
1982 they've been modified after we were contructed. */
1983 reason_str = PyObject_Str(uself->reason);
1984 if (reason_str == NULL)
1985 goto done;
1986 encoding_str = PyObject_Str(uself->encoding);
1987 if (encoding_str == NULL)
1988 goto done;
1989
1990 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001991 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00001992 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001993 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00001994 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001995 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001996 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001997 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001998 }
Eric Smith0facd772010-02-24 15:42:29 +00001999 else {
2000 result = PyUnicode_FromFormat(
2001 "'%U' codec can't decode bytes in position %zd-%zd: %U",
2002 encoding_str,
2003 uself->start,
2004 uself->end-1,
2005 reason_str
2006 );
2007 }
2008done:
2009 Py_XDECREF(reason_str);
2010 Py_XDECREF(encoding_str);
2011 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002012}
2013
2014static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002015 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002016 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002017 sizeof(PyUnicodeErrorObject), 0,
2018 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2019 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
2020 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002021 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
2022 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002023 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002024 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002025};
2026PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
2027
2028PyObject *
2029PyUnicodeDecodeError_Create(
2030 const char *encoding, const char *object, Py_ssize_t length,
2031 Py_ssize_t start, Py_ssize_t end, const char *reason)
2032{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00002033 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002034 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002035}
2036
2037
2038/*
2039 * UnicodeTranslateError extends UnicodeError
2040 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002041
2042static int
2043UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
2044 PyObject *kwds)
2045{
2046 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2047 return -1;
2048
2049 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002050 Py_CLEAR(self->reason);
2051
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002052 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002053 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002054 &self->start,
2055 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00002056 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002057 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002058 return -1;
2059 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002060
Thomas Wouters477c8d52006-05-27 19:21:47 +00002061 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002062 Py_INCREF(self->reason);
2063
2064 return 0;
2065}
2066
2067
2068static PyObject *
2069UnicodeTranslateError_str(PyObject *self)
2070{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002071 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00002072 PyObject *result = NULL;
2073 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002074
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04002075 if (!uself->object)
2076 /* Not properly initialized. */
2077 return PyUnicode_FromString("");
2078
Eric Smith0facd772010-02-24 15:42:29 +00002079 /* Get reason as a string, which it might not be if it's been
2080 modified after we were contructed. */
2081 reason_str = PyObject_Str(uself->reason);
2082 if (reason_str == NULL)
2083 goto done;
2084
Victor Stinner53b33e72011-11-21 01:17:27 +01002085 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2086 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002087 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002088 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002089 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002090 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002091 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002092 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002093 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002094 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002095 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002096 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002097 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002098 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002099 );
Eric Smith0facd772010-02-24 15:42:29 +00002100 } else {
2101 result = PyUnicode_FromFormat(
2102 "can't translate characters in position %zd-%zd: %U",
2103 uself->start,
2104 uself->end-1,
2105 reason_str
2106 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002107 }
Eric Smith0facd772010-02-24 15:42:29 +00002108done:
2109 Py_XDECREF(reason_str);
2110 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002111}
2112
2113static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002114 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002115 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002116 sizeof(PyUnicodeErrorObject), 0,
2117 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2118 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2119 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002120 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002121 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2122 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002123 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002124};
2125PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002127/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002128PyObject *
2129PyUnicodeTranslateError_Create(
2130 const Py_UNICODE *object, Py_ssize_t length,
2131 Py_ssize_t start, Py_ssize_t end, const char *reason)
2132{
2133 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002134 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002135}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002137PyObject *
2138_PyUnicodeTranslateError_Create(
2139 PyObject *object,
2140 Py_ssize_t start, Py_ssize_t end, const char *reason)
2141{
Victor Stinner69598d42014-04-04 20:59:44 +02002142 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002143 object, start, end, reason);
2144}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002145
2146/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002147 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002148 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002149SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002150 "Assertion failed.");
2151
2152
2153/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002154 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002155 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002156SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002157 "Base class for arithmetic errors.");
2158
2159
2160/*
2161 * FloatingPointError extends ArithmeticError
2162 */
2163SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2164 "Floating point operation failed.");
2165
2166
2167/*
2168 * OverflowError extends ArithmeticError
2169 */
2170SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2171 "Result too large to be represented.");
2172
2173
2174/*
2175 * ZeroDivisionError extends ArithmeticError
2176 */
2177SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2178 "Second argument to a division or modulo operation was zero.");
2179
2180
2181/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002182 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002183 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002184SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002185 "Internal error in the Python interpreter.\n"
2186 "\n"
2187 "Please report this to the Python maintainer, along with the traceback,\n"
2188 "the Python version, and the hardware/OS platform and version.");
2189
2190
2191/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002192 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002193 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002194SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002195 "Weak ref proxy used after referent went away.");
2196
2197
2198/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002199 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002200 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002201
2202#define MEMERRORS_SAVE 16
2203static PyBaseExceptionObject *memerrors_freelist = NULL;
2204static int memerrors_numfree = 0;
2205
2206static PyObject *
2207MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2208{
2209 PyBaseExceptionObject *self;
2210
2211 if (type != (PyTypeObject *) PyExc_MemoryError)
2212 return BaseException_new(type, args, kwds);
2213 if (memerrors_freelist == NULL)
2214 return BaseException_new(type, args, kwds);
2215 /* Fetch object from freelist and revive it */
2216 self = memerrors_freelist;
2217 self->args = PyTuple_New(0);
2218 /* This shouldn't happen since the empty tuple is persistent */
2219 if (self->args == NULL)
2220 return NULL;
2221 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2222 memerrors_numfree--;
2223 self->dict = NULL;
2224 _Py_NewReference((PyObject *)self);
2225 _PyObject_GC_TRACK(self);
2226 return (PyObject *)self;
2227}
2228
2229static void
2230MemoryError_dealloc(PyBaseExceptionObject *self)
2231{
2232 _PyObject_GC_UNTRACK(self);
2233 BaseException_clear(self);
2234 if (memerrors_numfree >= MEMERRORS_SAVE)
2235 Py_TYPE(self)->tp_free((PyObject *)self);
2236 else {
2237 self->dict = (PyObject *) memerrors_freelist;
2238 memerrors_freelist = self;
2239 memerrors_numfree++;
2240 }
2241}
2242
2243static void
2244preallocate_memerrors(void)
2245{
2246 /* We create enough MemoryErrors and then decref them, which will fill
2247 up the freelist. */
2248 int i;
2249 PyObject *errors[MEMERRORS_SAVE];
2250 for (i = 0; i < MEMERRORS_SAVE; i++) {
2251 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2252 NULL, NULL);
2253 if (!errors[i])
2254 Py_FatalError("Could not preallocate MemoryError object");
2255 }
2256 for (i = 0; i < MEMERRORS_SAVE; i++) {
2257 Py_DECREF(errors[i]);
2258 }
2259}
2260
2261static void
2262free_preallocated_memerrors(void)
2263{
2264 while (memerrors_freelist != NULL) {
2265 PyObject *self = (PyObject *) memerrors_freelist;
2266 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2267 Py_TYPE(self)->tp_free((PyObject *)self);
2268 }
2269}
2270
2271
2272static PyTypeObject _PyExc_MemoryError = {
2273 PyVarObject_HEAD_INIT(NULL, 0)
2274 "MemoryError",
2275 sizeof(PyBaseExceptionObject),
2276 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2277 0, 0, 0, 0, 0, 0, 0,
2278 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2279 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2280 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2281 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2282 (initproc)BaseException_init, 0, MemoryError_new
2283};
2284PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2285
Thomas Wouters477c8d52006-05-27 19:21:47 +00002286
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002287/*
2288 * BufferError extends Exception
2289 */
2290SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2291
Thomas Wouters477c8d52006-05-27 19:21:47 +00002292
2293/* Warning category docstrings */
2294
2295/*
2296 * Warning extends Exception
2297 */
2298SimpleExtendsException(PyExc_Exception, Warning,
2299 "Base class for warning categories.");
2300
2301
2302/*
2303 * UserWarning extends Warning
2304 */
2305SimpleExtendsException(PyExc_Warning, UserWarning,
2306 "Base class for warnings generated by user code.");
2307
2308
2309/*
2310 * DeprecationWarning extends Warning
2311 */
2312SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2313 "Base class for warnings about deprecated features.");
2314
2315
2316/*
2317 * PendingDeprecationWarning extends Warning
2318 */
2319SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2320 "Base class for warnings about features which will be deprecated\n"
2321 "in the future.");
2322
2323
2324/*
2325 * SyntaxWarning extends Warning
2326 */
2327SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2328 "Base class for warnings about dubious syntax.");
2329
2330
2331/*
2332 * RuntimeWarning extends Warning
2333 */
2334SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2335 "Base class for warnings about dubious runtime behavior.");
2336
2337
2338/*
2339 * FutureWarning extends Warning
2340 */
2341SimpleExtendsException(PyExc_Warning, FutureWarning,
2342 "Base class for warnings about constructs that will change semantically\n"
2343 "in the future.");
2344
2345
2346/*
2347 * ImportWarning extends Warning
2348 */
2349SimpleExtendsException(PyExc_Warning, ImportWarning,
2350 "Base class for warnings about probable mistakes in module imports");
2351
2352
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002353/*
2354 * UnicodeWarning extends Warning
2355 */
2356SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2357 "Base class for warnings about Unicode related problems, mostly\n"
2358 "related to conversion problems.");
2359
Georg Brandl08be72d2010-10-24 15:11:22 +00002360
Guido van Rossum98297ee2007-11-06 21:34:58 +00002361/*
2362 * BytesWarning extends Warning
2363 */
2364SimpleExtendsException(PyExc_Warning, BytesWarning,
2365 "Base class for warnings about bytes and buffer related problems, mostly\n"
2366 "related to conversion from str or comparing to str.");
2367
2368
Georg Brandl08be72d2010-10-24 15:11:22 +00002369/*
2370 * ResourceWarning extends Warning
2371 */
2372SimpleExtendsException(PyExc_Warning, ResourceWarning,
2373 "Base class for warnings about resource usage.");
2374
2375
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002376
Yury Selivanovf488fb42015-07-03 01:04:23 -04002377/* Pre-computed RecursionError instance for when recursion depth is reached.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002378 Meant to be used when normalizing the exception for exceeding the recursion
2379 depth will cause its own infinite recursion.
2380*/
2381PyObject *PyExc_RecursionErrorInst = NULL;
2382
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002383#define PRE_INIT(TYPE) \
2384 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2385 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2386 Py_FatalError("exceptions bootstrapping error."); \
2387 Py_INCREF(PyExc_ ## TYPE); \
2388 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002389
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002390#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002391 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2392 Py_FatalError("Module dictionary insertion problem.");
2393
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002394#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002395 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002396 PyExc_ ## NAME = PyExc_ ## TYPE; \
2397 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2398 Py_FatalError("Module dictionary insertion problem.");
2399
2400#define ADD_ERRNO(TYPE, CODE) { \
2401 PyObject *_code = PyLong_FromLong(CODE); \
2402 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2403 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2404 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002405 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002406 }
2407
2408#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002409#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002410/* The following constants were added to errno.h in VS2010 but have
2411 preferred WSA equivalents. */
2412#undef EADDRINUSE
2413#undef EADDRNOTAVAIL
2414#undef EAFNOSUPPORT
2415#undef EALREADY
2416#undef ECONNABORTED
2417#undef ECONNREFUSED
2418#undef ECONNRESET
2419#undef EDESTADDRREQ
2420#undef EHOSTUNREACH
2421#undef EINPROGRESS
2422#undef EISCONN
2423#undef ELOOP
2424#undef EMSGSIZE
2425#undef ENETDOWN
2426#undef ENETRESET
2427#undef ENETUNREACH
2428#undef ENOBUFS
2429#undef ENOPROTOOPT
2430#undef ENOTCONN
2431#undef ENOTSOCK
2432#undef EOPNOTSUPP
2433#undef EPROTONOSUPPORT
2434#undef EPROTOTYPE
2435#undef ETIMEDOUT
2436#undef EWOULDBLOCK
2437
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002438#if defined(WSAEALREADY) && !defined(EALREADY)
2439#define EALREADY WSAEALREADY
2440#endif
2441#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2442#define ECONNABORTED WSAECONNABORTED
2443#endif
2444#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2445#define ECONNREFUSED WSAECONNREFUSED
2446#endif
2447#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2448#define ECONNRESET WSAECONNRESET
2449#endif
2450#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2451#define EINPROGRESS WSAEINPROGRESS
2452#endif
2453#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2454#define ESHUTDOWN WSAESHUTDOWN
2455#endif
2456#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2457#define ETIMEDOUT WSAETIMEDOUT
2458#endif
2459#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2460#define EWOULDBLOCK WSAEWOULDBLOCK
2461#endif
2462#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002463
Martin v. Löwis1a214512008-06-11 05:26:20 +00002464void
Brett Cannonfd074152012-04-14 14:10:13 -04002465_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002466{
Brett Cannonfd074152012-04-14 14:10:13 -04002467 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002468
2469 PRE_INIT(BaseException)
2470 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002471 PRE_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002472 PRE_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002473 PRE_INIT(StopIteration)
2474 PRE_INIT(GeneratorExit)
2475 PRE_INIT(SystemExit)
2476 PRE_INIT(KeyboardInterrupt)
2477 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002478 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002479 PRE_INIT(EOFError)
2480 PRE_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002481 PRE_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002482 PRE_INIT(NotImplementedError)
2483 PRE_INIT(NameError)
2484 PRE_INIT(UnboundLocalError)
2485 PRE_INIT(AttributeError)
2486 PRE_INIT(SyntaxError)
2487 PRE_INIT(IndentationError)
2488 PRE_INIT(TabError)
2489 PRE_INIT(LookupError)
2490 PRE_INIT(IndexError)
2491 PRE_INIT(KeyError)
2492 PRE_INIT(ValueError)
2493 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002494 PRE_INIT(UnicodeEncodeError)
2495 PRE_INIT(UnicodeDecodeError)
2496 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002497 PRE_INIT(AssertionError)
2498 PRE_INIT(ArithmeticError)
2499 PRE_INIT(FloatingPointError)
2500 PRE_INIT(OverflowError)
2501 PRE_INIT(ZeroDivisionError)
2502 PRE_INIT(SystemError)
2503 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002504 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002505 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002506 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002507 PRE_INIT(Warning)
2508 PRE_INIT(UserWarning)
2509 PRE_INIT(DeprecationWarning)
2510 PRE_INIT(PendingDeprecationWarning)
2511 PRE_INIT(SyntaxWarning)
2512 PRE_INIT(RuntimeWarning)
2513 PRE_INIT(FutureWarning)
2514 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002515 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002516 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002517 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002518
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002519 /* OSError subclasses */
2520 PRE_INIT(ConnectionError);
2521
2522 PRE_INIT(BlockingIOError);
2523 PRE_INIT(BrokenPipeError);
2524 PRE_INIT(ChildProcessError);
2525 PRE_INIT(ConnectionAbortedError);
2526 PRE_INIT(ConnectionRefusedError);
2527 PRE_INIT(ConnectionResetError);
2528 PRE_INIT(FileExistsError);
2529 PRE_INIT(FileNotFoundError);
2530 PRE_INIT(IsADirectoryError);
2531 PRE_INIT(NotADirectoryError);
2532 PRE_INIT(InterruptedError);
2533 PRE_INIT(PermissionError);
2534 PRE_INIT(ProcessLookupError);
2535 PRE_INIT(TimeoutError);
2536
Thomas Wouters477c8d52006-05-27 19:21:47 +00002537 bdict = PyModule_GetDict(bltinmod);
2538 if (bdict == NULL)
2539 Py_FatalError("exceptions bootstrapping error.");
2540
2541 POST_INIT(BaseException)
2542 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002543 POST_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002544 POST_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002545 POST_INIT(StopIteration)
2546 POST_INIT(GeneratorExit)
2547 POST_INIT(SystemExit)
2548 POST_INIT(KeyboardInterrupt)
2549 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002550 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002551 INIT_ALIAS(EnvironmentError, OSError)
2552 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002553#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002554 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002555#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00002556 POST_INIT(EOFError)
2557 POST_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002558 POST_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002559 POST_INIT(NotImplementedError)
2560 POST_INIT(NameError)
2561 POST_INIT(UnboundLocalError)
2562 POST_INIT(AttributeError)
2563 POST_INIT(SyntaxError)
2564 POST_INIT(IndentationError)
2565 POST_INIT(TabError)
2566 POST_INIT(LookupError)
2567 POST_INIT(IndexError)
2568 POST_INIT(KeyError)
2569 POST_INIT(ValueError)
2570 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002571 POST_INIT(UnicodeEncodeError)
2572 POST_INIT(UnicodeDecodeError)
2573 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002574 POST_INIT(AssertionError)
2575 POST_INIT(ArithmeticError)
2576 POST_INIT(FloatingPointError)
2577 POST_INIT(OverflowError)
2578 POST_INIT(ZeroDivisionError)
2579 POST_INIT(SystemError)
2580 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002581 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002582 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002583 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002584 POST_INIT(Warning)
2585 POST_INIT(UserWarning)
2586 POST_INIT(DeprecationWarning)
2587 POST_INIT(PendingDeprecationWarning)
2588 POST_INIT(SyntaxWarning)
2589 POST_INIT(RuntimeWarning)
2590 POST_INIT(FutureWarning)
2591 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002592 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002593 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002594 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002595
Antoine Pitrouac456a12012-01-18 21:35:21 +01002596 if (!errnomap) {
2597 errnomap = PyDict_New();
2598 if (!errnomap)
2599 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2600 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002601
2602 /* OSError subclasses */
2603 POST_INIT(ConnectionError);
2604
2605 POST_INIT(BlockingIOError);
2606 ADD_ERRNO(BlockingIOError, EAGAIN);
2607 ADD_ERRNO(BlockingIOError, EALREADY);
2608 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2609 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2610 POST_INIT(BrokenPipeError);
2611 ADD_ERRNO(BrokenPipeError, EPIPE);
2612 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2613 POST_INIT(ChildProcessError);
2614 ADD_ERRNO(ChildProcessError, ECHILD);
2615 POST_INIT(ConnectionAbortedError);
2616 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2617 POST_INIT(ConnectionRefusedError);
2618 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2619 POST_INIT(ConnectionResetError);
2620 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2621 POST_INIT(FileExistsError);
2622 ADD_ERRNO(FileExistsError, EEXIST);
2623 POST_INIT(FileNotFoundError);
2624 ADD_ERRNO(FileNotFoundError, ENOENT);
2625 POST_INIT(IsADirectoryError);
2626 ADD_ERRNO(IsADirectoryError, EISDIR);
2627 POST_INIT(NotADirectoryError);
2628 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2629 POST_INIT(InterruptedError);
2630 ADD_ERRNO(InterruptedError, EINTR);
2631 POST_INIT(PermissionError);
2632 ADD_ERRNO(PermissionError, EACCES);
2633 ADD_ERRNO(PermissionError, EPERM);
2634 POST_INIT(ProcessLookupError);
2635 ADD_ERRNO(ProcessLookupError, ESRCH);
2636 POST_INIT(TimeoutError);
2637 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2638
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002639 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002640
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002641 if (!PyExc_RecursionErrorInst) {
Yury Selivanovf488fb42015-07-03 01:04:23 -04002642 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RecursionError, NULL, NULL);
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002643 if (!PyExc_RecursionErrorInst)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002644 Py_FatalError("Cannot pre-allocate RecursionError instance for "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002645 "recursion errors");
2646 else {
2647 PyBaseExceptionObject *err_inst =
2648 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2649 PyObject *args_tuple;
2650 PyObject *exc_message;
2651 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2652 if (!exc_message)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002653 Py_FatalError("cannot allocate argument for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002654 "pre-allocation");
2655 args_tuple = PyTuple_Pack(1, exc_message);
2656 if (!args_tuple)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002657 Py_FatalError("cannot allocate tuple for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002658 "pre-allocation");
2659 Py_DECREF(exc_message);
2660 if (BaseException_init(err_inst, args_tuple, NULL))
Yury Selivanovf488fb42015-07-03 01:04:23 -04002661 Py_FatalError("init of pre-allocated RecursionError failed");
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002662 Py_DECREF(args_tuple);
2663 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002664 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002665}
2666
2667void
2668_PyExc_Fini(void)
2669{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002670 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002671 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002672 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002673}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002674
2675/* Helper to do the equivalent of "raise X from Y" in C, but always using
2676 * the current exception rather than passing one in.
2677 *
2678 * We currently limit this to *only* exceptions that use the BaseException
2679 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2680 * those correctly without losing data and without losing backwards
2681 * compatibility.
2682 *
2683 * We also aim to rule out *all* exceptions that might be storing additional
2684 * state, whether by having a size difference relative to BaseException,
2685 * additional arguments passed in during construction or by having a
2686 * non-empty instance dict.
2687 *
2688 * We need to be very careful with what we wrap, since changing types to
2689 * a broader exception type would be backwards incompatible for
2690 * existing codecs, and with different init or new method implementations
2691 * may either not support instantiation with PyErr_Format or lose
2692 * information when instantiated that way.
2693 *
2694 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2695 * fact that exceptions are expected to support pickling. If more builtin
2696 * exceptions (e.g. AttributeError) start to be converted to rich
2697 * exceptions with additional attributes, that's probably a better approach
2698 * to pursue over adding special cases for particular stateful subclasses.
2699 *
2700 * Returns a borrowed reference to the new exception (if any), NULL if the
2701 * existing exception was left in place.
2702 */
2703PyObject *
2704_PyErr_TrySetFromCause(const char *format, ...)
2705{
2706 PyObject* msg_prefix;
2707 PyObject *exc, *val, *tb;
2708 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002709 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002710 PyObject *instance_args;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002711 Py_ssize_t num_args, caught_type_size, base_exc_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002712 PyObject *new_exc, *new_val, *new_tb;
2713 va_list vargs;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002714 int same_basic_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002715
Nick Coghlan8b097b42013-11-13 23:49:21 +10002716 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002717 caught_type = (PyTypeObject *)exc;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002718 /* Ensure type info indicates no extra state is stored at the C level
2719 * and that the type can be reinstantiated using PyErr_Format
2720 */
2721 caught_type_size = caught_type->tp_basicsize;
2722 base_exc_size = _PyExc_BaseException.tp_basicsize;
2723 same_basic_size = (
2724 caught_type_size == base_exc_size ||
2725 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
Victor Stinner12174a52014-08-15 23:17:38 +02002726 (caught_type_size == base_exc_size + (Py_ssize_t)sizeof(PyObject *))
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002727 )
2728 );
Benjamin Peterson079c9982013-11-13 23:25:01 -05002729 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002730 caught_type->tp_new != BaseException_new ||
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002731 !same_basic_size ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002732 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002733 /* We can't be sure we can wrap this safely, since it may contain
2734 * more state than just the exception type. Accordingly, we just
2735 * leave it alone.
2736 */
2737 PyErr_Restore(exc, val, tb);
2738 return NULL;
2739 }
2740
2741 /* Check the args are empty or contain a single string */
2742 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002743 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002744 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002745 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002746 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002747 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002748 /* More than 1 arg, or the one arg we do have isn't a string
2749 */
2750 PyErr_Restore(exc, val, tb);
2751 return NULL;
2752 }
2753
2754 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002755 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002756 if (dictptr != NULL && *dictptr != NULL &&
2757 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002758 /* While we could potentially copy a non-empty instance dictionary
2759 * to the replacement exception, for now we take the more
2760 * conservative path of leaving exceptions with attributes set
2761 * alone.
2762 */
2763 PyErr_Restore(exc, val, tb);
2764 return NULL;
2765 }
2766
2767 /* For exceptions that we can wrap safely, we chain the original
2768 * exception to a new one of the exact same type with an
2769 * error message that mentions the additional details and the
2770 * original exception.
2771 *
2772 * It would be nice to wrap OSError and various other exception
2773 * types as well, but that's quite a bit trickier due to the extra
2774 * state potentially stored on OSError instances.
2775 */
Nick Coghlan77b286b2014-01-27 00:53:38 +10002776 /* Ensure the traceback is set correctly on the existing exception */
2777 if (tb != NULL) {
2778 PyException_SetTraceback(val, tb);
2779 Py_DECREF(tb);
2780 }
Benjamin Petersone109ee82013-11-13 23:49:49 -05002781
Christian Heimes507eabd2013-11-14 01:39:35 +01002782#ifdef HAVE_STDARG_PROTOTYPES
2783 va_start(vargs, format);
2784#else
2785 va_start(vargs);
2786#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002787 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002788 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002789 if (msg_prefix == NULL) {
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002790 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002791 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002792 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002793 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002794
2795 PyErr_Format(exc, "%U (%s: %S)",
2796 msg_prefix, Py_TYPE(val)->tp_name, val);
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002797 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002798 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002799 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2800 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2801 PyException_SetCause(new_val, val);
2802 PyErr_Restore(new_exc, new_val, new_tb);
2803 return new_val;
2804}
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002805
2806
2807/* To help with migration from Python 2, SyntaxError.__init__ applies some
2808 * heuristics to try to report a more meaningful exception when print and
2809 * exec are used like statements.
2810 *
2811 * The heuristics are currently expected to detect the following cases:
2812 * - top level statement
2813 * - statement in a nested suite
2814 * - trailing section of a one line complex statement
2815 *
2816 * They're currently known not to trigger:
2817 * - after a semi-colon
2818 *
2819 * The error message can be a bit odd in cases where the "arguments" are
2820 * completely illegal syntactically, but that isn't worth the hassle of
2821 * fixing.
2822 *
2823 * We also can't do anything about cases that are legal Python 3 syntax
2824 * but mean something entirely different from what they did in Python 2
2825 * (omitting the arguments entirely, printing items preceded by a unary plus
2826 * or minus, using the stream redirection syntax).
2827 */
2828
2829static int
2830_check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start)
2831{
2832 /* Return values:
2833 * -1: an error occurred
2834 * 0: nothing happened
2835 * 1: the check triggered & the error message was changed
2836 */
2837 static PyObject *print_prefix = NULL;
2838 static PyObject *exec_prefix = NULL;
2839 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2840 int kind = PyUnicode_KIND(self->text);
2841 void *data = PyUnicode_DATA(self->text);
2842
2843 /* Ignore leading whitespace */
2844 while (start < text_len) {
2845 Py_UCS4 ch = PyUnicode_READ(kind, data, start);
2846 if (!Py_UNICODE_ISSPACE(ch))
2847 break;
2848 start++;
2849 }
2850 /* Checking against an empty or whitespace-only part of the string */
2851 if (start == text_len) {
2852 return 0;
2853 }
2854
2855 /* Check for legacy print statements */
2856 if (print_prefix == NULL) {
2857 print_prefix = PyUnicode_InternFromString("print ");
2858 if (print_prefix == NULL) {
2859 return -1;
2860 }
2861 }
2862 if (PyUnicode_Tailmatch(self->text, print_prefix,
2863 start, text_len, -1)) {
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02002864 Py_SETREF(self->msg,
2865 PyUnicode_FromString("Missing parentheses in call to 'print'"));
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002866 return 1;
2867 }
2868
2869 /* Check for legacy exec statements */
2870 if (exec_prefix == NULL) {
2871 exec_prefix = PyUnicode_InternFromString("exec ");
2872 if (exec_prefix == NULL) {
2873 return -1;
2874 }
2875 }
2876 if (PyUnicode_Tailmatch(self->text, exec_prefix,
2877 start, text_len, -1)) {
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02002878 Py_SETREF(self->msg,
2879 PyUnicode_FromString("Missing parentheses in call to 'exec'"));
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002880 return 1;
2881 }
2882 /* Fall back to the default error message */
2883 return 0;
2884}
2885
2886static int
2887_report_missing_parentheses(PySyntaxErrorObject *self)
2888{
2889 Py_UCS4 left_paren = 40;
2890 Py_ssize_t left_paren_index;
2891 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2892 int legacy_check_result = 0;
2893
2894 /* Skip entirely if there is an opening parenthesis */
2895 left_paren_index = PyUnicode_FindChar(self->text, left_paren,
2896 0, text_len, 1);
2897 if (left_paren_index < -1) {
2898 return -1;
2899 }
2900 if (left_paren_index != -1) {
2901 /* Use default error message for any line with an opening paren */
2902 return 0;
2903 }
2904 /* Handle the simple statement case */
2905 legacy_check_result = _check_for_legacy_statements(self, 0);
2906 if (legacy_check_result < 0) {
2907 return -1;
2908
2909 }
2910 if (legacy_check_result == 0) {
2911 /* Handle the one-line complex statement case */
2912 Py_UCS4 colon = 58;
2913 Py_ssize_t colon_index;
2914 colon_index = PyUnicode_FindChar(self->text, colon,
2915 0, text_len, 1);
2916 if (colon_index < -1) {
2917 return -1;
2918 }
2919 if (colon_index >= 0 && colon_index < text_len) {
2920 /* Check again, starting from just after the colon */
2921 if (_check_for_legacy_statements(self, colon_index+1) < 0) {
2922 return -1;
2923 }
2924 }
2925 }
2926 return 0;
2927}