1 /*
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
7 #define PY_SSIZE_T_CLEAN
8 #include <Python.h>
9 #include "pycore_initconfig.h"
10 #include "pycore_object.h"
11 #include "pycore_pymem.h"
12 #include "pycore_pystate.h"
13 #include "structmember.h"
14 #include "osdefs.h"
15
16
17 /* Compatibility aliases */
18 PyObject *PyExc_EnvironmentError = NULL;
19 PyObject *PyExc_IOError = NULL;
20 #ifdef MS_WINDOWS
21 PyObject *PyExc_WindowsError = NULL;
22 #endif
23
24 /* The dict map from errno codes to OSError subclasses */
25 static PyObject *errnomap = NULL;
26
27
28 /* NOTE: If the exception class hierarchy changes, don't forget to update
29 * Lib/test/exception_hierarchy.txt
30 */
31
32 /*
33 * BaseException
34 */
35 static PyObject *
BaseException_new(PyTypeObject * type,PyObject * args,PyObject * kwds)36 BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
37 {
38 PyBaseExceptionObject *self;
39
40 self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
41 if (!self)
42 return NULL;
43 /* the dict is created on the fly in PyObject_GenericSetAttr */
44 self->dict = NULL;
45 self->traceback = self->cause = self->context = NULL;
46 self->suppress_context = 0;
47
48 if (args) {
49 self->args = args;
50 Py_INCREF(args);
51 return (PyObject *)self;
52 }
53
54 self->args = PyTuple_New(0);
55 if (!self->args) {
56 Py_DECREF(self);
57 return NULL;
58 }
59
60 return (PyObject *)self;
61 }
62
63 static int
BaseException_init(PyBaseExceptionObject * self,PyObject * args,PyObject * kwds)64 BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
65 {
66 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
67 return -1;
68
69 Py_INCREF(args);
70 Py_XSETREF(self->args, args);
71
72 return 0;
73 }
74
75 static int
BaseException_clear(PyBaseExceptionObject * self)76 BaseException_clear(PyBaseExceptionObject *self)
77 {
78 Py_CLEAR(self->dict);
79 Py_CLEAR(self->args);
80 Py_CLEAR(self->traceback);
81 Py_CLEAR(self->cause);
82 Py_CLEAR(self->context);
83 return 0;
84 }
85
86 static void
BaseException_dealloc(PyBaseExceptionObject * self)87 BaseException_dealloc(PyBaseExceptionObject *self)
88 {
89 _PyObject_GC_UNTRACK(self);
90 BaseException_clear(self);
91 Py_TYPE(self)->tp_free((PyObject *)self);
92 }
93
94 static int
BaseException_traverse(PyBaseExceptionObject * self,visitproc visit,void * arg)95 BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
96 {
97 Py_VISIT(self->dict);
98 Py_VISIT(self->args);
99 Py_VISIT(self->traceback);
100 Py_VISIT(self->cause);
101 Py_VISIT(self->context);
102 return 0;
103 }
104
105 static PyObject *
BaseException_str(PyBaseExceptionObject * self)106 BaseException_str(PyBaseExceptionObject *self)
107 {
108 switch (PyTuple_GET_SIZE(self->args)) {
109 case 0:
110 return PyUnicode_FromString("");
111 case 1:
112 return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
113 default:
114 return PyObject_Str(self->args);
115 }
116 }
117
118 static PyObject *
BaseException_repr(PyBaseExceptionObject * self)119 BaseException_repr(PyBaseExceptionObject *self)
120 {
121 const char *name = _PyType_Name(Py_TYPE(self));
122 if (PyTuple_GET_SIZE(self->args) == 1)
123 return PyUnicode_FromFormat("%s(%R)", name,
124 PyTuple_GET_ITEM(self->args, 0));
125 else
126 return PyUnicode_FromFormat("%s%R", name, self->args);
127 }
128
129 /* Pickling support */
130 static PyObject *
BaseException_reduce(PyBaseExceptionObject * self,PyObject * Py_UNUSED (ignored))131 BaseException_reduce(PyBaseExceptionObject *self, PyObject *Py_UNUSED(ignored))
132 {
133 if (self->args && self->dict)
134 return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
135 else
136 return PyTuple_Pack(2, Py_TYPE(self), self->args);
137 }
138
139 /*
140 * Needed for backward compatibility, since exceptions used to store
141 * all their attributes in the __dict__. Code is taken from cPickle's
142 * load_build function.
143 */
144 static PyObject *
BaseException_setstate(PyObject * self,PyObject * state)145 BaseException_setstate(PyObject *self, PyObject *state)
146 {
147 PyObject *d_key, *d_value;
148 Py_ssize_t i = 0;
149
150 if (state != Py_None) {
151 if (!PyDict_Check(state)) {
152 PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
153 return NULL;
154 }
155 while (PyDict_Next(state, &i, &d_key, &d_value)) {
156 if (PyObject_SetAttr(self, d_key, d_value) < 0)
157 return NULL;
158 }
159 }
160 Py_RETURN_NONE;
161 }
162
163 static PyObject *
BaseException_with_traceback(PyObject * self,PyObject * tb)164 BaseException_with_traceback(PyObject *self, PyObject *tb) {
165 if (PyException_SetTraceback(self, tb))
166 return NULL;
167
168 Py_INCREF(self);
169 return self;
170 }
171
172 PyDoc_STRVAR(with_traceback_doc,
173 "Exception.with_traceback(tb) --\n\
174 set self.__traceback__ to tb and return self.");
175
176
177 static PyMethodDef BaseException_methods[] = {
178 {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
179 {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
180 {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
181 with_traceback_doc},
182 {NULL, NULL, 0, NULL},
183 };
184
185 static PyObject *
BaseException_get_args(PyBaseExceptionObject * self,void * Py_UNUSED (ignored))186 BaseException_get_args(PyBaseExceptionObject *self, void *Py_UNUSED(ignored))
187 {
188 if (self->args == NULL) {
189 Py_RETURN_NONE;
190 }
191 Py_INCREF(self->args);
192 return self->args;
193 }
194
195 static int
BaseException_set_args(PyBaseExceptionObject * self,PyObject * val,void * Py_UNUSED (ignored))196 BaseException_set_args(PyBaseExceptionObject *self, PyObject *val, void *Py_UNUSED(ignored))
197 {
198 PyObject *seq;
199 if (val == NULL) {
200 PyErr_SetString(PyExc_TypeError, "args may not be deleted");
201 return -1;
202 }
203 seq = PySequence_Tuple(val);
204 if (!seq)
205 return -1;
206 Py_XSETREF(self->args, seq);
207 return 0;
208 }
209
210 static PyObject *
BaseException_get_tb(PyBaseExceptionObject * self,void * Py_UNUSED (ignored))211 BaseException_get_tb(PyBaseExceptionObject *self, void *Py_UNUSED(ignored))
212 {
213 if (self->traceback == NULL) {
214 Py_RETURN_NONE;
215 }
216 Py_INCREF(self->traceback);
217 return self->traceback;
218 }
219
220 static int
BaseException_set_tb(PyBaseExceptionObject * self,PyObject * tb,void * Py_UNUSED (ignored))221 BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb, void *Py_UNUSED(ignored))
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
233 Py_INCREF(tb);
234 Py_XSETREF(self->traceback, tb);
235 return 0;
236 }
237
238 static PyObject *
BaseException_get_context(PyObject * self,void * Py_UNUSED (ignored))239 BaseException_get_context(PyObject *self, void *Py_UNUSED(ignored))
240 {
241 PyObject *res = PyException_GetContext(self);
242 if (res)
243 return res; /* new reference already returned above */
244 Py_RETURN_NONE;
245 }
246
247 static int
BaseException_set_context(PyObject * self,PyObject * arg,void * Py_UNUSED (ignored))248 BaseException_set_context(PyObject *self, PyObject *arg, void *Py_UNUSED(ignored))
249 {
250 if (arg == NULL) {
251 PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
252 return -1;
253 } else if (arg == Py_None) {
254 arg = NULL;
255 } else if (!PyExceptionInstance_Check(arg)) {
256 PyErr_SetString(PyExc_TypeError, "exception context must be None "
257 "or derive from BaseException");
258 return -1;
259 } else {
260 /* PyException_SetContext steals this reference */
261 Py_INCREF(arg);
262 }
263 PyException_SetContext(self, arg);
264 return 0;
265 }
266
267 static PyObject *
BaseException_get_cause(PyObject * self,void * Py_UNUSED (ignored))268 BaseException_get_cause(PyObject *self, void *Py_UNUSED(ignored))
269 {
270 PyObject *res = PyException_GetCause(self);
271 if (res)
272 return res; /* new reference already returned above */
273 Py_RETURN_NONE;
274 }
275
276 static int
BaseException_set_cause(PyObject * self,PyObject * arg,void * Py_UNUSED (ignored))277 BaseException_set_cause(PyObject *self, PyObject *arg, void *Py_UNUSED(ignored))
278 {
279 if (arg == NULL) {
280 PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
281 return -1;
282 } else if (arg == Py_None) {
283 arg = NULL;
284 } else if (!PyExceptionInstance_Check(arg)) {
285 PyErr_SetString(PyExc_TypeError, "exception cause must be None "
286 "or derive from BaseException");
287 return -1;
288 } else {
289 /* PyException_SetCause steals this reference */
290 Py_INCREF(arg);
291 }
292 PyException_SetCause(self, arg);
293 return 0;
294 }
295
296
297 static PyGetSetDef BaseException_getset[] = {
298 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
299 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
300 {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
301 {"__context__", BaseException_get_context,
302 BaseException_set_context, PyDoc_STR("exception context")},
303 {"__cause__", BaseException_get_cause,
304 BaseException_set_cause, PyDoc_STR("exception cause")},
305 {NULL},
306 };
307
308
309 PyObject *
PyException_GetTraceback(PyObject * self)310 PyException_GetTraceback(PyObject *self) {
311 PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
312 Py_XINCREF(base_self->traceback);
313 return base_self->traceback;
314 }
315
316
317 int
PyException_SetTraceback(PyObject * self,PyObject * tb)318 PyException_SetTraceback(PyObject *self, PyObject *tb) {
319 return BaseException_set_tb((PyBaseExceptionObject *)self, tb, NULL);
320 }
321
322 PyObject *
PyException_GetCause(PyObject * self)323 PyException_GetCause(PyObject *self) {
324 PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
325 Py_XINCREF(cause);
326 return cause;
327 }
328
329 /* Steals a reference to cause */
330 void
PyException_SetCause(PyObject * self,PyObject * cause)331 PyException_SetCause(PyObject *self, PyObject *cause)
332 {
333 ((PyBaseExceptionObject *)self)->suppress_context = 1;
334 Py_XSETREF(((PyBaseExceptionObject *)self)->cause, cause);
335 }
336
337 PyObject *
PyException_GetContext(PyObject * self)338 PyException_GetContext(PyObject *self) {
339 PyObject *context = ((PyBaseExceptionObject *)self)->context;
340 Py_XINCREF(context);
341 return context;
342 }
343
344 /* Steals a reference to context */
345 void
PyException_SetContext(PyObject * self,PyObject * context)346 PyException_SetContext(PyObject *self, PyObject *context)
347 {
348 Py_XSETREF(((PyBaseExceptionObject *)self)->context, context);
349 }
350
351 #undef PyExceptionClass_Name
352
353 const char *
PyExceptionClass_Name(PyObject * ob)354 PyExceptionClass_Name(PyObject *ob)
355 {
356 return ((PyTypeObject*)ob)->tp_name;
357 }
358
359 static struct PyMemberDef BaseException_members[] = {
360 {"__suppress_context__", T_BOOL,
361 offsetof(PyBaseExceptionObject, suppress_context)},
362 {NULL}
363 };
364
365
366 static PyTypeObject _PyExc_BaseException = {
367 PyVarObject_HEAD_INIT(NULL, 0)
368 "BaseException", /*tp_name*/
369 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
370 0, /*tp_itemsize*/
371 (destructor)BaseException_dealloc, /*tp_dealloc*/
372 0, /*tp_vectorcall_offset*/
373 0, /*tp_getattr*/
374 0, /*tp_setattr*/
375 0, /*tp_as_async*/
376 (reprfunc)BaseException_repr, /*tp_repr*/
377 0, /*tp_as_number*/
378 0, /*tp_as_sequence*/
379 0, /*tp_as_mapping*/
380 0, /*tp_hash */
381 0, /*tp_call*/
382 (reprfunc)BaseException_str, /*tp_str*/
383 PyObject_GenericGetAttr, /*tp_getattro*/
384 PyObject_GenericSetAttr, /*tp_setattro*/
385 0, /*tp_as_buffer*/
386 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
387 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
388 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
389 (traverseproc)BaseException_traverse, /* tp_traverse */
390 (inquiry)BaseException_clear, /* tp_clear */
391 0, /* tp_richcompare */
392 0, /* tp_weaklistoffset */
393 0, /* tp_iter */
394 0, /* tp_iternext */
395 BaseException_methods, /* tp_methods */
396 BaseException_members, /* tp_members */
397 BaseException_getset, /* tp_getset */
398 0, /* tp_base */
399 0, /* tp_dict */
400 0, /* tp_descr_get */
401 0, /* tp_descr_set */
402 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
403 (initproc)BaseException_init, /* tp_init */
404 0, /* tp_alloc */
405 BaseException_new, /* tp_new */
406 };
407 /* the CPython API expects exceptions to be (PyObject *) - both a hold-over
408 from the previous implmentation and also allowing Python objects to be used
409 in the API */
410 PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
411
412 /* note these macros omit the last semicolon so the macro invocation may
413 * include it and not look strange.
414 */
415 #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
416 static PyTypeObject _PyExc_ ## EXCNAME = { \
417 PyVarObject_HEAD_INIT(NULL, 0) \
418 # EXCNAME, \
419 sizeof(PyBaseExceptionObject), \
420 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
421 0, 0, 0, 0, 0, 0, 0, \
422 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
423 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
424 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
425 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
426 (initproc)BaseException_init, 0, BaseException_new,\
427 }; \
428 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
429
430 #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
431 static PyTypeObject _PyExc_ ## EXCNAME = { \
432 PyVarObject_HEAD_INIT(NULL, 0) \
433 # EXCNAME, \
434 sizeof(Py ## EXCSTORE ## Object), \
435 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
436 0, 0, 0, 0, 0, \
437 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
438 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
439 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
440 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
441 (initproc)EXCSTORE ## _init, 0, 0, \
442 }; \
443 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
444
445 #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
446 EXCMETHODS, EXCMEMBERS, EXCGETSET, \
447 EXCSTR, EXCDOC) \
448 static PyTypeObject _PyExc_ ## EXCNAME = { \
449 PyVarObject_HEAD_INIT(NULL, 0) \
450 # EXCNAME, \
451 sizeof(Py ## EXCSTORE ## Object), 0, \
452 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
453 (reprfunc)EXCSTR, 0, 0, 0, \
454 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
455 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
456 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
457 EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
458 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
459 (initproc)EXCSTORE ## _init, 0, EXCNEW,\
460 }; \
461 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
462
463
464 /*
465 * Exception extends BaseException
466 */
467 SimpleExtendsException(PyExc_BaseException, Exception,
468 "Common base class for all non-exit exceptions.");
469
470
471 /*
472 * TypeError extends Exception
473 */
474 SimpleExtendsException(PyExc_Exception, TypeError,
475 "Inappropriate argument type.");
476
477
478 /*
479 * StopAsyncIteration extends Exception
480 */
481 SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
482 "Signal the end from iterator.__anext__().");
483
484
485 /*
486 * StopIteration extends Exception
487 */
488
489 static PyMemberDef StopIteration_members[] = {
490 {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
491 PyDoc_STR("generator return value")},
492 {NULL} /* Sentinel */
493 };
494
495 static int
StopIteration_init(PyStopIterationObject * self,PyObject * args,PyObject * kwds)496 StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
497 {
498 Py_ssize_t size = PyTuple_GET_SIZE(args);
499 PyObject *value;
500
501 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
502 return -1;
503 Py_CLEAR(self->value);
504 if (size > 0)
505 value = PyTuple_GET_ITEM(args, 0);
506 else
507 value = Py_None;
508 Py_INCREF(value);
509 self->value = value;
510 return 0;
511 }
512
513 static int
StopIteration_clear(PyStopIterationObject * self)514 StopIteration_clear(PyStopIterationObject *self)
515 {
516 Py_CLEAR(self->value);
517 return BaseException_clear((PyBaseExceptionObject *)self);
518 }
519
520 static void
StopIteration_dealloc(PyStopIterationObject * self)521 StopIteration_dealloc(PyStopIterationObject *self)
522 {
523 _PyObject_GC_UNTRACK(self);
524 StopIteration_clear(self);
525 Py_TYPE(self)->tp_free((PyObject *)self);
526 }
527
528 static int
StopIteration_traverse(PyStopIterationObject * self,visitproc visit,void * arg)529 StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
530 {
531 Py_VISIT(self->value);
532 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
533 }
534
535 ComplexExtendsException(
536 PyExc_Exception, /* base */
537 StopIteration, /* name */
538 StopIteration, /* prefix for *_init, etc */
539 0, /* new */
540 0, /* methods */
541 StopIteration_members, /* members */
542 0, /* getset */
543 0, /* str */
544 "Signal the end from iterator.__next__()."
545 );
546
547
548 /*
549 * GeneratorExit extends BaseException
550 */
551 SimpleExtendsException(PyExc_BaseException, GeneratorExit,
552 "Request that a generator exit.");
553
554
555 /*
556 * SystemExit extends BaseException
557 */
558
559 static int
SystemExit_init(PySystemExitObject * self,PyObject * args,PyObject * kwds)560 SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
561 {
562 Py_ssize_t size = PyTuple_GET_SIZE(args);
563
564 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
565 return -1;
566
567 if (size == 0)
568 return 0;
569 if (size == 1) {
570 Py_INCREF(PyTuple_GET_ITEM(args, 0));
571 Py_XSETREF(self->code, PyTuple_GET_ITEM(args, 0));
572 }
573 else { /* size > 1 */
574 Py_INCREF(args);
575 Py_XSETREF(self->code, args);
576 }
577 return 0;
578 }
579
580 static int
SystemExit_clear(PySystemExitObject * self)581 SystemExit_clear(PySystemExitObject *self)
582 {
583 Py_CLEAR(self->code);
584 return BaseException_clear((PyBaseExceptionObject *)self);
585 }
586
587 static void
SystemExit_dealloc(PySystemExitObject * self)588 SystemExit_dealloc(PySystemExitObject *self)
589 {
590 _PyObject_GC_UNTRACK(self);
591 SystemExit_clear(self);
592 Py_TYPE(self)->tp_free((PyObject *)self);
593 }
594
595 static int
SystemExit_traverse(PySystemExitObject * self,visitproc visit,void * arg)596 SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
597 {
598 Py_VISIT(self->code);
599 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
600 }
601
602 static PyMemberDef SystemExit_members[] = {
603 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
604 PyDoc_STR("exception code")},
605 {NULL} /* Sentinel */
606 };
607
608 ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
609 0, 0, SystemExit_members, 0, 0,
610 "Request to exit from the interpreter.");
611
612 /*
613 * KeyboardInterrupt extends BaseException
614 */
615 SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
616 "Program interrupted by user.");
617
618
619 /*
620 * ImportError extends Exception
621 */
622
623 static int
ImportError_init(PyImportErrorObject * self,PyObject * args,PyObject * kwds)624 ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
625 {
626 static char *kwlist[] = {"name", "path", 0};
627 PyObject *empty_tuple;
628 PyObject *msg = NULL;
629 PyObject *name = NULL;
630 PyObject *path = NULL;
631
632 if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1)
633 return -1;
634
635 empty_tuple = PyTuple_New(0);
636 if (!empty_tuple)
637 return -1;
638 if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OO:ImportError", kwlist,
639 &name, &path)) {
640 Py_DECREF(empty_tuple);
641 return -1;
642 }
643 Py_DECREF(empty_tuple);
644
645 Py_XINCREF(name);
646 Py_XSETREF(self->name, name);
647
648 Py_XINCREF(path);
649 Py_XSETREF(self->path, path);
650
651 if (PyTuple_GET_SIZE(args) == 1) {
652 msg = PyTuple_GET_ITEM(args, 0);
653 Py_INCREF(msg);
654 }
655 Py_XSETREF(self->msg, msg);
656
657 return 0;
658 }
659
660 static int
ImportError_clear(PyImportErrorObject * self)661 ImportError_clear(PyImportErrorObject *self)
662 {
663 Py_CLEAR(self->msg);
664 Py_CLEAR(self->name);
665 Py_CLEAR(self->path);
666 return BaseException_clear((PyBaseExceptionObject *)self);
667 }
668
669 static void
ImportError_dealloc(PyImportErrorObject * self)670 ImportError_dealloc(PyImportErrorObject *self)
671 {
672 _PyObject_GC_UNTRACK(self);
673 ImportError_clear(self);
674 Py_TYPE(self)->tp_free((PyObject *)self);
675 }
676
677 static int
ImportError_traverse(PyImportErrorObject * self,visitproc visit,void * arg)678 ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
679 {
680 Py_VISIT(self->msg);
681 Py_VISIT(self->name);
682 Py_VISIT(self->path);
683 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
684 }
685
686 static PyObject *
ImportError_str(PyImportErrorObject * self)687 ImportError_str(PyImportErrorObject *self)
688 {
689 if (self->msg && PyUnicode_CheckExact(self->msg)) {
690 Py_INCREF(self->msg);
691 return self->msg;
692 }
693 else {
694 return BaseException_str((PyBaseExceptionObject *)self);
695 }
696 }
697
698 static PyObject *
ImportError_getstate(PyImportErrorObject * self)699 ImportError_getstate(PyImportErrorObject *self)
700 {
701 PyObject *dict = ((PyBaseExceptionObject *)self)->dict;
702 if (self->name || self->path) {
703 _Py_IDENTIFIER(name);
704 _Py_IDENTIFIER(path);
705 dict = dict ? PyDict_Copy(dict) : PyDict_New();
706 if (dict == NULL)
707 return NULL;
708 if (self->name && _PyDict_SetItemId(dict, &PyId_name, self->name) < 0) {
709 Py_DECREF(dict);
710 return NULL;
711 }
712 if (self->path && _PyDict_SetItemId(dict, &PyId_path, self->path) < 0) {
713 Py_DECREF(dict);
714 return NULL;
715 }
716 return dict;
717 }
718 else if (dict) {
719 Py_INCREF(dict);
720 return dict;
721 }
722 else {
723 Py_RETURN_NONE;
724 }
725 }
726
727 /* Pickling support */
728 static PyObject *
ImportError_reduce(PyImportErrorObject * self,PyObject * Py_UNUSED (ignored))729 ImportError_reduce(PyImportErrorObject *self, PyObject *Py_UNUSED(ignored))
730 {
731 PyObject *res;
732 PyObject *args;
733 PyObject *state = ImportError_getstate(self);
734 if (state == NULL)
735 return NULL;
736 args = ((PyBaseExceptionObject *)self)->args;
737 if (state == Py_None)
738 res = PyTuple_Pack(2, Py_TYPE(self), args);
739 else
740 res = PyTuple_Pack(3, Py_TYPE(self), args, state);
741 Py_DECREF(state);
742 return res;
743 }
744
745 static PyMemberDef ImportError_members[] = {
746 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
747 PyDoc_STR("exception message")},
748 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
749 PyDoc_STR("module name")},
750 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
751 PyDoc_STR("module path")},
752 {NULL} /* Sentinel */
753 };
754
755 static PyMethodDef ImportError_methods[] = {
756 {"__reduce__", (PyCFunction)ImportError_reduce, METH_NOARGS},
757 {NULL}
758 };
759
760 ComplexExtendsException(PyExc_Exception, ImportError,
761 ImportError, 0 /* new */,
762 ImportError_methods, ImportError_members,
763 0 /* getset */, ImportError_str,
764 "Import can't find module, or can't find name in "
765 "module.");
766
767 /*
768 * ModuleNotFoundError extends ImportError
769 */
770
771 MiddlingExtendsException(PyExc_ImportError, ModuleNotFoundError, ImportError,
772 "Module not found.");
773
774 /*
775 * OSError extends Exception
776 */
777
778 #ifdef MS_WINDOWS
779 #include "errmap.h"
780 #endif
781
782 /* Where a function has a single filename, such as open() or some
783 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
784 * called, giving a third argument which is the filename. But, so
785 * that old code using in-place unpacking doesn't break, e.g.:
786 *
787 * except OSError, (errno, strerror):
788 *
789 * we hack args so that it only contains two items. This also
790 * means we need our own __str__() which prints out the filename
791 * when it was supplied.
792 *
793 * (If a function has two filenames, such as rename(), symlink(),
794 * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
795 * which allows passing in a second filename.)
796 */
797
798 /* This function doesn't cleanup on error, the caller should */
799 static int
oserror_parse_args(PyObject ** p_args,PyObject ** myerrno,PyObject ** strerror,PyObject ** filename,PyObject ** filename2,PyObject ** winerror)800 oserror_parse_args(PyObject **p_args,
801 PyObject **myerrno, PyObject **strerror,
802 PyObject **filename, PyObject **filename2
803 #ifdef MS_WINDOWS
804 , PyObject **winerror
805 #endif
806 )
807 {
808 Py_ssize_t nargs;
809 PyObject *args = *p_args;
810 #ifndef MS_WINDOWS
811 /*
812 * ignored on non-Windows platforms,
813 * but parsed so OSError has a consistent signature
814 */
815 PyObject *_winerror = NULL;
816 PyObject **winerror = &_winerror;
817 #endif /* MS_WINDOWS */
818
819 nargs = PyTuple_GET_SIZE(args);
820
821 if (nargs >= 2 && nargs <= 5) {
822 if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
823 myerrno, strerror,
824 filename, winerror, filename2))
825 return -1;
826 #ifdef MS_WINDOWS
827 if (*winerror && PyLong_Check(*winerror)) {
828 long errcode, winerrcode;
829 PyObject *newargs;
830 Py_ssize_t i;
831
832 winerrcode = PyLong_AsLong(*winerror);
833 if (winerrcode == -1 && PyErr_Occurred())
834 return -1;
835 /* Set errno to the corresponding POSIX errno (overriding
836 first argument). Windows Socket error codes (>= 10000)
837 have the same value as their POSIX counterparts.
838 */
839 if (winerrcode < 10000)
840 errcode = winerror_to_errno(winerrcode);
841 else
842 errcode = winerrcode;
843 *myerrno = PyLong_FromLong(errcode);
844 if (!*myerrno)
845 return -1;
846 newargs = PyTuple_New(nargs);
847 if (!newargs)
848 return -1;
849 PyTuple_SET_ITEM(newargs, 0, *myerrno);
850 for (i = 1; i < nargs; i++) {
851 PyObject *val = PyTuple_GET_ITEM(args, i);
852 Py_INCREF(val);
853 PyTuple_SET_ITEM(newargs, i, val);
854 }
855 Py_DECREF(args);
856 args = *p_args = newargs;
857 }
858 #endif /* MS_WINDOWS */
859 }
860
861 return 0;
862 }
863
864 static int
oserror_init(PyOSErrorObject * self,PyObject ** p_args,PyObject * myerrno,PyObject * strerror,PyObject * filename,PyObject * filename2,PyObject * winerror)865 oserror_init(PyOSErrorObject *self, PyObject **p_args,
866 PyObject *myerrno, PyObject *strerror,
867 PyObject *filename, PyObject *filename2
868 #ifdef MS_WINDOWS
869 , PyObject *winerror
870 #endif
871 )
872 {
873 PyObject *args = *p_args;
874 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
875
876 /* self->filename will remain Py_None otherwise */
877 if (filename && filename != Py_None) {
878 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
879 PyNumber_Check(filename)) {
880 /* BlockingIOError's 3rd argument can be the number of
881 * characters written.
882 */
883 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
884 if (self->written == -1 && PyErr_Occurred())
885 return -1;
886 }
887 else {
888 Py_INCREF(filename);
889 self->filename = filename;
890
891 if (filename2 && filename2 != Py_None) {
892 Py_INCREF(filename2);
893 self->filename2 = filename2;
894 }
895
896 if (nargs >= 2 && nargs <= 5) {
897 /* filename, filename2, and winerror are removed from the args tuple
898 (for compatibility purposes, see test_exceptions.py) */
899 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
900 if (!subslice)
901 return -1;
902
903 Py_DECREF(args); /* replacing args */
904 *p_args = args = subslice;
905 }
906 }
907 }
908 Py_XINCREF(myerrno);
909 self->myerrno = myerrno;
910
911 Py_XINCREF(strerror);
912 self->strerror = strerror;
913
914 #ifdef MS_WINDOWS
915 Py_XINCREF(winerror);
916 self->winerror = winerror;
917 #endif
918
919 /* Steals the reference to args */
920 Py_XSETREF(self->args, args);
921 *p_args = args = NULL;
922
923 return 0;
924 }
925
926 static PyObject *
927 OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
928 static int
929 OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
930
931 static int
oserror_use_init(PyTypeObject * type)932 oserror_use_init(PyTypeObject *type)
933 {
934 /* When __init__ is defined in an OSError subclass, we want any
935 extraneous argument to __new__ to be ignored. The only reasonable
936 solution, given __new__ takes a variable number of arguments,
937 is to defer arg parsing and initialization to __init__.
938
939 But when __new__ is overridden as well, it should call our __new__
940 with the right arguments.
941
942 (see http://bugs.python.org/issue12555#msg148829 )
943 */
944 if (type->tp_init != (initproc) OSError_init &&
945 type->tp_new == (newfunc) OSError_new) {
946 assert((PyObject *) type != PyExc_OSError);
947 return 1;
948 }
949 return 0;
950 }
951
952 static PyObject *
OSError_new(PyTypeObject * type,PyObject * args,PyObject * kwds)953 OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
954 {
955 PyOSErrorObject *self = NULL;
956 PyObject *myerrno = NULL, *strerror = NULL;
957 PyObject *filename = NULL, *filename2 = NULL;
958 #ifdef MS_WINDOWS
959 PyObject *winerror = NULL;
960 #endif
961
962 Py_INCREF(args);
963
964 if (!oserror_use_init(type)) {
965 if (!_PyArg_NoKeywords(type->tp_name, kwds))
966 goto error;
967
968 if (oserror_parse_args(&args, &myerrno, &strerror,
969 &filename, &filename2
970 #ifdef MS_WINDOWS
971 , &winerror
972 #endif
973 ))
974 goto error;
975
976 if (myerrno && PyLong_Check(myerrno) &&
977 errnomap && (PyObject *) type == PyExc_OSError) {
978 PyObject *newtype;
979 newtype = PyDict_GetItemWithError(errnomap, myerrno);
980 if (newtype) {
981 assert(PyType_Check(newtype));
982 type = (PyTypeObject *) newtype;
983 }
984 else if (PyErr_Occurred())
985 goto error;
986 }
987 }
988
989 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
990 if (!self)
991 goto error;
992
993 self->dict = NULL;
994 self->traceback = self->cause = self->context = NULL;
995 self->written = -1;
996
997 if (!oserror_use_init(type)) {
998 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
999 #ifdef MS_WINDOWS
1000 , winerror
1001 #endif
1002 ))
1003 goto error;
1004 }
1005 else {
1006 self->args = PyTuple_New(0);
1007 if (self->args == NULL)
1008 goto error;
1009 }
1010
1011 Py_XDECREF(args);
1012 return (PyObject *) self;
1013
1014 error:
1015 Py_XDECREF(args);
1016 Py_XDECREF(self);
1017 return NULL;
1018 }
1019
1020 static int
OSError_init(PyOSErrorObject * self,PyObject * args,PyObject * kwds)1021 OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
1022 {
1023 PyObject *myerrno = NULL, *strerror = NULL;
1024 PyObject *filename = NULL, *filename2 = NULL;
1025 #ifdef MS_WINDOWS
1026 PyObject *winerror = NULL;
1027 #endif
1028
1029 if (!oserror_use_init(Py_TYPE(self)))
1030 /* Everything already done in OSError_new */
1031 return 0;
1032
1033 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
1034 return -1;
1035
1036 Py_INCREF(args);
1037 if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
1038 #ifdef MS_WINDOWS
1039 , &winerror
1040 #endif
1041 ))
1042 goto error;
1043
1044 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
1045 #ifdef MS_WINDOWS
1046 , winerror
1047 #endif
1048 ))
1049 goto error;
1050
1051 return 0;
1052
1053 error:
1054 Py_DECREF(args);
1055 return -1;
1056 }
1057
1058 static int
OSError_clear(PyOSErrorObject * self)1059 OSError_clear(PyOSErrorObject *self)
1060 {
1061 Py_CLEAR(self->myerrno);
1062 Py_CLEAR(self->strerror);
1063 Py_CLEAR(self->filename);
1064 Py_CLEAR(self->filename2);
1065 #ifdef MS_WINDOWS
1066 Py_CLEAR(self->winerror);
1067 #endif
1068 return BaseException_clear((PyBaseExceptionObject *)self);
1069 }
1070
1071 static void
OSError_dealloc(PyOSErrorObject * self)1072 OSError_dealloc(PyOSErrorObject *self)
1073 {
1074 _PyObject_GC_UNTRACK(self);
1075 OSError_clear(self);
1076 Py_TYPE(self)->tp_free((PyObject *)self);
1077 }
1078
1079 static int
OSError_traverse(PyOSErrorObject * self,visitproc visit,void * arg)1080 OSError_traverse(PyOSErrorObject *self, visitproc visit,
1081 void *arg)
1082 {
1083 Py_VISIT(self->myerrno);
1084 Py_VISIT(self->strerror);
1085 Py_VISIT(self->filename);
1086 Py_VISIT(self->filename2);
1087 #ifdef MS_WINDOWS
1088 Py_VISIT(self->winerror);
1089 #endif
1090 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1091 }
1092
1093 static PyObject *
OSError_str(PyOSErrorObject * self)1094 OSError_str(PyOSErrorObject *self)
1095 {
1096 #define OR_NONE(x) ((x)?(x):Py_None)
1097 #ifdef MS_WINDOWS
1098 /* If available, winerror has the priority over myerrno */
1099 if (self->winerror && self->filename) {
1100 if (self->filename2) {
1101 return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
1102 OR_NONE(self->winerror),
1103 OR_NONE(self->strerror),
1104 self->filename,
1105 self->filename2);
1106 } else {
1107 return PyUnicode_FromFormat("[WinError %S] %S: %R",
1108 OR_NONE(self->winerror),
1109 OR_NONE(self->strerror),
1110 self->filename);
1111 }
1112 }
1113 if (self->winerror && self->strerror)
1114 return PyUnicode_FromFormat("[WinError %S] %S",
1115 self->winerror ? self->winerror: Py_None,
1116 self->strerror ? self->strerror: Py_None);
1117 #endif
1118 if (self->filename) {
1119 if (self->filename2) {
1120 return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
1121 OR_NONE(self->myerrno),
1122 OR_NONE(self->strerror),
1123 self->filename,
1124 self->filename2);
1125 } else {
1126 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1127 OR_NONE(self->myerrno),
1128 OR_NONE(self->strerror),
1129 self->filename);
1130 }
1131 }
1132 if (self->myerrno && self->strerror)
1133 return PyUnicode_FromFormat("[Errno %S] %S",
1134 self->myerrno, self->strerror);
1135 return BaseException_str((PyBaseExceptionObject *)self);
1136 }
1137
1138 static PyObject *
OSError_reduce(PyOSErrorObject * self,PyObject * Py_UNUSED (ignored))1139 OSError_reduce(PyOSErrorObject *self, PyObject *Py_UNUSED(ignored))
1140 {
1141 PyObject *args = self->args;
1142 PyObject *res = NULL, *tmp;
1143
1144 /* self->args is only the first two real arguments if there was a
1145 * file name given to OSError. */
1146 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
1147 Py_ssize_t size = self->filename2 ? 5 : 3;
1148 args = PyTuple_New(size);
1149 if (!args)
1150 return NULL;
1151
1152 tmp = PyTuple_GET_ITEM(self->args, 0);
1153 Py_INCREF(tmp);
1154 PyTuple_SET_ITEM(args, 0, tmp);
1155
1156 tmp = PyTuple_GET_ITEM(self->args, 1);
1157 Py_INCREF(tmp);
1158 PyTuple_SET_ITEM(args, 1, tmp);
1159
1160 Py_INCREF(self->filename);
1161 PyTuple_SET_ITEM(args, 2, self->filename);
1162
1163 if (self->filename2) {
1164 /*
1165 * This tuple is essentially used as OSError(*args).
1166 * So, to recreate filename2, we need to pass in
1167 * winerror as well.
1168 */
1169 Py_INCREF(Py_None);
1170 PyTuple_SET_ITEM(args, 3, Py_None);
1171
1172 /* filename2 */
1173 Py_INCREF(self->filename2);
1174 PyTuple_SET_ITEM(args, 4, self->filename2);
1175 }
1176 } else
1177 Py_INCREF(args);
1178
1179 if (self->dict)
1180 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
1181 else
1182 res = PyTuple_Pack(2, Py_TYPE(self), args);
1183 Py_DECREF(args);
1184 return res;
1185 }
1186
1187 static PyObject *
OSError_written_get(PyOSErrorObject * self,void * context)1188 OSError_written_get(PyOSErrorObject *self, void *context)
1189 {
1190 if (self->written == -1) {
1191 PyErr_SetString(PyExc_AttributeError, "characters_written");
1192 return NULL;
1193 }
1194 return PyLong_FromSsize_t(self->written);
1195 }
1196
1197 static int
OSError_written_set(PyOSErrorObject * self,PyObject * arg,void * context)1198 OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1199 {
1200 if (arg == NULL) {
1201 if (self->written == -1) {
1202 PyErr_SetString(PyExc_AttributeError, "characters_written");
1203 return -1;
1204 }
1205 self->written = -1;
1206 return 0;
1207 }
1208 Py_ssize_t n;
1209 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1210 if (n == -1 && PyErr_Occurred())
1211 return -1;
1212 self->written = n;
1213 return 0;
1214 }
1215
1216 static PyMemberDef OSError_members[] = {
1217 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1218 PyDoc_STR("POSIX exception code")},
1219 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1220 PyDoc_STR("exception strerror")},
1221 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1222 PyDoc_STR("exception filename")},
1223 {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
1224 PyDoc_STR("second exception filename")},
1225 #ifdef MS_WINDOWS
1226 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1227 PyDoc_STR("Win32 exception code")},
1228 #endif
1229 {NULL} /* Sentinel */
1230 };
1231
1232 static PyMethodDef OSError_methods[] = {
1233 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
1234 {NULL}
1235 };
1236
1237 static PyGetSetDef OSError_getset[] = {
1238 {"characters_written", (getter) OSError_written_get,
1239 (setter) OSError_written_set, NULL},
1240 {NULL}
1241 };
1242
1243
1244 ComplexExtendsException(PyExc_Exception, OSError,
1245 OSError, OSError_new,
1246 OSError_methods, OSError_members, OSError_getset,
1247 OSError_str,
1248 "Base class for I/O related errors.");
1249
1250
1251 /*
1252 * Various OSError subclasses
1253 */
1254 MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1255 "I/O operation would block.");
1256 MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1257 "Connection error.");
1258 MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1259 "Child process error.");
1260 MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1261 "Broken pipe.");
1262 MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1263 "Connection aborted.");
1264 MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1265 "Connection refused.");
1266 MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1267 "Connection reset.");
1268 MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1269 "File already exists.");
1270 MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1271 "File not found.");
1272 MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1273 "Operation doesn't work on directories.");
1274 MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1275 "Operation only works on directories.");
1276 MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1277 "Interrupted by signal.");
1278 MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1279 "Not enough permissions.");
1280 MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1281 "Process not found.");
1282 MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1283 "Timeout expired.");
1284
1285 /*
1286 * EOFError extends Exception
1287 */
1288 SimpleExtendsException(PyExc_Exception, EOFError,
1289 "Read beyond end of file.");
1290
1291
1292 /*
1293 * RuntimeError extends Exception
1294 */
1295 SimpleExtendsException(PyExc_Exception, RuntimeError,
1296 "Unspecified run-time error.");
1297
1298 /*
1299 * RecursionError extends RuntimeError
1300 */
1301 SimpleExtendsException(PyExc_RuntimeError, RecursionError,
1302 "Recursion limit exceeded.");
1303
1304 /*
1305 * NotImplementedError extends RuntimeError
1306 */
1307 SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1308 "Method or function hasn't been implemented yet.");
1309
1310 /*
1311 * NameError extends Exception
1312 */
1313 SimpleExtendsException(PyExc_Exception, NameError,
1314 "Name not found globally.");
1315
1316 /*
1317 * UnboundLocalError extends NameError
1318 */
1319 SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1320 "Local name referenced but not bound to a value.");
1321
1322 /*
1323 * AttributeError extends Exception
1324 */
1325 SimpleExtendsException(PyExc_Exception, AttributeError,
1326 "Attribute not found.");
1327
1328
1329 /*
1330 * SyntaxError extends Exception
1331 */
1332
1333 /* Helper function to customize error message for some syntax errors */
1334 static int _report_missing_parentheses(PySyntaxErrorObject *self);
1335
1336 static int
SyntaxError_init(PySyntaxErrorObject * self,PyObject * args,PyObject * kwds)1337 SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1338 {
1339 PyObject *info = NULL;
1340 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1341
1342 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1343 return -1;
1344
1345 if (lenargs >= 1) {
1346 Py_INCREF(PyTuple_GET_ITEM(args, 0));
1347 Py_XSETREF(self->msg, PyTuple_GET_ITEM(args, 0));
1348 }
1349 if (lenargs == 2) {
1350 info = PyTuple_GET_ITEM(args, 1);
1351 info = PySequence_Tuple(info);
1352 if (!info)
1353 return -1;
1354
1355 if (PyTuple_GET_SIZE(info) != 4) {
1356 /* not a very good error message, but it's what Python 2.4 gives */
1357 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1358 Py_DECREF(info);
1359 return -1;
1360 }
1361
1362 Py_INCREF(PyTuple_GET_ITEM(info, 0));
1363 Py_XSETREF(self->filename, PyTuple_GET_ITEM(info, 0));
1364
1365 Py_INCREF(PyTuple_GET_ITEM(info, 1));
1366 Py_XSETREF(self->lineno, PyTuple_GET_ITEM(info, 1));
1367
1368 Py_INCREF(PyTuple_GET_ITEM(info, 2));
1369 Py_XSETREF(self->offset, PyTuple_GET_ITEM(info, 2));
1370
1371 Py_INCREF(PyTuple_GET_ITEM(info, 3));
1372 Py_XSETREF(self->text, PyTuple_GET_ITEM(info, 3));
1373
1374 Py_DECREF(info);
1375
1376 /*
1377 * Issue #21669: Custom error for 'print' & 'exec' as statements
1378 *
1379 * Only applies to SyntaxError instances, not to subclasses such
1380 * as TabError or IndentationError (see issue #31161)
1381 */
1382 if ((PyObject*)Py_TYPE(self) == PyExc_SyntaxError &&
1383 self->text && PyUnicode_Check(self->text) &&
1384 _report_missing_parentheses(self) < 0) {
1385 return -1;
1386 }
1387 }
1388 return 0;
1389 }
1390
1391 static int
SyntaxError_clear(PySyntaxErrorObject * self)1392 SyntaxError_clear(PySyntaxErrorObject *self)
1393 {
1394 Py_CLEAR(self->msg);
1395 Py_CLEAR(self->filename);
1396 Py_CLEAR(self->lineno);
1397 Py_CLEAR(self->offset);
1398 Py_CLEAR(self->text);
1399 Py_CLEAR(self->print_file_and_line);
1400 return BaseException_clear((PyBaseExceptionObject *)self);
1401 }
1402
1403 static void
SyntaxError_dealloc(PySyntaxErrorObject * self)1404 SyntaxError_dealloc(PySyntaxErrorObject *self)
1405 {
1406 _PyObject_GC_UNTRACK(self);
1407 SyntaxError_clear(self);
1408 Py_TYPE(self)->tp_free((PyObject *)self);
1409 }
1410
1411 static int
SyntaxError_traverse(PySyntaxErrorObject * self,visitproc visit,void * arg)1412 SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1413 {
1414 Py_VISIT(self->msg);
1415 Py_VISIT(self->filename);
1416 Py_VISIT(self->lineno);
1417 Py_VISIT(self->offset);
1418 Py_VISIT(self->text);
1419 Py_VISIT(self->print_file_and_line);
1420 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1421 }
1422
1423 /* This is called "my_basename" instead of just "basename" to avoid name
1424 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1425 defined, and Python does define that. */
1426 static PyObject*
my_basename(PyObject * name)1427 my_basename(PyObject *name)
1428 {
1429 Py_ssize_t i, size, offset;
1430 int kind;
1431 void *data;
1432
1433 if (PyUnicode_READY(name))
1434 return NULL;
1435 kind = PyUnicode_KIND(name);
1436 data = PyUnicode_DATA(name);
1437 size = PyUnicode_GET_LENGTH(name);
1438 offset = 0;
1439 for(i=0; i < size; i++) {
1440 if (PyUnicode_READ(kind, data, i) == SEP)
1441 offset = i + 1;
1442 }
1443 if (offset != 0)
1444 return PyUnicode_Substring(name, offset, size);
1445 else {
1446 Py_INCREF(name);
1447 return name;
1448 }
1449 }
1450
1451
1452 static PyObject *
SyntaxError_str(PySyntaxErrorObject * self)1453 SyntaxError_str(PySyntaxErrorObject *self)
1454 {
1455 int have_lineno = 0;
1456 PyObject *filename;
1457 PyObject *result;
1458 /* Below, we always ignore overflow errors, just printing -1.
1459 Still, we cannot allow an OverflowError to be raised, so
1460 we need to call PyLong_AsLongAndOverflow. */
1461 int overflow;
1462
1463 /* XXX -- do all the additional formatting with filename and
1464 lineno here */
1465
1466 if (self->filename && PyUnicode_Check(self->filename)) {
1467 filename = my_basename(self->filename);
1468 if (filename == NULL)
1469 return NULL;
1470 } else {
1471 filename = NULL;
1472 }
1473 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
1474
1475 if (!filename && !have_lineno)
1476 return PyObject_Str(self->msg ? self->msg : Py_None);
1477
1478 if (filename && have_lineno)
1479 result = PyUnicode_FromFormat("%S (%U, line %ld)",
1480 self->msg ? self->msg : Py_None,
1481 filename,
1482 PyLong_AsLongAndOverflow(self->lineno, &overflow));
1483 else if (filename)
1484 result = PyUnicode_FromFormat("%S (%U)",
1485 self->msg ? self->msg : Py_None,
1486 filename);
1487 else /* only have_lineno */
1488 result = PyUnicode_FromFormat("%S (line %ld)",
1489 self->msg ? self->msg : Py_None,
1490 PyLong_AsLongAndOverflow(self->lineno, &overflow));
1491 Py_XDECREF(filename);
1492 return result;
1493 }
1494
1495 static PyMemberDef SyntaxError_members[] = {
1496 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1497 PyDoc_STR("exception msg")},
1498 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1499 PyDoc_STR("exception filename")},
1500 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1501 PyDoc_STR("exception lineno")},
1502 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1503 PyDoc_STR("exception offset")},
1504 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1505 PyDoc_STR("exception text")},
1506 {"print_file_and_line", T_OBJECT,
1507 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1508 PyDoc_STR("exception print_file_and_line")},
1509 {NULL} /* Sentinel */
1510 };
1511
1512 ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
1513 0, 0, SyntaxError_members, 0,
1514 SyntaxError_str, "Invalid syntax.");
1515
1516
1517 /*
1518 * IndentationError extends SyntaxError
1519 */
1520 MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1521 "Improper indentation.");
1522
1523
1524 /*
1525 * TabError extends IndentationError
1526 */
1527 MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1528 "Improper mixture of spaces and tabs.");
1529
1530
1531 /*
1532 * LookupError extends Exception
1533 */
1534 SimpleExtendsException(PyExc_Exception, LookupError,
1535 "Base class for lookup errors.");
1536
1537
1538 /*
1539 * IndexError extends LookupError
1540 */
1541 SimpleExtendsException(PyExc_LookupError, IndexError,
1542 "Sequence index out of range.");
1543
1544
1545 /*
1546 * KeyError extends LookupError
1547 */
1548 static PyObject *
KeyError_str(PyBaseExceptionObject * self)1549 KeyError_str(PyBaseExceptionObject *self)
1550 {
1551 /* If args is a tuple of exactly one item, apply repr to args[0].
1552 This is done so that e.g. the exception raised by {}[''] prints
1553 KeyError: ''
1554 rather than the confusing
1555 KeyError
1556 alone. The downside is that if KeyError is raised with an explanatory
1557 string, that string will be displayed in quotes. Too bad.
1558 If args is anything else, use the default BaseException__str__().
1559 */
1560 if (PyTuple_GET_SIZE(self->args) == 1) {
1561 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
1562 }
1563 return BaseException_str(self);
1564 }
1565
1566 ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
1567 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
1568
1569
1570 /*
1571 * ValueError extends Exception
1572 */
1573 SimpleExtendsException(PyExc_Exception, ValueError,
1574 "Inappropriate argument value (of correct type).");
1575
1576 /*
1577 * UnicodeError extends ValueError
1578 */
1579
1580 SimpleExtendsException(PyExc_ValueError, UnicodeError,
1581 "Unicode related error.");
1582
1583 static PyObject *
get_string(PyObject * attr,const char * name)1584 get_string(PyObject *attr, const char *name)
1585 {
1586 if (!attr) {
1587 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1588 return NULL;
1589 }
1590
1591 if (!PyBytes_Check(attr)) {
1592 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1593 return NULL;
1594 }
1595 Py_INCREF(attr);
1596 return attr;
1597 }
1598
1599 static PyObject *
get_unicode(PyObject * attr,const char * name)1600 get_unicode(PyObject *attr, const char *name)
1601 {
1602 if (!attr) {
1603 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1604 return NULL;
1605 }
1606
1607 if (!PyUnicode_Check(attr)) {
1608 PyErr_Format(PyExc_TypeError,
1609 "%.200s attribute must be unicode", name);
1610 return NULL;
1611 }
1612 Py_INCREF(attr);
1613 return attr;
1614 }
1615
1616 static int
set_unicodefromstring(PyObject ** attr,const char * value)1617 set_unicodefromstring(PyObject **attr, const char *value)
1618 {
1619 PyObject *obj = PyUnicode_FromString(value);
1620 if (!obj)
1621 return -1;
1622 Py_XSETREF(*attr, obj);
1623 return 0;
1624 }
1625
1626 PyObject *
PyUnicodeEncodeError_GetEncoding(PyObject * exc)1627 PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1628 {
1629 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
1630 }
1631
1632 PyObject *
PyUnicodeDecodeError_GetEncoding(PyObject * exc)1633 PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1634 {
1635 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
1636 }
1637
1638 PyObject *
PyUnicodeEncodeError_GetObject(PyObject * exc)1639 PyUnicodeEncodeError_GetObject(PyObject *exc)
1640 {
1641 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1642 }
1643
1644 PyObject *
PyUnicodeDecodeError_GetObject(PyObject * exc)1645 PyUnicodeDecodeError_GetObject(PyObject *exc)
1646 {
1647 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
1648 }
1649
1650 PyObject *
PyUnicodeTranslateError_GetObject(PyObject * exc)1651 PyUnicodeTranslateError_GetObject(PyObject *exc)
1652 {
1653 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1654 }
1655
1656 int
PyUnicodeEncodeError_GetStart(PyObject * exc,Py_ssize_t * start)1657 PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1658 {
1659 Py_ssize_t size;
1660 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1661 "object");
1662 if (!obj)
1663 return -1;
1664 *start = ((PyUnicodeErrorObject *)exc)->start;
1665 size = PyUnicode_GET_LENGTH(obj);
1666 if (*start<0)
1667 *start = 0; /*XXX check for values <0*/
1668 if (*start>=size)
1669 *start = size-1;
1670 Py_DECREF(obj);
1671 return 0;
1672 }
1673
1674
1675 int
PyUnicodeDecodeError_GetStart(PyObject * exc,Py_ssize_t * start)1676 PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1677 {
1678 Py_ssize_t size;
1679 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
1680 if (!obj)
1681 return -1;
1682 size = PyBytes_GET_SIZE(obj);
1683 *start = ((PyUnicodeErrorObject *)exc)->start;
1684 if (*start<0)
1685 *start = 0;
1686 if (*start>=size)
1687 *start = size-1;
1688 Py_DECREF(obj);
1689 return 0;
1690 }
1691
1692
1693 int
PyUnicodeTranslateError_GetStart(PyObject * exc,Py_ssize_t * start)1694 PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1695 {
1696 return PyUnicodeEncodeError_GetStart(exc, start);
1697 }
1698
1699
1700 int
PyUnicodeEncodeError_SetStart(PyObject * exc,Py_ssize_t start)1701 PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1702 {
1703 ((PyUnicodeErrorObject *)exc)->start = start;
1704 return 0;
1705 }
1706
1707
1708 int
PyUnicodeDecodeError_SetStart(PyObject * exc,Py_ssize_t start)1709 PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1710 {
1711 ((PyUnicodeErrorObject *)exc)->start = start;
1712 return 0;
1713 }
1714
1715
1716 int
PyUnicodeTranslateError_SetStart(PyObject * exc,Py_ssize_t start)1717 PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1718 {
1719 ((PyUnicodeErrorObject *)exc)->start = start;
1720 return 0;
1721 }
1722
1723
1724 int
PyUnicodeEncodeError_GetEnd(PyObject * exc,Py_ssize_t * end)1725 PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1726 {
1727 Py_ssize_t size;
1728 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1729 "object");
1730 if (!obj)
1731 return -1;
1732 *end = ((PyUnicodeErrorObject *)exc)->end;
1733 size = PyUnicode_GET_LENGTH(obj);
1734 if (*end<1)
1735 *end = 1;
1736 if (*end>size)
1737 *end = size;
1738 Py_DECREF(obj);
1739 return 0;
1740 }
1741
1742
1743 int
PyUnicodeDecodeError_GetEnd(PyObject * exc,Py_ssize_t * end)1744 PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1745 {
1746 Py_ssize_t size;
1747 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
1748 if (!obj)
1749 return -1;
1750 size = PyBytes_GET_SIZE(obj);
1751 *end = ((PyUnicodeErrorObject *)exc)->end;
1752 if (*end<1)
1753 *end = 1;
1754 if (*end>size)
1755 *end = size;
1756 Py_DECREF(obj);
1757 return 0;
1758 }
1759
1760
1761 int
PyUnicodeTranslateError_GetEnd(PyObject * exc,Py_ssize_t * end)1762 PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
1763 {
1764 return PyUnicodeEncodeError_GetEnd(exc, end);
1765 }
1766
1767
1768 int
PyUnicodeEncodeError_SetEnd(PyObject * exc,Py_ssize_t end)1769 PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1770 {
1771 ((PyUnicodeErrorObject *)exc)->end = end;
1772 return 0;
1773 }
1774
1775
1776 int
PyUnicodeDecodeError_SetEnd(PyObject * exc,Py_ssize_t end)1777 PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1778 {
1779 ((PyUnicodeErrorObject *)exc)->end = end;
1780 return 0;
1781 }
1782
1783
1784 int
PyUnicodeTranslateError_SetEnd(PyObject * exc,Py_ssize_t end)1785 PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1786 {
1787 ((PyUnicodeErrorObject *)exc)->end = end;
1788 return 0;
1789 }
1790
1791 PyObject *
PyUnicodeEncodeError_GetReason(PyObject * exc)1792 PyUnicodeEncodeError_GetReason(PyObject *exc)
1793 {
1794 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
1795 }
1796
1797
1798 PyObject *
PyUnicodeDecodeError_GetReason(PyObject * exc)1799 PyUnicodeDecodeError_GetReason(PyObject *exc)
1800 {
1801 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
1802 }
1803
1804
1805 PyObject *
PyUnicodeTranslateError_GetReason(PyObject * exc)1806 PyUnicodeTranslateError_GetReason(PyObject *exc)
1807 {
1808 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
1809 }
1810
1811
1812 int
PyUnicodeEncodeError_SetReason(PyObject * exc,const char * reason)1813 PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1814 {
1815 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1816 reason);
1817 }
1818
1819
1820 int
PyUnicodeDecodeError_SetReason(PyObject * exc,const char * reason)1821 PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1822 {
1823 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1824 reason);
1825 }
1826
1827
1828 int
PyUnicodeTranslateError_SetReason(PyObject * exc,const char * reason)1829 PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1830 {
1831 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1832 reason);
1833 }
1834
1835
1836 static int
UnicodeError_clear(PyUnicodeErrorObject * self)1837 UnicodeError_clear(PyUnicodeErrorObject *self)
1838 {
1839 Py_CLEAR(self->encoding);
1840 Py_CLEAR(self->object);
1841 Py_CLEAR(self->reason);
1842 return BaseException_clear((PyBaseExceptionObject *)self);
1843 }
1844
1845 static void
UnicodeError_dealloc(PyUnicodeErrorObject * self)1846 UnicodeError_dealloc(PyUnicodeErrorObject *self)
1847 {
1848 _PyObject_GC_UNTRACK(self);
1849 UnicodeError_clear(self);
1850 Py_TYPE(self)->tp_free((PyObject *)self);
1851 }
1852
1853 static int
UnicodeError_traverse(PyUnicodeErrorObject * self,visitproc visit,void * arg)1854 UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1855 {
1856 Py_VISIT(self->encoding);
1857 Py_VISIT(self->object);
1858 Py_VISIT(self->reason);
1859 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1860 }
1861
1862 static PyMemberDef UnicodeError_members[] = {
1863 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1864 PyDoc_STR("exception encoding")},
1865 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1866 PyDoc_STR("exception object")},
1867 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
1868 PyDoc_STR("exception start")},
1869 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
1870 PyDoc_STR("exception end")},
1871 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1872 PyDoc_STR("exception reason")},
1873 {NULL} /* Sentinel */
1874 };
1875
1876
1877 /*
1878 * UnicodeEncodeError extends UnicodeError
1879 */
1880
1881 static int
UnicodeEncodeError_init(PyObject * self,PyObject * args,PyObject * kwds)1882 UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1883 {
1884 PyUnicodeErrorObject *err;
1885
1886 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1887 return -1;
1888
1889 err = (PyUnicodeErrorObject *)self;
1890
1891 Py_CLEAR(err->encoding);
1892 Py_CLEAR(err->object);
1893 Py_CLEAR(err->reason);
1894
1895 if (!PyArg_ParseTuple(args, "UUnnU",
1896 &err->encoding, &err->object,
1897 &err->start, &err->end, &err->reason)) {
1898 err->encoding = err->object = err->reason = NULL;
1899 return -1;
1900 }
1901
1902 Py_INCREF(err->encoding);
1903 Py_INCREF(err->object);
1904 Py_INCREF(err->reason);
1905
1906 return 0;
1907 }
1908
1909 static PyObject *
UnicodeEncodeError_str(PyObject * self)1910 UnicodeEncodeError_str(PyObject *self)
1911 {
1912 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
1913 PyObject *result = NULL;
1914 PyObject *reason_str = NULL;
1915 PyObject *encoding_str = NULL;
1916
1917 if (!uself->object)
1918 /* Not properly initialized. */
1919 return PyUnicode_FromString("");
1920
1921 /* Get reason and encoding as strings, which they might not be if
1922 they've been modified after we were constructed. */
1923 reason_str = PyObject_Str(uself->reason);
1924 if (reason_str == NULL)
1925 goto done;
1926 encoding_str = PyObject_Str(uself->encoding);
1927 if (encoding_str == NULL)
1928 goto done;
1929
1930 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1931 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
1932 const char *fmt;
1933 if (badchar <= 0xff)
1934 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
1935 else if (badchar <= 0xffff)
1936 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
1937 else
1938 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
1939 result = PyUnicode_FromFormat(
1940 fmt,
1941 encoding_str,
1942 (int)badchar,
1943 uself->start,
1944 reason_str);
1945 }
1946 else {
1947 result = PyUnicode_FromFormat(
1948 "'%U' codec can't encode characters in position %zd-%zd: %U",
1949 encoding_str,
1950 uself->start,
1951 uself->end-1,
1952 reason_str);
1953 }
1954 done:
1955 Py_XDECREF(reason_str);
1956 Py_XDECREF(encoding_str);
1957 return result;
1958 }
1959
1960 static PyTypeObject _PyExc_UnicodeEncodeError = {
1961 PyVarObject_HEAD_INIT(NULL, 0)
1962 "UnicodeEncodeError",
1963 sizeof(PyUnicodeErrorObject), 0,
1964 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1965 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1966 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1967 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1968 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
1969 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
1970 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
1971 };
1972 PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1973
1974 PyObject *
PyUnicodeEncodeError_Create(const char * encoding,const Py_UNICODE * object,Py_ssize_t length,Py_ssize_t start,Py_ssize_t end,const char * reason)1975 PyUnicodeEncodeError_Create(
1976 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1977 Py_ssize_t start, Py_ssize_t end, const char *reason)
1978 {
1979 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
1980 encoding, object, length, start, end, reason);
1981 }
1982
1983
1984 /*
1985 * UnicodeDecodeError extends UnicodeError
1986 */
1987
1988 static int
UnicodeDecodeError_init(PyObject * self,PyObject * args,PyObject * kwds)1989 UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1990 {
1991 PyUnicodeErrorObject *ude;
1992
1993 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1994 return -1;
1995
1996 ude = (PyUnicodeErrorObject *)self;
1997
1998 Py_CLEAR(ude->encoding);
1999 Py_CLEAR(ude->object);
2000 Py_CLEAR(ude->reason);
2001
2002 if (!PyArg_ParseTuple(args, "UOnnU",
2003 &ude->encoding, &ude->object,
2004 &ude->start, &ude->end, &ude->reason)) {
2005 ude->encoding = ude->object = ude->reason = NULL;
2006 return -1;
2007 }
2008
2009 Py_INCREF(ude->encoding);
2010 Py_INCREF(ude->object);
2011 Py_INCREF(ude->reason);
2012
2013 if (!PyBytes_Check(ude->object)) {
2014 Py_buffer view;
2015 if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
2016 goto error;
2017 Py_XSETREF(ude->object, PyBytes_FromStringAndSize(view.buf, view.len));
2018 PyBuffer_Release(&view);
2019 if (!ude->object)
2020 goto error;
2021 }
2022 return 0;
2023
2024 error:
2025 Py_CLEAR(ude->encoding);
2026 Py_CLEAR(ude->object);
2027 Py_CLEAR(ude->reason);
2028 return -1;
2029 }
2030
2031 static PyObject *
UnicodeDecodeError_str(PyObject * self)2032 UnicodeDecodeError_str(PyObject *self)
2033 {
2034 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
2035 PyObject *result = NULL;
2036 PyObject *reason_str = NULL;
2037 PyObject *encoding_str = NULL;
2038
2039 if (!uself->object)
2040 /* Not properly initialized. */
2041 return PyUnicode_FromString("");
2042
2043 /* Get reason and encoding as strings, which they might not be if
2044 they've been modified after we were constructed. */
2045 reason_str = PyObject_Str(uself->reason);
2046 if (reason_str == NULL)
2047 goto done;
2048 encoding_str = PyObject_Str(uself->encoding);
2049 if (encoding_str == NULL)
2050 goto done;
2051
2052 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
2053 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
2054 result = PyUnicode_FromFormat(
2055 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
2056 encoding_str,
2057 byte,
2058 uself->start,
2059 reason_str);
2060 }
2061 else {
2062 result = PyUnicode_FromFormat(
2063 "'%U' codec can't decode bytes in position %zd-%zd: %U",
2064 encoding_str,
2065 uself->start,
2066 uself->end-1,
2067 reason_str
2068 );
2069 }
2070 done:
2071 Py_XDECREF(reason_str);
2072 Py_XDECREF(encoding_str);
2073 return result;
2074 }
2075
2076 static PyTypeObject _PyExc_UnicodeDecodeError = {
2077 PyVarObject_HEAD_INIT(NULL, 0)
2078 "UnicodeDecodeError",
2079 sizeof(PyUnicodeErrorObject), 0,
2080 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2081 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
2082 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2083 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
2084 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2085 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
2086 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
2087 };
2088 PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
2089
2090 PyObject *
PyUnicodeDecodeError_Create(const char * encoding,const char * object,Py_ssize_t length,Py_ssize_t start,Py_ssize_t end,const char * reason)2091 PyUnicodeDecodeError_Create(
2092 const char *encoding, const char *object, Py_ssize_t length,
2093 Py_ssize_t start, Py_ssize_t end, const char *reason)
2094 {
2095 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
2096 encoding, object, length, start, end, reason);
2097 }
2098
2099
2100 /*
2101 * UnicodeTranslateError extends UnicodeError
2102 */
2103
2104 static int
UnicodeTranslateError_init(PyUnicodeErrorObject * self,PyObject * args,PyObject * kwds)2105 UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
2106 PyObject *kwds)
2107 {
2108 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2109 return -1;
2110
2111 Py_CLEAR(self->object);
2112 Py_CLEAR(self->reason);
2113
2114 if (!PyArg_ParseTuple(args, "UnnU",
2115 &self->object,
2116 &self->start, &self->end, &self->reason)) {
2117 self->object = self->reason = NULL;
2118 return -1;
2119 }
2120
2121 Py_INCREF(self->object);
2122 Py_INCREF(self->reason);
2123
2124 return 0;
2125 }
2126
2127
2128 static PyObject *
UnicodeTranslateError_str(PyObject * self)2129 UnicodeTranslateError_str(PyObject *self)
2130 {
2131 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
2132 PyObject *result = NULL;
2133 PyObject *reason_str = NULL;
2134
2135 if (!uself->object)
2136 /* Not properly initialized. */
2137 return PyUnicode_FromString("");
2138
2139 /* Get reason as a string, which it might not be if it's been
2140 modified after we were constructed. */
2141 reason_str = PyObject_Str(uself->reason);
2142 if (reason_str == NULL)
2143 goto done;
2144
2145 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2146 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
2147 const char *fmt;
2148 if (badchar <= 0xff)
2149 fmt = "can't translate character '\\x%02x' in position %zd: %U";
2150 else if (badchar <= 0xffff)
2151 fmt = "can't translate character '\\u%04x' in position %zd: %U";
2152 else
2153 fmt = "can't translate character '\\U%08x' in position %zd: %U";
2154 result = PyUnicode_FromFormat(
2155 fmt,
2156 (int)badchar,
2157 uself->start,
2158 reason_str
2159 );
2160 } else {
2161 result = PyUnicode_FromFormat(
2162 "can't translate characters in position %zd-%zd: %U",
2163 uself->start,
2164 uself->end-1,
2165 reason_str
2166 );
2167 }
2168 done:
2169 Py_XDECREF(reason_str);
2170 return result;
2171 }
2172
2173 static PyTypeObject _PyExc_UnicodeTranslateError = {
2174 PyVarObject_HEAD_INIT(NULL, 0)
2175 "UnicodeTranslateError",
2176 sizeof(PyUnicodeErrorObject), 0,
2177 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2178 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2179 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2180 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
2181 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2182 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
2183 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
2184 };
2185 PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2186
2187 /* Deprecated. */
2188 PyObject *
PyUnicodeTranslateError_Create(const Py_UNICODE * object,Py_ssize_t length,Py_ssize_t start,Py_ssize_t end,const char * reason)2189 PyUnicodeTranslateError_Create(
2190 const Py_UNICODE *object, Py_ssize_t length,
2191 Py_ssize_t start, Py_ssize_t end, const char *reason)
2192 {
2193 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
2194 object, length, start, end, reason);
2195 }
2196
2197 PyObject *
_PyUnicodeTranslateError_Create(PyObject * object,Py_ssize_t start,Py_ssize_t end,const char * reason)2198 _PyUnicodeTranslateError_Create(
2199 PyObject *object,
2200 Py_ssize_t start, Py_ssize_t end, const char *reason)
2201 {
2202 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
2203 object, start, end, reason);
2204 }
2205
2206 /*
2207 * AssertionError extends Exception
2208 */
2209 SimpleExtendsException(PyExc_Exception, AssertionError,
2210 "Assertion failed.");
2211
2212
2213 /*
2214 * ArithmeticError extends Exception
2215 */
2216 SimpleExtendsException(PyExc_Exception, ArithmeticError,
2217 "Base class for arithmetic errors.");
2218
2219
2220 /*
2221 * FloatingPointError extends ArithmeticError
2222 */
2223 SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2224 "Floating point operation failed.");
2225
2226
2227 /*
2228 * OverflowError extends ArithmeticError
2229 */
2230 SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2231 "Result too large to be represented.");
2232
2233
2234 /*
2235 * ZeroDivisionError extends ArithmeticError
2236 */
2237 SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2238 "Second argument to a division or modulo operation was zero.");
2239
2240
2241 /*
2242 * SystemError extends Exception
2243 */
2244 SimpleExtendsException(PyExc_Exception, SystemError,
2245 "Internal error in the Python interpreter.\n"
2246 "\n"
2247 "Please report this to the Python maintainer, along with the traceback,\n"
2248 "the Python version, and the hardware/OS platform and version.");
2249
2250
2251 /*
2252 * ReferenceError extends Exception
2253 */
2254 SimpleExtendsException(PyExc_Exception, ReferenceError,
2255 "Weak ref proxy used after referent went away.");
2256
2257
2258 /*
2259 * MemoryError extends Exception
2260 */
2261
2262 #define MEMERRORS_SAVE 16
2263 static PyBaseExceptionObject *memerrors_freelist = NULL;
2264 static int memerrors_numfree = 0;
2265
2266 static PyObject *
MemoryError_new(PyTypeObject * type,PyObject * args,PyObject * kwds)2267 MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2268 {
2269 PyBaseExceptionObject *self;
2270
2271 if (type != (PyTypeObject *) PyExc_MemoryError)
2272 return BaseException_new(type, args, kwds);
2273 if (memerrors_freelist == NULL)
2274 return BaseException_new(type, args, kwds);
2275 /* Fetch object from freelist and revive it */
2276 self = memerrors_freelist;
2277 self->args = PyTuple_New(0);
2278 /* This shouldn't happen since the empty tuple is persistent */
2279 if (self->args == NULL)
2280 return NULL;
2281 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2282 memerrors_numfree--;
2283 self->dict = NULL;
2284 _Py_NewReference((PyObject *)self);
2285 _PyObject_GC_TRACK(self);
2286 return (PyObject *)self;
2287 }
2288
2289 static void
MemoryError_dealloc(PyBaseExceptionObject * self)2290 MemoryError_dealloc(PyBaseExceptionObject *self)
2291 {
2292 _PyObject_GC_UNTRACK(self);
2293 BaseException_clear(self);
2294 if (memerrors_numfree >= MEMERRORS_SAVE)
2295 Py_TYPE(self)->tp_free((PyObject *)self);
2296 else {
2297 self->dict = (PyObject *) memerrors_freelist;
2298 memerrors_freelist = self;
2299 memerrors_numfree++;
2300 }
2301 }
2302
2303 static int
preallocate_memerrors(void)2304 preallocate_memerrors(void)
2305 {
2306 /* We create enough MemoryErrors and then decref them, which will fill
2307 up the freelist. */
2308 int i;
2309 PyObject *errors[MEMERRORS_SAVE];
2310 for (i = 0; i < MEMERRORS_SAVE; i++) {
2311 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2312 NULL, NULL);
2313 if (!errors[i]) {
2314 return -1;
2315 }
2316 }
2317 for (i = 0; i < MEMERRORS_SAVE; i++) {
2318 Py_DECREF(errors[i]);
2319 }
2320 return 0;
2321 }
2322
2323 static void
free_preallocated_memerrors(void)2324 free_preallocated_memerrors(void)
2325 {
2326 while (memerrors_freelist != NULL) {
2327 PyObject *self = (PyObject *) memerrors_freelist;
2328 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2329 Py_TYPE(self)->tp_free((PyObject *)self);
2330 }
2331 }
2332
2333
2334 static PyTypeObject _PyExc_MemoryError = {
2335 PyVarObject_HEAD_INIT(NULL, 0)
2336 "MemoryError",
2337 sizeof(PyBaseExceptionObject),
2338 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2339 0, 0, 0, 0, 0, 0, 0,
2340 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2341 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2342 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2343 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2344 (initproc)BaseException_init, 0, MemoryError_new
2345 };
2346 PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2347
2348
2349 /*
2350 * BufferError extends Exception
2351 */
2352 SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2353
2354
2355 /* Warning category docstrings */
2356
2357 /*
2358 * Warning extends Exception
2359 */
2360 SimpleExtendsException(PyExc_Exception, Warning,
2361 "Base class for warning categories.");
2362
2363
2364 /*
2365 * UserWarning extends Warning
2366 */
2367 SimpleExtendsException(PyExc_Warning, UserWarning,
2368 "Base class for warnings generated by user code.");
2369
2370
2371 /*
2372 * DeprecationWarning extends Warning
2373 */
2374 SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2375 "Base class for warnings about deprecated features.");
2376
2377
2378 /*
2379 * PendingDeprecationWarning extends Warning
2380 */
2381 SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2382 "Base class for warnings about features which will be deprecated\n"
2383 "in the future.");
2384
2385
2386 /*
2387 * SyntaxWarning extends Warning
2388 */
2389 SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2390 "Base class for warnings about dubious syntax.");
2391
2392
2393 /*
2394 * RuntimeWarning extends Warning
2395 */
2396 SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2397 "Base class for warnings about dubious runtime behavior.");
2398
2399
2400 /*
2401 * FutureWarning extends Warning
2402 */
2403 SimpleExtendsException(PyExc_Warning, FutureWarning,
2404 "Base class for warnings about constructs that will change semantically\n"
2405 "in the future.");
2406
2407
2408 /*
2409 * ImportWarning extends Warning
2410 */
2411 SimpleExtendsException(PyExc_Warning, ImportWarning,
2412 "Base class for warnings about probable mistakes in module imports");
2413
2414
2415 /*
2416 * UnicodeWarning extends Warning
2417 */
2418 SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2419 "Base class for warnings about Unicode related problems, mostly\n"
2420 "related to conversion problems.");
2421
2422
2423 /*
2424 * BytesWarning extends Warning
2425 */
2426 SimpleExtendsException(PyExc_Warning, BytesWarning,
2427 "Base class for warnings about bytes and buffer related problems, mostly\n"
2428 "related to conversion from str or comparing to str.");
2429
2430
2431 /*
2432 * ResourceWarning extends Warning
2433 */
2434 SimpleExtendsException(PyExc_Warning, ResourceWarning,
2435 "Base class for warnings about resource usage.");
2436
2437
2438
2439 #ifdef MS_WINDOWS
2440 #include <winsock2.h>
2441 /* The following constants were added to errno.h in VS2010 but have
2442 preferred WSA equivalents. */
2443 #undef EADDRINUSE
2444 #undef EADDRNOTAVAIL
2445 #undef EAFNOSUPPORT
2446 #undef EALREADY
2447 #undef ECONNABORTED
2448 #undef ECONNREFUSED
2449 #undef ECONNRESET
2450 #undef EDESTADDRREQ
2451 #undef EHOSTUNREACH
2452 #undef EINPROGRESS
2453 #undef EISCONN
2454 #undef ELOOP
2455 #undef EMSGSIZE
2456 #undef ENETDOWN
2457 #undef ENETRESET
2458 #undef ENETUNREACH
2459 #undef ENOBUFS
2460 #undef ENOPROTOOPT
2461 #undef ENOTCONN
2462 #undef ENOTSOCK
2463 #undef EOPNOTSUPP
2464 #undef EPROTONOSUPPORT
2465 #undef EPROTOTYPE
2466 #undef ETIMEDOUT
2467 #undef EWOULDBLOCK
2468
2469 #if defined(WSAEALREADY) && !defined(EALREADY)
2470 #define EALREADY WSAEALREADY
2471 #endif
2472 #if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2473 #define ECONNABORTED WSAECONNABORTED
2474 #endif
2475 #if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2476 #define ECONNREFUSED WSAECONNREFUSED
2477 #endif
2478 #if defined(WSAECONNRESET) && !defined(ECONNRESET)
2479 #define ECONNRESET WSAECONNRESET
2480 #endif
2481 #if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2482 #define EINPROGRESS WSAEINPROGRESS
2483 #endif
2484 #if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2485 #define ESHUTDOWN WSAESHUTDOWN
2486 #endif
2487 #if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2488 #define ETIMEDOUT WSAETIMEDOUT
2489 #endif
2490 #if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2491 #define EWOULDBLOCK WSAEWOULDBLOCK
2492 #endif
2493 #endif /* MS_WINDOWS */
2494
2495 PyStatus
_PyExc_Init(void)2496 _PyExc_Init(void)
2497 {
2498 #define PRE_INIT(TYPE) \
2499 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2500 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) { \
2501 return _PyStatus_ERR("exceptions bootstrapping error."); \
2502 } \
2503 Py_INCREF(PyExc_ ## TYPE); \
2504 }
2505
2506 #define ADD_ERRNO(TYPE, CODE) \
2507 do { \
2508 PyObject *_code = PyLong_FromLong(CODE); \
2509 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2510 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2511 return _PyStatus_ERR("errmap insertion problem."); \
2512 Py_DECREF(_code); \
2513 } while (0)
2514
2515 PRE_INIT(BaseException);
2516 PRE_INIT(Exception);
2517 PRE_INIT(TypeError);
2518 PRE_INIT(StopAsyncIteration);
2519 PRE_INIT(StopIteration);
2520 PRE_INIT(GeneratorExit);
2521 PRE_INIT(SystemExit);
2522 PRE_INIT(KeyboardInterrupt);
2523 PRE_INIT(ImportError);
2524 PRE_INIT(ModuleNotFoundError);
2525 PRE_INIT(OSError);
2526 PRE_INIT(EOFError);
2527 PRE_INIT(RuntimeError);
2528 PRE_INIT(RecursionError);
2529 PRE_INIT(NotImplementedError);
2530 PRE_INIT(NameError);
2531 PRE_INIT(UnboundLocalError);
2532 PRE_INIT(AttributeError);
2533 PRE_INIT(SyntaxError);
2534 PRE_INIT(IndentationError);
2535 PRE_INIT(TabError);
2536 PRE_INIT(LookupError);
2537 PRE_INIT(IndexError);
2538 PRE_INIT(KeyError);
2539 PRE_INIT(ValueError);
2540 PRE_INIT(UnicodeError);
2541 PRE_INIT(UnicodeEncodeError);
2542 PRE_INIT(UnicodeDecodeError);
2543 PRE_INIT(UnicodeTranslateError);
2544 PRE_INIT(AssertionError);
2545 PRE_INIT(ArithmeticError);
2546 PRE_INIT(FloatingPointError);
2547 PRE_INIT(OverflowError);
2548 PRE_INIT(ZeroDivisionError);
2549 PRE_INIT(SystemError);
2550 PRE_INIT(ReferenceError);
2551 PRE_INIT(MemoryError);
2552 PRE_INIT(BufferError);
2553 PRE_INIT(Warning);
2554 PRE_INIT(UserWarning);
2555 PRE_INIT(DeprecationWarning);
2556 PRE_INIT(PendingDeprecationWarning);
2557 PRE_INIT(SyntaxWarning);
2558 PRE_INIT(RuntimeWarning);
2559 PRE_INIT(FutureWarning);
2560 PRE_INIT(ImportWarning);
2561 PRE_INIT(UnicodeWarning);
2562 PRE_INIT(BytesWarning);
2563 PRE_INIT(ResourceWarning);
2564
2565 /* OSError subclasses */
2566 PRE_INIT(ConnectionError);
2567
2568 PRE_INIT(BlockingIOError);
2569 PRE_INIT(BrokenPipeError);
2570 PRE_INIT(ChildProcessError);
2571 PRE_INIT(ConnectionAbortedError);
2572 PRE_INIT(ConnectionRefusedError);
2573 PRE_INIT(ConnectionResetError);
2574 PRE_INIT(FileExistsError);
2575 PRE_INIT(FileNotFoundError);
2576 PRE_INIT(IsADirectoryError);
2577 PRE_INIT(NotADirectoryError);
2578 PRE_INIT(InterruptedError);
2579 PRE_INIT(PermissionError);
2580 PRE_INIT(ProcessLookupError);
2581 PRE_INIT(TimeoutError);
2582
2583 if (preallocate_memerrors() < 0) {
2584 return _PyStatus_ERR("Could not preallocate MemoryError object");
2585 }
2586
2587 /* Add exceptions to errnomap */
2588 if (!errnomap) {
2589 errnomap = PyDict_New();
2590 if (!errnomap) {
2591 return _PyStatus_ERR("Cannot allocate map from errnos to OSError subclasses");
2592 }
2593 }
2594
2595 ADD_ERRNO(BlockingIOError, EAGAIN);
2596 ADD_ERRNO(BlockingIOError, EALREADY);
2597 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2598 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2599 ADD_ERRNO(BrokenPipeError, EPIPE);
2600 #ifdef ESHUTDOWN
2601 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2602 #endif
2603 ADD_ERRNO(ChildProcessError, ECHILD);
2604 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2605 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2606 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2607 ADD_ERRNO(FileExistsError, EEXIST);
2608 ADD_ERRNO(FileNotFoundError, ENOENT);
2609 ADD_ERRNO(IsADirectoryError, EISDIR);
2610 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2611 ADD_ERRNO(InterruptedError, EINTR);
2612 ADD_ERRNO(PermissionError, EACCES);
2613 ADD_ERRNO(PermissionError, EPERM);
2614 ADD_ERRNO(ProcessLookupError, ESRCH);
2615 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2616
2617 return _PyStatus_OK();
2618
2619 #undef PRE_INIT
2620 #undef ADD_ERRNO
2621 }
2622
2623
2624 /* Add exception types to the builtins module */
2625 PyStatus
_PyBuiltins_AddExceptions(PyObject * bltinmod)2626 _PyBuiltins_AddExceptions(PyObject *bltinmod)
2627 {
2628 #define POST_INIT(TYPE) \
2629 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) { \
2630 return _PyStatus_ERR("Module dictionary insertion problem."); \
2631 }
2632
2633 #define INIT_ALIAS(NAME, TYPE) \
2634 do { \
2635 Py_INCREF(PyExc_ ## TYPE); \
2636 Py_XDECREF(PyExc_ ## NAME); \
2637 PyExc_ ## NAME = PyExc_ ## TYPE; \
2638 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) { \
2639 return _PyStatus_ERR("Module dictionary insertion problem."); \
2640 } \
2641 } while (0)
2642
2643 PyObject *bdict;
2644
2645 bdict = PyModule_GetDict(bltinmod);
2646 if (bdict == NULL) {
2647 return _PyStatus_ERR("exceptions bootstrapping error.");
2648 }
2649
2650 POST_INIT(BaseException);
2651 POST_INIT(Exception);
2652 POST_INIT(TypeError);
2653 POST_INIT(StopAsyncIteration);
2654 POST_INIT(StopIteration);
2655 POST_INIT(GeneratorExit);
2656 POST_INIT(SystemExit);
2657 POST_INIT(KeyboardInterrupt);
2658 POST_INIT(ImportError);
2659 POST_INIT(ModuleNotFoundError);
2660 POST_INIT(OSError);
2661 INIT_ALIAS(EnvironmentError, OSError);
2662 INIT_ALIAS(IOError, OSError);
2663 #ifdef MS_WINDOWS
2664 INIT_ALIAS(WindowsError, OSError);
2665 #endif
2666 POST_INIT(EOFError);
2667 POST_INIT(RuntimeError);
2668 POST_INIT(RecursionError);
2669 POST_INIT(NotImplementedError);
2670 POST_INIT(NameError);
2671 POST_INIT(UnboundLocalError);
2672 POST_INIT(AttributeError);
2673 POST_INIT(SyntaxError);
2674 POST_INIT(IndentationError);
2675 POST_INIT(TabError);
2676 POST_INIT(LookupError);
2677 POST_INIT(IndexError);
2678 POST_INIT(KeyError);
2679 POST_INIT(ValueError);
2680 POST_INIT(UnicodeError);
2681 POST_INIT(UnicodeEncodeError);
2682 POST_INIT(UnicodeDecodeError);
2683 POST_INIT(UnicodeTranslateError);
2684 POST_INIT(AssertionError);
2685 POST_INIT(ArithmeticError);
2686 POST_INIT(FloatingPointError);
2687 POST_INIT(OverflowError);
2688 POST_INIT(ZeroDivisionError);
2689 POST_INIT(SystemError);
2690 POST_INIT(ReferenceError);
2691 POST_INIT(MemoryError);
2692 POST_INIT(BufferError);
2693 POST_INIT(Warning);
2694 POST_INIT(UserWarning);
2695 POST_INIT(DeprecationWarning);
2696 POST_INIT(PendingDeprecationWarning);
2697 POST_INIT(SyntaxWarning);
2698 POST_INIT(RuntimeWarning);
2699 POST_INIT(FutureWarning);
2700 POST_INIT(ImportWarning);
2701 POST_INIT(UnicodeWarning);
2702 POST_INIT(BytesWarning);
2703 POST_INIT(ResourceWarning);
2704
2705 /* OSError subclasses */
2706 POST_INIT(ConnectionError);
2707
2708 POST_INIT(BlockingIOError);
2709 POST_INIT(BrokenPipeError);
2710 POST_INIT(ChildProcessError);
2711 POST_INIT(ConnectionAbortedError);
2712 POST_INIT(ConnectionRefusedError);
2713 POST_INIT(ConnectionResetError);
2714 POST_INIT(FileExistsError);
2715 POST_INIT(FileNotFoundError);
2716 POST_INIT(IsADirectoryError);
2717 POST_INIT(NotADirectoryError);
2718 POST_INIT(InterruptedError);
2719 POST_INIT(PermissionError);
2720 POST_INIT(ProcessLookupError);
2721 POST_INIT(TimeoutError);
2722
2723 return _PyStatus_OK();
2724
2725 #undef POST_INIT
2726 #undef INIT_ALIAS
2727 }
2728
2729 void
_PyExc_Fini(void)2730 _PyExc_Fini(void)
2731 {
2732 free_preallocated_memerrors();
2733 Py_CLEAR(errnomap);
2734 }
2735
2736 /* Helper to do the equivalent of "raise X from Y" in C, but always using
2737 * the current exception rather than passing one in.
2738 *
2739 * We currently limit this to *only* exceptions that use the BaseException
2740 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2741 * those correctly without losing data and without losing backwards
2742 * compatibility.
2743 *
2744 * We also aim to rule out *all* exceptions that might be storing additional
2745 * state, whether by having a size difference relative to BaseException,
2746 * additional arguments passed in during construction or by having a
2747 * non-empty instance dict.
2748 *
2749 * We need to be very careful with what we wrap, since changing types to
2750 * a broader exception type would be backwards incompatible for
2751 * existing codecs, and with different init or new method implementations
2752 * may either not support instantiation with PyErr_Format or lose
2753 * information when instantiated that way.
2754 *
2755 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2756 * fact that exceptions are expected to support pickling. If more builtin
2757 * exceptions (e.g. AttributeError) start to be converted to rich
2758 * exceptions with additional attributes, that's probably a better approach
2759 * to pursue over adding special cases for particular stateful subclasses.
2760 *
2761 * Returns a borrowed reference to the new exception (if any), NULL if the
2762 * existing exception was left in place.
2763 */
2764 PyObject *
_PyErr_TrySetFromCause(const char * format,...)2765 _PyErr_TrySetFromCause(const char *format, ...)
2766 {
2767 PyObject* msg_prefix;
2768 PyObject *exc, *val, *tb;
2769 PyTypeObject *caught_type;
2770 PyObject **dictptr;
2771 PyObject *instance_args;
2772 Py_ssize_t num_args, caught_type_size, base_exc_size;
2773 PyObject *new_exc, *new_val, *new_tb;
2774 va_list vargs;
2775 int same_basic_size;
2776
2777 PyErr_Fetch(&exc, &val, &tb);
2778 caught_type = (PyTypeObject *)exc;
2779 /* Ensure type info indicates no extra state is stored at the C level
2780 * and that the type can be reinstantiated using PyErr_Format
2781 */
2782 caught_type_size = caught_type->tp_basicsize;
2783 base_exc_size = _PyExc_BaseException.tp_basicsize;
2784 same_basic_size = (
2785 caught_type_size == base_exc_size ||
2786 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
2787 (caught_type_size == base_exc_size + (Py_ssize_t)sizeof(PyObject *))
2788 )
2789 );
2790 if (caught_type->tp_init != (initproc)BaseException_init ||
2791 caught_type->tp_new != BaseException_new ||
2792 !same_basic_size ||
2793 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
2794 /* We can't be sure we can wrap this safely, since it may contain
2795 * more state than just the exception type. Accordingly, we just
2796 * leave it alone.
2797 */
2798 PyErr_Restore(exc, val, tb);
2799 return NULL;
2800 }
2801
2802 /* Check the args are empty or contain a single string */
2803 PyErr_NormalizeException(&exc, &val, &tb);
2804 instance_args = ((PyBaseExceptionObject *)val)->args;
2805 num_args = PyTuple_GET_SIZE(instance_args);
2806 if (num_args > 1 ||
2807 (num_args == 1 &&
2808 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
2809 /* More than 1 arg, or the one arg we do have isn't a string
2810 */
2811 PyErr_Restore(exc, val, tb);
2812 return NULL;
2813 }
2814
2815 /* Ensure the instance dict is also empty */
2816 dictptr = _PyObject_GetDictPtr(val);
2817 if (dictptr != NULL && *dictptr != NULL &&
2818 PyDict_GET_SIZE(*dictptr) > 0) {
2819 /* While we could potentially copy a non-empty instance dictionary
2820 * to the replacement exception, for now we take the more
2821 * conservative path of leaving exceptions with attributes set
2822 * alone.
2823 */
2824 PyErr_Restore(exc, val, tb);
2825 return NULL;
2826 }
2827
2828 /* For exceptions that we can wrap safely, we chain the original
2829 * exception to a new one of the exact same type with an
2830 * error message that mentions the additional details and the
2831 * original exception.
2832 *
2833 * It would be nice to wrap OSError and various other exception
2834 * types as well, but that's quite a bit trickier due to the extra
2835 * state potentially stored on OSError instances.
2836 */
2837 /* Ensure the traceback is set correctly on the existing exception */
2838 if (tb != NULL) {
2839 PyException_SetTraceback(val, tb);
2840 Py_DECREF(tb);
2841 }
2842
2843 #ifdef HAVE_STDARG_PROTOTYPES
2844 va_start(vargs, format);
2845 #else
2846 va_start(vargs);
2847 #endif
2848 msg_prefix = PyUnicode_FromFormatV(format, vargs);
2849 va_end(vargs);
2850 if (msg_prefix == NULL) {
2851 Py_DECREF(exc);
2852 Py_DECREF(val);
2853 return NULL;
2854 }
2855
2856 PyErr_Format(exc, "%U (%s: %S)",
2857 msg_prefix, Py_TYPE(val)->tp_name, val);
2858 Py_DECREF(exc);
2859 Py_DECREF(msg_prefix);
2860 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2861 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2862 PyException_SetCause(new_val, val);
2863 PyErr_Restore(new_exc, new_val, new_tb);
2864 return new_val;
2865 }
2866
2867
2868 /* To help with migration from Python 2, SyntaxError.__init__ applies some
2869 * heuristics to try to report a more meaningful exception when print and
2870 * exec are used like statements.
2871 *
2872 * The heuristics are currently expected to detect the following cases:
2873 * - top level statement
2874 * - statement in a nested suite
2875 * - trailing section of a one line complex statement
2876 *
2877 * They're currently known not to trigger:
2878 * - after a semi-colon
2879 *
2880 * The error message can be a bit odd in cases where the "arguments" are
2881 * completely illegal syntactically, but that isn't worth the hassle of
2882 * fixing.
2883 *
2884 * We also can't do anything about cases that are legal Python 3 syntax
2885 * but mean something entirely different from what they did in Python 2
2886 * (omitting the arguments entirely, printing items preceded by a unary plus
2887 * or minus, using the stream redirection syntax).
2888 */
2889
2890
2891 // Static helper for setting legacy print error message
2892 static int
_set_legacy_print_statement_msg(PySyntaxErrorObject * self,Py_ssize_t start)2893 _set_legacy_print_statement_msg(PySyntaxErrorObject *self, Py_ssize_t start)
2894 {
2895 // PRINT_OFFSET is to remove the `print ` prefix from the data.
2896 const int PRINT_OFFSET = 6;
2897 const int STRIP_BOTH = 2;
2898 Py_ssize_t start_pos = start + PRINT_OFFSET;
2899 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2900 Py_UCS4 semicolon = ';';
2901 Py_ssize_t end_pos = PyUnicode_FindChar(self->text, semicolon,
2902 start_pos, text_len, 1);
2903 if (end_pos < -1) {
2904 return -1;
2905 } else if (end_pos == -1) {
2906 end_pos = text_len;
2907 }
2908
2909 PyObject *data = PyUnicode_Substring(self->text, start_pos, end_pos);
2910 if (data == NULL) {
2911 return -1;
2912 }
2913
2914 PyObject *strip_sep_obj = PyUnicode_FromString(" \t\r\n");
2915 if (strip_sep_obj == NULL) {
2916 Py_DECREF(data);
2917 return -1;
2918 }
2919
2920 PyObject *new_data = _PyUnicode_XStrip(data, STRIP_BOTH, strip_sep_obj);
2921 Py_DECREF(data);
2922 Py_DECREF(strip_sep_obj);
2923 if (new_data == NULL) {
2924 return -1;
2925 }
2926 // gets the modified text_len after stripping `print `
2927 text_len = PyUnicode_GET_LENGTH(new_data);
2928 const char *maybe_end_arg = "";
2929 if (text_len > 0 && PyUnicode_READ_CHAR(new_data, text_len-1) == ',') {
2930 maybe_end_arg = " end=\" \"";
2931 }
2932 PyObject *error_msg = PyUnicode_FromFormat(
2933 "Missing parentheses in call to 'print'. Did you mean print(%U%s)?",
2934 new_data, maybe_end_arg
2935 );
2936 Py_DECREF(new_data);
2937 if (error_msg == NULL)
2938 return -1;
2939
2940 Py_XSETREF(self->msg, error_msg);
2941 return 1;
2942 }
2943
2944 static int
_check_for_legacy_statements(PySyntaxErrorObject * self,Py_ssize_t start)2945 _check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start)
2946 {
2947 /* Return values:
2948 * -1: an error occurred
2949 * 0: nothing happened
2950 * 1: the check triggered & the error message was changed
2951 */
2952 static PyObject *print_prefix = NULL;
2953 static PyObject *exec_prefix = NULL;
2954 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text), match;
2955 int kind = PyUnicode_KIND(self->text);
2956 void *data = PyUnicode_DATA(self->text);
2957
2958 /* Ignore leading whitespace */
2959 while (start < text_len) {
2960 Py_UCS4 ch = PyUnicode_READ(kind, data, start);
2961 if (!Py_UNICODE_ISSPACE(ch))
2962 break;
2963 start++;
2964 }
2965 /* Checking against an empty or whitespace-only part of the string */
2966 if (start == text_len) {
2967 return 0;
2968 }
2969
2970 /* Check for legacy print statements */
2971 if (print_prefix == NULL) {
2972 print_prefix = PyUnicode_InternFromString("print ");
2973 if (print_prefix == NULL) {
2974 return -1;
2975 }
2976 }
2977 match = PyUnicode_Tailmatch(self->text, print_prefix,
2978 start, text_len, -1);
2979 if (match == -1) {
2980 return -1;
2981 }
2982 if (match) {
2983 return _set_legacy_print_statement_msg(self, start);
2984 }
2985
2986 /* Check for legacy exec statements */
2987 if (exec_prefix == NULL) {
2988 exec_prefix = PyUnicode_InternFromString("exec ");
2989 if (exec_prefix == NULL) {
2990 return -1;
2991 }
2992 }
2993 match = PyUnicode_Tailmatch(self->text, exec_prefix, start, text_len, -1);
2994 if (match == -1) {
2995 return -1;
2996 }
2997 if (match) {
2998 PyObject *msg = PyUnicode_FromString("Missing parentheses in call "
2999 "to 'exec'");
3000 if (msg == NULL) {
3001 return -1;
3002 }
3003 Py_XSETREF(self->msg, msg);
3004 return 1;
3005 }
3006 /* Fall back to the default error message */
3007 return 0;
3008 }
3009
3010 static int
_report_missing_parentheses(PySyntaxErrorObject * self)3011 _report_missing_parentheses(PySyntaxErrorObject *self)
3012 {
3013 Py_UCS4 left_paren = 40;
3014 Py_ssize_t left_paren_index;
3015 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
3016 int legacy_check_result = 0;
3017
3018 /* Skip entirely if there is an opening parenthesis */
3019 left_paren_index = PyUnicode_FindChar(self->text, left_paren,
3020 0, text_len, 1);
3021 if (left_paren_index < -1) {
3022 return -1;
3023 }
3024 if (left_paren_index != -1) {
3025 /* Use default error message for any line with an opening paren */
3026 return 0;
3027 }
3028 /* Handle the simple statement case */
3029 legacy_check_result = _check_for_legacy_statements(self, 0);
3030 if (legacy_check_result < 0) {
3031 return -1;
3032
3033 }
3034 if (legacy_check_result == 0) {
3035 /* Handle the one-line complex statement case */
3036 Py_UCS4 colon = 58;
3037 Py_ssize_t colon_index;
3038 colon_index = PyUnicode_FindChar(self->text, colon,
3039 0, text_len, 1);
3040 if (colon_index < -1) {
3041 return -1;
3042 }
3043 if (colon_index >= 0 && colon_index < text_len) {
3044 /* Check again, starting from just after the colon */
3045 if (_check_for_legacy_statements(self, colon_index+1) < 0) {
3046 return -1;
3047 }
3048 }
3049 }
3050 return 0;
3051 }
3052