blob: aaff0bc63d9ae7b5b26c0c2c1331ae811784f502 [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 Storchaka48842712016-04-06 09:45:48 +0300209 Py_XSETREF(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 Storchaka48842712016-04-06 09:45:48 +0300238 Py_XSETREF(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;
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200564 if (size == 1) {
565 Py_INCREF(PyTuple_GET_ITEM(args, 0));
Serhiy Storchaka48842712016-04-06 09:45:48 +0300566 Py_XSETREF(self->code, PyTuple_GET_ITEM(args, 0));
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200567 }
568 else { /* size > 1 */
569 Py_INCREF(args);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300570 Py_XSETREF(self->code, args);
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200571 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572 return 0;
573}
574
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000575static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000576SystemExit_clear(PySystemExitObject *self)
577{
578 Py_CLEAR(self->code);
579 return BaseException_clear((PyBaseExceptionObject *)self);
580}
581
582static void
583SystemExit_dealloc(PySystemExitObject *self)
584{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000585 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586 SystemExit_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000587 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588}
589
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000590static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000591SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
592{
593 Py_VISIT(self->code);
594 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
595}
596
597static PyMemberDef SystemExit_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
599 PyDoc_STR("exception code")},
600 {NULL} /* Sentinel */
601};
602
603ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200604 0, 0, SystemExit_members, 0, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000605 "Request to exit from the interpreter.");
606
607/*
608 * KeyboardInterrupt extends BaseException
609 */
610SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
611 "Program interrupted by user.");
612
613
614/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000615 * ImportError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000616 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000617
Brett Cannon79ec55e2012-04-12 20:24:54 -0400618static int
619ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
620{
621 PyObject *msg = NULL;
622 PyObject *name = NULL;
623 PyObject *path = NULL;
624
625/* Macro replacement doesn't allow ## to start the first line of a macro,
626 so we move the assignment and NULL check into the if-statement. */
627#define GET_KWD(kwd) { \
628 kwd = PyDict_GetItemString(kwds, #kwd); \
629 if (kwd) { \
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200630 Py_INCREF(kwd); \
Serhiy Storchaka48842712016-04-06 09:45:48 +0300631 Py_XSETREF(self->kwd, kwd); \
Brett Cannon79ec55e2012-04-12 20:24:54 -0400632 if (PyDict_DelItemString(kwds, #kwd)) \
633 return -1; \
634 } \
635 }
636
637 if (kwds) {
638 GET_KWD(name);
639 GET_KWD(path);
640 }
641
642 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
643 return -1;
644 if (PyTuple_GET_SIZE(args) != 1)
645 return 0;
646 if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
647 return -1;
648
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +0200649 Py_INCREF(msg);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300650 Py_XSETREF(self->msg, msg);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400651
652 return 0;
653}
654
655static int
656ImportError_clear(PyImportErrorObject *self)
657{
658 Py_CLEAR(self->msg);
659 Py_CLEAR(self->name);
660 Py_CLEAR(self->path);
661 return BaseException_clear((PyBaseExceptionObject *)self);
662}
663
664static void
665ImportError_dealloc(PyImportErrorObject *self)
666{
667 _PyObject_GC_UNTRACK(self);
668 ImportError_clear(self);
669 Py_TYPE(self)->tp_free((PyObject *)self);
670}
671
672static int
673ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
674{
675 Py_VISIT(self->msg);
676 Py_VISIT(self->name);
677 Py_VISIT(self->path);
678 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
679}
680
681static PyObject *
682ImportError_str(PyImportErrorObject *self)
683{
Brett Cannon07c6e712012-08-24 13:05:09 -0400684 if (self->msg && PyUnicode_CheckExact(self->msg)) {
Brett Cannon79ec55e2012-04-12 20:24:54 -0400685 Py_INCREF(self->msg);
686 return self->msg;
687 }
688 else {
689 return BaseException_str((PyBaseExceptionObject *)self);
690 }
691}
692
693static PyMemberDef ImportError_members[] = {
694 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
695 PyDoc_STR("exception message")},
696 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
697 PyDoc_STR("module name")},
698 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
699 PyDoc_STR("module path")},
700 {NULL} /* Sentinel */
701};
702
703static PyMethodDef ImportError_methods[] = {
704 {NULL}
705};
706
707ComplexExtendsException(PyExc_Exception, ImportError,
708 ImportError, 0 /* new */,
709 ImportError_methods, ImportError_members,
710 0 /* getset */, ImportError_str,
711 "Import can't find module, or can't find name in "
712 "module.");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713
714/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200715 * OSError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716 */
717
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200718#ifdef MS_WINDOWS
719#include "errmap.h"
720#endif
721
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722/* Where a function has a single filename, such as open() or some
723 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
724 * called, giving a third argument which is the filename. But, so
725 * that old code using in-place unpacking doesn't break, e.g.:
726 *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200727 * except OSError, (errno, strerror):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000728 *
729 * we hack args so that it only contains two items. This also
730 * means we need our own __str__() which prints out the filename
731 * when it was supplied.
Larry Hastingsb0827312014-02-09 22:05:19 -0800732 *
733 * (If a function has two filenames, such as rename(), symlink(),
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800734 * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
735 * which allows passing in a second filename.)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000736 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200737
Antoine Pitroue0e27352011-12-15 14:31:28 +0100738/* This function doesn't cleanup on error, the caller should */
739static int
740oserror_parse_args(PyObject **p_args,
741 PyObject **myerrno, PyObject **strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800742 PyObject **filename, PyObject **filename2
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200743#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100744 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200745#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100746 )
747{
748 Py_ssize_t nargs;
749 PyObject *args = *p_args;
Larry Hastingsb0827312014-02-09 22:05:19 -0800750#ifndef MS_WINDOWS
751 /*
752 * ignored on non-Windows platforms,
753 * but parsed so OSError has a consistent signature
754 */
755 PyObject *_winerror = NULL;
756 PyObject **winerror = &_winerror;
757#endif /* MS_WINDOWS */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200759 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000760
Larry Hastingsb0827312014-02-09 22:05:19 -0800761 if (nargs >= 2 && nargs <= 5) {
762 if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
763 myerrno, strerror,
764 filename, winerror, filename2))
Antoine Pitroue0e27352011-12-15 14:31:28 +0100765 return -1;
Larry Hastingsb0827312014-02-09 22:05:19 -0800766#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100767 if (*winerror && PyLong_Check(*winerror)) {
768 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200769 PyObject *newargs;
770 Py_ssize_t i;
771
Antoine Pitroue0e27352011-12-15 14:31:28 +0100772 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200773 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100774 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200775 /* Set errno to the corresponding POSIX errno (overriding
776 first argument). Windows Socket error codes (>= 10000)
777 have the same value as their POSIX counterparts.
778 */
779 if (winerrcode < 10000)
780 errcode = winerror_to_errno(winerrcode);
781 else
782 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100783 *myerrno = PyLong_FromLong(errcode);
784 if (!*myerrno)
785 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200786 newargs = PyTuple_New(nargs);
787 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100788 return -1;
789 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200790 for (i = 1; i < nargs; i++) {
791 PyObject *val = PyTuple_GET_ITEM(args, i);
792 Py_INCREF(val);
793 PyTuple_SET_ITEM(newargs, i, val);
794 }
795 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100796 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200797 }
Larry Hastingsb0827312014-02-09 22:05:19 -0800798#endif /* MS_WINDOWS */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200799 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000800
Antoine Pitroue0e27352011-12-15 14:31:28 +0100801 return 0;
802}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000803
Antoine Pitroue0e27352011-12-15 14:31:28 +0100804static int
805oserror_init(PyOSErrorObject *self, PyObject **p_args,
806 PyObject *myerrno, PyObject *strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800807 PyObject *filename, PyObject *filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100808#ifdef MS_WINDOWS
809 , PyObject *winerror
810#endif
811 )
812{
813 PyObject *args = *p_args;
814 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000815
816 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200817 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100818 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200819 PyNumber_Check(filename)) {
820 /* BlockingIOError's 3rd argument can be the number of
821 * characters written.
822 */
823 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
824 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100825 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200826 }
827 else {
828 Py_INCREF(filename);
829 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000830
Larry Hastingsb0827312014-02-09 22:05:19 -0800831 if (filename2 && filename2 != Py_None) {
832 Py_INCREF(filename2);
833 self->filename2 = filename2;
834 }
835
836 if (nargs >= 2 && nargs <= 5) {
837 /* filename, filename2, and winerror are removed from the args tuple
838 (for compatibility purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100839 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200840 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100841 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000842
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200843 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100844 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200845 }
846 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000847 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200848 Py_XINCREF(myerrno);
849 self->myerrno = myerrno;
850
851 Py_XINCREF(strerror);
852 self->strerror = strerror;
853
854#ifdef MS_WINDOWS
855 Py_XINCREF(winerror);
856 self->winerror = winerror;
857#endif
858
Antoine Pitroue0e27352011-12-15 14:31:28 +0100859 /* Steals the reference to args */
Serhiy Storchaka48842712016-04-06 09:45:48 +0300860 Py_XSETREF(self->args, args);
Victor Stinner46ef3192013-11-14 22:31:41 +0100861 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100862
863 return 0;
864}
865
866static PyObject *
867OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
868static int
869OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
870
871static int
872oserror_use_init(PyTypeObject *type)
873{
Martin Panter7462b6492015-11-02 03:37:02 +0000874 /* When __init__ is defined in an OSError subclass, we want any
Antoine Pitroue0e27352011-12-15 14:31:28 +0100875 extraneous argument to __new__ to be ignored. The only reasonable
876 solution, given __new__ takes a variable number of arguments,
877 is to defer arg parsing and initialization to __init__.
878
Martin Pantere26da7c2016-06-02 10:07:09 +0000879 But when __new__ is overridden as well, it should call our __new__
Antoine Pitroue0e27352011-12-15 14:31:28 +0100880 with the right arguments.
881
882 (see http://bugs.python.org/issue12555#msg148829 )
883 */
884 if (type->tp_init != (initproc) OSError_init &&
885 type->tp_new == (newfunc) OSError_new) {
886 assert((PyObject *) type != PyExc_OSError);
887 return 1;
888 }
889 return 0;
890}
891
892static PyObject *
893OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
894{
895 PyOSErrorObject *self = NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800896 PyObject *myerrno = NULL, *strerror = NULL;
897 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100898#ifdef MS_WINDOWS
899 PyObject *winerror = NULL;
900#endif
901
Victor Stinner46ef3192013-11-14 22:31:41 +0100902 Py_INCREF(args);
903
Antoine Pitroue0e27352011-12-15 14:31:28 +0100904 if (!oserror_use_init(type)) {
905 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100906 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100907
Larry Hastingsb0827312014-02-09 22:05:19 -0800908 if (oserror_parse_args(&args, &myerrno, &strerror,
909 &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100910#ifdef MS_WINDOWS
911 , &winerror
912#endif
913 ))
914 goto error;
915
916 if (myerrno && PyLong_Check(myerrno) &&
917 errnomap && (PyObject *) type == PyExc_OSError) {
918 PyObject *newtype;
919 newtype = PyDict_GetItem(errnomap, myerrno);
920 if (newtype) {
921 assert(PyType_Check(newtype));
922 type = (PyTypeObject *) newtype;
923 }
924 else if (PyErr_Occurred())
925 goto error;
926 }
927 }
928
929 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
930 if (!self)
931 goto error;
932
933 self->dict = NULL;
934 self->traceback = self->cause = self->context = NULL;
935 self->written = -1;
936
937 if (!oserror_use_init(type)) {
Larry Hastingsb0827312014-02-09 22:05:19 -0800938 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100939#ifdef MS_WINDOWS
940 , winerror
941#endif
942 ))
943 goto error;
944 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200945 else {
946 self->args = PyTuple_New(0);
947 if (self->args == NULL)
948 goto error;
949 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100950
Victor Stinner46ef3192013-11-14 22:31:41 +0100951 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200952 return (PyObject *) self;
953
954error:
955 Py_XDECREF(args);
956 Py_XDECREF(self);
957 return NULL;
958}
959
960static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100961OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200962{
Larry Hastingsb0827312014-02-09 22:05:19 -0800963 PyObject *myerrno = NULL, *strerror = NULL;
964 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100965#ifdef MS_WINDOWS
966 PyObject *winerror = NULL;
967#endif
968
969 if (!oserror_use_init(Py_TYPE(self)))
970 /* Everything already done in OSError_new */
971 return 0;
972
973 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
974 return -1;
975
976 Py_INCREF(args);
Larry Hastingsb0827312014-02-09 22:05:19 -0800977 if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100978#ifdef MS_WINDOWS
979 , &winerror
980#endif
981 ))
982 goto error;
983
Larry Hastingsb0827312014-02-09 22:05:19 -0800984 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100985#ifdef MS_WINDOWS
986 , winerror
987#endif
988 ))
989 goto error;
990
Thomas Wouters477c8d52006-05-27 19:21:47 +0000991 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100992
993error:
994 Py_XDECREF(args);
995 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000996}
997
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000998static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200999OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001000{
1001 Py_CLEAR(self->myerrno);
1002 Py_CLEAR(self->strerror);
1003 Py_CLEAR(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001004 Py_CLEAR(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001005#ifdef MS_WINDOWS
1006 Py_CLEAR(self->winerror);
1007#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001008 return BaseException_clear((PyBaseExceptionObject *)self);
1009}
1010
1011static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001012OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001013{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001014 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001015 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001016 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001017}
1018
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001019static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001020OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001021 void *arg)
1022{
1023 Py_VISIT(self->myerrno);
1024 Py_VISIT(self->strerror);
1025 Py_VISIT(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001026 Py_VISIT(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001027#ifdef MS_WINDOWS
1028 Py_VISIT(self->winerror);
1029#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001030 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1031}
1032
1033static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001034OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035{
Larry Hastingsb0827312014-02-09 22:05:19 -08001036#define OR_NONE(x) ((x)?(x):Py_None)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001037#ifdef MS_WINDOWS
1038 /* If available, winerror has the priority over myerrno */
Larry Hastingsb0827312014-02-09 22:05:19 -08001039 if (self->winerror && self->filename) {
1040 if (self->filename2) {
1041 return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
1042 OR_NONE(self->winerror),
1043 OR_NONE(self->strerror),
1044 self->filename,
1045 self->filename2);
1046 } else {
1047 return PyUnicode_FromFormat("[WinError %S] %S: %R",
1048 OR_NONE(self->winerror),
1049 OR_NONE(self->strerror),
1050 self->filename);
1051 }
1052 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001053 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001054 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001055 self->winerror ? self->winerror: Py_None,
1056 self->strerror ? self->strerror: Py_None);
1057#endif
Larry Hastingsb0827312014-02-09 22:05:19 -08001058 if (self->filename) {
1059 if (self->filename2) {
1060 return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
1061 OR_NONE(self->myerrno),
1062 OR_NONE(self->strerror),
1063 self->filename,
1064 self->filename2);
1065 } else {
1066 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1067 OR_NONE(self->myerrno),
1068 OR_NONE(self->strerror),
1069 self->filename);
1070 }
1071 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001072 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001073 return PyUnicode_FromFormat("[Errno %S] %S",
1074 self->myerrno ? self->myerrno: Py_None,
1075 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001076 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001077}
1078
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001080OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001081{
1082 PyObject *args = self->args;
1083 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001084
Thomas Wouters477c8d52006-05-27 19:21:47 +00001085 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001086 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001087 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Larry Hastingsb0827312014-02-09 22:05:19 -08001088 Py_ssize_t size = self->filename2 ? 5 : 3;
1089 args = PyTuple_New(size);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001090 if (!args)
1091 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001092
1093 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001094 Py_INCREF(tmp);
1095 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001096
1097 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001098 Py_INCREF(tmp);
1099 PyTuple_SET_ITEM(args, 1, tmp);
1100
1101 Py_INCREF(self->filename);
1102 PyTuple_SET_ITEM(args, 2, self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001103
1104 if (self->filename2) {
1105 /*
1106 * This tuple is essentially used as OSError(*args).
1107 * So, to recreate filename2, we need to pass in
1108 * winerror as well.
1109 */
1110 Py_INCREF(Py_None);
1111 PyTuple_SET_ITEM(args, 3, Py_None);
1112
1113 /* filename2 */
1114 Py_INCREF(self->filename2);
1115 PyTuple_SET_ITEM(args, 4, self->filename2);
1116 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001117 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001118 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001119
1120 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001121 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001122 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001123 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001124 Py_DECREF(args);
1125 return res;
1126}
1127
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001128static PyObject *
1129OSError_written_get(PyOSErrorObject *self, void *context)
1130{
1131 if (self->written == -1) {
1132 PyErr_SetString(PyExc_AttributeError, "characters_written");
1133 return NULL;
1134 }
1135 return PyLong_FromSsize_t(self->written);
1136}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001137
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001138static int
1139OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1140{
1141 Py_ssize_t n;
1142 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1143 if (n == -1 && PyErr_Occurred())
1144 return -1;
1145 self->written = n;
1146 return 0;
1147}
1148
1149static PyMemberDef OSError_members[] = {
1150 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1151 PyDoc_STR("POSIX exception code")},
1152 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1153 PyDoc_STR("exception strerror")},
1154 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1155 PyDoc_STR("exception filename")},
Larry Hastingsb0827312014-02-09 22:05:19 -08001156 {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
1157 PyDoc_STR("second exception filename")},
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001158#ifdef MS_WINDOWS
1159 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1160 PyDoc_STR("Win32 exception code")},
1161#endif
1162 {NULL} /* Sentinel */
1163};
1164
1165static PyMethodDef OSError_methods[] = {
1166 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001167 {NULL}
1168};
1169
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001170static PyGetSetDef OSError_getset[] = {
1171 {"characters_written", (getter) OSError_written_get,
1172 (setter) OSError_written_set, NULL},
1173 {NULL}
1174};
1175
1176
1177ComplexExtendsException(PyExc_Exception, OSError,
1178 OSError, OSError_new,
1179 OSError_methods, OSError_members, OSError_getset,
1180 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001181 "Base class for I/O related errors.");
1182
1183
1184/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001185 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001186 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001187MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1188 "I/O operation would block.");
1189MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1190 "Connection error.");
1191MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1192 "Child process error.");
1193MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1194 "Broken pipe.");
1195MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1196 "Connection aborted.");
1197MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1198 "Connection refused.");
1199MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1200 "Connection reset.");
1201MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1202 "File already exists.");
1203MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1204 "File not found.");
1205MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1206 "Operation doesn't work on directories.");
1207MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1208 "Operation only works on directories.");
1209MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1210 "Interrupted by signal.");
1211MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1212 "Not enough permissions.");
1213MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1214 "Process not found.");
1215MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1216 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001217
1218/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001219 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001221SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001222 "Read beyond end of file.");
1223
1224
1225/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001226 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001227 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001228SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001229 "Unspecified run-time error.");
1230
Yury Selivanovf488fb42015-07-03 01:04:23 -04001231/*
1232 * RecursionError extends RuntimeError
1233 */
1234SimpleExtendsException(PyExc_RuntimeError, RecursionError,
1235 "Recursion limit exceeded.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001236
1237/*
1238 * NotImplementedError extends RuntimeError
1239 */
1240SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1241 "Method or function hasn't been implemented yet.");
1242
1243/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001244 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001245 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001246SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001247 "Name not found globally.");
1248
1249/*
1250 * UnboundLocalError extends NameError
1251 */
1252SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1253 "Local name referenced but not bound to a value.");
1254
1255/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001256 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001258SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001259 "Attribute not found.");
1260
1261
1262/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001263 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001264 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001265
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001266/* Helper function to customise error message for some syntax errors */
1267static int _report_missing_parentheses(PySyntaxErrorObject *self);
1268
Thomas Wouters477c8d52006-05-27 19:21:47 +00001269static int
1270SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1271{
1272 PyObject *info = NULL;
1273 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1274
1275 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1276 return -1;
1277
1278 if (lenargs >= 1) {
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001279 Py_INCREF(PyTuple_GET_ITEM(args, 0));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001280 Py_XSETREF(self->msg, PyTuple_GET_ITEM(args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001281 }
1282 if (lenargs == 2) {
1283 info = PyTuple_GET_ITEM(args, 1);
1284 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001285 if (!info)
1286 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001287
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001288 if (PyTuple_GET_SIZE(info) != 4) {
1289 /* not a very good error message, but it's what Python 2.4 gives */
1290 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1291 Py_DECREF(info);
1292 return -1;
1293 }
1294
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001295 Py_INCREF(PyTuple_GET_ITEM(info, 0));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001296 Py_XSETREF(self->filename, PyTuple_GET_ITEM(info, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001297
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001298 Py_INCREF(PyTuple_GET_ITEM(info, 1));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001299 Py_XSETREF(self->lineno, PyTuple_GET_ITEM(info, 1));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001300
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001301 Py_INCREF(PyTuple_GET_ITEM(info, 2));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001302 Py_XSETREF(self->offset, PyTuple_GET_ITEM(info, 2));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001303
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001304 Py_INCREF(PyTuple_GET_ITEM(info, 3));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001305 Py_XSETREF(self->text, PyTuple_GET_ITEM(info, 3));
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001306
1307 Py_DECREF(info);
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001308
1309 /* Issue #21669: Custom error for 'print' & 'exec' as statements */
1310 if (self->text && PyUnicode_Check(self->text)) {
1311 if (_report_missing_parentheses(self) < 0) {
1312 return -1;
1313 }
1314 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001315 }
1316 return 0;
1317}
1318
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001319static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001320SyntaxError_clear(PySyntaxErrorObject *self)
1321{
1322 Py_CLEAR(self->msg);
1323 Py_CLEAR(self->filename);
1324 Py_CLEAR(self->lineno);
1325 Py_CLEAR(self->offset);
1326 Py_CLEAR(self->text);
1327 Py_CLEAR(self->print_file_and_line);
1328 return BaseException_clear((PyBaseExceptionObject *)self);
1329}
1330
1331static void
1332SyntaxError_dealloc(PySyntaxErrorObject *self)
1333{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001334 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001335 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001336 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001337}
1338
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001339static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001340SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1341{
1342 Py_VISIT(self->msg);
1343 Py_VISIT(self->filename);
1344 Py_VISIT(self->lineno);
1345 Py_VISIT(self->offset);
1346 Py_VISIT(self->text);
1347 Py_VISIT(self->print_file_and_line);
1348 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1349}
1350
1351/* This is called "my_basename" instead of just "basename" to avoid name
1352 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1353 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001354static PyObject*
1355my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001356{
Victor Stinner6237daf2010-04-28 17:26:19 +00001357 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001358 int kind;
1359 void *data;
1360
1361 if (PyUnicode_READY(name))
1362 return NULL;
1363 kind = PyUnicode_KIND(name);
1364 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001365 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001366 offset = 0;
1367 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001369 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001370 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371 if (offset != 0)
1372 return PyUnicode_Substring(name, offset, size);
1373 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001374 Py_INCREF(name);
1375 return name;
1376 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001377}
1378
1379
1380static PyObject *
1381SyntaxError_str(PySyntaxErrorObject *self)
1382{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001383 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001384 PyObject *filename;
1385 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001386 /* Below, we always ignore overflow errors, just printing -1.
1387 Still, we cannot allow an OverflowError to be raised, so
1388 we need to call PyLong_AsLongAndOverflow. */
1389 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390
1391 /* XXX -- do all the additional formatting with filename and
1392 lineno here */
1393
Neal Norwitzed2b7392007-08-26 04:51:10 +00001394 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001395 filename = my_basename(self->filename);
1396 if (filename == NULL)
1397 return NULL;
1398 } else {
1399 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001400 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001401 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001402
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001403 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001404 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001405
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001406 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001407 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001408 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001409 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001411 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001412 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001413 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001414 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001415 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001416 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001417 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001418 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001419 Py_XDECREF(filename);
1420 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001421}
1422
1423static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001424 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1425 PyDoc_STR("exception msg")},
1426 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1427 PyDoc_STR("exception filename")},
1428 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1429 PyDoc_STR("exception lineno")},
1430 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1431 PyDoc_STR("exception offset")},
1432 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1433 PyDoc_STR("exception text")},
1434 {"print_file_and_line", T_OBJECT,
1435 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1436 PyDoc_STR("exception print_file_and_line")},
1437 {NULL} /* Sentinel */
1438};
1439
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001440ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001441 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001442 SyntaxError_str, "Invalid syntax.");
1443
1444
1445/*
1446 * IndentationError extends SyntaxError
1447 */
1448MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1449 "Improper indentation.");
1450
1451
1452/*
1453 * TabError extends IndentationError
1454 */
1455MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1456 "Improper mixture of spaces and tabs.");
1457
1458
1459/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001460 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001461 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001462SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001463 "Base class for lookup errors.");
1464
1465
1466/*
1467 * IndexError extends LookupError
1468 */
1469SimpleExtendsException(PyExc_LookupError, IndexError,
1470 "Sequence index out of range.");
1471
1472
1473/*
1474 * KeyError extends LookupError
1475 */
1476static PyObject *
1477KeyError_str(PyBaseExceptionObject *self)
1478{
1479 /* If args is a tuple of exactly one item, apply repr to args[0].
1480 This is done so that e.g. the exception raised by {}[''] prints
1481 KeyError: ''
1482 rather than the confusing
1483 KeyError
1484 alone. The downside is that if KeyError is raised with an explanatory
1485 string, that string will be displayed in quotes. Too bad.
1486 If args is anything else, use the default BaseException__str__().
1487 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001488 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001489 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001490 }
1491 return BaseException_str(self);
1492}
1493
1494ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001495 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001496
1497
1498/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001499 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001500 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001501SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001502 "Inappropriate argument value (of correct type).");
1503
1504/*
1505 * UnicodeError extends ValueError
1506 */
1507
1508SimpleExtendsException(PyExc_ValueError, UnicodeError,
1509 "Unicode related error.");
1510
Thomas Wouters477c8d52006-05-27 19:21:47 +00001511static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001512get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001513{
1514 if (!attr) {
1515 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1516 return NULL;
1517 }
1518
Christian Heimes72b710a2008-05-26 13:28:38 +00001519 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001520 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1521 return NULL;
1522 }
1523 Py_INCREF(attr);
1524 return attr;
1525}
1526
1527static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001528get_unicode(PyObject *attr, const char *name)
1529{
1530 if (!attr) {
1531 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1532 return NULL;
1533 }
1534
1535 if (!PyUnicode_Check(attr)) {
1536 PyErr_Format(PyExc_TypeError,
1537 "%.200s attribute must be unicode", name);
1538 return NULL;
1539 }
1540 Py_INCREF(attr);
1541 return attr;
1542}
1543
Walter Dörwaldd2034312007-05-18 16:29:38 +00001544static int
1545set_unicodefromstring(PyObject **attr, const char *value)
1546{
1547 PyObject *obj = PyUnicode_FromString(value);
1548 if (!obj)
1549 return -1;
Serhiy Storchaka48842712016-04-06 09:45:48 +03001550 Py_XSETREF(*attr, obj);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001551 return 0;
1552}
1553
Thomas Wouters477c8d52006-05-27 19:21:47 +00001554PyObject *
1555PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1556{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001557 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001558}
1559
1560PyObject *
1561PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1562{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001563 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001564}
1565
1566PyObject *
1567PyUnicodeEncodeError_GetObject(PyObject *exc)
1568{
1569 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1570}
1571
1572PyObject *
1573PyUnicodeDecodeError_GetObject(PyObject *exc)
1574{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001575 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001576}
1577
1578PyObject *
1579PyUnicodeTranslateError_GetObject(PyObject *exc)
1580{
1581 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1582}
1583
1584int
1585PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1586{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001587 Py_ssize_t size;
1588 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1589 "object");
1590 if (!obj)
1591 return -1;
1592 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001593 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001594 if (*start<0)
1595 *start = 0; /*XXX check for values <0*/
1596 if (*start>=size)
1597 *start = size-1;
1598 Py_DECREF(obj);
1599 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001600}
1601
1602
1603int
1604PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1605{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001606 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001607 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001608 if (!obj)
1609 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001610 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001611 *start = ((PyUnicodeErrorObject *)exc)->start;
1612 if (*start<0)
1613 *start = 0;
1614 if (*start>=size)
1615 *start = size-1;
1616 Py_DECREF(obj);
1617 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001618}
1619
1620
1621int
1622PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1623{
1624 return PyUnicodeEncodeError_GetStart(exc, start);
1625}
1626
1627
1628int
1629PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1630{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001631 ((PyUnicodeErrorObject *)exc)->start = start;
1632 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001633}
1634
1635
1636int
1637PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1638{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001639 ((PyUnicodeErrorObject *)exc)->start = start;
1640 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001641}
1642
1643
1644int
1645PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1646{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001647 ((PyUnicodeErrorObject *)exc)->start = start;
1648 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001649}
1650
1651
1652int
1653PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1654{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001655 Py_ssize_t size;
1656 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1657 "object");
1658 if (!obj)
1659 return -1;
1660 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001661 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001662 if (*end<1)
1663 *end = 1;
1664 if (*end>size)
1665 *end = size;
1666 Py_DECREF(obj);
1667 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001668}
1669
1670
1671int
1672PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1673{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001674 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001675 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001676 if (!obj)
1677 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001678 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001679 *end = ((PyUnicodeErrorObject *)exc)->end;
1680 if (*end<1)
1681 *end = 1;
1682 if (*end>size)
1683 *end = size;
1684 Py_DECREF(obj);
1685 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001686}
1687
1688
1689int
1690PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1691{
1692 return PyUnicodeEncodeError_GetEnd(exc, start);
1693}
1694
1695
1696int
1697PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1698{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001699 ((PyUnicodeErrorObject *)exc)->end = end;
1700 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001701}
1702
1703
1704int
1705PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1706{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001707 ((PyUnicodeErrorObject *)exc)->end = end;
1708 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001709}
1710
1711
1712int
1713PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1714{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001715 ((PyUnicodeErrorObject *)exc)->end = end;
1716 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001717}
1718
1719PyObject *
1720PyUnicodeEncodeError_GetReason(PyObject *exc)
1721{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001722 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001723}
1724
1725
1726PyObject *
1727PyUnicodeDecodeError_GetReason(PyObject *exc)
1728{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001729 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001730}
1731
1732
1733PyObject *
1734PyUnicodeTranslateError_GetReason(PyObject *exc)
1735{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001736 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001737}
1738
1739
1740int
1741PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1742{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001743 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1744 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001745}
1746
1747
1748int
1749PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1750{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001751 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1752 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001753}
1754
1755
1756int
1757PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1758{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001759 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1760 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001761}
1762
1763
Thomas Wouters477c8d52006-05-27 19:21:47 +00001764static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001765UnicodeError_clear(PyUnicodeErrorObject *self)
1766{
1767 Py_CLEAR(self->encoding);
1768 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001769 Py_CLEAR(self->reason);
1770 return BaseException_clear((PyBaseExceptionObject *)self);
1771}
1772
1773static void
1774UnicodeError_dealloc(PyUnicodeErrorObject *self)
1775{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001776 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001777 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001778 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001779}
1780
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001781static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001782UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1783{
1784 Py_VISIT(self->encoding);
1785 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001786 Py_VISIT(self->reason);
1787 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1788}
1789
1790static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001791 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1792 PyDoc_STR("exception encoding")},
1793 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1794 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001795 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001796 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001797 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001798 PyDoc_STR("exception end")},
1799 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1800 PyDoc_STR("exception reason")},
1801 {NULL} /* Sentinel */
1802};
1803
1804
1805/*
1806 * UnicodeEncodeError extends UnicodeError
1807 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001808
1809static int
1810UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1811{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001812 PyUnicodeErrorObject *err;
1813
Thomas Wouters477c8d52006-05-27 19:21:47 +00001814 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1815 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001816
1817 err = (PyUnicodeErrorObject *)self;
1818
1819 Py_CLEAR(err->encoding);
1820 Py_CLEAR(err->object);
1821 Py_CLEAR(err->reason);
1822
1823 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1824 &PyUnicode_Type, &err->encoding,
1825 &PyUnicode_Type, &err->object,
1826 &err->start,
1827 &err->end,
1828 &PyUnicode_Type, &err->reason)) {
1829 err->encoding = err->object = err->reason = NULL;
1830 return -1;
1831 }
1832
Martin v. Löwisb09af032011-11-04 11:16:41 +01001833 if (PyUnicode_READY(err->object) < -1) {
1834 err->encoding = NULL;
1835 return -1;
1836 }
1837
Guido van Rossum98297ee2007-11-06 21:34:58 +00001838 Py_INCREF(err->encoding);
1839 Py_INCREF(err->object);
1840 Py_INCREF(err->reason);
1841
1842 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001843}
1844
1845static PyObject *
1846UnicodeEncodeError_str(PyObject *self)
1847{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001848 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001849 PyObject *result = NULL;
1850 PyObject *reason_str = NULL;
1851 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001852
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001853 if (!uself->object)
1854 /* Not properly initialized. */
1855 return PyUnicode_FromString("");
1856
Eric Smith0facd772010-02-24 15:42:29 +00001857 /* Get reason and encoding as strings, which they might not be if
1858 they've been modified after we were contructed. */
1859 reason_str = PyObject_Str(uself->reason);
1860 if (reason_str == NULL)
1861 goto done;
1862 encoding_str = PyObject_Str(uself->encoding);
1863 if (encoding_str == NULL)
1864 goto done;
1865
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001866 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1867 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001868 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001869 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001870 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001871 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001872 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001873 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001874 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001875 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001876 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001877 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001878 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001879 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001880 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001881 }
Eric Smith0facd772010-02-24 15:42:29 +00001882 else {
1883 result = PyUnicode_FromFormat(
1884 "'%U' codec can't encode characters in position %zd-%zd: %U",
1885 encoding_str,
1886 uself->start,
1887 uself->end-1,
1888 reason_str);
1889 }
1890done:
1891 Py_XDECREF(reason_str);
1892 Py_XDECREF(encoding_str);
1893 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001894}
1895
1896static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001897 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001898 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001899 sizeof(PyUnicodeErrorObject), 0,
1900 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1901 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1902 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001903 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1904 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001905 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001906 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001907};
1908PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1909
1910PyObject *
1911PyUnicodeEncodeError_Create(
1912 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1913 Py_ssize_t start, Py_ssize_t end, const char *reason)
1914{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001915 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001916 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001917}
1918
1919
1920/*
1921 * UnicodeDecodeError extends UnicodeError
1922 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001923
1924static int
1925UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1926{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001927 PyUnicodeErrorObject *ude;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001928
Thomas Wouters477c8d52006-05-27 19:21:47 +00001929 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1930 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001931
1932 ude = (PyUnicodeErrorObject *)self;
1933
1934 Py_CLEAR(ude->encoding);
1935 Py_CLEAR(ude->object);
1936 Py_CLEAR(ude->reason);
1937
1938 if (!PyArg_ParseTuple(args, "O!OnnO!",
1939 &PyUnicode_Type, &ude->encoding,
1940 &ude->object,
1941 &ude->start,
1942 &ude->end,
1943 &PyUnicode_Type, &ude->reason)) {
1944 ude->encoding = ude->object = ude->reason = NULL;
1945 return -1;
1946 }
1947
Guido van Rossum98297ee2007-11-06 21:34:58 +00001948 Py_INCREF(ude->encoding);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001949 Py_INCREF(ude->object);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001950 Py_INCREF(ude->reason);
1951
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001952 if (!PyBytes_Check(ude->object)) {
1953 Py_buffer view;
1954 if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
1955 goto error;
Serhiy Storchaka48842712016-04-06 09:45:48 +03001956 Py_XSETREF(ude->object, PyBytes_FromStringAndSize(view.buf, view.len));
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001957 PyBuffer_Release(&view);
1958 if (!ude->object)
1959 goto error;
1960 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001961 return 0;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001962
1963error:
1964 Py_CLEAR(ude->encoding);
1965 Py_CLEAR(ude->object);
1966 Py_CLEAR(ude->reason);
1967 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001968}
1969
1970static PyObject *
1971UnicodeDecodeError_str(PyObject *self)
1972{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001973 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001974 PyObject *result = NULL;
1975 PyObject *reason_str = NULL;
1976 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001977
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001978 if (!uself->object)
1979 /* Not properly initialized. */
1980 return PyUnicode_FromString("");
1981
Eric Smith0facd772010-02-24 15:42:29 +00001982 /* Get reason and encoding as strings, which they might not be if
1983 they've been modified after we were contructed. */
1984 reason_str = PyObject_Str(uself->reason);
1985 if (reason_str == NULL)
1986 goto done;
1987 encoding_str = PyObject_Str(uself->encoding);
1988 if (encoding_str == NULL)
1989 goto done;
1990
1991 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001992 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00001993 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001994 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00001995 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001996 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001997 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001998 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001999 }
Eric Smith0facd772010-02-24 15:42:29 +00002000 else {
2001 result = PyUnicode_FromFormat(
2002 "'%U' codec can't decode bytes in position %zd-%zd: %U",
2003 encoding_str,
2004 uself->start,
2005 uself->end-1,
2006 reason_str
2007 );
2008 }
2009done:
2010 Py_XDECREF(reason_str);
2011 Py_XDECREF(encoding_str);
2012 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002013}
2014
2015static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002016 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002017 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002018 sizeof(PyUnicodeErrorObject), 0,
2019 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2020 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
2021 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002022 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
2023 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002024 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002025 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002026};
2027PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
2028
2029PyObject *
2030PyUnicodeDecodeError_Create(
2031 const char *encoding, const char *object, Py_ssize_t length,
2032 Py_ssize_t start, Py_ssize_t end, const char *reason)
2033{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00002034 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002035 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002036}
2037
2038
2039/*
2040 * UnicodeTranslateError extends UnicodeError
2041 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002042
2043static int
2044UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
2045 PyObject *kwds)
2046{
2047 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2048 return -1;
2049
2050 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002051 Py_CLEAR(self->reason);
2052
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002053 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002054 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002055 &self->start,
2056 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00002057 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002058 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002059 return -1;
2060 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002061
Thomas Wouters477c8d52006-05-27 19:21:47 +00002062 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002063 Py_INCREF(self->reason);
2064
2065 return 0;
2066}
2067
2068
2069static PyObject *
2070UnicodeTranslateError_str(PyObject *self)
2071{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002072 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00002073 PyObject *result = NULL;
2074 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002075
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04002076 if (!uself->object)
2077 /* Not properly initialized. */
2078 return PyUnicode_FromString("");
2079
Eric Smith0facd772010-02-24 15:42:29 +00002080 /* Get reason as a string, which it might not be if it's been
2081 modified after we were contructed. */
2082 reason_str = PyObject_Str(uself->reason);
2083 if (reason_str == NULL)
2084 goto done;
2085
Victor Stinner53b33e72011-11-21 01:17:27 +01002086 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2087 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002088 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002089 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002090 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002091 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002092 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002093 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002094 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002095 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002096 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002097 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002098 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002099 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002100 );
Eric Smith0facd772010-02-24 15:42:29 +00002101 } else {
2102 result = PyUnicode_FromFormat(
2103 "can't translate characters in position %zd-%zd: %U",
2104 uself->start,
2105 uself->end-1,
2106 reason_str
2107 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002108 }
Eric Smith0facd772010-02-24 15:42:29 +00002109done:
2110 Py_XDECREF(reason_str);
2111 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002112}
2113
2114static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002115 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002116 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002117 sizeof(PyUnicodeErrorObject), 0,
2118 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2119 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2120 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002121 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002122 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2123 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002124 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002125};
2126PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002128/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002129PyObject *
2130PyUnicodeTranslateError_Create(
2131 const Py_UNICODE *object, Py_ssize_t length,
2132 Py_ssize_t start, Py_ssize_t end, const char *reason)
2133{
2134 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002135 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002136}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002138PyObject *
2139_PyUnicodeTranslateError_Create(
2140 PyObject *object,
2141 Py_ssize_t start, Py_ssize_t end, const char *reason)
2142{
Victor Stinner69598d42014-04-04 20:59:44 +02002143 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002144 object, start, end, reason);
2145}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002146
2147/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002148 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002149 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002150SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002151 "Assertion failed.");
2152
2153
2154/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002155 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002156 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002157SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002158 "Base class for arithmetic errors.");
2159
2160
2161/*
2162 * FloatingPointError extends ArithmeticError
2163 */
2164SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2165 "Floating point operation failed.");
2166
2167
2168/*
2169 * OverflowError extends ArithmeticError
2170 */
2171SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2172 "Result too large to be represented.");
2173
2174
2175/*
2176 * ZeroDivisionError extends ArithmeticError
2177 */
2178SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2179 "Second argument to a division or modulo operation was zero.");
2180
2181
2182/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002183 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002184 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002185SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002186 "Internal error in the Python interpreter.\n"
2187 "\n"
2188 "Please report this to the Python maintainer, along with the traceback,\n"
2189 "the Python version, and the hardware/OS platform and version.");
2190
2191
2192/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002193 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002194 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002195SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002196 "Weak ref proxy used after referent went away.");
2197
2198
2199/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002200 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002201 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002202
2203#define MEMERRORS_SAVE 16
2204static PyBaseExceptionObject *memerrors_freelist = NULL;
2205static int memerrors_numfree = 0;
2206
2207static PyObject *
2208MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2209{
2210 PyBaseExceptionObject *self;
2211
2212 if (type != (PyTypeObject *) PyExc_MemoryError)
2213 return BaseException_new(type, args, kwds);
2214 if (memerrors_freelist == NULL)
2215 return BaseException_new(type, args, kwds);
2216 /* Fetch object from freelist and revive it */
2217 self = memerrors_freelist;
2218 self->args = PyTuple_New(0);
2219 /* This shouldn't happen since the empty tuple is persistent */
2220 if (self->args == NULL)
2221 return NULL;
2222 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2223 memerrors_numfree--;
2224 self->dict = NULL;
2225 _Py_NewReference((PyObject *)self);
2226 _PyObject_GC_TRACK(self);
2227 return (PyObject *)self;
2228}
2229
2230static void
2231MemoryError_dealloc(PyBaseExceptionObject *self)
2232{
2233 _PyObject_GC_UNTRACK(self);
2234 BaseException_clear(self);
2235 if (memerrors_numfree >= MEMERRORS_SAVE)
2236 Py_TYPE(self)->tp_free((PyObject *)self);
2237 else {
2238 self->dict = (PyObject *) memerrors_freelist;
2239 memerrors_freelist = self;
2240 memerrors_numfree++;
2241 }
2242}
2243
2244static void
2245preallocate_memerrors(void)
2246{
2247 /* We create enough MemoryErrors and then decref them, which will fill
2248 up the freelist. */
2249 int i;
2250 PyObject *errors[MEMERRORS_SAVE];
2251 for (i = 0; i < MEMERRORS_SAVE; i++) {
2252 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2253 NULL, NULL);
2254 if (!errors[i])
2255 Py_FatalError("Could not preallocate MemoryError object");
2256 }
2257 for (i = 0; i < MEMERRORS_SAVE; i++) {
2258 Py_DECREF(errors[i]);
2259 }
2260}
2261
2262static void
2263free_preallocated_memerrors(void)
2264{
2265 while (memerrors_freelist != NULL) {
2266 PyObject *self = (PyObject *) memerrors_freelist;
2267 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2268 Py_TYPE(self)->tp_free((PyObject *)self);
2269 }
2270}
2271
2272
2273static PyTypeObject _PyExc_MemoryError = {
2274 PyVarObject_HEAD_INIT(NULL, 0)
2275 "MemoryError",
2276 sizeof(PyBaseExceptionObject),
2277 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2278 0, 0, 0, 0, 0, 0, 0,
2279 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2280 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2281 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2282 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2283 (initproc)BaseException_init, 0, MemoryError_new
2284};
2285PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2286
Thomas Wouters477c8d52006-05-27 19:21:47 +00002287
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002288/*
2289 * BufferError extends Exception
2290 */
2291SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2292
Thomas Wouters477c8d52006-05-27 19:21:47 +00002293
2294/* Warning category docstrings */
2295
2296/*
2297 * Warning extends Exception
2298 */
2299SimpleExtendsException(PyExc_Exception, Warning,
2300 "Base class for warning categories.");
2301
2302
2303/*
2304 * UserWarning extends Warning
2305 */
2306SimpleExtendsException(PyExc_Warning, UserWarning,
2307 "Base class for warnings generated by user code.");
2308
2309
2310/*
2311 * DeprecationWarning extends Warning
2312 */
2313SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2314 "Base class for warnings about deprecated features.");
2315
2316
2317/*
2318 * PendingDeprecationWarning extends Warning
2319 */
2320SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2321 "Base class for warnings about features which will be deprecated\n"
2322 "in the future.");
2323
2324
2325/*
2326 * SyntaxWarning extends Warning
2327 */
2328SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2329 "Base class for warnings about dubious syntax.");
2330
2331
2332/*
2333 * RuntimeWarning extends Warning
2334 */
2335SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2336 "Base class for warnings about dubious runtime behavior.");
2337
2338
2339/*
2340 * FutureWarning extends Warning
2341 */
2342SimpleExtendsException(PyExc_Warning, FutureWarning,
2343 "Base class for warnings about constructs that will change semantically\n"
2344 "in the future.");
2345
2346
2347/*
2348 * ImportWarning extends Warning
2349 */
2350SimpleExtendsException(PyExc_Warning, ImportWarning,
2351 "Base class for warnings about probable mistakes in module imports");
2352
2353
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002354/*
2355 * UnicodeWarning extends Warning
2356 */
2357SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2358 "Base class for warnings about Unicode related problems, mostly\n"
2359 "related to conversion problems.");
2360
Georg Brandl08be72d2010-10-24 15:11:22 +00002361
Guido van Rossum98297ee2007-11-06 21:34:58 +00002362/*
2363 * BytesWarning extends Warning
2364 */
2365SimpleExtendsException(PyExc_Warning, BytesWarning,
2366 "Base class for warnings about bytes and buffer related problems, mostly\n"
2367 "related to conversion from str or comparing to str.");
2368
2369
Georg Brandl08be72d2010-10-24 15:11:22 +00002370/*
2371 * ResourceWarning extends Warning
2372 */
2373SimpleExtendsException(PyExc_Warning, ResourceWarning,
2374 "Base class for warnings about resource usage.");
2375
2376
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002377
Yury Selivanovf488fb42015-07-03 01:04:23 -04002378/* Pre-computed RecursionError instance for when recursion depth is reached.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002379 Meant to be used when normalizing the exception for exceeding the recursion
2380 depth will cause its own infinite recursion.
2381*/
2382PyObject *PyExc_RecursionErrorInst = NULL;
2383
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002384#define PRE_INIT(TYPE) \
2385 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2386 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2387 Py_FatalError("exceptions bootstrapping error."); \
2388 Py_INCREF(PyExc_ ## TYPE); \
2389 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002390
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002391#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002392 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2393 Py_FatalError("Module dictionary insertion problem.");
2394
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002395#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002396 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002397 PyExc_ ## NAME = PyExc_ ## TYPE; \
2398 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2399 Py_FatalError("Module dictionary insertion problem.");
2400
2401#define ADD_ERRNO(TYPE, CODE) { \
2402 PyObject *_code = PyLong_FromLong(CODE); \
2403 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2404 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2405 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002406 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002407 }
2408
2409#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002410#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002411/* The following constants were added to errno.h in VS2010 but have
2412 preferred WSA equivalents. */
2413#undef EADDRINUSE
2414#undef EADDRNOTAVAIL
2415#undef EAFNOSUPPORT
2416#undef EALREADY
2417#undef ECONNABORTED
2418#undef ECONNREFUSED
2419#undef ECONNRESET
2420#undef EDESTADDRREQ
2421#undef EHOSTUNREACH
2422#undef EINPROGRESS
2423#undef EISCONN
2424#undef ELOOP
2425#undef EMSGSIZE
2426#undef ENETDOWN
2427#undef ENETRESET
2428#undef ENETUNREACH
2429#undef ENOBUFS
2430#undef ENOPROTOOPT
2431#undef ENOTCONN
2432#undef ENOTSOCK
2433#undef EOPNOTSUPP
2434#undef EPROTONOSUPPORT
2435#undef EPROTOTYPE
2436#undef ETIMEDOUT
2437#undef EWOULDBLOCK
2438
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002439#if defined(WSAEALREADY) && !defined(EALREADY)
2440#define EALREADY WSAEALREADY
2441#endif
2442#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2443#define ECONNABORTED WSAECONNABORTED
2444#endif
2445#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2446#define ECONNREFUSED WSAECONNREFUSED
2447#endif
2448#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2449#define ECONNRESET WSAECONNRESET
2450#endif
2451#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2452#define EINPROGRESS WSAEINPROGRESS
2453#endif
2454#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2455#define ESHUTDOWN WSAESHUTDOWN
2456#endif
2457#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2458#define ETIMEDOUT WSAETIMEDOUT
2459#endif
2460#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2461#define EWOULDBLOCK WSAEWOULDBLOCK
2462#endif
2463#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002464
Martin v. Löwis1a214512008-06-11 05:26:20 +00002465void
Brett Cannonfd074152012-04-14 14:10:13 -04002466_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002467{
Brett Cannonfd074152012-04-14 14:10:13 -04002468 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002469
2470 PRE_INIT(BaseException)
2471 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002472 PRE_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002473 PRE_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002474 PRE_INIT(StopIteration)
2475 PRE_INIT(GeneratorExit)
2476 PRE_INIT(SystemExit)
2477 PRE_INIT(KeyboardInterrupt)
2478 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002479 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002480 PRE_INIT(EOFError)
2481 PRE_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002482 PRE_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002483 PRE_INIT(NotImplementedError)
2484 PRE_INIT(NameError)
2485 PRE_INIT(UnboundLocalError)
2486 PRE_INIT(AttributeError)
2487 PRE_INIT(SyntaxError)
2488 PRE_INIT(IndentationError)
2489 PRE_INIT(TabError)
2490 PRE_INIT(LookupError)
2491 PRE_INIT(IndexError)
2492 PRE_INIT(KeyError)
2493 PRE_INIT(ValueError)
2494 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002495 PRE_INIT(UnicodeEncodeError)
2496 PRE_INIT(UnicodeDecodeError)
2497 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002498 PRE_INIT(AssertionError)
2499 PRE_INIT(ArithmeticError)
2500 PRE_INIT(FloatingPointError)
2501 PRE_INIT(OverflowError)
2502 PRE_INIT(ZeroDivisionError)
2503 PRE_INIT(SystemError)
2504 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002505 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002506 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002507 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002508 PRE_INIT(Warning)
2509 PRE_INIT(UserWarning)
2510 PRE_INIT(DeprecationWarning)
2511 PRE_INIT(PendingDeprecationWarning)
2512 PRE_INIT(SyntaxWarning)
2513 PRE_INIT(RuntimeWarning)
2514 PRE_INIT(FutureWarning)
2515 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002516 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002517 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002518 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002519
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002520 /* OSError subclasses */
2521 PRE_INIT(ConnectionError);
2522
2523 PRE_INIT(BlockingIOError);
2524 PRE_INIT(BrokenPipeError);
2525 PRE_INIT(ChildProcessError);
2526 PRE_INIT(ConnectionAbortedError);
2527 PRE_INIT(ConnectionRefusedError);
2528 PRE_INIT(ConnectionResetError);
2529 PRE_INIT(FileExistsError);
2530 PRE_INIT(FileNotFoundError);
2531 PRE_INIT(IsADirectoryError);
2532 PRE_INIT(NotADirectoryError);
2533 PRE_INIT(InterruptedError);
2534 PRE_INIT(PermissionError);
2535 PRE_INIT(ProcessLookupError);
2536 PRE_INIT(TimeoutError);
2537
Thomas Wouters477c8d52006-05-27 19:21:47 +00002538 bdict = PyModule_GetDict(bltinmod);
2539 if (bdict == NULL)
2540 Py_FatalError("exceptions bootstrapping error.");
2541
2542 POST_INIT(BaseException)
2543 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002544 POST_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002545 POST_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002546 POST_INIT(StopIteration)
2547 POST_INIT(GeneratorExit)
2548 POST_INIT(SystemExit)
2549 POST_INIT(KeyboardInterrupt)
2550 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002551 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002552 INIT_ALIAS(EnvironmentError, OSError)
2553 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002554#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002555 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002556#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00002557 POST_INIT(EOFError)
2558 POST_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002559 POST_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002560 POST_INIT(NotImplementedError)
2561 POST_INIT(NameError)
2562 POST_INIT(UnboundLocalError)
2563 POST_INIT(AttributeError)
2564 POST_INIT(SyntaxError)
2565 POST_INIT(IndentationError)
2566 POST_INIT(TabError)
2567 POST_INIT(LookupError)
2568 POST_INIT(IndexError)
2569 POST_INIT(KeyError)
2570 POST_INIT(ValueError)
2571 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002572 POST_INIT(UnicodeEncodeError)
2573 POST_INIT(UnicodeDecodeError)
2574 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002575 POST_INIT(AssertionError)
2576 POST_INIT(ArithmeticError)
2577 POST_INIT(FloatingPointError)
2578 POST_INIT(OverflowError)
2579 POST_INIT(ZeroDivisionError)
2580 POST_INIT(SystemError)
2581 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002582 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002583 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002584 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002585 POST_INIT(Warning)
2586 POST_INIT(UserWarning)
2587 POST_INIT(DeprecationWarning)
2588 POST_INIT(PendingDeprecationWarning)
2589 POST_INIT(SyntaxWarning)
2590 POST_INIT(RuntimeWarning)
2591 POST_INIT(FutureWarning)
2592 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002593 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002594 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002595 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002596
Antoine Pitrouac456a12012-01-18 21:35:21 +01002597 if (!errnomap) {
2598 errnomap = PyDict_New();
2599 if (!errnomap)
2600 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2601 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002602
2603 /* OSError subclasses */
2604 POST_INIT(ConnectionError);
2605
2606 POST_INIT(BlockingIOError);
2607 ADD_ERRNO(BlockingIOError, EAGAIN);
2608 ADD_ERRNO(BlockingIOError, EALREADY);
2609 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2610 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2611 POST_INIT(BrokenPipeError);
2612 ADD_ERRNO(BrokenPipeError, EPIPE);
2613 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2614 POST_INIT(ChildProcessError);
2615 ADD_ERRNO(ChildProcessError, ECHILD);
2616 POST_INIT(ConnectionAbortedError);
2617 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2618 POST_INIT(ConnectionRefusedError);
2619 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2620 POST_INIT(ConnectionResetError);
2621 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2622 POST_INIT(FileExistsError);
2623 ADD_ERRNO(FileExistsError, EEXIST);
2624 POST_INIT(FileNotFoundError);
2625 ADD_ERRNO(FileNotFoundError, ENOENT);
2626 POST_INIT(IsADirectoryError);
2627 ADD_ERRNO(IsADirectoryError, EISDIR);
2628 POST_INIT(NotADirectoryError);
2629 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2630 POST_INIT(InterruptedError);
2631 ADD_ERRNO(InterruptedError, EINTR);
2632 POST_INIT(PermissionError);
2633 ADD_ERRNO(PermissionError, EACCES);
2634 ADD_ERRNO(PermissionError, EPERM);
2635 POST_INIT(ProcessLookupError);
2636 ADD_ERRNO(ProcessLookupError, ESRCH);
2637 POST_INIT(TimeoutError);
2638 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2639
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002640 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002641
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002642 if (!PyExc_RecursionErrorInst) {
Yury Selivanovf488fb42015-07-03 01:04:23 -04002643 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RecursionError, NULL, NULL);
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002644 if (!PyExc_RecursionErrorInst)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002645 Py_FatalError("Cannot pre-allocate RecursionError instance for "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002646 "recursion errors");
2647 else {
2648 PyBaseExceptionObject *err_inst =
2649 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2650 PyObject *args_tuple;
2651 PyObject *exc_message;
2652 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2653 if (!exc_message)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002654 Py_FatalError("cannot allocate argument for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002655 "pre-allocation");
2656 args_tuple = PyTuple_Pack(1, exc_message);
2657 if (!args_tuple)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002658 Py_FatalError("cannot allocate tuple for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002659 "pre-allocation");
2660 Py_DECREF(exc_message);
2661 if (BaseException_init(err_inst, args_tuple, NULL))
Yury Selivanovf488fb42015-07-03 01:04:23 -04002662 Py_FatalError("init of pre-allocated RecursionError failed");
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002663 Py_DECREF(args_tuple);
2664 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002665 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002666}
2667
2668void
2669_PyExc_Fini(void)
2670{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002671 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002672 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002673 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002674}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002675
2676/* Helper to do the equivalent of "raise X from Y" in C, but always using
2677 * the current exception rather than passing one in.
2678 *
2679 * We currently limit this to *only* exceptions that use the BaseException
2680 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2681 * those correctly without losing data and without losing backwards
2682 * compatibility.
2683 *
2684 * We also aim to rule out *all* exceptions that might be storing additional
2685 * state, whether by having a size difference relative to BaseException,
2686 * additional arguments passed in during construction or by having a
2687 * non-empty instance dict.
2688 *
2689 * We need to be very careful with what we wrap, since changing types to
2690 * a broader exception type would be backwards incompatible for
2691 * existing codecs, and with different init or new method implementations
2692 * may either not support instantiation with PyErr_Format or lose
2693 * information when instantiated that way.
2694 *
2695 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2696 * fact that exceptions are expected to support pickling. If more builtin
2697 * exceptions (e.g. AttributeError) start to be converted to rich
2698 * exceptions with additional attributes, that's probably a better approach
2699 * to pursue over adding special cases for particular stateful subclasses.
2700 *
2701 * Returns a borrowed reference to the new exception (if any), NULL if the
2702 * existing exception was left in place.
2703 */
2704PyObject *
2705_PyErr_TrySetFromCause(const char *format, ...)
2706{
2707 PyObject* msg_prefix;
2708 PyObject *exc, *val, *tb;
2709 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002710 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002711 PyObject *instance_args;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002712 Py_ssize_t num_args, caught_type_size, base_exc_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002713 PyObject *new_exc, *new_val, *new_tb;
2714 va_list vargs;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002715 int same_basic_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002716
Nick Coghlan8b097b42013-11-13 23:49:21 +10002717 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002718 caught_type = (PyTypeObject *)exc;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002719 /* Ensure type info indicates no extra state is stored at the C level
2720 * and that the type can be reinstantiated using PyErr_Format
2721 */
2722 caught_type_size = caught_type->tp_basicsize;
2723 base_exc_size = _PyExc_BaseException.tp_basicsize;
2724 same_basic_size = (
2725 caught_type_size == base_exc_size ||
2726 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
Victor Stinner12174a52014-08-15 23:17:38 +02002727 (caught_type_size == base_exc_size + (Py_ssize_t)sizeof(PyObject *))
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002728 )
2729 );
Benjamin Peterson079c9982013-11-13 23:25:01 -05002730 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002731 caught_type->tp_new != BaseException_new ||
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002732 !same_basic_size ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002733 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002734 /* We can't be sure we can wrap this safely, since it may contain
2735 * more state than just the exception type. Accordingly, we just
2736 * leave it alone.
2737 */
2738 PyErr_Restore(exc, val, tb);
2739 return NULL;
2740 }
2741
2742 /* Check the args are empty or contain a single string */
2743 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002744 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002745 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002746 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002747 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002748 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002749 /* More than 1 arg, or the one arg we do have isn't a string
2750 */
2751 PyErr_Restore(exc, val, tb);
2752 return NULL;
2753 }
2754
2755 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002756 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002757 if (dictptr != NULL && *dictptr != NULL &&
2758 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002759 /* While we could potentially copy a non-empty instance dictionary
2760 * to the replacement exception, for now we take the more
2761 * conservative path of leaving exceptions with attributes set
2762 * alone.
2763 */
2764 PyErr_Restore(exc, val, tb);
2765 return NULL;
2766 }
2767
2768 /* For exceptions that we can wrap safely, we chain the original
2769 * exception to a new one of the exact same type with an
2770 * error message that mentions the additional details and the
2771 * original exception.
2772 *
2773 * It would be nice to wrap OSError and various other exception
2774 * types as well, but that's quite a bit trickier due to the extra
2775 * state potentially stored on OSError instances.
2776 */
Nick Coghlan77b286b2014-01-27 00:53:38 +10002777 /* Ensure the traceback is set correctly on the existing exception */
2778 if (tb != NULL) {
2779 PyException_SetTraceback(val, tb);
2780 Py_DECREF(tb);
2781 }
Benjamin Petersone109ee82013-11-13 23:49:49 -05002782
Christian Heimes507eabd2013-11-14 01:39:35 +01002783#ifdef HAVE_STDARG_PROTOTYPES
2784 va_start(vargs, format);
2785#else
2786 va_start(vargs);
2787#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002788 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002789 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002790 if (msg_prefix == NULL) {
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002791 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002792 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002793 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002794 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002795
2796 PyErr_Format(exc, "%U (%s: %S)",
2797 msg_prefix, Py_TYPE(val)->tp_name, val);
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002798 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002799 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002800 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2801 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2802 PyException_SetCause(new_val, val);
2803 PyErr_Restore(new_exc, new_val, new_tb);
2804 return new_val;
2805}
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002806
2807
2808/* To help with migration from Python 2, SyntaxError.__init__ applies some
2809 * heuristics to try to report a more meaningful exception when print and
2810 * exec are used like statements.
2811 *
2812 * The heuristics are currently expected to detect the following cases:
2813 * - top level statement
2814 * - statement in a nested suite
2815 * - trailing section of a one line complex statement
2816 *
2817 * They're currently known not to trigger:
2818 * - after a semi-colon
2819 *
2820 * The error message can be a bit odd in cases where the "arguments" are
2821 * completely illegal syntactically, but that isn't worth the hassle of
2822 * fixing.
2823 *
2824 * We also can't do anything about cases that are legal Python 3 syntax
2825 * but mean something entirely different from what they did in Python 2
2826 * (omitting the arguments entirely, printing items preceded by a unary plus
2827 * or minus, using the stream redirection syntax).
2828 */
2829
2830static int
2831_check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start)
2832{
2833 /* Return values:
2834 * -1: an error occurred
2835 * 0: nothing happened
2836 * 1: the check triggered & the error message was changed
2837 */
2838 static PyObject *print_prefix = NULL;
2839 static PyObject *exec_prefix = NULL;
2840 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2841 int kind = PyUnicode_KIND(self->text);
2842 void *data = PyUnicode_DATA(self->text);
2843
2844 /* Ignore leading whitespace */
2845 while (start < text_len) {
2846 Py_UCS4 ch = PyUnicode_READ(kind, data, start);
2847 if (!Py_UNICODE_ISSPACE(ch))
2848 break;
2849 start++;
2850 }
2851 /* Checking against an empty or whitespace-only part of the string */
2852 if (start == text_len) {
2853 return 0;
2854 }
2855
2856 /* Check for legacy print statements */
2857 if (print_prefix == NULL) {
2858 print_prefix = PyUnicode_InternFromString("print ");
2859 if (print_prefix == NULL) {
2860 return -1;
2861 }
2862 }
2863 if (PyUnicode_Tailmatch(self->text, print_prefix,
2864 start, text_len, -1)) {
Serhiy Storchaka48842712016-04-06 09:45:48 +03002865 Py_XSETREF(self->msg,
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02002866 PyUnicode_FromString("Missing parentheses in call to 'print'"));
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002867 return 1;
2868 }
2869
2870 /* Check for legacy exec statements */
2871 if (exec_prefix == NULL) {
2872 exec_prefix = PyUnicode_InternFromString("exec ");
2873 if (exec_prefix == NULL) {
2874 return -1;
2875 }
2876 }
2877 if (PyUnicode_Tailmatch(self->text, exec_prefix,
2878 start, text_len, -1)) {
Serhiy Storchaka48842712016-04-06 09:45:48 +03002879 Py_XSETREF(self->msg,
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02002880 PyUnicode_FromString("Missing parentheses in call to 'exec'"));
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002881 return 1;
2882 }
2883 /* Fall back to the default error message */
2884 return 0;
2885}
2886
2887static int
2888_report_missing_parentheses(PySyntaxErrorObject *self)
2889{
2890 Py_UCS4 left_paren = 40;
2891 Py_ssize_t left_paren_index;
2892 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2893 int legacy_check_result = 0;
2894
2895 /* Skip entirely if there is an opening parenthesis */
2896 left_paren_index = PyUnicode_FindChar(self->text, left_paren,
2897 0, text_len, 1);
2898 if (left_paren_index < -1) {
2899 return -1;
2900 }
2901 if (left_paren_index != -1) {
2902 /* Use default error message for any line with an opening paren */
2903 return 0;
2904 }
2905 /* Handle the simple statement case */
2906 legacy_check_result = _check_for_legacy_statements(self, 0);
2907 if (legacy_check_result < 0) {
2908 return -1;
2909
2910 }
2911 if (legacy_check_result == 0) {
2912 /* Handle the one-line complex statement case */
2913 Py_UCS4 colon = 58;
2914 Py_ssize_t colon_index;
2915 colon_index = PyUnicode_FindChar(self->text, colon,
2916 0, text_len, 1);
2917 if (colon_index < -1) {
2918 return -1;
2919 }
2920 if (colon_index >= 0 && colon_index < text_len) {
2921 /* Check again, starting from just after the colon */
2922 if (_check_for_legacy_statements(self, colon_index+1) < 0) {
2923 return -1;
2924 }
2925 }
2926 }
2927 return 0;
2928}