blob: e85d743dab0a0e8236487da6c975eef8d6c324a0 [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{
Christian Heimes90aa7642007-12-19 02:45:37 +000062 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000063 return -1;
64
Serhiy Storchaka576f1322016-01-05 21:27:54 +020065 Py_INCREF(args);
Serhiy Storchakaec397562016-04-06 09:50:03 +030066 Py_XSETREF(self->args, args);
Thomas Wouters477c8d52006-05-27 19:21:47 +000067
Thomas Wouters477c8d52006-05-27 19:21:47 +000068 return 0;
69}
70
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000071static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000072BaseException_clear(PyBaseExceptionObject *self)
73{
74 Py_CLEAR(self->dict);
75 Py_CLEAR(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +000076 Py_CLEAR(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +000077 Py_CLEAR(self->cause);
78 Py_CLEAR(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +000079 return 0;
80}
81
82static void
83BaseException_dealloc(PyBaseExceptionObject *self)
84{
Thomas Wouters89f507f2006-12-13 04:49:30 +000085 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000086 BaseException_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +000087 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000088}
89
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000090static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000091BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
92{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000093 Py_VISIT(self->dict);
Thomas Wouters477c8d52006-05-27 19:21:47 +000094 Py_VISIT(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +000095 Py_VISIT(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +000096 Py_VISIT(self->cause);
97 Py_VISIT(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +000098 return 0;
99}
100
101static PyObject *
102BaseException_str(PyBaseExceptionObject *self)
103{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000104 switch (PyTuple_GET_SIZE(self->args)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000105 case 0:
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +0000106 return PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000107 case 1:
Thomas Heller519a0422007-11-15 20:48:54 +0000108 return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 default:
Thomas Heller519a0422007-11-15 20:48:54 +0000110 return PyObject_Str(self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000111 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000112}
113
114static PyObject *
115BaseException_repr(PyBaseExceptionObject *self)
116{
Serhiy Storchakac6792272013-10-19 21:03:34 +0300117 const char *name;
118 const char *dot;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000119
Serhiy Storchakac6792272013-10-19 21:03:34 +0300120 name = Py_TYPE(self)->tp_name;
121 dot = (const char *) strrchr(name, '.');
Thomas Wouters477c8d52006-05-27 19:21:47 +0000122 if (dot != NULL) name = dot+1;
123
Walter Dörwald7569dfe2007-05-19 21:49:49 +0000124 return PyUnicode_FromFormat("%s%R", name, self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000125}
126
127/* Pickling support */
128static PyObject *
129BaseException_reduce(PyBaseExceptionObject *self)
130{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000131 if (self->args && self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +0000132 return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000133 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000134 return PyTuple_Pack(2, Py_TYPE(self), self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000135}
136
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000137/*
138 * Needed for backward compatibility, since exceptions used to store
139 * all their attributes in the __dict__. Code is taken from cPickle's
140 * load_build function.
141 */
142static PyObject *
143BaseException_setstate(PyObject *self, PyObject *state)
144{
145 PyObject *d_key, *d_value;
146 Py_ssize_t i = 0;
147
148 if (state != Py_None) {
149 if (!PyDict_Check(state)) {
150 PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
151 return NULL;
152 }
153 while (PyDict_Next(state, &i, &d_key, &d_value)) {
154 if (PyObject_SetAttr(self, d_key, d_value) < 0)
155 return NULL;
156 }
157 }
158 Py_RETURN_NONE;
159}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000160
Collin Winter828f04a2007-08-31 00:04:24 +0000161static PyObject *
162BaseException_with_traceback(PyObject *self, PyObject *tb) {
163 if (PyException_SetTraceback(self, tb))
164 return NULL;
165
166 Py_INCREF(self);
167 return self;
168}
169
Georg Brandl76941002008-05-05 21:38:47 +0000170PyDoc_STRVAR(with_traceback_doc,
171"Exception.with_traceback(tb) --\n\
172 set self.__traceback__ to tb and return self.");
173
Thomas Wouters477c8d52006-05-27 19:21:47 +0000174
175static PyMethodDef BaseException_methods[] = {
176 {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000177 {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
Georg Brandl76941002008-05-05 21:38:47 +0000178 {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
179 with_traceback_doc},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000180 {NULL, NULL, 0, NULL},
181};
182
Thomas Wouters477c8d52006-05-27 19:21:47 +0000183static PyObject *
184BaseException_get_args(PyBaseExceptionObject *self)
185{
186 if (self->args == NULL) {
187 Py_INCREF(Py_None);
188 return Py_None;
189 }
190 Py_INCREF(self->args);
191 return self->args;
192}
193
194static int
195BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
196{
197 PyObject *seq;
198 if (val == NULL) {
199 PyErr_SetString(PyExc_TypeError, "args may not be deleted");
200 return -1;
201 }
202 seq = PySequence_Tuple(val);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500203 if (!seq)
204 return -1;
Serhiy Storchaka48842712016-04-06 09:45:48 +0300205 Py_XSETREF(self->args, seq);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000206 return 0;
207}
208
Collin Winter828f04a2007-08-31 00:04:24 +0000209static PyObject *
210BaseException_get_tb(PyBaseExceptionObject *self)
211{
212 if (self->traceback == NULL) {
213 Py_INCREF(Py_None);
214 return Py_None;
215 }
216 Py_INCREF(self->traceback);
217 return self->traceback;
218}
219
220static int
221BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb)
222{
223 if (tb == NULL) {
224 PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
225 return -1;
226 }
227 else if (!(tb == Py_None || PyTraceBack_Check(tb))) {
228 PyErr_SetString(PyExc_TypeError,
229 "__traceback__ must be a traceback or None");
230 return -1;
231 }
232
Serhiy Storchaka37665722016-08-20 21:22:03 +0300233 Py_INCREF(tb);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300234 Py_XSETREF(self->traceback, tb);
Collin Winter828f04a2007-08-31 00:04:24 +0000235 return 0;
236}
237
Georg Brandlab6f2f62009-03-31 04:16:10 +0000238static PyObject *
239BaseException_get_context(PyObject *self) {
240 PyObject *res = PyException_GetContext(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500241 if (res)
242 return res; /* new reference already returned above */
Georg Brandlab6f2f62009-03-31 04:16:10 +0000243 Py_RETURN_NONE;
244}
245
246static int
247BaseException_set_context(PyObject *self, PyObject *arg) {
248 if (arg == NULL) {
249 PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
250 return -1;
251 } else if (arg == Py_None) {
252 arg = NULL;
253 } else if (!PyExceptionInstance_Check(arg)) {
254 PyErr_SetString(PyExc_TypeError, "exception context must be None "
255 "or derive from BaseException");
256 return -1;
257 } else {
258 /* PyException_SetContext steals this reference */
259 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 }
Georg Brandlab6f2f62009-03-31 04:16:10 +0000261 PyException_SetContext(self, arg);
262 return 0;
263}
264
265static PyObject *
266BaseException_get_cause(PyObject *self) {
267 PyObject *res = PyException_GetCause(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500268 if (res)
269 return res; /* new reference already returned above */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700270 Py_RETURN_NONE;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000271}
272
273static int
274BaseException_set_cause(PyObject *self, PyObject *arg) {
275 if (arg == NULL) {
276 PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
277 return -1;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700278 } else if (arg == Py_None) {
279 arg = NULL;
280 } else if (!PyExceptionInstance_Check(arg)) {
281 PyErr_SetString(PyExc_TypeError, "exception cause must be None "
282 "or derive from BaseException");
283 return -1;
284 } else {
285 /* PyException_SetCause steals this reference */
286 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700288 PyException_SetCause(self, arg);
289 return 0;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000290}
291
Guido van Rossum360e4b82007-05-14 22:51:27 +0000292
Thomas Wouters477c8d52006-05-27 19:21:47 +0000293static PyGetSetDef BaseException_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500294 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000295 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
Collin Winter828f04a2007-08-31 00:04:24 +0000296 {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
Georg Brandlab6f2f62009-03-31 04:16:10 +0000297 {"__context__", (getter)BaseException_get_context,
298 (setter)BaseException_set_context, PyDoc_STR("exception context")},
299 {"__cause__", (getter)BaseException_get_cause,
300 (setter)BaseException_set_cause, PyDoc_STR("exception cause")},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000301 {NULL},
302};
303
304
Collin Winter828f04a2007-08-31 00:04:24 +0000305PyObject *
306PyException_GetTraceback(PyObject *self) {
307 PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
308 Py_XINCREF(base_self->traceback);
309 return base_self->traceback;
310}
311
312
313int
314PyException_SetTraceback(PyObject *self, PyObject *tb) {
315 return BaseException_set_tb((PyBaseExceptionObject *)self, tb);
316}
317
318PyObject *
319PyException_GetCause(PyObject *self) {
320 PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
321 Py_XINCREF(cause);
322 return cause;
323}
324
325/* Steals a reference to cause */
326void
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200327PyException_SetCause(PyObject *self, PyObject *cause)
328{
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700329 ((PyBaseExceptionObject *)self)->suppress_context = 1;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300330 Py_XSETREF(((PyBaseExceptionObject *)self)->cause, cause);
Collin Winter828f04a2007-08-31 00:04:24 +0000331}
332
333PyObject *
334PyException_GetContext(PyObject *self) {
335 PyObject *context = ((PyBaseExceptionObject *)self)->context;
336 Py_XINCREF(context);
337 return context;
338}
339
340/* Steals a reference to context */
341void
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200342PyException_SetContext(PyObject *self, PyObject *context)
343{
Serhiy Storchakaec397562016-04-06 09:50:03 +0300344 Py_XSETREF(((PyBaseExceptionObject *)self)->context, context);
Collin Winter828f04a2007-08-31 00:04:24 +0000345}
346
347
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700348static struct PyMemberDef BaseException_members[] = {
349 {"__suppress_context__", T_BOOL,
Antoine Pitrou32bc80c2012-05-16 12:51:55 +0200350 offsetof(PyBaseExceptionObject, suppress_context)},
351 {NULL}
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700352};
353
354
Thomas Wouters477c8d52006-05-27 19:21:47 +0000355static PyTypeObject _PyExc_BaseException = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000356 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +0000357 "BaseException", /*tp_name*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000358 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
359 0, /*tp_itemsize*/
360 (destructor)BaseException_dealloc, /*tp_dealloc*/
361 0, /*tp_print*/
362 0, /*tp_getattr*/
363 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000364 0, /* tp_reserved; */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000365 (reprfunc)BaseException_repr, /*tp_repr*/
366 0, /*tp_as_number*/
Brett Cannonba7bf492007-02-27 00:15:55 +0000367 0, /*tp_as_sequence*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000368 0, /*tp_as_mapping*/
369 0, /*tp_hash */
370 0, /*tp_call*/
371 (reprfunc)BaseException_str, /*tp_str*/
372 PyObject_GenericGetAttr, /*tp_getattro*/
373 PyObject_GenericSetAttr, /*tp_setattro*/
374 0, /*tp_as_buffer*/
Thomas Wouters27d517b2007-02-25 20:39:11 +0000375 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000377 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
378 (traverseproc)BaseException_traverse, /* tp_traverse */
379 (inquiry)BaseException_clear, /* tp_clear */
380 0, /* tp_richcompare */
381 0, /* tp_weaklistoffset */
382 0, /* tp_iter */
383 0, /* tp_iternext */
384 BaseException_methods, /* tp_methods */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700385 BaseException_members, /* tp_members */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000386 BaseException_getset, /* tp_getset */
387 0, /* tp_base */
388 0, /* tp_dict */
389 0, /* tp_descr_get */
390 0, /* tp_descr_set */
391 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
392 (initproc)BaseException_init, /* tp_init */
393 0, /* tp_alloc */
394 BaseException_new, /* tp_new */
395};
396/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
397from the previous implmentation and also allowing Python objects to be used
398in the API */
399PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
400
401/* note these macros omit the last semicolon so the macro invocation may
402 * include it and not look strange.
403 */
404#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
405static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000406 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000407 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000408 sizeof(PyBaseExceptionObject), \
409 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
410 0, 0, 0, 0, 0, 0, 0, \
411 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
412 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
413 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
414 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
415 (initproc)BaseException_init, 0, BaseException_new,\
416}; \
417PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
418
419#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
420static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000421 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000422 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000423 sizeof(Py ## EXCSTORE ## Object), \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000424 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000425 0, 0, 0, 0, 0, \
426 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000427 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
428 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000429 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200430 (initproc)EXCSTORE ## _init, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431}; \
432PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
433
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200434#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
435 EXCMETHODS, EXCMEMBERS, EXCGETSET, \
436 EXCSTR, EXCDOC) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000438 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000439 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000440 sizeof(Py ## EXCSTORE ## Object), 0, \
441 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
442 (reprfunc)EXCSTR, 0, 0, 0, \
443 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
444 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
445 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200446 EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200448 (initproc)EXCSTORE ## _init, 0, EXCNEW,\
Thomas Wouters477c8d52006-05-27 19:21:47 +0000449}; \
450PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
451
452
453/*
454 * Exception extends BaseException
455 */
456SimpleExtendsException(PyExc_BaseException, Exception,
457 "Common base class for all non-exit exceptions.");
458
459
460/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000461 * TypeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000462 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000463SimpleExtendsException(PyExc_Exception, TypeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000464 "Inappropriate argument type.");
465
466
467/*
Yury Selivanov75445082015-05-11 22:57:16 -0400468 * StopAsyncIteration extends Exception
469 */
470SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
471 "Signal the end from iterator.__anext__().");
472
473
474/*
Thomas Wouters477c8d52006-05-27 19:21:47 +0000475 * StopIteration extends Exception
476 */
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000477
478static PyMemberDef StopIteration_members[] = {
479 {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
480 PyDoc_STR("generator return value")},
481 {NULL} /* Sentinel */
482};
483
484static int
485StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
486{
487 Py_ssize_t size = PyTuple_GET_SIZE(args);
488 PyObject *value;
489
490 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
491 return -1;
492 Py_CLEAR(self->value);
493 if (size > 0)
494 value = PyTuple_GET_ITEM(args, 0);
495 else
496 value = Py_None;
497 Py_INCREF(value);
498 self->value = value;
499 return 0;
500}
501
502static int
503StopIteration_clear(PyStopIterationObject *self)
504{
505 Py_CLEAR(self->value);
506 return BaseException_clear((PyBaseExceptionObject *)self);
507}
508
509static void
510StopIteration_dealloc(PyStopIterationObject *self)
511{
512 _PyObject_GC_UNTRACK(self);
513 StopIteration_clear(self);
514 Py_TYPE(self)->tp_free((PyObject *)self);
515}
516
517static int
518StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
519{
520 Py_VISIT(self->value);
521 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
522}
523
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000524ComplexExtendsException(
525 PyExc_Exception, /* base */
526 StopIteration, /* name */
527 StopIteration, /* prefix for *_init, etc */
528 0, /* new */
529 0, /* methods */
530 StopIteration_members, /* members */
531 0, /* getset */
532 0, /* str */
533 "Signal the end from iterator.__next__()."
534);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000535
536
537/*
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000538 * GeneratorExit extends BaseException
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539 */
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000540SimpleExtendsException(PyExc_BaseException, GeneratorExit,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000541 "Request that a generator exit.");
542
543
544/*
545 * SystemExit extends BaseException
546 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547
548static int
549SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
550{
551 Py_ssize_t size = PyTuple_GET_SIZE(args);
552
553 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
554 return -1;
555
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000556 if (size == 0)
557 return 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200558 if (size == 1) {
559 Py_INCREF(PyTuple_GET_ITEM(args, 0));
Serhiy Storchaka48842712016-04-06 09:45:48 +0300560 Py_XSETREF(self->code, PyTuple_GET_ITEM(args, 0));
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200561 }
562 else { /* size > 1 */
563 Py_INCREF(args);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300564 Py_XSETREF(self->code, args);
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200565 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000566 return 0;
567}
568
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000569static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000570SystemExit_clear(PySystemExitObject *self)
571{
572 Py_CLEAR(self->code);
573 return BaseException_clear((PyBaseExceptionObject *)self);
574}
575
576static void
577SystemExit_dealloc(PySystemExitObject *self)
578{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000579 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000580 SystemExit_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000581 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000582}
583
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000584static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
586{
587 Py_VISIT(self->code);
588 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
589}
590
591static PyMemberDef SystemExit_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000592 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
593 PyDoc_STR("exception code")},
594 {NULL} /* Sentinel */
595};
596
597ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200598 0, 0, SystemExit_members, 0, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000599 "Request to exit from the interpreter.");
600
601/*
602 * KeyboardInterrupt extends BaseException
603 */
604SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
605 "Program interrupted by user.");
606
607
608/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000609 * ImportError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000610 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000611
Brett Cannon79ec55e2012-04-12 20:24:54 -0400612static int
613ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
614{
615 PyObject *msg = NULL;
616 PyObject *name = NULL;
617 PyObject *path = NULL;
618
619/* Macro replacement doesn't allow ## to start the first line of a macro,
620 so we move the assignment and NULL check into the if-statement. */
621#define GET_KWD(kwd) { \
622 kwd = PyDict_GetItemString(kwds, #kwd); \
623 if (kwd) { \
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200624 Py_INCREF(kwd); \
Serhiy Storchaka48842712016-04-06 09:45:48 +0300625 Py_XSETREF(self->kwd, kwd); \
Brett Cannon79ec55e2012-04-12 20:24:54 -0400626 if (PyDict_DelItemString(kwds, #kwd)) \
627 return -1; \
628 } \
629 }
630
631 if (kwds) {
632 GET_KWD(name);
633 GET_KWD(path);
634 }
635
636 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
637 return -1;
638 if (PyTuple_GET_SIZE(args) != 1)
639 return 0;
640 if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
641 return -1;
642
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +0200643 Py_INCREF(msg);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300644 Py_XSETREF(self->msg, msg);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400645
646 return 0;
647}
648
649static int
650ImportError_clear(PyImportErrorObject *self)
651{
652 Py_CLEAR(self->msg);
653 Py_CLEAR(self->name);
654 Py_CLEAR(self->path);
655 return BaseException_clear((PyBaseExceptionObject *)self);
656}
657
658static void
659ImportError_dealloc(PyImportErrorObject *self)
660{
661 _PyObject_GC_UNTRACK(self);
662 ImportError_clear(self);
663 Py_TYPE(self)->tp_free((PyObject *)self);
664}
665
666static int
667ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
668{
669 Py_VISIT(self->msg);
670 Py_VISIT(self->name);
671 Py_VISIT(self->path);
672 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
673}
674
675static PyObject *
676ImportError_str(PyImportErrorObject *self)
677{
Brett Cannon07c6e712012-08-24 13:05:09 -0400678 if (self->msg && PyUnicode_CheckExact(self->msg)) {
Brett Cannon79ec55e2012-04-12 20:24:54 -0400679 Py_INCREF(self->msg);
680 return self->msg;
681 }
682 else {
683 return BaseException_str((PyBaseExceptionObject *)self);
684 }
685}
686
687static PyMemberDef ImportError_members[] = {
688 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
689 PyDoc_STR("exception message")},
690 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
691 PyDoc_STR("module name")},
692 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
693 PyDoc_STR("module path")},
694 {NULL} /* Sentinel */
695};
696
697static PyMethodDef ImportError_methods[] = {
698 {NULL}
699};
700
701ComplexExtendsException(PyExc_Exception, ImportError,
702 ImportError, 0 /* new */,
703 ImportError_methods, ImportError_members,
704 0 /* getset */, ImportError_str,
705 "Import can't find module, or can't find name in "
706 "module.");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000707
708/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200709 * OSError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000710 */
711
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200712#ifdef MS_WINDOWS
713#include "errmap.h"
714#endif
715
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716/* Where a function has a single filename, such as open() or some
717 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
718 * called, giving a third argument which is the filename. But, so
719 * that old code using in-place unpacking doesn't break, e.g.:
720 *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200721 * except OSError, (errno, strerror):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722 *
723 * we hack args so that it only contains two items. This also
724 * means we need our own __str__() which prints out the filename
725 * when it was supplied.
Larry Hastingsb0827312014-02-09 22:05:19 -0800726 *
727 * (If a function has two filenames, such as rename(), symlink(),
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800728 * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
729 * which allows passing in a second filename.)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200731
Antoine Pitroue0e27352011-12-15 14:31:28 +0100732/* This function doesn't cleanup on error, the caller should */
733static int
734oserror_parse_args(PyObject **p_args,
735 PyObject **myerrno, PyObject **strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800736 PyObject **filename, PyObject **filename2
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200737#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100738 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200739#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100740 )
741{
742 Py_ssize_t nargs;
743 PyObject *args = *p_args;
Larry Hastingsb0827312014-02-09 22:05:19 -0800744#ifndef MS_WINDOWS
745 /*
746 * ignored on non-Windows platforms,
747 * but parsed so OSError has a consistent signature
748 */
749 PyObject *_winerror = NULL;
750 PyObject **winerror = &_winerror;
751#endif /* MS_WINDOWS */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000752
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200753 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000754
Larry Hastingsb0827312014-02-09 22:05:19 -0800755 if (nargs >= 2 && nargs <= 5) {
756 if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
757 myerrno, strerror,
758 filename, winerror, filename2))
Antoine Pitroue0e27352011-12-15 14:31:28 +0100759 return -1;
Larry Hastingsb0827312014-02-09 22:05:19 -0800760#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100761 if (*winerror && PyLong_Check(*winerror)) {
762 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200763 PyObject *newargs;
764 Py_ssize_t i;
765
Antoine Pitroue0e27352011-12-15 14:31:28 +0100766 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200767 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100768 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200769 /* Set errno to the corresponding POSIX errno (overriding
770 first argument). Windows Socket error codes (>= 10000)
771 have the same value as their POSIX counterparts.
772 */
773 if (winerrcode < 10000)
774 errcode = winerror_to_errno(winerrcode);
775 else
776 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100777 *myerrno = PyLong_FromLong(errcode);
778 if (!*myerrno)
779 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200780 newargs = PyTuple_New(nargs);
781 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100782 return -1;
783 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200784 for (i = 1; i < nargs; i++) {
785 PyObject *val = PyTuple_GET_ITEM(args, i);
786 Py_INCREF(val);
787 PyTuple_SET_ITEM(newargs, i, val);
788 }
789 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100790 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200791 }
Larry Hastingsb0827312014-02-09 22:05:19 -0800792#endif /* MS_WINDOWS */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200793 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000794
Antoine Pitroue0e27352011-12-15 14:31:28 +0100795 return 0;
796}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000797
Antoine Pitroue0e27352011-12-15 14:31:28 +0100798static int
799oserror_init(PyOSErrorObject *self, PyObject **p_args,
800 PyObject *myerrno, PyObject *strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800801 PyObject *filename, PyObject *filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100802#ifdef MS_WINDOWS
803 , PyObject *winerror
804#endif
805 )
806{
807 PyObject *args = *p_args;
808 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000809
810 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200811 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100812 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200813 PyNumber_Check(filename)) {
814 /* BlockingIOError's 3rd argument can be the number of
815 * characters written.
816 */
817 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
818 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100819 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200820 }
821 else {
822 Py_INCREF(filename);
823 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000824
Larry Hastingsb0827312014-02-09 22:05:19 -0800825 if (filename2 && filename2 != Py_None) {
826 Py_INCREF(filename2);
827 self->filename2 = filename2;
828 }
829
830 if (nargs >= 2 && nargs <= 5) {
831 /* filename, filename2, and winerror are removed from the args tuple
832 (for compatibility purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100833 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200834 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100835 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000836
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200837 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100838 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200839 }
840 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000841 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200842 Py_XINCREF(myerrno);
843 self->myerrno = myerrno;
844
845 Py_XINCREF(strerror);
846 self->strerror = strerror;
847
848#ifdef MS_WINDOWS
849 Py_XINCREF(winerror);
850 self->winerror = winerror;
851#endif
852
Antoine Pitroue0e27352011-12-15 14:31:28 +0100853 /* Steals the reference to args */
Serhiy Storchaka48842712016-04-06 09:45:48 +0300854 Py_XSETREF(self->args, args);
Victor Stinner46ef3192013-11-14 22:31:41 +0100855 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100856
857 return 0;
858}
859
860static PyObject *
861OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
862static int
863OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
864
865static int
866oserror_use_init(PyTypeObject *type)
867{
Martin Panter7462b6492015-11-02 03:37:02 +0000868 /* When __init__ is defined in an OSError subclass, we want any
Antoine Pitroue0e27352011-12-15 14:31:28 +0100869 extraneous argument to __new__ to be ignored. The only reasonable
870 solution, given __new__ takes a variable number of arguments,
871 is to defer arg parsing and initialization to __init__.
872
Martin Pantere26da7c2016-06-02 10:07:09 +0000873 But when __new__ is overridden as well, it should call our __new__
Antoine Pitroue0e27352011-12-15 14:31:28 +0100874 with the right arguments.
875
876 (see http://bugs.python.org/issue12555#msg148829 )
877 */
878 if (type->tp_init != (initproc) OSError_init &&
879 type->tp_new == (newfunc) OSError_new) {
880 assert((PyObject *) type != PyExc_OSError);
881 return 1;
882 }
883 return 0;
884}
885
886static PyObject *
887OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
888{
889 PyOSErrorObject *self = NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800890 PyObject *myerrno = NULL, *strerror = NULL;
891 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100892#ifdef MS_WINDOWS
893 PyObject *winerror = NULL;
894#endif
895
Victor Stinner46ef3192013-11-14 22:31:41 +0100896 Py_INCREF(args);
897
Antoine Pitroue0e27352011-12-15 14:31:28 +0100898 if (!oserror_use_init(type)) {
899 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100900 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100901
Larry Hastingsb0827312014-02-09 22:05:19 -0800902 if (oserror_parse_args(&args, &myerrno, &strerror,
903 &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100904#ifdef MS_WINDOWS
905 , &winerror
906#endif
907 ))
908 goto error;
909
910 if (myerrno && PyLong_Check(myerrno) &&
911 errnomap && (PyObject *) type == PyExc_OSError) {
912 PyObject *newtype;
913 newtype = PyDict_GetItem(errnomap, myerrno);
914 if (newtype) {
915 assert(PyType_Check(newtype));
916 type = (PyTypeObject *) newtype;
917 }
918 else if (PyErr_Occurred())
919 goto error;
920 }
921 }
922
923 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
924 if (!self)
925 goto error;
926
927 self->dict = NULL;
928 self->traceback = self->cause = self->context = NULL;
929 self->written = -1;
930
931 if (!oserror_use_init(type)) {
Larry Hastingsb0827312014-02-09 22:05:19 -0800932 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100933#ifdef MS_WINDOWS
934 , winerror
935#endif
936 ))
937 goto error;
938 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200939 else {
940 self->args = PyTuple_New(0);
941 if (self->args == NULL)
942 goto error;
943 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100944
Victor Stinner46ef3192013-11-14 22:31:41 +0100945 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200946 return (PyObject *) self;
947
948error:
949 Py_XDECREF(args);
950 Py_XDECREF(self);
951 return NULL;
952}
953
954static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100955OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200956{
Larry Hastingsb0827312014-02-09 22:05:19 -0800957 PyObject *myerrno = NULL, *strerror = NULL;
958 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100959#ifdef MS_WINDOWS
960 PyObject *winerror = NULL;
961#endif
962
963 if (!oserror_use_init(Py_TYPE(self)))
964 /* Everything already done in OSError_new */
965 return 0;
966
967 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
968 return -1;
969
970 Py_INCREF(args);
Larry Hastingsb0827312014-02-09 22:05:19 -0800971 if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100972#ifdef MS_WINDOWS
973 , &winerror
974#endif
975 ))
976 goto error;
977
Larry Hastingsb0827312014-02-09 22:05:19 -0800978 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100979#ifdef MS_WINDOWS
980 , winerror
981#endif
982 ))
983 goto error;
984
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100986
987error:
Serhiy Storchaka37665722016-08-20 21:22:03 +0300988 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100989 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000990}
991
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000992static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200993OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000994{
995 Py_CLEAR(self->myerrno);
996 Py_CLEAR(self->strerror);
997 Py_CLEAR(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -0800998 Py_CLEAR(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200999#ifdef MS_WINDOWS
1000 Py_CLEAR(self->winerror);
1001#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002 return BaseException_clear((PyBaseExceptionObject *)self);
1003}
1004
1005static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001006OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001007{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001008 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001009 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001010 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001011}
1012
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001013static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001014OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001015 void *arg)
1016{
1017 Py_VISIT(self->myerrno);
1018 Py_VISIT(self->strerror);
1019 Py_VISIT(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001020 Py_VISIT(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001021#ifdef MS_WINDOWS
1022 Py_VISIT(self->winerror);
1023#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001024 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1025}
1026
1027static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001028OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001029{
Larry Hastingsb0827312014-02-09 22:05:19 -08001030#define OR_NONE(x) ((x)?(x):Py_None)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001031#ifdef MS_WINDOWS
1032 /* If available, winerror has the priority over myerrno */
Larry Hastingsb0827312014-02-09 22:05:19 -08001033 if (self->winerror && self->filename) {
1034 if (self->filename2) {
1035 return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
1036 OR_NONE(self->winerror),
1037 OR_NONE(self->strerror),
1038 self->filename,
1039 self->filename2);
1040 } else {
1041 return PyUnicode_FromFormat("[WinError %S] %S: %R",
1042 OR_NONE(self->winerror),
1043 OR_NONE(self->strerror),
1044 self->filename);
1045 }
1046 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001047 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001048 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001049 self->winerror ? self->winerror: Py_None,
1050 self->strerror ? self->strerror: Py_None);
1051#endif
Larry Hastingsb0827312014-02-09 22:05:19 -08001052 if (self->filename) {
1053 if (self->filename2) {
1054 return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
1055 OR_NONE(self->myerrno),
1056 OR_NONE(self->strerror),
1057 self->filename,
1058 self->filename2);
1059 } else {
1060 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1061 OR_NONE(self->myerrno),
1062 OR_NONE(self->strerror),
1063 self->filename);
1064 }
1065 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001066 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001067 return PyUnicode_FromFormat("[Errno %S] %S",
Serhiy Storchaka37665722016-08-20 21:22:03 +03001068 self->myerrno, self->strerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001069 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001070}
1071
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001073OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001074{
1075 PyObject *args = self->args;
1076 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001077
Thomas Wouters477c8d52006-05-27 19:21:47 +00001078 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001079 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001080 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Larry Hastingsb0827312014-02-09 22:05:19 -08001081 Py_ssize_t size = self->filename2 ? 5 : 3;
1082 args = PyTuple_New(size);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001083 if (!args)
1084 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001085
1086 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001087 Py_INCREF(tmp);
1088 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001089
1090 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091 Py_INCREF(tmp);
1092 PyTuple_SET_ITEM(args, 1, tmp);
1093
1094 Py_INCREF(self->filename);
1095 PyTuple_SET_ITEM(args, 2, self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001096
1097 if (self->filename2) {
1098 /*
1099 * This tuple is essentially used as OSError(*args).
1100 * So, to recreate filename2, we need to pass in
1101 * winerror as well.
1102 */
1103 Py_INCREF(Py_None);
1104 PyTuple_SET_ITEM(args, 3, Py_None);
1105
1106 /* filename2 */
1107 Py_INCREF(self->filename2);
1108 PyTuple_SET_ITEM(args, 4, self->filename2);
1109 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001110 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001111 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001112
1113 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001114 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001115 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001116 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001117 Py_DECREF(args);
1118 return res;
1119}
1120
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001121static PyObject *
1122OSError_written_get(PyOSErrorObject *self, void *context)
1123{
1124 if (self->written == -1) {
1125 PyErr_SetString(PyExc_AttributeError, "characters_written");
1126 return NULL;
1127 }
1128 return PyLong_FromSsize_t(self->written);
1129}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001130
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001131static int
1132OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1133{
1134 Py_ssize_t n;
1135 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1136 if (n == -1 && PyErr_Occurred())
1137 return -1;
1138 self->written = n;
1139 return 0;
1140}
1141
1142static PyMemberDef OSError_members[] = {
1143 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1144 PyDoc_STR("POSIX exception code")},
1145 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1146 PyDoc_STR("exception strerror")},
1147 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1148 PyDoc_STR("exception filename")},
Larry Hastingsb0827312014-02-09 22:05:19 -08001149 {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
1150 PyDoc_STR("second exception filename")},
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001151#ifdef MS_WINDOWS
1152 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1153 PyDoc_STR("Win32 exception code")},
1154#endif
1155 {NULL} /* Sentinel */
1156};
1157
1158static PyMethodDef OSError_methods[] = {
1159 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001160 {NULL}
1161};
1162
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001163static PyGetSetDef OSError_getset[] = {
1164 {"characters_written", (getter) OSError_written_get,
1165 (setter) OSError_written_set, NULL},
1166 {NULL}
1167};
1168
1169
1170ComplexExtendsException(PyExc_Exception, OSError,
1171 OSError, OSError_new,
1172 OSError_methods, OSError_members, OSError_getset,
1173 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001174 "Base class for I/O related errors.");
1175
1176
1177/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001178 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001179 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001180MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1181 "I/O operation would block.");
1182MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1183 "Connection error.");
1184MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1185 "Child process error.");
1186MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1187 "Broken pipe.");
1188MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1189 "Connection aborted.");
1190MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1191 "Connection refused.");
1192MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1193 "Connection reset.");
1194MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1195 "File already exists.");
1196MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1197 "File not found.");
1198MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1199 "Operation doesn't work on directories.");
1200MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1201 "Operation only works on directories.");
1202MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1203 "Interrupted by signal.");
1204MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1205 "Not enough permissions.");
1206MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1207 "Process not found.");
1208MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1209 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001210
1211/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001212 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001213 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001214SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001215 "Read beyond end of file.");
1216
1217
1218/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001219 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001221SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001222 "Unspecified run-time error.");
1223
Yury Selivanovf488fb42015-07-03 01:04:23 -04001224/*
1225 * RecursionError extends RuntimeError
1226 */
1227SimpleExtendsException(PyExc_RuntimeError, RecursionError,
1228 "Recursion limit exceeded.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001229
1230/*
1231 * NotImplementedError extends RuntimeError
1232 */
1233SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1234 "Method or function hasn't been implemented yet.");
1235
1236/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001237 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001238 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001239SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240 "Name not found globally.");
1241
1242/*
1243 * UnboundLocalError extends NameError
1244 */
1245SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1246 "Local name referenced but not bound to a value.");
1247
1248/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001249 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001250 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001251SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001252 "Attribute not found.");
1253
1254
1255/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001256 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001258
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001259/* Helper function to customise error message for some syntax errors */
1260static int _report_missing_parentheses(PySyntaxErrorObject *self);
1261
Thomas Wouters477c8d52006-05-27 19:21:47 +00001262static int
1263SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1264{
1265 PyObject *info = NULL;
1266 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1267
1268 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1269 return -1;
1270
1271 if (lenargs >= 1) {
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001272 Py_INCREF(PyTuple_GET_ITEM(args, 0));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001273 Py_XSETREF(self->msg, PyTuple_GET_ITEM(args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001274 }
1275 if (lenargs == 2) {
1276 info = PyTuple_GET_ITEM(args, 1);
1277 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001278 if (!info)
1279 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001280
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001281 if (PyTuple_GET_SIZE(info) != 4) {
1282 /* not a very good error message, but it's what Python 2.4 gives */
1283 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1284 Py_DECREF(info);
1285 return -1;
1286 }
1287
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001288 Py_INCREF(PyTuple_GET_ITEM(info, 0));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001289 Py_XSETREF(self->filename, PyTuple_GET_ITEM(info, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001290
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001291 Py_INCREF(PyTuple_GET_ITEM(info, 1));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001292 Py_XSETREF(self->lineno, PyTuple_GET_ITEM(info, 1));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001293
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001294 Py_INCREF(PyTuple_GET_ITEM(info, 2));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001295 Py_XSETREF(self->offset, PyTuple_GET_ITEM(info, 2));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001296
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001297 Py_INCREF(PyTuple_GET_ITEM(info, 3));
Serhiy Storchaka48842712016-04-06 09:45:48 +03001298 Py_XSETREF(self->text, PyTuple_GET_ITEM(info, 3));
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001299
1300 Py_DECREF(info);
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001301
1302 /* Issue #21669: Custom error for 'print' & 'exec' as statements */
1303 if (self->text && PyUnicode_Check(self->text)) {
1304 if (_report_missing_parentheses(self) < 0) {
1305 return -1;
1306 }
1307 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001308 }
1309 return 0;
1310}
1311
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001312static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001313SyntaxError_clear(PySyntaxErrorObject *self)
1314{
1315 Py_CLEAR(self->msg);
1316 Py_CLEAR(self->filename);
1317 Py_CLEAR(self->lineno);
1318 Py_CLEAR(self->offset);
1319 Py_CLEAR(self->text);
1320 Py_CLEAR(self->print_file_and_line);
1321 return BaseException_clear((PyBaseExceptionObject *)self);
1322}
1323
1324static void
1325SyntaxError_dealloc(PySyntaxErrorObject *self)
1326{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001327 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001328 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001329 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001330}
1331
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001332static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001333SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1334{
1335 Py_VISIT(self->msg);
1336 Py_VISIT(self->filename);
1337 Py_VISIT(self->lineno);
1338 Py_VISIT(self->offset);
1339 Py_VISIT(self->text);
1340 Py_VISIT(self->print_file_and_line);
1341 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1342}
1343
1344/* This is called "my_basename" instead of just "basename" to avoid name
1345 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1346 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001347static PyObject*
1348my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001349{
Victor Stinner6237daf2010-04-28 17:26:19 +00001350 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001351 int kind;
1352 void *data;
1353
1354 if (PyUnicode_READY(name))
1355 return NULL;
1356 kind = PyUnicode_KIND(name);
1357 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001358 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001359 offset = 0;
1360 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001361 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001362 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 if (offset != 0)
1365 return PyUnicode_Substring(name, offset, size);
1366 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001367 Py_INCREF(name);
1368 return name;
1369 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001370}
1371
1372
1373static PyObject *
1374SyntaxError_str(PySyntaxErrorObject *self)
1375{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001376 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001377 PyObject *filename;
1378 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001379 /* Below, we always ignore overflow errors, just printing -1.
1380 Still, we cannot allow an OverflowError to be raised, so
1381 we need to call PyLong_AsLongAndOverflow. */
1382 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001383
1384 /* XXX -- do all the additional formatting with filename and
1385 lineno here */
1386
Neal Norwitzed2b7392007-08-26 04:51:10 +00001387 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001388 filename = my_basename(self->filename);
1389 if (filename == NULL)
1390 return NULL;
1391 } else {
1392 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001393 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001394 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001396 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001397 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001398
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001399 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001400 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001401 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001402 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001404 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001405 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001406 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001407 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001408 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001409 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001410 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001411 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001412 Py_XDECREF(filename);
1413 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001414}
1415
1416static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001417 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1418 PyDoc_STR("exception msg")},
1419 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1420 PyDoc_STR("exception filename")},
1421 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1422 PyDoc_STR("exception lineno")},
1423 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1424 PyDoc_STR("exception offset")},
1425 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1426 PyDoc_STR("exception text")},
1427 {"print_file_and_line", T_OBJECT,
1428 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1429 PyDoc_STR("exception print_file_and_line")},
1430 {NULL} /* Sentinel */
1431};
1432
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001433ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001434 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001435 SyntaxError_str, "Invalid syntax.");
1436
1437
1438/*
1439 * IndentationError extends SyntaxError
1440 */
1441MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1442 "Improper indentation.");
1443
1444
1445/*
1446 * TabError extends IndentationError
1447 */
1448MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1449 "Improper mixture of spaces and tabs.");
1450
1451
1452/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001453 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001454 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001455SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001456 "Base class for lookup errors.");
1457
1458
1459/*
1460 * IndexError extends LookupError
1461 */
1462SimpleExtendsException(PyExc_LookupError, IndexError,
1463 "Sequence index out of range.");
1464
1465
1466/*
1467 * KeyError extends LookupError
1468 */
1469static PyObject *
1470KeyError_str(PyBaseExceptionObject *self)
1471{
1472 /* If args is a tuple of exactly one item, apply repr to args[0].
1473 This is done so that e.g. the exception raised by {}[''] prints
1474 KeyError: ''
1475 rather than the confusing
1476 KeyError
1477 alone. The downside is that if KeyError is raised with an explanatory
1478 string, that string will be displayed in quotes. Too bad.
1479 If args is anything else, use the default BaseException__str__().
1480 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001481 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001482 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001483 }
1484 return BaseException_str(self);
1485}
1486
1487ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001488 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489
1490
1491/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001492 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001493 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001494SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001495 "Inappropriate argument value (of correct type).");
1496
1497/*
1498 * UnicodeError extends ValueError
1499 */
1500
1501SimpleExtendsException(PyExc_ValueError, UnicodeError,
1502 "Unicode related error.");
1503
Thomas Wouters477c8d52006-05-27 19:21:47 +00001504static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001505get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001506{
1507 if (!attr) {
1508 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1509 return NULL;
1510 }
1511
Christian Heimes72b710a2008-05-26 13:28:38 +00001512 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001513 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1514 return NULL;
1515 }
1516 Py_INCREF(attr);
1517 return attr;
1518}
1519
1520static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001521get_unicode(PyObject *attr, const char *name)
1522{
1523 if (!attr) {
1524 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1525 return NULL;
1526 }
1527
1528 if (!PyUnicode_Check(attr)) {
1529 PyErr_Format(PyExc_TypeError,
1530 "%.200s attribute must be unicode", name);
1531 return NULL;
1532 }
1533 Py_INCREF(attr);
1534 return attr;
1535}
1536
Walter Dörwaldd2034312007-05-18 16:29:38 +00001537static int
1538set_unicodefromstring(PyObject **attr, const char *value)
1539{
1540 PyObject *obj = PyUnicode_FromString(value);
1541 if (!obj)
1542 return -1;
Serhiy Storchaka48842712016-04-06 09:45:48 +03001543 Py_XSETREF(*attr, obj);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001544 return 0;
1545}
1546
Thomas Wouters477c8d52006-05-27 19:21:47 +00001547PyObject *
1548PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1549{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001550 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001551}
1552
1553PyObject *
1554PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1555{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001556 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001557}
1558
1559PyObject *
1560PyUnicodeEncodeError_GetObject(PyObject *exc)
1561{
1562 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1563}
1564
1565PyObject *
1566PyUnicodeDecodeError_GetObject(PyObject *exc)
1567{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001568 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001569}
1570
1571PyObject *
1572PyUnicodeTranslateError_GetObject(PyObject *exc)
1573{
1574 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1575}
1576
1577int
1578PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1579{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001580 Py_ssize_t size;
1581 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1582 "object");
1583 if (!obj)
1584 return -1;
1585 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001586 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001587 if (*start<0)
1588 *start = 0; /*XXX check for values <0*/
1589 if (*start>=size)
1590 *start = size-1;
1591 Py_DECREF(obj);
1592 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001593}
1594
1595
1596int
1597PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1598{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001599 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001600 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001601 if (!obj)
1602 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001603 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001604 *start = ((PyUnicodeErrorObject *)exc)->start;
1605 if (*start<0)
1606 *start = 0;
1607 if (*start>=size)
1608 *start = size-1;
1609 Py_DECREF(obj);
1610 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001611}
1612
1613
1614int
1615PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1616{
1617 return PyUnicodeEncodeError_GetStart(exc, start);
1618}
1619
1620
1621int
1622PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1623{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001624 ((PyUnicodeErrorObject *)exc)->start = start;
1625 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001626}
1627
1628
1629int
1630PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1631{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001632 ((PyUnicodeErrorObject *)exc)->start = start;
1633 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001634}
1635
1636
1637int
1638PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1639{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001640 ((PyUnicodeErrorObject *)exc)->start = start;
1641 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001642}
1643
1644
1645int
1646PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1647{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001648 Py_ssize_t size;
1649 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1650 "object");
1651 if (!obj)
1652 return -1;
1653 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001654 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001655 if (*end<1)
1656 *end = 1;
1657 if (*end>size)
1658 *end = size;
1659 Py_DECREF(obj);
1660 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001661}
1662
1663
1664int
1665PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1666{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001667 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001668 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001669 if (!obj)
1670 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001671 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001672 *end = ((PyUnicodeErrorObject *)exc)->end;
1673 if (*end<1)
1674 *end = 1;
1675 if (*end>size)
1676 *end = size;
1677 Py_DECREF(obj);
1678 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001679}
1680
1681
1682int
1683PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1684{
1685 return PyUnicodeEncodeError_GetEnd(exc, start);
1686}
1687
1688
1689int
1690PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1691{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001692 ((PyUnicodeErrorObject *)exc)->end = end;
1693 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001694}
1695
1696
1697int
1698PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1699{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001700 ((PyUnicodeErrorObject *)exc)->end = end;
1701 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001702}
1703
1704
1705int
1706PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1707{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001708 ((PyUnicodeErrorObject *)exc)->end = end;
1709 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001710}
1711
1712PyObject *
1713PyUnicodeEncodeError_GetReason(PyObject *exc)
1714{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001715 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716}
1717
1718
1719PyObject *
1720PyUnicodeDecodeError_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 *
1727PyUnicodeTranslateError_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
1733int
1734PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1735{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001736 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1737 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001738}
1739
1740
1741int
1742PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1743{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001744 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1745 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001746}
1747
1748
1749int
1750PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1751{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001752 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1753 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001754}
1755
1756
Thomas Wouters477c8d52006-05-27 19:21:47 +00001757static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001758UnicodeError_clear(PyUnicodeErrorObject *self)
1759{
1760 Py_CLEAR(self->encoding);
1761 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001762 Py_CLEAR(self->reason);
1763 return BaseException_clear((PyBaseExceptionObject *)self);
1764}
1765
1766static void
1767UnicodeError_dealloc(PyUnicodeErrorObject *self)
1768{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001769 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001770 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001771 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001772}
1773
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001774static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001775UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1776{
1777 Py_VISIT(self->encoding);
1778 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001779 Py_VISIT(self->reason);
1780 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1781}
1782
1783static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001784 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1785 PyDoc_STR("exception encoding")},
1786 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1787 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001788 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001789 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001790 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001791 PyDoc_STR("exception end")},
1792 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1793 PyDoc_STR("exception reason")},
1794 {NULL} /* Sentinel */
1795};
1796
1797
1798/*
1799 * UnicodeEncodeError extends UnicodeError
1800 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001801
1802static int
1803UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1804{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001805 PyUnicodeErrorObject *err;
1806
Thomas Wouters477c8d52006-05-27 19:21:47 +00001807 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1808 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001809
1810 err = (PyUnicodeErrorObject *)self;
1811
1812 Py_CLEAR(err->encoding);
1813 Py_CLEAR(err->object);
1814 Py_CLEAR(err->reason);
1815
1816 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1817 &PyUnicode_Type, &err->encoding,
1818 &PyUnicode_Type, &err->object,
1819 &err->start,
1820 &err->end,
1821 &PyUnicode_Type, &err->reason)) {
1822 err->encoding = err->object = err->reason = NULL;
1823 return -1;
1824 }
1825
Martin v. Löwisb09af032011-11-04 11:16:41 +01001826 if (PyUnicode_READY(err->object) < -1) {
1827 err->encoding = NULL;
1828 return -1;
1829 }
1830
Guido van Rossum98297ee2007-11-06 21:34:58 +00001831 Py_INCREF(err->encoding);
1832 Py_INCREF(err->object);
1833 Py_INCREF(err->reason);
1834
1835 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001836}
1837
1838static PyObject *
1839UnicodeEncodeError_str(PyObject *self)
1840{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001841 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001842 PyObject *result = NULL;
1843 PyObject *reason_str = NULL;
1844 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001845
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001846 if (!uself->object)
1847 /* Not properly initialized. */
1848 return PyUnicode_FromString("");
1849
Eric Smith0facd772010-02-24 15:42:29 +00001850 /* Get reason and encoding as strings, which they might not be if
Martin Pantereb995702016-07-28 01:11:04 +00001851 they've been modified after we were constructed. */
Eric Smith0facd772010-02-24 15:42:29 +00001852 reason_str = PyObject_Str(uself->reason);
1853 if (reason_str == NULL)
1854 goto done;
1855 encoding_str = PyObject_Str(uself->encoding);
1856 if (encoding_str == NULL)
1857 goto done;
1858
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001859 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1860 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001861 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001862 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001863 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001864 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001865 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001866 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001867 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001868 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001869 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001870 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001871 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001872 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001873 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001874 }
Eric Smith0facd772010-02-24 15:42:29 +00001875 else {
1876 result = PyUnicode_FromFormat(
1877 "'%U' codec can't encode characters in position %zd-%zd: %U",
1878 encoding_str,
1879 uself->start,
1880 uself->end-1,
1881 reason_str);
1882 }
1883done:
1884 Py_XDECREF(reason_str);
1885 Py_XDECREF(encoding_str);
1886 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001887}
1888
1889static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001890 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001891 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001892 sizeof(PyUnicodeErrorObject), 0,
1893 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1894 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1895 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001896 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1897 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001898 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001899 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001900};
1901PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1902
1903PyObject *
1904PyUnicodeEncodeError_Create(
1905 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1906 Py_ssize_t start, Py_ssize_t end, const char *reason)
1907{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001908 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001909 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001910}
1911
1912
1913/*
1914 * UnicodeDecodeError extends UnicodeError
1915 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916
1917static int
1918UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1919{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001920 PyUnicodeErrorObject *ude;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001921
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1923 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001924
1925 ude = (PyUnicodeErrorObject *)self;
1926
1927 Py_CLEAR(ude->encoding);
1928 Py_CLEAR(ude->object);
1929 Py_CLEAR(ude->reason);
1930
1931 if (!PyArg_ParseTuple(args, "O!OnnO!",
1932 &PyUnicode_Type, &ude->encoding,
1933 &ude->object,
1934 &ude->start,
1935 &ude->end,
1936 &PyUnicode_Type, &ude->reason)) {
1937 ude->encoding = ude->object = ude->reason = NULL;
1938 return -1;
1939 }
1940
Guido van Rossum98297ee2007-11-06 21:34:58 +00001941 Py_INCREF(ude->encoding);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001942 Py_INCREF(ude->object);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001943 Py_INCREF(ude->reason);
1944
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001945 if (!PyBytes_Check(ude->object)) {
1946 Py_buffer view;
1947 if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
1948 goto error;
Serhiy Storchaka48842712016-04-06 09:45:48 +03001949 Py_XSETREF(ude->object, PyBytes_FromStringAndSize(view.buf, view.len));
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001950 PyBuffer_Release(&view);
1951 if (!ude->object)
1952 goto error;
1953 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001954 return 0;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001955
1956error:
1957 Py_CLEAR(ude->encoding);
1958 Py_CLEAR(ude->object);
1959 Py_CLEAR(ude->reason);
1960 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001961}
1962
1963static PyObject *
1964UnicodeDecodeError_str(PyObject *self)
1965{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001966 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001967 PyObject *result = NULL;
1968 PyObject *reason_str = NULL;
1969 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001970
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001971 if (!uself->object)
1972 /* Not properly initialized. */
1973 return PyUnicode_FromString("");
1974
Eric Smith0facd772010-02-24 15:42:29 +00001975 /* Get reason and encoding as strings, which they might not be if
Martin Pantereb995702016-07-28 01:11:04 +00001976 they've been modified after we were constructed. */
Eric Smith0facd772010-02-24 15:42:29 +00001977 reason_str = PyObject_Str(uself->reason);
1978 if (reason_str == NULL)
1979 goto done;
1980 encoding_str = PyObject_Str(uself->encoding);
1981 if (encoding_str == NULL)
1982 goto done;
1983
1984 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001985 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00001986 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001987 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00001988 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001989 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001990 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001991 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001992 }
Eric Smith0facd772010-02-24 15:42:29 +00001993 else {
1994 result = PyUnicode_FromFormat(
1995 "'%U' codec can't decode bytes in position %zd-%zd: %U",
1996 encoding_str,
1997 uself->start,
1998 uself->end-1,
1999 reason_str
2000 );
2001 }
2002done:
2003 Py_XDECREF(reason_str);
2004 Py_XDECREF(encoding_str);
2005 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002006}
2007
2008static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002009 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002010 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002011 sizeof(PyUnicodeErrorObject), 0,
2012 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2013 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
2014 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002015 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
2016 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002017 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002018 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002019};
2020PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
2021
2022PyObject *
2023PyUnicodeDecodeError_Create(
2024 const char *encoding, const char *object, Py_ssize_t length,
2025 Py_ssize_t start, Py_ssize_t end, const char *reason)
2026{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00002027 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002028 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002029}
2030
2031
2032/*
2033 * UnicodeTranslateError extends UnicodeError
2034 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002035
2036static int
2037UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
2038 PyObject *kwds)
2039{
2040 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2041 return -1;
2042
2043 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002044 Py_CLEAR(self->reason);
2045
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002046 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002047 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002048 &self->start,
2049 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00002050 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002051 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002052 return -1;
2053 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002054
Thomas Wouters477c8d52006-05-27 19:21:47 +00002055 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002056 Py_INCREF(self->reason);
2057
2058 return 0;
2059}
2060
2061
2062static PyObject *
2063UnicodeTranslateError_str(PyObject *self)
2064{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002065 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00002066 PyObject *result = NULL;
2067 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002068
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04002069 if (!uself->object)
2070 /* Not properly initialized. */
2071 return PyUnicode_FromString("");
2072
Eric Smith0facd772010-02-24 15:42:29 +00002073 /* Get reason as a string, which it might not be if it's been
Martin Pantereb995702016-07-28 01:11:04 +00002074 modified after we were constructed. */
Eric Smith0facd772010-02-24 15:42:29 +00002075 reason_str = PyObject_Str(uself->reason);
2076 if (reason_str == NULL)
2077 goto done;
2078
Victor Stinner53b33e72011-11-21 01:17:27 +01002079 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2080 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002081 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002082 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002083 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002084 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002085 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002086 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002087 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002088 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002089 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002090 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002091 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002092 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002093 );
Eric Smith0facd772010-02-24 15:42:29 +00002094 } else {
2095 result = PyUnicode_FromFormat(
2096 "can't translate characters in position %zd-%zd: %U",
2097 uself->start,
2098 uself->end-1,
2099 reason_str
2100 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002101 }
Eric Smith0facd772010-02-24 15:42:29 +00002102done:
2103 Py_XDECREF(reason_str);
2104 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002105}
2106
2107static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002108 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002109 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002110 sizeof(PyUnicodeErrorObject), 0,
2111 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2112 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2113 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002114 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002115 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2116 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002117 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002118};
2119PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2120
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002121/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002122PyObject *
2123PyUnicodeTranslateError_Create(
2124 const Py_UNICODE *object, Py_ssize_t length,
2125 Py_ssize_t start, Py_ssize_t end, const char *reason)
2126{
2127 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002128 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002129}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131PyObject *
2132_PyUnicodeTranslateError_Create(
2133 PyObject *object,
2134 Py_ssize_t start, Py_ssize_t end, const char *reason)
2135{
Victor Stinner69598d42014-04-04 20:59:44 +02002136 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002137 object, start, end, reason);
2138}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002139
2140/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002141 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002142 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002143SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002144 "Assertion failed.");
2145
2146
2147/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002148 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002149 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002150SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002151 "Base class for arithmetic errors.");
2152
2153
2154/*
2155 * FloatingPointError extends ArithmeticError
2156 */
2157SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2158 "Floating point operation failed.");
2159
2160
2161/*
2162 * OverflowError extends ArithmeticError
2163 */
2164SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2165 "Result too large to be represented.");
2166
2167
2168/*
2169 * ZeroDivisionError extends ArithmeticError
2170 */
2171SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2172 "Second argument to a division or modulo operation was zero.");
2173
2174
2175/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002176 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002177 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002178SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002179 "Internal error in the Python interpreter.\n"
2180 "\n"
2181 "Please report this to the Python maintainer, along with the traceback,\n"
2182 "the Python version, and the hardware/OS platform and version.");
2183
2184
2185/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002186 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002187 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002188SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002189 "Weak ref proxy used after referent went away.");
2190
2191
2192/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002193 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002194 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002195
2196#define MEMERRORS_SAVE 16
2197static PyBaseExceptionObject *memerrors_freelist = NULL;
2198static int memerrors_numfree = 0;
2199
2200static PyObject *
2201MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2202{
2203 PyBaseExceptionObject *self;
2204
2205 if (type != (PyTypeObject *) PyExc_MemoryError)
2206 return BaseException_new(type, args, kwds);
2207 if (memerrors_freelist == NULL)
2208 return BaseException_new(type, args, kwds);
2209 /* Fetch object from freelist and revive it */
2210 self = memerrors_freelist;
2211 self->args = PyTuple_New(0);
2212 /* This shouldn't happen since the empty tuple is persistent */
2213 if (self->args == NULL)
2214 return NULL;
2215 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2216 memerrors_numfree--;
2217 self->dict = NULL;
2218 _Py_NewReference((PyObject *)self);
2219 _PyObject_GC_TRACK(self);
2220 return (PyObject *)self;
2221}
2222
2223static void
2224MemoryError_dealloc(PyBaseExceptionObject *self)
2225{
2226 _PyObject_GC_UNTRACK(self);
2227 BaseException_clear(self);
2228 if (memerrors_numfree >= MEMERRORS_SAVE)
2229 Py_TYPE(self)->tp_free((PyObject *)self);
2230 else {
2231 self->dict = (PyObject *) memerrors_freelist;
2232 memerrors_freelist = self;
2233 memerrors_numfree++;
2234 }
2235}
2236
2237static void
2238preallocate_memerrors(void)
2239{
2240 /* We create enough MemoryErrors and then decref them, which will fill
2241 up the freelist. */
2242 int i;
2243 PyObject *errors[MEMERRORS_SAVE];
2244 for (i = 0; i < MEMERRORS_SAVE; i++) {
2245 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2246 NULL, NULL);
2247 if (!errors[i])
2248 Py_FatalError("Could not preallocate MemoryError object");
2249 }
2250 for (i = 0; i < MEMERRORS_SAVE; i++) {
2251 Py_DECREF(errors[i]);
2252 }
2253}
2254
2255static void
2256free_preallocated_memerrors(void)
2257{
2258 while (memerrors_freelist != NULL) {
2259 PyObject *self = (PyObject *) memerrors_freelist;
2260 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2261 Py_TYPE(self)->tp_free((PyObject *)self);
2262 }
2263}
2264
2265
2266static PyTypeObject _PyExc_MemoryError = {
2267 PyVarObject_HEAD_INIT(NULL, 0)
2268 "MemoryError",
2269 sizeof(PyBaseExceptionObject),
2270 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2271 0, 0, 0, 0, 0, 0, 0,
2272 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2273 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2274 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2275 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2276 (initproc)BaseException_init, 0, MemoryError_new
2277};
2278PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2279
Thomas Wouters477c8d52006-05-27 19:21:47 +00002280
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002281/*
2282 * BufferError extends Exception
2283 */
2284SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2285
Thomas Wouters477c8d52006-05-27 19:21:47 +00002286
2287/* Warning category docstrings */
2288
2289/*
2290 * Warning extends Exception
2291 */
2292SimpleExtendsException(PyExc_Exception, Warning,
2293 "Base class for warning categories.");
2294
2295
2296/*
2297 * UserWarning extends Warning
2298 */
2299SimpleExtendsException(PyExc_Warning, UserWarning,
2300 "Base class for warnings generated by user code.");
2301
2302
2303/*
2304 * DeprecationWarning extends Warning
2305 */
2306SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2307 "Base class for warnings about deprecated features.");
2308
2309
2310/*
2311 * PendingDeprecationWarning extends Warning
2312 */
2313SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2314 "Base class for warnings about features which will be deprecated\n"
2315 "in the future.");
2316
2317
2318/*
2319 * SyntaxWarning extends Warning
2320 */
2321SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2322 "Base class for warnings about dubious syntax.");
2323
2324
2325/*
2326 * RuntimeWarning extends Warning
2327 */
2328SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2329 "Base class for warnings about dubious runtime behavior.");
2330
2331
2332/*
2333 * FutureWarning extends Warning
2334 */
2335SimpleExtendsException(PyExc_Warning, FutureWarning,
2336 "Base class for warnings about constructs that will change semantically\n"
2337 "in the future.");
2338
2339
2340/*
2341 * ImportWarning extends Warning
2342 */
2343SimpleExtendsException(PyExc_Warning, ImportWarning,
2344 "Base class for warnings about probable mistakes in module imports");
2345
2346
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002347/*
2348 * UnicodeWarning extends Warning
2349 */
2350SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2351 "Base class for warnings about Unicode related problems, mostly\n"
2352 "related to conversion problems.");
2353
Georg Brandl08be72d2010-10-24 15:11:22 +00002354
Guido van Rossum98297ee2007-11-06 21:34:58 +00002355/*
2356 * BytesWarning extends Warning
2357 */
2358SimpleExtendsException(PyExc_Warning, BytesWarning,
2359 "Base class for warnings about bytes and buffer related problems, mostly\n"
2360 "related to conversion from str or comparing to str.");
2361
2362
Georg Brandl08be72d2010-10-24 15:11:22 +00002363/*
2364 * ResourceWarning extends Warning
2365 */
2366SimpleExtendsException(PyExc_Warning, ResourceWarning,
2367 "Base class for warnings about resource usage.");
2368
2369
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002370
Yury Selivanovf488fb42015-07-03 01:04:23 -04002371/* Pre-computed RecursionError instance for when recursion depth is reached.
Thomas Wouters89d996e2007-09-08 17:39:28 +00002372 Meant to be used when normalizing the exception for exceeding the recursion
2373 depth will cause its own infinite recursion.
2374*/
2375PyObject *PyExc_RecursionErrorInst = NULL;
2376
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002377#define PRE_INIT(TYPE) \
2378 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2379 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2380 Py_FatalError("exceptions bootstrapping error."); \
2381 Py_INCREF(PyExc_ ## TYPE); \
2382 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002383
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002384#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002385 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2386 Py_FatalError("Module dictionary insertion problem.");
2387
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002388#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002389 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002390 PyExc_ ## NAME = PyExc_ ## TYPE; \
2391 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2392 Py_FatalError("Module dictionary insertion problem.");
2393
2394#define ADD_ERRNO(TYPE, CODE) { \
2395 PyObject *_code = PyLong_FromLong(CODE); \
2396 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2397 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2398 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002399 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002400 }
2401
2402#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002403#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002404/* The following constants were added to errno.h in VS2010 but have
2405 preferred WSA equivalents. */
2406#undef EADDRINUSE
2407#undef EADDRNOTAVAIL
2408#undef EAFNOSUPPORT
2409#undef EALREADY
2410#undef ECONNABORTED
2411#undef ECONNREFUSED
2412#undef ECONNRESET
2413#undef EDESTADDRREQ
2414#undef EHOSTUNREACH
2415#undef EINPROGRESS
2416#undef EISCONN
2417#undef ELOOP
2418#undef EMSGSIZE
2419#undef ENETDOWN
2420#undef ENETRESET
2421#undef ENETUNREACH
2422#undef ENOBUFS
2423#undef ENOPROTOOPT
2424#undef ENOTCONN
2425#undef ENOTSOCK
2426#undef EOPNOTSUPP
2427#undef EPROTONOSUPPORT
2428#undef EPROTOTYPE
2429#undef ETIMEDOUT
2430#undef EWOULDBLOCK
2431
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002432#if defined(WSAEALREADY) && !defined(EALREADY)
2433#define EALREADY WSAEALREADY
2434#endif
2435#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2436#define ECONNABORTED WSAECONNABORTED
2437#endif
2438#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2439#define ECONNREFUSED WSAECONNREFUSED
2440#endif
2441#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2442#define ECONNRESET WSAECONNRESET
2443#endif
2444#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2445#define EINPROGRESS WSAEINPROGRESS
2446#endif
2447#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2448#define ESHUTDOWN WSAESHUTDOWN
2449#endif
2450#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2451#define ETIMEDOUT WSAETIMEDOUT
2452#endif
2453#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2454#define EWOULDBLOCK WSAEWOULDBLOCK
2455#endif
2456#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002457
Martin v. Löwis1a214512008-06-11 05:26:20 +00002458void
Brett Cannonfd074152012-04-14 14:10:13 -04002459_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002460{
Brett Cannonfd074152012-04-14 14:10:13 -04002461 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002462
2463 PRE_INIT(BaseException)
2464 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002465 PRE_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002466 PRE_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002467 PRE_INIT(StopIteration)
2468 PRE_INIT(GeneratorExit)
2469 PRE_INIT(SystemExit)
2470 PRE_INIT(KeyboardInterrupt)
2471 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002472 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002473 PRE_INIT(EOFError)
2474 PRE_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002475 PRE_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002476 PRE_INIT(NotImplementedError)
2477 PRE_INIT(NameError)
2478 PRE_INIT(UnboundLocalError)
2479 PRE_INIT(AttributeError)
2480 PRE_INIT(SyntaxError)
2481 PRE_INIT(IndentationError)
2482 PRE_INIT(TabError)
2483 PRE_INIT(LookupError)
2484 PRE_INIT(IndexError)
2485 PRE_INIT(KeyError)
2486 PRE_INIT(ValueError)
2487 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002488 PRE_INIT(UnicodeEncodeError)
2489 PRE_INIT(UnicodeDecodeError)
2490 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002491 PRE_INIT(AssertionError)
2492 PRE_INIT(ArithmeticError)
2493 PRE_INIT(FloatingPointError)
2494 PRE_INIT(OverflowError)
2495 PRE_INIT(ZeroDivisionError)
2496 PRE_INIT(SystemError)
2497 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002498 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002499 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002500 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002501 PRE_INIT(Warning)
2502 PRE_INIT(UserWarning)
2503 PRE_INIT(DeprecationWarning)
2504 PRE_INIT(PendingDeprecationWarning)
2505 PRE_INIT(SyntaxWarning)
2506 PRE_INIT(RuntimeWarning)
2507 PRE_INIT(FutureWarning)
2508 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002509 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002510 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002511 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002512
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002513 /* OSError subclasses */
2514 PRE_INIT(ConnectionError);
2515
2516 PRE_INIT(BlockingIOError);
2517 PRE_INIT(BrokenPipeError);
2518 PRE_INIT(ChildProcessError);
2519 PRE_INIT(ConnectionAbortedError);
2520 PRE_INIT(ConnectionRefusedError);
2521 PRE_INIT(ConnectionResetError);
2522 PRE_INIT(FileExistsError);
2523 PRE_INIT(FileNotFoundError);
2524 PRE_INIT(IsADirectoryError);
2525 PRE_INIT(NotADirectoryError);
2526 PRE_INIT(InterruptedError);
2527 PRE_INIT(PermissionError);
2528 PRE_INIT(ProcessLookupError);
2529 PRE_INIT(TimeoutError);
2530
Thomas Wouters477c8d52006-05-27 19:21:47 +00002531 bdict = PyModule_GetDict(bltinmod);
2532 if (bdict == NULL)
2533 Py_FatalError("exceptions bootstrapping error.");
2534
2535 POST_INIT(BaseException)
2536 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002537 POST_INIT(TypeError)
Yury Selivanov75445082015-05-11 22:57:16 -04002538 POST_INIT(StopAsyncIteration)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002539 POST_INIT(StopIteration)
2540 POST_INIT(GeneratorExit)
2541 POST_INIT(SystemExit)
2542 POST_INIT(KeyboardInterrupt)
2543 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002544 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002545 INIT_ALIAS(EnvironmentError, OSError)
2546 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002547#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002548 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002549#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00002550 POST_INIT(EOFError)
2551 POST_INIT(RuntimeError)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002552 POST_INIT(RecursionError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002553 POST_INIT(NotImplementedError)
2554 POST_INIT(NameError)
2555 POST_INIT(UnboundLocalError)
2556 POST_INIT(AttributeError)
2557 POST_INIT(SyntaxError)
2558 POST_INIT(IndentationError)
2559 POST_INIT(TabError)
2560 POST_INIT(LookupError)
2561 POST_INIT(IndexError)
2562 POST_INIT(KeyError)
2563 POST_INIT(ValueError)
2564 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002565 POST_INIT(UnicodeEncodeError)
2566 POST_INIT(UnicodeDecodeError)
2567 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002568 POST_INIT(AssertionError)
2569 POST_INIT(ArithmeticError)
2570 POST_INIT(FloatingPointError)
2571 POST_INIT(OverflowError)
2572 POST_INIT(ZeroDivisionError)
2573 POST_INIT(SystemError)
2574 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002575 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002576 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002577 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002578 POST_INIT(Warning)
2579 POST_INIT(UserWarning)
2580 POST_INIT(DeprecationWarning)
2581 POST_INIT(PendingDeprecationWarning)
2582 POST_INIT(SyntaxWarning)
2583 POST_INIT(RuntimeWarning)
2584 POST_INIT(FutureWarning)
2585 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002586 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002587 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002588 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002589
Antoine Pitrouac456a12012-01-18 21:35:21 +01002590 if (!errnomap) {
2591 errnomap = PyDict_New();
2592 if (!errnomap)
2593 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2594 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002595
2596 /* OSError subclasses */
2597 POST_INIT(ConnectionError);
2598
2599 POST_INIT(BlockingIOError);
2600 ADD_ERRNO(BlockingIOError, EAGAIN);
2601 ADD_ERRNO(BlockingIOError, EALREADY);
2602 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2603 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2604 POST_INIT(BrokenPipeError);
2605 ADD_ERRNO(BrokenPipeError, EPIPE);
Berker Peksaga787e5f2016-07-30 14:14:12 +03002606#ifdef ESHUTDOWN
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002607 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
Berker Peksaga787e5f2016-07-30 14:14:12 +03002608#endif
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002609 POST_INIT(ChildProcessError);
2610 ADD_ERRNO(ChildProcessError, ECHILD);
2611 POST_INIT(ConnectionAbortedError);
2612 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2613 POST_INIT(ConnectionRefusedError);
2614 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2615 POST_INIT(ConnectionResetError);
2616 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2617 POST_INIT(FileExistsError);
2618 ADD_ERRNO(FileExistsError, EEXIST);
2619 POST_INIT(FileNotFoundError);
2620 ADD_ERRNO(FileNotFoundError, ENOENT);
2621 POST_INIT(IsADirectoryError);
2622 ADD_ERRNO(IsADirectoryError, EISDIR);
2623 POST_INIT(NotADirectoryError);
2624 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2625 POST_INIT(InterruptedError);
2626 ADD_ERRNO(InterruptedError, EINTR);
2627 POST_INIT(PermissionError);
2628 ADD_ERRNO(PermissionError, EACCES);
2629 ADD_ERRNO(PermissionError, EPERM);
2630 POST_INIT(ProcessLookupError);
2631 ADD_ERRNO(ProcessLookupError, ESRCH);
2632 POST_INIT(TimeoutError);
2633 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2634
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002635 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002636
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002637 if (!PyExc_RecursionErrorInst) {
Yury Selivanovf488fb42015-07-03 01:04:23 -04002638 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RecursionError, NULL, NULL);
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002639 if (!PyExc_RecursionErrorInst)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002640 Py_FatalError("Cannot pre-allocate RecursionError instance for "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002641 "recursion errors");
2642 else {
2643 PyBaseExceptionObject *err_inst =
2644 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2645 PyObject *args_tuple;
2646 PyObject *exc_message;
2647 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2648 if (!exc_message)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002649 Py_FatalError("cannot allocate argument for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002650 "pre-allocation");
2651 args_tuple = PyTuple_Pack(1, exc_message);
2652 if (!args_tuple)
Yury Selivanovf488fb42015-07-03 01:04:23 -04002653 Py_FatalError("cannot allocate tuple for RecursionError "
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002654 "pre-allocation");
2655 Py_DECREF(exc_message);
2656 if (BaseException_init(err_inst, args_tuple, NULL))
Yury Selivanovf488fb42015-07-03 01:04:23 -04002657 Py_FatalError("init of pre-allocated RecursionError failed");
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002658 Py_DECREF(args_tuple);
2659 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002660 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002661}
2662
2663void
2664_PyExc_Fini(void)
2665{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002666 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002667 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002668 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002669}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002670
2671/* Helper to do the equivalent of "raise X from Y" in C, but always using
2672 * the current exception rather than passing one in.
2673 *
2674 * We currently limit this to *only* exceptions that use the BaseException
2675 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2676 * those correctly without losing data and without losing backwards
2677 * compatibility.
2678 *
2679 * We also aim to rule out *all* exceptions that might be storing additional
2680 * state, whether by having a size difference relative to BaseException,
2681 * additional arguments passed in during construction or by having a
2682 * non-empty instance dict.
2683 *
2684 * We need to be very careful with what we wrap, since changing types to
2685 * a broader exception type would be backwards incompatible for
2686 * existing codecs, and with different init or new method implementations
2687 * may either not support instantiation with PyErr_Format or lose
2688 * information when instantiated that way.
2689 *
2690 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2691 * fact that exceptions are expected to support pickling. If more builtin
2692 * exceptions (e.g. AttributeError) start to be converted to rich
2693 * exceptions with additional attributes, that's probably a better approach
2694 * to pursue over adding special cases for particular stateful subclasses.
2695 *
2696 * Returns a borrowed reference to the new exception (if any), NULL if the
2697 * existing exception was left in place.
2698 */
2699PyObject *
2700_PyErr_TrySetFromCause(const char *format, ...)
2701{
2702 PyObject* msg_prefix;
2703 PyObject *exc, *val, *tb;
2704 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002705 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002706 PyObject *instance_args;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002707 Py_ssize_t num_args, caught_type_size, base_exc_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002708 PyObject *new_exc, *new_val, *new_tb;
2709 va_list vargs;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002710 int same_basic_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002711
Nick Coghlan8b097b42013-11-13 23:49:21 +10002712 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002713 caught_type = (PyTypeObject *)exc;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002714 /* Ensure type info indicates no extra state is stored at the C level
2715 * and that the type can be reinstantiated using PyErr_Format
2716 */
2717 caught_type_size = caught_type->tp_basicsize;
2718 base_exc_size = _PyExc_BaseException.tp_basicsize;
2719 same_basic_size = (
2720 caught_type_size == base_exc_size ||
2721 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
Victor Stinner12174a52014-08-15 23:17:38 +02002722 (caught_type_size == base_exc_size + (Py_ssize_t)sizeof(PyObject *))
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002723 )
2724 );
Benjamin Peterson079c9982013-11-13 23:25:01 -05002725 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002726 caught_type->tp_new != BaseException_new ||
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002727 !same_basic_size ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002728 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002729 /* We can't be sure we can wrap this safely, since it may contain
2730 * more state than just the exception type. Accordingly, we just
2731 * leave it alone.
2732 */
2733 PyErr_Restore(exc, val, tb);
2734 return NULL;
2735 }
2736
2737 /* Check the args are empty or contain a single string */
2738 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002739 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002740 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002741 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002742 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002743 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002744 /* More than 1 arg, or the one arg we do have isn't a string
2745 */
2746 PyErr_Restore(exc, val, tb);
2747 return NULL;
2748 }
2749
2750 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002751 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002752 if (dictptr != NULL && *dictptr != NULL &&
2753 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002754 /* While we could potentially copy a non-empty instance dictionary
2755 * to the replacement exception, for now we take the more
2756 * conservative path of leaving exceptions with attributes set
2757 * alone.
2758 */
2759 PyErr_Restore(exc, val, tb);
2760 return NULL;
2761 }
2762
2763 /* For exceptions that we can wrap safely, we chain the original
2764 * exception to a new one of the exact same type with an
2765 * error message that mentions the additional details and the
2766 * original exception.
2767 *
2768 * It would be nice to wrap OSError and various other exception
2769 * types as well, but that's quite a bit trickier due to the extra
2770 * state potentially stored on OSError instances.
2771 */
Nick Coghlan77b286b2014-01-27 00:53:38 +10002772 /* Ensure the traceback is set correctly on the existing exception */
2773 if (tb != NULL) {
2774 PyException_SetTraceback(val, tb);
2775 Py_DECREF(tb);
2776 }
Benjamin Petersone109ee82013-11-13 23:49:49 -05002777
Christian Heimes507eabd2013-11-14 01:39:35 +01002778#ifdef HAVE_STDARG_PROTOTYPES
2779 va_start(vargs, format);
2780#else
2781 va_start(vargs);
2782#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002783 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002784 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002785 if (msg_prefix == NULL) {
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002786 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002787 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002788 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002789 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002790
2791 PyErr_Format(exc, "%U (%s: %S)",
2792 msg_prefix, Py_TYPE(val)->tp_name, val);
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002793 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002794 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002795 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2796 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2797 PyException_SetCause(new_val, val);
2798 PyErr_Restore(new_exc, new_val, new_tb);
2799 return new_val;
2800}
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002801
2802
2803/* To help with migration from Python 2, SyntaxError.__init__ applies some
2804 * heuristics to try to report a more meaningful exception when print and
2805 * exec are used like statements.
2806 *
2807 * The heuristics are currently expected to detect the following cases:
2808 * - top level statement
2809 * - statement in a nested suite
2810 * - trailing section of a one line complex statement
2811 *
2812 * They're currently known not to trigger:
2813 * - after a semi-colon
2814 *
2815 * The error message can be a bit odd in cases where the "arguments" are
2816 * completely illegal syntactically, but that isn't worth the hassle of
2817 * fixing.
2818 *
2819 * We also can't do anything about cases that are legal Python 3 syntax
2820 * but mean something entirely different from what they did in Python 2
2821 * (omitting the arguments entirely, printing items preceded by a unary plus
2822 * or minus, using the stream redirection syntax).
2823 */
2824
2825static int
2826_check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start)
2827{
2828 /* Return values:
2829 * -1: an error occurred
2830 * 0: nothing happened
2831 * 1: the check triggered & the error message was changed
2832 */
2833 static PyObject *print_prefix = NULL;
2834 static PyObject *exec_prefix = NULL;
2835 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2836 int kind = PyUnicode_KIND(self->text);
2837 void *data = PyUnicode_DATA(self->text);
2838
2839 /* Ignore leading whitespace */
2840 while (start < text_len) {
2841 Py_UCS4 ch = PyUnicode_READ(kind, data, start);
2842 if (!Py_UNICODE_ISSPACE(ch))
2843 break;
2844 start++;
2845 }
2846 /* Checking against an empty or whitespace-only part of the string */
2847 if (start == text_len) {
2848 return 0;
2849 }
2850
2851 /* Check for legacy print statements */
2852 if (print_prefix == NULL) {
2853 print_prefix = PyUnicode_InternFromString("print ");
2854 if (print_prefix == NULL) {
2855 return -1;
2856 }
2857 }
2858 if (PyUnicode_Tailmatch(self->text, print_prefix,
2859 start, text_len, -1)) {
Serhiy Storchaka48842712016-04-06 09:45:48 +03002860 Py_XSETREF(self->msg,
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02002861 PyUnicode_FromString("Missing parentheses in call to 'print'"));
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002862 return 1;
2863 }
2864
2865 /* Check for legacy exec statements */
2866 if (exec_prefix == NULL) {
2867 exec_prefix = PyUnicode_InternFromString("exec ");
2868 if (exec_prefix == NULL) {
2869 return -1;
2870 }
2871 }
2872 if (PyUnicode_Tailmatch(self->text, exec_prefix,
2873 start, text_len, -1)) {
Serhiy Storchaka48842712016-04-06 09:45:48 +03002874 Py_XSETREF(self->msg,
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02002875 PyUnicode_FromString("Missing parentheses in call to 'exec'"));
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002876 return 1;
2877 }
2878 /* Fall back to the default error message */
2879 return 0;
2880}
2881
2882static int
2883_report_missing_parentheses(PySyntaxErrorObject *self)
2884{
2885 Py_UCS4 left_paren = 40;
2886 Py_ssize_t left_paren_index;
2887 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2888 int legacy_check_result = 0;
2889
2890 /* Skip entirely if there is an opening parenthesis */
2891 left_paren_index = PyUnicode_FindChar(self->text, left_paren,
2892 0, text_len, 1);
2893 if (left_paren_index < -1) {
2894 return -1;
2895 }
2896 if (left_paren_index != -1) {
2897 /* Use default error message for any line with an opening paren */
2898 return 0;
2899 }
2900 /* Handle the simple statement case */
2901 legacy_check_result = _check_for_legacy_statements(self, 0);
2902 if (legacy_check_result < 0) {
2903 return -1;
2904
2905 }
2906 if (legacy_check_result == 0) {
2907 /* Handle the one-line complex statement case */
2908 Py_UCS4 colon = 58;
2909 Py_ssize_t colon_index;
2910 colon_index = PyUnicode_FindChar(self->text, colon,
2911 0, text_len, 1);
2912 if (colon_index < -1) {
2913 return -1;
2914 }
2915 if (colon_index >= 0 && colon_index < text_len) {
2916 /* Check again, starting from just after the colon */
2917 if (_check_for_legacy_statements(self, colon_index+1) < 0) {
2918 return -1;
2919 }
2920 }
2921 }
2922 return 0;
2923}