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