Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Objects/exceptions.c
12 views
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
#include <Python.h>
8
#include <stdbool.h>
9
#include "pycore_abstract.h" // _PyObject_RealIsSubclass()
10
#include "pycore_ceval.h" // _Py_EnterRecursiveCall
11
#include "pycore_pyerrors.h" // struct _PyErr_SetRaisedException
12
#include "pycore_exceptions.h" // struct _Py_exc_state
13
#include "pycore_initconfig.h"
14
#include "pycore_object.h"
15
#include "structmember.h" // PyMemberDef
16
#include "osdefs.h" // SEP
17
18
19
/* Compatibility aliases */
20
PyObject *PyExc_EnvironmentError = NULL; // borrowed ref
21
PyObject *PyExc_IOError = NULL; // borrowed ref
22
#ifdef MS_WINDOWS
23
PyObject *PyExc_WindowsError = NULL; // borrowed ref
24
#endif
25
26
27
static struct _Py_exc_state*
28
get_exc_state(void)
29
{
30
PyInterpreterState *interp = _PyInterpreterState_GET();
31
return &interp->exc_state;
32
}
33
34
35
/* NOTE: If the exception class hierarchy changes, don't forget to update
36
* Lib/test/exception_hierarchy.txt
37
*/
38
39
/*
40
* BaseException
41
*/
42
static PyObject *
43
BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
44
{
45
PyBaseExceptionObject *self;
46
47
self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
48
if (!self)
49
return NULL;
50
/* the dict is created on the fly in PyObject_GenericSetAttr */
51
self->dict = NULL;
52
self->notes = NULL;
53
self->traceback = self->cause = self->context = NULL;
54
self->suppress_context = 0;
55
56
if (args) {
57
self->args = Py_NewRef(args);
58
return (PyObject *)self;
59
}
60
61
self->args = PyTuple_New(0);
62
if (!self->args) {
63
Py_DECREF(self);
64
return NULL;
65
}
66
67
return (PyObject *)self;
68
}
69
70
static int
71
BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
72
{
73
if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
74
return -1;
75
76
Py_XSETREF(self->args, Py_NewRef(args));
77
return 0;
78
}
79
80
static int
81
BaseException_clear(PyBaseExceptionObject *self)
82
{
83
Py_CLEAR(self->dict);
84
Py_CLEAR(self->args);
85
Py_CLEAR(self->notes);
86
Py_CLEAR(self->traceback);
87
Py_CLEAR(self->cause);
88
Py_CLEAR(self->context);
89
return 0;
90
}
91
92
static void
93
BaseException_dealloc(PyBaseExceptionObject *self)
94
{
95
PyObject_GC_UnTrack(self);
96
// bpo-44348: The trashcan mechanism prevents stack overflow when deleting
97
// long chains of exceptions. For example, exceptions can be chained
98
// through the __context__ attributes or the __traceback__ attribute.
99
Py_TRASHCAN_BEGIN(self, BaseException_dealloc)
100
BaseException_clear(self);
101
Py_TYPE(self)->tp_free((PyObject *)self);
102
Py_TRASHCAN_END
103
}
104
105
static int
106
BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
107
{
108
Py_VISIT(self->dict);
109
Py_VISIT(self->args);
110
Py_VISIT(self->notes);
111
Py_VISIT(self->traceback);
112
Py_VISIT(self->cause);
113
Py_VISIT(self->context);
114
return 0;
115
}
116
117
static PyObject *
118
BaseException_str(PyBaseExceptionObject *self)
119
{
120
switch (PyTuple_GET_SIZE(self->args)) {
121
case 0:
122
return PyUnicode_FromString("");
123
case 1:
124
return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
125
default:
126
return PyObject_Str(self->args);
127
}
128
}
129
130
static PyObject *
131
BaseException_repr(PyBaseExceptionObject *self)
132
{
133
const char *name = _PyType_Name(Py_TYPE(self));
134
if (PyTuple_GET_SIZE(self->args) == 1)
135
return PyUnicode_FromFormat("%s(%R)", name,
136
PyTuple_GET_ITEM(self->args, 0));
137
else
138
return PyUnicode_FromFormat("%s%R", name, self->args);
139
}
140
141
/* Pickling support */
142
static PyObject *
143
BaseException_reduce(PyBaseExceptionObject *self, PyObject *Py_UNUSED(ignored))
144
{
145
if (self->args && self->dict)
146
return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
147
else
148
return PyTuple_Pack(2, Py_TYPE(self), self->args);
149
}
150
151
/*
152
* Needed for backward compatibility, since exceptions used to store
153
* all their attributes in the __dict__. Code is taken from cPickle's
154
* load_build function.
155
*/
156
static PyObject *
157
BaseException_setstate(PyObject *self, PyObject *state)
158
{
159
PyObject *d_key, *d_value;
160
Py_ssize_t i = 0;
161
162
if (state != Py_None) {
163
if (!PyDict_Check(state)) {
164
PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
165
return NULL;
166
}
167
while (PyDict_Next(state, &i, &d_key, &d_value)) {
168
Py_INCREF(d_key);
169
Py_INCREF(d_value);
170
int res = PyObject_SetAttr(self, d_key, d_value);
171
Py_DECREF(d_value);
172
Py_DECREF(d_key);
173
if (res < 0) {
174
return NULL;
175
}
176
}
177
}
178
Py_RETURN_NONE;
179
}
180
181
static PyObject *
182
BaseException_with_traceback(PyObject *self, PyObject *tb) {
183
if (PyException_SetTraceback(self, tb))
184
return NULL;
185
186
return Py_NewRef(self);
187
}
188
189
PyDoc_STRVAR(with_traceback_doc,
190
"Exception.with_traceback(tb) --\n\
191
set self.__traceback__ to tb and return self.");
192
193
static inline PyBaseExceptionObject*
194
_PyBaseExceptionObject_cast(PyObject *exc)
195
{
196
assert(PyExceptionInstance_Check(exc));
197
return (PyBaseExceptionObject *)exc;
198
}
199
200
static PyObject *
201
BaseException_add_note(PyObject *self, PyObject *note)
202
{
203
if (!PyUnicode_Check(note)) {
204
PyErr_Format(PyExc_TypeError,
205
"note must be a str, not '%s'",
206
Py_TYPE(note)->tp_name);
207
return NULL;
208
}
209
210
PyObject *notes;
211
if (_PyObject_LookupAttr(self, &_Py_ID(__notes__), &notes) < 0) {
212
return NULL;
213
}
214
if (notes == NULL) {
215
notes = PyList_New(0);
216
if (notes == NULL) {
217
return NULL;
218
}
219
if (PyObject_SetAttr(self, &_Py_ID(__notes__), notes) < 0) {
220
Py_DECREF(notes);
221
return NULL;
222
}
223
}
224
else if (!PyList_Check(notes)) {
225
Py_DECREF(notes);
226
PyErr_SetString(PyExc_TypeError, "Cannot add note: __notes__ is not a list");
227
return NULL;
228
}
229
if (PyList_Append(notes, note) < 0) {
230
Py_DECREF(notes);
231
return NULL;
232
}
233
Py_DECREF(notes);
234
Py_RETURN_NONE;
235
}
236
237
PyDoc_STRVAR(add_note_doc,
238
"Exception.add_note(note) --\n\
239
add a note to the exception");
240
241
static PyMethodDef BaseException_methods[] = {
242
{"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
243
{"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
244
{"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
245
with_traceback_doc},
246
{"add_note", (PyCFunction)BaseException_add_note, METH_O,
247
add_note_doc},
248
{NULL, NULL, 0, NULL},
249
};
250
251
static PyObject *
252
BaseException_get_args(PyBaseExceptionObject *self, void *Py_UNUSED(ignored))
253
{
254
if (self->args == NULL) {
255
Py_RETURN_NONE;
256
}
257
return Py_NewRef(self->args);
258
}
259
260
static int
261
BaseException_set_args(PyBaseExceptionObject *self, PyObject *val, void *Py_UNUSED(ignored))
262
{
263
PyObject *seq;
264
if (val == NULL) {
265
PyErr_SetString(PyExc_TypeError, "args may not be deleted");
266
return -1;
267
}
268
seq = PySequence_Tuple(val);
269
if (!seq)
270
return -1;
271
Py_XSETREF(self->args, seq);
272
return 0;
273
}
274
275
static PyObject *
276
BaseException_get_tb(PyBaseExceptionObject *self, void *Py_UNUSED(ignored))
277
{
278
if (self->traceback == NULL) {
279
Py_RETURN_NONE;
280
}
281
return Py_NewRef(self->traceback);
282
}
283
284
static int
285
BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb, void *Py_UNUSED(ignored))
286
{
287
if (tb == NULL) {
288
PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
289
return -1;
290
}
291
if (PyTraceBack_Check(tb)) {
292
Py_XSETREF(self->traceback, Py_NewRef(tb));
293
}
294
else if (tb == Py_None) {
295
Py_CLEAR(self->traceback);
296
}
297
else {
298
PyErr_SetString(PyExc_TypeError,
299
"__traceback__ must be a traceback or None");
300
return -1;
301
}
302
return 0;
303
}
304
305
static PyObject *
306
BaseException_get_context(PyObject *self, void *Py_UNUSED(ignored))
307
{
308
PyObject *res = PyException_GetContext(self);
309
if (res)
310
return res; /* new reference already returned above */
311
Py_RETURN_NONE;
312
}
313
314
static int
315
BaseException_set_context(PyObject *self, PyObject *arg, void *Py_UNUSED(ignored))
316
{
317
if (arg == NULL) {
318
PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
319
return -1;
320
} else if (arg == Py_None) {
321
arg = NULL;
322
} else if (!PyExceptionInstance_Check(arg)) {
323
PyErr_SetString(PyExc_TypeError, "exception context must be None "
324
"or derive from BaseException");
325
return -1;
326
} else {
327
/* PyException_SetContext steals this reference */
328
Py_INCREF(arg);
329
}
330
PyException_SetContext(self, arg);
331
return 0;
332
}
333
334
static PyObject *
335
BaseException_get_cause(PyObject *self, void *Py_UNUSED(ignored))
336
{
337
PyObject *res = PyException_GetCause(self);
338
if (res)
339
return res; /* new reference already returned above */
340
Py_RETURN_NONE;
341
}
342
343
static int
344
BaseException_set_cause(PyObject *self, PyObject *arg, void *Py_UNUSED(ignored))
345
{
346
if (arg == NULL) {
347
PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
348
return -1;
349
} else if (arg == Py_None) {
350
arg = NULL;
351
} else if (!PyExceptionInstance_Check(arg)) {
352
PyErr_SetString(PyExc_TypeError, "exception cause must be None "
353
"or derive from BaseException");
354
return -1;
355
} else {
356
/* PyException_SetCause steals this reference */
357
Py_INCREF(arg);
358
}
359
PyException_SetCause(self, arg);
360
return 0;
361
}
362
363
364
static PyGetSetDef BaseException_getset[] = {
365
{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
366
{"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
367
{"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
368
{"__context__", BaseException_get_context,
369
BaseException_set_context, PyDoc_STR("exception context")},
370
{"__cause__", BaseException_get_cause,
371
BaseException_set_cause, PyDoc_STR("exception cause")},
372
{NULL},
373
};
374
375
376
PyObject *
377
PyException_GetTraceback(PyObject *self)
378
{
379
PyBaseExceptionObject *base_self = _PyBaseExceptionObject_cast(self);
380
return Py_XNewRef(base_self->traceback);
381
}
382
383
384
int
385
PyException_SetTraceback(PyObject *self, PyObject *tb)
386
{
387
return BaseException_set_tb(_PyBaseExceptionObject_cast(self), tb, NULL);
388
}
389
390
PyObject *
391
PyException_GetCause(PyObject *self)
392
{
393
PyObject *cause = _PyBaseExceptionObject_cast(self)->cause;
394
return Py_XNewRef(cause);
395
}
396
397
/* Steals a reference to cause */
398
void
399
PyException_SetCause(PyObject *self, PyObject *cause)
400
{
401
PyBaseExceptionObject *base_self = _PyBaseExceptionObject_cast(self);
402
base_self->suppress_context = 1;
403
Py_XSETREF(base_self->cause, cause);
404
}
405
406
PyObject *
407
PyException_GetContext(PyObject *self)
408
{
409
PyObject *context = _PyBaseExceptionObject_cast(self)->context;
410
return Py_XNewRef(context);
411
}
412
413
/* Steals a reference to context */
414
void
415
PyException_SetContext(PyObject *self, PyObject *context)
416
{
417
Py_XSETREF(_PyBaseExceptionObject_cast(self)->context, context);
418
}
419
420
PyObject *
421
PyException_GetArgs(PyObject *self)
422
{
423
PyObject *args = _PyBaseExceptionObject_cast(self)->args;
424
return Py_NewRef(args);
425
}
426
427
void
428
PyException_SetArgs(PyObject *self, PyObject *args)
429
{
430
Py_INCREF(args);
431
Py_XSETREF(_PyBaseExceptionObject_cast(self)->args, args);
432
}
433
434
const char *
435
PyExceptionClass_Name(PyObject *ob)
436
{
437
assert(PyExceptionClass_Check(ob));
438
return ((PyTypeObject*)ob)->tp_name;
439
}
440
441
static struct PyMemberDef BaseException_members[] = {
442
{"__suppress_context__", T_BOOL,
443
offsetof(PyBaseExceptionObject, suppress_context)},
444
{NULL}
445
};
446
447
448
static PyTypeObject _PyExc_BaseException = {
449
PyVarObject_HEAD_INIT(NULL, 0)
450
"BaseException", /*tp_name*/
451
sizeof(PyBaseExceptionObject), /*tp_basicsize*/
452
0, /*tp_itemsize*/
453
(destructor)BaseException_dealloc, /*tp_dealloc*/
454
0, /*tp_vectorcall_offset*/
455
0, /*tp_getattr*/
456
0, /*tp_setattr*/
457
0, /*tp_as_async*/
458
(reprfunc)BaseException_repr, /*tp_repr*/
459
0, /*tp_as_number*/
460
0, /*tp_as_sequence*/
461
0, /*tp_as_mapping*/
462
0, /*tp_hash */
463
0, /*tp_call*/
464
(reprfunc)BaseException_str, /*tp_str*/
465
PyObject_GenericGetAttr, /*tp_getattro*/
466
PyObject_GenericSetAttr, /*tp_setattro*/
467
0, /*tp_as_buffer*/
468
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
469
Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
470
PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
471
(traverseproc)BaseException_traverse, /* tp_traverse */
472
(inquiry)BaseException_clear, /* tp_clear */
473
0, /* tp_richcompare */
474
0, /* tp_weaklistoffset */
475
0, /* tp_iter */
476
0, /* tp_iternext */
477
BaseException_methods, /* tp_methods */
478
BaseException_members, /* tp_members */
479
BaseException_getset, /* tp_getset */
480
0, /* tp_base */
481
0, /* tp_dict */
482
0, /* tp_descr_get */
483
0, /* tp_descr_set */
484
offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
485
(initproc)BaseException_init, /* tp_init */
486
0, /* tp_alloc */
487
BaseException_new, /* tp_new */
488
};
489
/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
490
from the previous implementation and also allowing Python objects to be used
491
in the API */
492
PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
493
494
/* note these macros omit the last semicolon so the macro invocation may
495
* include it and not look strange.
496
*/
497
#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
498
static PyTypeObject _PyExc_ ## EXCNAME = { \
499
PyVarObject_HEAD_INIT(NULL, 0) \
500
# EXCNAME, \
501
sizeof(PyBaseExceptionObject), \
502
0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
503
0, 0, 0, 0, 0, 0, 0, \
504
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
505
PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
506
(inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
507
0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
508
(initproc)BaseException_init, 0, BaseException_new,\
509
}; \
510
PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
511
512
#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
513
static PyTypeObject _PyExc_ ## EXCNAME = { \
514
PyVarObject_HEAD_INIT(NULL, 0) \
515
# EXCNAME, \
516
sizeof(Py ## EXCSTORE ## Object), \
517
0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
518
0, 0, 0, 0, 0, \
519
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
520
PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
521
(inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
522
0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
523
(initproc)EXCSTORE ## _init, 0, 0, \
524
}; \
525
PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
526
527
#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
528
EXCMETHODS, EXCMEMBERS, EXCGETSET, \
529
EXCSTR, EXCDOC) \
530
static PyTypeObject _PyExc_ ## EXCNAME = { \
531
PyVarObject_HEAD_INIT(NULL, 0) \
532
# EXCNAME, \
533
sizeof(Py ## EXCSTORE ## Object), 0, \
534
(destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
535
(reprfunc)EXCSTR, 0, 0, 0, \
536
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
537
PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
538
(inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
539
EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
540
0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
541
(initproc)EXCSTORE ## _init, 0, EXCNEW,\
542
}; \
543
PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
544
545
546
/*
547
* Exception extends BaseException
548
*/
549
SimpleExtendsException(PyExc_BaseException, Exception,
550
"Common base class for all non-exit exceptions.");
551
552
553
/*
554
* TypeError extends Exception
555
*/
556
SimpleExtendsException(PyExc_Exception, TypeError,
557
"Inappropriate argument type.");
558
559
560
/*
561
* StopAsyncIteration extends Exception
562
*/
563
SimpleExtendsException(PyExc_Exception, StopAsyncIteration,
564
"Signal the end from iterator.__anext__().");
565
566
567
/*
568
* StopIteration extends Exception
569
*/
570
571
static PyMemberDef StopIteration_members[] = {
572
{"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
573
PyDoc_STR("generator return value")},
574
{NULL} /* Sentinel */
575
};
576
577
static int
578
StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
579
{
580
Py_ssize_t size = PyTuple_GET_SIZE(args);
581
PyObject *value;
582
583
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
584
return -1;
585
Py_CLEAR(self->value);
586
if (size > 0)
587
value = PyTuple_GET_ITEM(args, 0);
588
else
589
value = Py_None;
590
self->value = Py_NewRef(value);
591
return 0;
592
}
593
594
static int
595
StopIteration_clear(PyStopIterationObject *self)
596
{
597
Py_CLEAR(self->value);
598
return BaseException_clear((PyBaseExceptionObject *)self);
599
}
600
601
static void
602
StopIteration_dealloc(PyStopIterationObject *self)
603
{
604
PyObject_GC_UnTrack(self);
605
StopIteration_clear(self);
606
Py_TYPE(self)->tp_free((PyObject *)self);
607
}
608
609
static int
610
StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
611
{
612
Py_VISIT(self->value);
613
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
614
}
615
616
ComplexExtendsException(PyExc_Exception, StopIteration, StopIteration,
617
0, 0, StopIteration_members, 0, 0,
618
"Signal the end from iterator.__next__().");
619
620
621
/*
622
* GeneratorExit extends BaseException
623
*/
624
SimpleExtendsException(PyExc_BaseException, GeneratorExit,
625
"Request that a generator exit.");
626
627
628
/*
629
* SystemExit extends BaseException
630
*/
631
632
static int
633
SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
634
{
635
Py_ssize_t size = PyTuple_GET_SIZE(args);
636
637
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
638
return -1;
639
640
if (size == 0)
641
return 0;
642
if (size == 1) {
643
Py_XSETREF(self->code, Py_NewRef(PyTuple_GET_ITEM(args, 0)));
644
}
645
else { /* size > 1 */
646
Py_XSETREF(self->code, Py_NewRef(args));
647
}
648
return 0;
649
}
650
651
static int
652
SystemExit_clear(PySystemExitObject *self)
653
{
654
Py_CLEAR(self->code);
655
return BaseException_clear((PyBaseExceptionObject *)self);
656
}
657
658
static void
659
SystemExit_dealloc(PySystemExitObject *self)
660
{
661
_PyObject_GC_UNTRACK(self);
662
SystemExit_clear(self);
663
Py_TYPE(self)->tp_free((PyObject *)self);
664
}
665
666
static int
667
SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
668
{
669
Py_VISIT(self->code);
670
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
671
}
672
673
static PyMemberDef SystemExit_members[] = {
674
{"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
675
PyDoc_STR("exception code")},
676
{NULL} /* Sentinel */
677
};
678
679
ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
680
0, 0, SystemExit_members, 0, 0,
681
"Request to exit from the interpreter.");
682
683
/*
684
* BaseExceptionGroup extends BaseException
685
* ExceptionGroup extends BaseExceptionGroup and Exception
686
*/
687
688
689
static inline PyBaseExceptionGroupObject*
690
_PyBaseExceptionGroupObject_cast(PyObject *exc)
691
{
692
assert(_PyBaseExceptionGroup_Check(exc));
693
return (PyBaseExceptionGroupObject *)exc;
694
}
695
696
static PyObject *
697
BaseExceptionGroup_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
698
{
699
struct _Py_exc_state *state = get_exc_state();
700
PyTypeObject *PyExc_ExceptionGroup =
701
(PyTypeObject*)state->PyExc_ExceptionGroup;
702
703
PyObject *message = NULL;
704
PyObject *exceptions = NULL;
705
706
if (!PyArg_ParseTuple(args,
707
"UO:BaseExceptionGroup.__new__",
708
&message,
709
&exceptions)) {
710
return NULL;
711
}
712
713
if (!PySequence_Check(exceptions)) {
714
PyErr_SetString(
715
PyExc_TypeError,
716
"second argument (exceptions) must be a sequence");
717
return NULL;
718
}
719
720
exceptions = PySequence_Tuple(exceptions);
721
if (!exceptions) {
722
return NULL;
723
}
724
725
/* We are now holding a ref to the exceptions tuple */
726
727
Py_ssize_t numexcs = PyTuple_GET_SIZE(exceptions);
728
if (numexcs == 0) {
729
PyErr_SetString(
730
PyExc_ValueError,
731
"second argument (exceptions) must be a non-empty sequence");
732
goto error;
733
}
734
735
bool nested_base_exceptions = false;
736
for (Py_ssize_t i = 0; i < numexcs; i++) {
737
PyObject *exc = PyTuple_GET_ITEM(exceptions, i);
738
if (!exc) {
739
goto error;
740
}
741
if (!PyExceptionInstance_Check(exc)) {
742
PyErr_Format(
743
PyExc_ValueError,
744
"Item %d of second argument (exceptions) is not an exception",
745
i);
746
goto error;
747
}
748
int is_nonbase_exception = PyObject_IsInstance(exc, PyExc_Exception);
749
if (is_nonbase_exception < 0) {
750
goto error;
751
}
752
else if (is_nonbase_exception == 0) {
753
nested_base_exceptions = true;
754
}
755
}
756
757
PyTypeObject *cls = type;
758
if (cls == PyExc_ExceptionGroup) {
759
if (nested_base_exceptions) {
760
PyErr_SetString(PyExc_TypeError,
761
"Cannot nest BaseExceptions in an ExceptionGroup");
762
goto error;
763
}
764
}
765
else if (cls == (PyTypeObject*)PyExc_BaseExceptionGroup) {
766
if (!nested_base_exceptions) {
767
/* All nested exceptions are Exception subclasses,
768
* wrap them in an ExceptionGroup
769
*/
770
cls = PyExc_ExceptionGroup;
771
}
772
}
773
else {
774
/* user-defined subclass */
775
if (nested_base_exceptions) {
776
int nonbase = PyObject_IsSubclass((PyObject*)cls, PyExc_Exception);
777
if (nonbase == -1) {
778
goto error;
779
}
780
else if (nonbase == 1) {
781
PyErr_Format(PyExc_TypeError,
782
"Cannot nest BaseExceptions in '%.200s'",
783
cls->tp_name);
784
goto error;
785
}
786
}
787
}
788
789
if (!cls) {
790
/* Don't crash during interpreter shutdown
791
* (PyExc_ExceptionGroup may have been cleared)
792
*/
793
cls = (PyTypeObject*)PyExc_BaseExceptionGroup;
794
}
795
PyBaseExceptionGroupObject *self =
796
_PyBaseExceptionGroupObject_cast(BaseException_new(cls, args, kwds));
797
if (!self) {
798
goto error;
799
}
800
801
self->msg = Py_NewRef(message);
802
self->excs = exceptions;
803
return (PyObject*)self;
804
error:
805
Py_DECREF(exceptions);
806
return NULL;
807
}
808
809
PyObject *
810
_PyExc_CreateExceptionGroup(const char *msg_str, PyObject *excs)
811
{
812
PyObject *msg = PyUnicode_FromString(msg_str);
813
if (!msg) {
814
return NULL;
815
}
816
PyObject *args = PyTuple_Pack(2, msg, excs);
817
Py_DECREF(msg);
818
if (!args) {
819
return NULL;
820
}
821
PyObject *result = PyObject_CallObject(PyExc_BaseExceptionGroup, args);
822
Py_DECREF(args);
823
return result;
824
}
825
826
static int
827
BaseExceptionGroup_init(PyBaseExceptionGroupObject *self,
828
PyObject *args, PyObject *kwds)
829
{
830
if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) {
831
return -1;
832
}
833
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) {
834
return -1;
835
}
836
return 0;
837
}
838
839
static int
840
BaseExceptionGroup_clear(PyBaseExceptionGroupObject *self)
841
{
842
Py_CLEAR(self->msg);
843
Py_CLEAR(self->excs);
844
return BaseException_clear((PyBaseExceptionObject *)self);
845
}
846
847
static void
848
BaseExceptionGroup_dealloc(PyBaseExceptionGroupObject *self)
849
{
850
_PyObject_GC_UNTRACK(self);
851
BaseExceptionGroup_clear(self);
852
Py_TYPE(self)->tp_free((PyObject *)self);
853
}
854
855
static int
856
BaseExceptionGroup_traverse(PyBaseExceptionGroupObject *self,
857
visitproc visit, void *arg)
858
{
859
Py_VISIT(self->msg);
860
Py_VISIT(self->excs);
861
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
862
}
863
864
static PyObject *
865
BaseExceptionGroup_str(PyBaseExceptionGroupObject *self)
866
{
867
assert(self->msg);
868
assert(PyUnicode_Check(self->msg));
869
870
assert(PyTuple_CheckExact(self->excs));
871
Py_ssize_t num_excs = PyTuple_Size(self->excs);
872
return PyUnicode_FromFormat(
873
"%S (%zd sub-exception%s)",
874
self->msg, num_excs, num_excs > 1 ? "s" : "");
875
}
876
877
static PyObject *
878
BaseExceptionGroup_derive(PyObject *self_, PyObject *args)
879
{
880
PyBaseExceptionGroupObject *self = _PyBaseExceptionGroupObject_cast(self_);
881
PyObject *excs = NULL;
882
if (!PyArg_ParseTuple(args, "O", &excs)) {
883
return NULL;
884
}
885
PyObject *init_args = PyTuple_Pack(2, self->msg, excs);
886
if (!init_args) {
887
return NULL;
888
}
889
PyObject *eg = PyObject_CallObject(
890
PyExc_BaseExceptionGroup, init_args);
891
Py_DECREF(init_args);
892
return eg;
893
}
894
895
static int
896
exceptiongroup_subset(
897
PyBaseExceptionGroupObject *_orig, PyObject *excs, PyObject **result)
898
{
899
/* Sets *result to an ExceptionGroup wrapping excs with metadata from
900
* _orig. If excs is empty, sets *result to NULL.
901
* Returns 0 on success and -1 on error.
902
903
* This function is used by split() to construct the match/rest parts,
904
* so excs is the matching or non-matching sub-sequence of orig->excs
905
* (this function does not verify that it is a subsequence).
906
*/
907
PyObject *orig = (PyObject *)_orig;
908
909
*result = NULL;
910
Py_ssize_t num_excs = PySequence_Size(excs);
911
if (num_excs < 0) {
912
return -1;
913
}
914
else if (num_excs == 0) {
915
return 0;
916
}
917
918
PyObject *eg = PyObject_CallMethod(
919
orig, "derive", "(O)", excs);
920
if (!eg) {
921
return -1;
922
}
923
924
if (!_PyBaseExceptionGroup_Check(eg)) {
925
PyErr_SetString(PyExc_TypeError,
926
"derive must return an instance of BaseExceptionGroup");
927
goto error;
928
}
929
930
/* Now we hold a reference to the new eg */
931
932
PyObject *tb = PyException_GetTraceback(orig);
933
if (tb) {
934
int res = PyException_SetTraceback(eg, tb);
935
Py_DECREF(tb);
936
if (res < 0) {
937
goto error;
938
}
939
}
940
PyException_SetContext(eg, PyException_GetContext(orig));
941
PyException_SetCause(eg, PyException_GetCause(orig));
942
943
PyObject *notes;
944
if (_PyObject_LookupAttr(orig, &_Py_ID(__notes__), &notes) < 0) {
945
goto error;
946
}
947
if (notes) {
948
if (PySequence_Check(notes)) {
949
/* Make a copy so the parts have independent notes lists. */
950
PyObject *notes_copy = PySequence_List(notes);
951
Py_DECREF(notes);
952
if (notes_copy == NULL) {
953
goto error;
954
}
955
int res = PyObject_SetAttr(eg, &_Py_ID(__notes__), notes_copy);
956
Py_DECREF(notes_copy);
957
if (res < 0) {
958
goto error;
959
}
960
}
961
else {
962
/* __notes__ is supposed to be a list, and split() is not a
963
* good place to report earlier user errors, so we just ignore
964
* notes of non-sequence type.
965
*/
966
Py_DECREF(notes);
967
}
968
}
969
970
*result = eg;
971
return 0;
972
error:
973
Py_DECREF(eg);
974
return -1;
975
}
976
977
typedef enum {
978
/* Exception type or tuple of thereof */
979
EXCEPTION_GROUP_MATCH_BY_TYPE = 0,
980
/* A PyFunction returning True for matching exceptions */
981
EXCEPTION_GROUP_MATCH_BY_PREDICATE = 1,
982
/* A set of the IDs of leaf exceptions to include in the result.
983
* This matcher type is used internally by the interpreter
984
* to construct reraised exceptions.
985
*/
986
EXCEPTION_GROUP_MATCH_INSTANCE_IDS = 2
987
} _exceptiongroup_split_matcher_type;
988
989
static int
990
get_matcher_type(PyObject *value,
991
_exceptiongroup_split_matcher_type *type)
992
{
993
assert(value);
994
995
if (PyCallable_Check(value) && !PyType_Check(value)) {
996
*type = EXCEPTION_GROUP_MATCH_BY_PREDICATE;
997
return 0;
998
}
999
1000
if (PyExceptionClass_Check(value)) {
1001
*type = EXCEPTION_GROUP_MATCH_BY_TYPE;
1002
return 0;
1003
}
1004
1005
if (PyTuple_CheckExact(value)) {
1006
Py_ssize_t n = PyTuple_GET_SIZE(value);
1007
for (Py_ssize_t i=0; i<n; i++) {
1008
if (!PyExceptionClass_Check(PyTuple_GET_ITEM(value, i))) {
1009
goto error;
1010
}
1011
}
1012
*type = EXCEPTION_GROUP_MATCH_BY_TYPE;
1013
return 0;
1014
}
1015
1016
error:
1017
PyErr_SetString(
1018
PyExc_TypeError,
1019
"expected an exception type, a tuple of exception types, or a callable (other than a class)");
1020
return -1;
1021
}
1022
1023
static int
1024
exceptiongroup_split_check_match(PyObject *exc,
1025
_exceptiongroup_split_matcher_type matcher_type,
1026
PyObject *matcher_value)
1027
{
1028
switch (matcher_type) {
1029
case EXCEPTION_GROUP_MATCH_BY_TYPE: {
1030
assert(PyExceptionClass_Check(matcher_value) ||
1031
PyTuple_CheckExact(matcher_value));
1032
return PyErr_GivenExceptionMatches(exc, matcher_value);
1033
}
1034
case EXCEPTION_GROUP_MATCH_BY_PREDICATE: {
1035
assert(PyCallable_Check(matcher_value) && !PyType_Check(matcher_value));
1036
PyObject *exc_matches = PyObject_CallOneArg(matcher_value, exc);
1037
if (exc_matches == NULL) {
1038
return -1;
1039
}
1040
int is_true = PyObject_IsTrue(exc_matches);
1041
Py_DECREF(exc_matches);
1042
return is_true;
1043
}
1044
case EXCEPTION_GROUP_MATCH_INSTANCE_IDS: {
1045
assert(PySet_Check(matcher_value));
1046
if (!_PyBaseExceptionGroup_Check(exc)) {
1047
PyObject *exc_id = PyLong_FromVoidPtr(exc);
1048
if (exc_id == NULL) {
1049
return -1;
1050
}
1051
int res = PySet_Contains(matcher_value, exc_id);
1052
Py_DECREF(exc_id);
1053
return res;
1054
}
1055
return 0;
1056
}
1057
}
1058
return 0;
1059
}
1060
1061
typedef struct {
1062
PyObject *match;
1063
PyObject *rest;
1064
} _exceptiongroup_split_result;
1065
1066
static int
1067
exceptiongroup_split_recursive(PyObject *exc,
1068
_exceptiongroup_split_matcher_type matcher_type,
1069
PyObject *matcher_value,
1070
bool construct_rest,
1071
_exceptiongroup_split_result *result)
1072
{
1073
result->match = NULL;
1074
result->rest = NULL;
1075
1076
int is_match = exceptiongroup_split_check_match(
1077
exc, matcher_type, matcher_value);
1078
if (is_match < 0) {
1079
return -1;
1080
}
1081
1082
if (is_match) {
1083
/* Full match */
1084
result->match = Py_NewRef(exc);
1085
return 0;
1086
}
1087
else if (!_PyBaseExceptionGroup_Check(exc)) {
1088
/* Leaf exception and no match */
1089
if (construct_rest) {
1090
result->rest = Py_NewRef(exc);
1091
}
1092
return 0;
1093
}
1094
1095
/* Partial match */
1096
1097
PyBaseExceptionGroupObject *eg = _PyBaseExceptionGroupObject_cast(exc);
1098
assert(PyTuple_CheckExact(eg->excs));
1099
Py_ssize_t num_excs = PyTuple_Size(eg->excs);
1100
if (num_excs < 0) {
1101
return -1;
1102
}
1103
assert(num_excs > 0); /* checked in constructor, and excs is read-only */
1104
1105
int retval = -1;
1106
PyObject *match_list = PyList_New(0);
1107
if (!match_list) {
1108
return -1;
1109
}
1110
1111
PyObject *rest_list = NULL;
1112
if (construct_rest) {
1113
rest_list = PyList_New(0);
1114
if (!rest_list) {
1115
goto done;
1116
}
1117
}
1118
/* recursive calls */
1119
for (Py_ssize_t i = 0; i < num_excs; i++) {
1120
PyObject *e = PyTuple_GET_ITEM(eg->excs, i);
1121
_exceptiongroup_split_result rec_result;
1122
if (_Py_EnterRecursiveCall(" in exceptiongroup_split_recursive")) {
1123
goto done;
1124
}
1125
if (exceptiongroup_split_recursive(
1126
e, matcher_type, matcher_value,
1127
construct_rest, &rec_result) < 0) {
1128
assert(!rec_result.match);
1129
assert(!rec_result.rest);
1130
_Py_LeaveRecursiveCall();
1131
goto done;
1132
}
1133
_Py_LeaveRecursiveCall();
1134
if (rec_result.match) {
1135
assert(PyList_CheckExact(match_list));
1136
if (PyList_Append(match_list, rec_result.match) < 0) {
1137
Py_DECREF(rec_result.match);
1138
Py_XDECREF(rec_result.rest);
1139
goto done;
1140
}
1141
Py_DECREF(rec_result.match);
1142
}
1143
if (rec_result.rest) {
1144
assert(construct_rest);
1145
assert(PyList_CheckExact(rest_list));
1146
if (PyList_Append(rest_list, rec_result.rest) < 0) {
1147
Py_DECREF(rec_result.rest);
1148
goto done;
1149
}
1150
Py_DECREF(rec_result.rest);
1151
}
1152
}
1153
1154
/* construct result */
1155
if (exceptiongroup_subset(eg, match_list, &result->match) < 0) {
1156
goto done;
1157
}
1158
1159
if (construct_rest) {
1160
assert(PyList_CheckExact(rest_list));
1161
if (exceptiongroup_subset(eg, rest_list, &result->rest) < 0) {
1162
Py_CLEAR(result->match);
1163
goto done;
1164
}
1165
}
1166
retval = 0;
1167
done:
1168
Py_DECREF(match_list);
1169
Py_XDECREF(rest_list);
1170
if (retval < 0) {
1171
Py_CLEAR(result->match);
1172
Py_CLEAR(result->rest);
1173
}
1174
return retval;
1175
}
1176
1177
static PyObject *
1178
BaseExceptionGroup_split(PyObject *self, PyObject *args)
1179
{
1180
PyObject *matcher_value = NULL;
1181
if (!PyArg_UnpackTuple(args, "split", 1, 1, &matcher_value)) {
1182
return NULL;
1183
}
1184
1185
_exceptiongroup_split_matcher_type matcher_type;
1186
if (get_matcher_type(matcher_value, &matcher_type) < 0) {
1187
return NULL;
1188
}
1189
1190
_exceptiongroup_split_result split_result;
1191
bool construct_rest = true;
1192
if (exceptiongroup_split_recursive(
1193
self, matcher_type, matcher_value,
1194
construct_rest, &split_result) < 0) {
1195
return NULL;
1196
}
1197
1198
PyObject *result = PyTuple_Pack(
1199
2,
1200
split_result.match ? split_result.match : Py_None,
1201
split_result.rest ? split_result.rest : Py_None);
1202
1203
Py_XDECREF(split_result.match);
1204
Py_XDECREF(split_result.rest);
1205
return result;
1206
}
1207
1208
static PyObject *
1209
BaseExceptionGroup_subgroup(PyObject *self, PyObject *args)
1210
{
1211
PyObject *matcher_value = NULL;
1212
if (!PyArg_UnpackTuple(args, "subgroup", 1, 1, &matcher_value)) {
1213
return NULL;
1214
}
1215
1216
_exceptiongroup_split_matcher_type matcher_type;
1217
if (get_matcher_type(matcher_value, &matcher_type) < 0) {
1218
return NULL;
1219
}
1220
1221
_exceptiongroup_split_result split_result;
1222
bool construct_rest = false;
1223
if (exceptiongroup_split_recursive(
1224
self, matcher_type, matcher_value,
1225
construct_rest, &split_result) < 0) {
1226
return NULL;
1227
}
1228
1229
PyObject *result = Py_NewRef(
1230
split_result.match ? split_result.match : Py_None);
1231
1232
Py_XDECREF(split_result.match);
1233
assert(!split_result.rest);
1234
return result;
1235
}
1236
1237
static int
1238
collect_exception_group_leaf_ids(PyObject *exc, PyObject *leaf_ids)
1239
{
1240
if (Py_IsNone(exc)) {
1241
return 0;
1242
}
1243
1244
assert(PyExceptionInstance_Check(exc));
1245
assert(PySet_Check(leaf_ids));
1246
1247
/* Add IDs of all leaf exceptions in exc to the leaf_ids set */
1248
1249
if (!_PyBaseExceptionGroup_Check(exc)) {
1250
PyObject *exc_id = PyLong_FromVoidPtr(exc);
1251
if (exc_id == NULL) {
1252
return -1;
1253
}
1254
int res = PySet_Add(leaf_ids, exc_id);
1255
Py_DECREF(exc_id);
1256
return res;
1257
}
1258
PyBaseExceptionGroupObject *eg = _PyBaseExceptionGroupObject_cast(exc);
1259
Py_ssize_t num_excs = PyTuple_GET_SIZE(eg->excs);
1260
/* recursive calls */
1261
for (Py_ssize_t i = 0; i < num_excs; i++) {
1262
PyObject *e = PyTuple_GET_ITEM(eg->excs, i);
1263
if (_Py_EnterRecursiveCall(" in collect_exception_group_leaf_ids")) {
1264
return -1;
1265
}
1266
int res = collect_exception_group_leaf_ids(e, leaf_ids);
1267
_Py_LeaveRecursiveCall();
1268
if (res < 0) {
1269
return -1;
1270
}
1271
}
1272
return 0;
1273
}
1274
1275
/* This function is used by the interpreter to construct reraised
1276
* exception groups. It takes an exception group eg and a list
1277
* of exception groups keep and returns the sub-exception group
1278
* of eg which contains all leaf exceptions that are contained
1279
* in any exception group in keep.
1280
*/
1281
static PyObject *
1282
exception_group_projection(PyObject *eg, PyObject *keep)
1283
{
1284
assert(_PyBaseExceptionGroup_Check(eg));
1285
assert(PyList_CheckExact(keep));
1286
1287
PyObject *leaf_ids = PySet_New(NULL);
1288
if (!leaf_ids) {
1289
return NULL;
1290
}
1291
1292
Py_ssize_t n = PyList_GET_SIZE(keep);
1293
for (Py_ssize_t i = 0; i < n; i++) {
1294
PyObject *e = PyList_GET_ITEM(keep, i);
1295
assert(e != NULL);
1296
assert(_PyBaseExceptionGroup_Check(e));
1297
if (collect_exception_group_leaf_ids(e, leaf_ids) < 0) {
1298
Py_DECREF(leaf_ids);
1299
return NULL;
1300
}
1301
}
1302
1303
_exceptiongroup_split_result split_result;
1304
bool construct_rest = false;
1305
int err = exceptiongroup_split_recursive(
1306
eg, EXCEPTION_GROUP_MATCH_INSTANCE_IDS, leaf_ids,
1307
construct_rest, &split_result);
1308
Py_DECREF(leaf_ids);
1309
if (err < 0) {
1310
return NULL;
1311
}
1312
1313
PyObject *result = split_result.match ?
1314
split_result.match : Py_NewRef(Py_None);
1315
assert(split_result.rest == NULL);
1316
return result;
1317
}
1318
1319
static bool
1320
is_same_exception_metadata(PyObject *exc1, PyObject *exc2)
1321
{
1322
assert(PyExceptionInstance_Check(exc1));
1323
assert(PyExceptionInstance_Check(exc2));
1324
1325
PyBaseExceptionObject *e1 = (PyBaseExceptionObject *)exc1;
1326
PyBaseExceptionObject *e2 = (PyBaseExceptionObject *)exc2;
1327
1328
return (e1->notes == e2->notes &&
1329
e1->traceback == e2->traceback &&
1330
e1->cause == e2->cause &&
1331
e1->context == e2->context);
1332
}
1333
1334
/*
1335
This function is used by the interpreter to calculate
1336
the exception group to be raised at the end of a
1337
try-except* construct.
1338
1339
orig: the original except that was caught.
1340
excs: a list of exceptions that were raised/reraised
1341
in the except* clauses.
1342
1343
Calculates an exception group to raise. It contains
1344
all exceptions in excs, where those that were reraised
1345
have same nesting structure as in orig, and those that
1346
were raised (if any) are added as siblings in a new EG.
1347
1348
Returns NULL and sets an exception on failure.
1349
*/
1350
PyObject *
1351
_PyExc_PrepReraiseStar(PyObject *orig, PyObject *excs)
1352
{
1353
/* orig must be a raised & caught exception, so it has a traceback */
1354
assert(PyExceptionInstance_Check(orig));
1355
assert(_PyBaseExceptionObject_cast(orig)->traceback != NULL);
1356
1357
assert(PyList_Check(excs));
1358
1359
Py_ssize_t numexcs = PyList_GET_SIZE(excs);
1360
1361
if (numexcs == 0) {
1362
return Py_NewRef(Py_None);
1363
}
1364
1365
if (!_PyBaseExceptionGroup_Check(orig)) {
1366
/* a naked exception was caught and wrapped. Only one except* clause
1367
* could have executed,so there is at most one exception to raise.
1368
*/
1369
1370
assert(numexcs == 1 || (numexcs == 2 && PyList_GET_ITEM(excs, 1) == Py_None));
1371
1372
PyObject *e = PyList_GET_ITEM(excs, 0);
1373
assert(e != NULL);
1374
return Py_NewRef(e);
1375
}
1376
1377
PyObject *raised_list = PyList_New(0);
1378
if (raised_list == NULL) {
1379
return NULL;
1380
}
1381
PyObject* reraised_list = PyList_New(0);
1382
if (reraised_list == NULL) {
1383
Py_DECREF(raised_list);
1384
return NULL;
1385
}
1386
1387
/* Now we are holding refs to raised_list and reraised_list */
1388
1389
PyObject *result = NULL;
1390
1391
/* Split excs into raised and reraised by comparing metadata with orig */
1392
for (Py_ssize_t i = 0; i < numexcs; i++) {
1393
PyObject *e = PyList_GET_ITEM(excs, i);
1394
assert(e != NULL);
1395
if (Py_IsNone(e)) {
1396
continue;
1397
}
1398
bool is_reraise = is_same_exception_metadata(e, orig);
1399
PyObject *append_list = is_reraise ? reraised_list : raised_list;
1400
if (PyList_Append(append_list, e) < 0) {
1401
goto done;
1402
}
1403
}
1404
1405
PyObject *reraised_eg = exception_group_projection(orig, reraised_list);
1406
if (reraised_eg == NULL) {
1407
goto done;
1408
}
1409
1410
if (!Py_IsNone(reraised_eg)) {
1411
assert(is_same_exception_metadata(reraised_eg, orig));
1412
}
1413
Py_ssize_t num_raised = PyList_GET_SIZE(raised_list);
1414
if (num_raised == 0) {
1415
result = reraised_eg;
1416
}
1417
else if (num_raised > 0) {
1418
int res = 0;
1419
if (!Py_IsNone(reraised_eg)) {
1420
res = PyList_Append(raised_list, reraised_eg);
1421
}
1422
Py_DECREF(reraised_eg);
1423
if (res < 0) {
1424
goto done;
1425
}
1426
if (PyList_GET_SIZE(raised_list) > 1) {
1427
result = _PyExc_CreateExceptionGroup("", raised_list);
1428
}
1429
else {
1430
result = Py_NewRef(PyList_GetItem(raised_list, 0));
1431
}
1432
if (result == NULL) {
1433
goto done;
1434
}
1435
}
1436
1437
done:
1438
Py_XDECREF(raised_list);
1439
Py_XDECREF(reraised_list);
1440
return result;
1441
}
1442
1443
PyObject *
1444
PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs)
1445
{
1446
if (orig == NULL || !PyExceptionInstance_Check(orig)) {
1447
PyErr_SetString(PyExc_TypeError, "orig must be an exception instance");
1448
return NULL;
1449
}
1450
if (excs == NULL || !PyList_Check(excs)) {
1451
PyErr_SetString(PyExc_TypeError,
1452
"excs must be a list of exception instances");
1453
return NULL;
1454
}
1455
Py_ssize_t numexcs = PyList_GET_SIZE(excs);
1456
for (Py_ssize_t i = 0; i < numexcs; i++) {
1457
PyObject *exc = PyList_GET_ITEM(excs, i);
1458
if (exc == NULL || !(PyExceptionInstance_Check(exc) || Py_IsNone(exc))) {
1459
PyErr_Format(PyExc_TypeError,
1460
"item %d of excs is not an exception", i);
1461
return NULL;
1462
}
1463
}
1464
1465
/* Make sure that orig has something as traceback, in the interpreter
1466
* it always does because it's a raised exception.
1467
*/
1468
PyObject *tb = PyException_GetTraceback(orig);
1469
1470
if (tb == NULL) {
1471
PyErr_Format(PyExc_ValueError, "orig must be a raised exception");
1472
return NULL;
1473
}
1474
Py_DECREF(tb);
1475
1476
return _PyExc_PrepReraiseStar(orig, excs);
1477
}
1478
1479
static PyMemberDef BaseExceptionGroup_members[] = {
1480
{"message", T_OBJECT, offsetof(PyBaseExceptionGroupObject, msg), READONLY,
1481
PyDoc_STR("exception message")},
1482
{"exceptions", T_OBJECT, offsetof(PyBaseExceptionGroupObject, excs), READONLY,
1483
PyDoc_STR("nested exceptions")},
1484
{NULL} /* Sentinel */
1485
};
1486
1487
static PyMethodDef BaseExceptionGroup_methods[] = {
1488
{"__class_getitem__", (PyCFunction)Py_GenericAlias,
1489
METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
1490
{"derive", (PyCFunction)BaseExceptionGroup_derive, METH_VARARGS},
1491
{"split", (PyCFunction)BaseExceptionGroup_split, METH_VARARGS},
1492
{"subgroup", (PyCFunction)BaseExceptionGroup_subgroup, METH_VARARGS},
1493
{NULL}
1494
};
1495
1496
ComplexExtendsException(PyExc_BaseException, BaseExceptionGroup,
1497
BaseExceptionGroup, BaseExceptionGroup_new /* new */,
1498
BaseExceptionGroup_methods, BaseExceptionGroup_members,
1499
0 /* getset */, BaseExceptionGroup_str,
1500
"A combination of multiple unrelated exceptions.");
1501
1502
/*
1503
* ExceptionGroup extends BaseExceptionGroup, Exception
1504
*/
1505
static PyObject*
1506
create_exception_group_class(void) {
1507
struct _Py_exc_state *state = get_exc_state();
1508
1509
PyObject *bases = PyTuple_Pack(
1510
2, PyExc_BaseExceptionGroup, PyExc_Exception);
1511
if (bases == NULL) {
1512
return NULL;
1513
}
1514
1515
assert(!state->PyExc_ExceptionGroup);
1516
state->PyExc_ExceptionGroup = PyErr_NewException(
1517
"builtins.ExceptionGroup", bases, NULL);
1518
1519
Py_DECREF(bases);
1520
return state->PyExc_ExceptionGroup;
1521
}
1522
1523
/*
1524
* KeyboardInterrupt extends BaseException
1525
*/
1526
SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
1527
"Program interrupted by user.");
1528
1529
1530
/*
1531
* ImportError extends Exception
1532
*/
1533
1534
static int
1535
ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
1536
{
1537
static char *kwlist[] = {"name", "path", "name_from", 0};
1538
PyObject *empty_tuple;
1539
PyObject *msg = NULL;
1540
PyObject *name = NULL;
1541
PyObject *path = NULL;
1542
PyObject *name_from = NULL;
1543
1544
if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1)
1545
return -1;
1546
1547
empty_tuple = PyTuple_New(0);
1548
if (!empty_tuple)
1549
return -1;
1550
if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OOO:ImportError", kwlist,
1551
&name, &path, &name_from)) {
1552
Py_DECREF(empty_tuple);
1553
return -1;
1554
}
1555
Py_DECREF(empty_tuple);
1556
1557
Py_XSETREF(self->name, Py_XNewRef(name));
1558
Py_XSETREF(self->path, Py_XNewRef(path));
1559
Py_XSETREF(self->name_from, Py_XNewRef(name_from));
1560
1561
if (PyTuple_GET_SIZE(args) == 1) {
1562
msg = Py_NewRef(PyTuple_GET_ITEM(args, 0));
1563
}
1564
Py_XSETREF(self->msg, msg);
1565
1566
return 0;
1567
}
1568
1569
static int
1570
ImportError_clear(PyImportErrorObject *self)
1571
{
1572
Py_CLEAR(self->msg);
1573
Py_CLEAR(self->name);
1574
Py_CLEAR(self->path);
1575
Py_CLEAR(self->name_from);
1576
return BaseException_clear((PyBaseExceptionObject *)self);
1577
}
1578
1579
static void
1580
ImportError_dealloc(PyImportErrorObject *self)
1581
{
1582
_PyObject_GC_UNTRACK(self);
1583
ImportError_clear(self);
1584
Py_TYPE(self)->tp_free((PyObject *)self);
1585
}
1586
1587
static int
1588
ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
1589
{
1590
Py_VISIT(self->msg);
1591
Py_VISIT(self->name);
1592
Py_VISIT(self->path);
1593
Py_VISIT(self->name_from);
1594
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1595
}
1596
1597
static PyObject *
1598
ImportError_str(PyImportErrorObject *self)
1599
{
1600
if (self->msg && PyUnicode_CheckExact(self->msg)) {
1601
return Py_NewRef(self->msg);
1602
}
1603
else {
1604
return BaseException_str((PyBaseExceptionObject *)self);
1605
}
1606
}
1607
1608
static PyObject *
1609
ImportError_getstate(PyImportErrorObject *self)
1610
{
1611
PyObject *dict = ((PyBaseExceptionObject *)self)->dict;
1612
if (self->name || self->path || self->name_from) {
1613
dict = dict ? PyDict_Copy(dict) : PyDict_New();
1614
if (dict == NULL)
1615
return NULL;
1616
if (self->name && PyDict_SetItem(dict, &_Py_ID(name), self->name) < 0) {
1617
Py_DECREF(dict);
1618
return NULL;
1619
}
1620
if (self->path && PyDict_SetItem(dict, &_Py_ID(path), self->path) < 0) {
1621
Py_DECREF(dict);
1622
return NULL;
1623
}
1624
if (self->name_from && PyDict_SetItem(dict, &_Py_ID(name_from), self->name_from) < 0) {
1625
Py_DECREF(dict);
1626
return NULL;
1627
}
1628
return dict;
1629
}
1630
else if (dict) {
1631
return Py_NewRef(dict);
1632
}
1633
else {
1634
Py_RETURN_NONE;
1635
}
1636
}
1637
1638
/* Pickling support */
1639
static PyObject *
1640
ImportError_reduce(PyImportErrorObject *self, PyObject *Py_UNUSED(ignored))
1641
{
1642
PyObject *res;
1643
PyObject *args;
1644
PyObject *state = ImportError_getstate(self);
1645
if (state == NULL)
1646
return NULL;
1647
args = ((PyBaseExceptionObject *)self)->args;
1648
if (state == Py_None)
1649
res = PyTuple_Pack(2, Py_TYPE(self), args);
1650
else
1651
res = PyTuple_Pack(3, Py_TYPE(self), args, state);
1652
Py_DECREF(state);
1653
return res;
1654
}
1655
1656
static PyMemberDef ImportError_members[] = {
1657
{"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
1658
PyDoc_STR("exception message")},
1659
{"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
1660
PyDoc_STR("module name")},
1661
{"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
1662
PyDoc_STR("module path")},
1663
{"name_from", T_OBJECT, offsetof(PyImportErrorObject, name_from), 0,
1664
PyDoc_STR("name imported from module")},
1665
{NULL} /* Sentinel */
1666
};
1667
1668
static PyMethodDef ImportError_methods[] = {
1669
{"__reduce__", (PyCFunction)ImportError_reduce, METH_NOARGS},
1670
{NULL}
1671
};
1672
1673
ComplexExtendsException(PyExc_Exception, ImportError,
1674
ImportError, 0 /* new */,
1675
ImportError_methods, ImportError_members,
1676
0 /* getset */, ImportError_str,
1677
"Import can't find module, or can't find name in "
1678
"module.");
1679
1680
/*
1681
* ModuleNotFoundError extends ImportError
1682
*/
1683
1684
MiddlingExtendsException(PyExc_ImportError, ModuleNotFoundError, ImportError,
1685
"Module not found.");
1686
1687
/*
1688
* OSError extends Exception
1689
*/
1690
1691
#ifdef MS_WINDOWS
1692
#include "errmap.h"
1693
#endif
1694
1695
/* Where a function has a single filename, such as open() or some
1696
* of the os module functions, PyErr_SetFromErrnoWithFilename() is
1697
* called, giving a third argument which is the filename. But, so
1698
* that old code using in-place unpacking doesn't break, e.g.:
1699
*
1700
* except OSError, (errno, strerror):
1701
*
1702
* we hack args so that it only contains two items. This also
1703
* means we need our own __str__() which prints out the filename
1704
* when it was supplied.
1705
*
1706
* (If a function has two filenames, such as rename(), symlink(),
1707
* or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
1708
* which allows passing in a second filename.)
1709
*/
1710
1711
/* This function doesn't cleanup on error, the caller should */
1712
static int
1713
oserror_parse_args(PyObject **p_args,
1714
PyObject **myerrno, PyObject **strerror,
1715
PyObject **filename, PyObject **filename2
1716
#ifdef MS_WINDOWS
1717
, PyObject **winerror
1718
#endif
1719
)
1720
{
1721
Py_ssize_t nargs;
1722
PyObject *args = *p_args;
1723
#ifndef MS_WINDOWS
1724
/*
1725
* ignored on non-Windows platforms,
1726
* but parsed so OSError has a consistent signature
1727
*/
1728
PyObject *_winerror = NULL;
1729
PyObject **winerror = &_winerror;
1730
#endif /* MS_WINDOWS */
1731
1732
nargs = PyTuple_GET_SIZE(args);
1733
1734
if (nargs >= 2 && nargs <= 5) {
1735
if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
1736
myerrno, strerror,
1737
filename, winerror, filename2))
1738
return -1;
1739
#ifdef MS_WINDOWS
1740
if (*winerror && PyLong_Check(*winerror)) {
1741
long errcode, winerrcode;
1742
PyObject *newargs;
1743
Py_ssize_t i;
1744
1745
winerrcode = PyLong_AsLong(*winerror);
1746
if (winerrcode == -1 && PyErr_Occurred())
1747
return -1;
1748
errcode = winerror_to_errno(winerrcode);
1749
*myerrno = PyLong_FromLong(errcode);
1750
if (!*myerrno)
1751
return -1;
1752
newargs = PyTuple_New(nargs);
1753
if (!newargs)
1754
return -1;
1755
PyTuple_SET_ITEM(newargs, 0, *myerrno);
1756
for (i = 1; i < nargs; i++) {
1757
PyObject *val = PyTuple_GET_ITEM(args, i);
1758
PyTuple_SET_ITEM(newargs, i, Py_NewRef(val));
1759
}
1760
Py_DECREF(args);
1761
args = *p_args = newargs;
1762
}
1763
#endif /* MS_WINDOWS */
1764
}
1765
1766
return 0;
1767
}
1768
1769
static int
1770
oserror_init(PyOSErrorObject *self, PyObject **p_args,
1771
PyObject *myerrno, PyObject *strerror,
1772
PyObject *filename, PyObject *filename2
1773
#ifdef MS_WINDOWS
1774
, PyObject *winerror
1775
#endif
1776
)
1777
{
1778
PyObject *args = *p_args;
1779
Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1780
1781
/* self->filename will remain Py_None otherwise */
1782
if (filename && filename != Py_None) {
1783
if (Py_IS_TYPE(self, (PyTypeObject *) PyExc_BlockingIOError) &&
1784
PyNumber_Check(filename)) {
1785
/* BlockingIOError's 3rd argument can be the number of
1786
* characters written.
1787
*/
1788
self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
1789
if (self->written == -1 && PyErr_Occurred())
1790
return -1;
1791
}
1792
else {
1793
self->filename = Py_NewRef(filename);
1794
1795
if (filename2 && filename2 != Py_None) {
1796
self->filename2 = Py_NewRef(filename2);
1797
}
1798
1799
if (nargs >= 2 && nargs <= 5) {
1800
/* filename, filename2, and winerror are removed from the args tuple
1801
(for compatibility purposes, see test_exceptions.py) */
1802
PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
1803
if (!subslice)
1804
return -1;
1805
1806
Py_DECREF(args); /* replacing args */
1807
*p_args = args = subslice;
1808
}
1809
}
1810
}
1811
self->myerrno = Py_XNewRef(myerrno);
1812
self->strerror = Py_XNewRef(strerror);
1813
#ifdef MS_WINDOWS
1814
self->winerror = Py_XNewRef(winerror);
1815
#endif
1816
1817
/* Steals the reference to args */
1818
Py_XSETREF(self->args, args);
1819
*p_args = args = NULL;
1820
1821
return 0;
1822
}
1823
1824
static PyObject *
1825
OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1826
static int
1827
OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
1828
1829
static int
1830
oserror_use_init(PyTypeObject *type)
1831
{
1832
/* When __init__ is defined in an OSError subclass, we want any
1833
extraneous argument to __new__ to be ignored. The only reasonable
1834
solution, given __new__ takes a variable number of arguments,
1835
is to defer arg parsing and initialization to __init__.
1836
1837
But when __new__ is overridden as well, it should call our __new__
1838
with the right arguments.
1839
1840
(see http://bugs.python.org/issue12555#msg148829 )
1841
*/
1842
if (type->tp_init != (initproc) OSError_init &&
1843
type->tp_new == (newfunc) OSError_new) {
1844
assert((PyObject *) type != PyExc_OSError);
1845
return 1;
1846
}
1847
return 0;
1848
}
1849
1850
static PyObject *
1851
OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1852
{
1853
PyOSErrorObject *self = NULL;
1854
PyObject *myerrno = NULL, *strerror = NULL;
1855
PyObject *filename = NULL, *filename2 = NULL;
1856
#ifdef MS_WINDOWS
1857
PyObject *winerror = NULL;
1858
#endif
1859
1860
Py_INCREF(args);
1861
1862
if (!oserror_use_init(type)) {
1863
if (!_PyArg_NoKeywords(type->tp_name, kwds))
1864
goto error;
1865
1866
if (oserror_parse_args(&args, &myerrno, &strerror,
1867
&filename, &filename2
1868
#ifdef MS_WINDOWS
1869
, &winerror
1870
#endif
1871
))
1872
goto error;
1873
1874
struct _Py_exc_state *state = get_exc_state();
1875
if (myerrno && PyLong_Check(myerrno) &&
1876
state->errnomap && (PyObject *) type == PyExc_OSError) {
1877
PyObject *newtype;
1878
newtype = PyDict_GetItemWithError(state->errnomap, myerrno);
1879
if (newtype) {
1880
type = _PyType_CAST(newtype);
1881
}
1882
else if (PyErr_Occurred())
1883
goto error;
1884
}
1885
}
1886
1887
self = (PyOSErrorObject *) type->tp_alloc(type, 0);
1888
if (!self)
1889
goto error;
1890
1891
self->dict = NULL;
1892
self->traceback = self->cause = self->context = NULL;
1893
self->written = -1;
1894
1895
if (!oserror_use_init(type)) {
1896
if (oserror_init(self, &args, myerrno, strerror, filename, filename2
1897
#ifdef MS_WINDOWS
1898
, winerror
1899
#endif
1900
))
1901
goto error;
1902
}
1903
else {
1904
self->args = PyTuple_New(0);
1905
if (self->args == NULL)
1906
goto error;
1907
}
1908
1909
Py_XDECREF(args);
1910
return (PyObject *) self;
1911
1912
error:
1913
Py_XDECREF(args);
1914
Py_XDECREF(self);
1915
return NULL;
1916
}
1917
1918
static int
1919
OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
1920
{
1921
PyObject *myerrno = NULL, *strerror = NULL;
1922
PyObject *filename = NULL, *filename2 = NULL;
1923
#ifdef MS_WINDOWS
1924
PyObject *winerror = NULL;
1925
#endif
1926
1927
if (!oserror_use_init(Py_TYPE(self)))
1928
/* Everything already done in OSError_new */
1929
return 0;
1930
1931
if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
1932
return -1;
1933
1934
Py_INCREF(args);
1935
if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
1936
#ifdef MS_WINDOWS
1937
, &winerror
1938
#endif
1939
))
1940
goto error;
1941
1942
if (oserror_init(self, &args, myerrno, strerror, filename, filename2
1943
#ifdef MS_WINDOWS
1944
, winerror
1945
#endif
1946
))
1947
goto error;
1948
1949
return 0;
1950
1951
error:
1952
Py_DECREF(args);
1953
return -1;
1954
}
1955
1956
static int
1957
OSError_clear(PyOSErrorObject *self)
1958
{
1959
Py_CLEAR(self->myerrno);
1960
Py_CLEAR(self->strerror);
1961
Py_CLEAR(self->filename);
1962
Py_CLEAR(self->filename2);
1963
#ifdef MS_WINDOWS
1964
Py_CLEAR(self->winerror);
1965
#endif
1966
return BaseException_clear((PyBaseExceptionObject *)self);
1967
}
1968
1969
static void
1970
OSError_dealloc(PyOSErrorObject *self)
1971
{
1972
_PyObject_GC_UNTRACK(self);
1973
OSError_clear(self);
1974
Py_TYPE(self)->tp_free((PyObject *)self);
1975
}
1976
1977
static int
1978
OSError_traverse(PyOSErrorObject *self, visitproc visit,
1979
void *arg)
1980
{
1981
Py_VISIT(self->myerrno);
1982
Py_VISIT(self->strerror);
1983
Py_VISIT(self->filename);
1984
Py_VISIT(self->filename2);
1985
#ifdef MS_WINDOWS
1986
Py_VISIT(self->winerror);
1987
#endif
1988
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1989
}
1990
1991
static PyObject *
1992
OSError_str(PyOSErrorObject *self)
1993
{
1994
#define OR_NONE(x) ((x)?(x):Py_None)
1995
#ifdef MS_WINDOWS
1996
/* If available, winerror has the priority over myerrno */
1997
if (self->winerror && self->filename) {
1998
if (self->filename2) {
1999
return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
2000
OR_NONE(self->winerror),
2001
OR_NONE(self->strerror),
2002
self->filename,
2003
self->filename2);
2004
} else {
2005
return PyUnicode_FromFormat("[WinError %S] %S: %R",
2006
OR_NONE(self->winerror),
2007
OR_NONE(self->strerror),
2008
self->filename);
2009
}
2010
}
2011
if (self->winerror && self->strerror)
2012
return PyUnicode_FromFormat("[WinError %S] %S",
2013
self->winerror ? self->winerror: Py_None,
2014
self->strerror ? self->strerror: Py_None);
2015
#endif
2016
if (self->filename) {
2017
if (self->filename2) {
2018
return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
2019
OR_NONE(self->myerrno),
2020
OR_NONE(self->strerror),
2021
self->filename,
2022
self->filename2);
2023
} else {
2024
return PyUnicode_FromFormat("[Errno %S] %S: %R",
2025
OR_NONE(self->myerrno),
2026
OR_NONE(self->strerror),
2027
self->filename);
2028
}
2029
}
2030
if (self->myerrno && self->strerror)
2031
return PyUnicode_FromFormat("[Errno %S] %S",
2032
self->myerrno, self->strerror);
2033
return BaseException_str((PyBaseExceptionObject *)self);
2034
}
2035
2036
static PyObject *
2037
OSError_reduce(PyOSErrorObject *self, PyObject *Py_UNUSED(ignored))
2038
{
2039
PyObject *args = self->args;
2040
PyObject *res = NULL;
2041
2042
/* self->args is only the first two real arguments if there was a
2043
* file name given to OSError. */
2044
if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
2045
Py_ssize_t size = self->filename2 ? 5 : 3;
2046
args = PyTuple_New(size);
2047
if (!args)
2048
return NULL;
2049
2050
PyTuple_SET_ITEM(args, 0, Py_NewRef(PyTuple_GET_ITEM(self->args, 0)));
2051
PyTuple_SET_ITEM(args, 1, Py_NewRef(PyTuple_GET_ITEM(self->args, 1)));
2052
PyTuple_SET_ITEM(args, 2, Py_NewRef(self->filename));
2053
2054
if (self->filename2) {
2055
/*
2056
* This tuple is essentially used as OSError(*args).
2057
* So, to recreate filename2, we need to pass in
2058
* winerror as well.
2059
*/
2060
PyTuple_SET_ITEM(args, 3, Py_NewRef(Py_None));
2061
2062
/* filename2 */
2063
PyTuple_SET_ITEM(args, 4, Py_NewRef(self->filename2));
2064
}
2065
} else
2066
Py_INCREF(args);
2067
2068
if (self->dict)
2069
res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
2070
else
2071
res = PyTuple_Pack(2, Py_TYPE(self), args);
2072
Py_DECREF(args);
2073
return res;
2074
}
2075
2076
static PyObject *
2077
OSError_written_get(PyOSErrorObject *self, void *context)
2078
{
2079
if (self->written == -1) {
2080
PyErr_SetString(PyExc_AttributeError, "characters_written");
2081
return NULL;
2082
}
2083
return PyLong_FromSsize_t(self->written);
2084
}
2085
2086
static int
2087
OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
2088
{
2089
if (arg == NULL) {
2090
if (self->written == -1) {
2091
PyErr_SetString(PyExc_AttributeError, "characters_written");
2092
return -1;
2093
}
2094
self->written = -1;
2095
return 0;
2096
}
2097
Py_ssize_t n;
2098
n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
2099
if (n == -1 && PyErr_Occurred())
2100
return -1;
2101
self->written = n;
2102
return 0;
2103
}
2104
2105
static PyMemberDef OSError_members[] = {
2106
{"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
2107
PyDoc_STR("POSIX exception code")},
2108
{"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
2109
PyDoc_STR("exception strerror")},
2110
{"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
2111
PyDoc_STR("exception filename")},
2112
{"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
2113
PyDoc_STR("second exception filename")},
2114
#ifdef MS_WINDOWS
2115
{"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
2116
PyDoc_STR("Win32 exception code")},
2117
#endif
2118
{NULL} /* Sentinel */
2119
};
2120
2121
static PyMethodDef OSError_methods[] = {
2122
{"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
2123
{NULL}
2124
};
2125
2126
static PyGetSetDef OSError_getset[] = {
2127
{"characters_written", (getter) OSError_written_get,
2128
(setter) OSError_written_set, NULL},
2129
{NULL}
2130
};
2131
2132
2133
ComplexExtendsException(PyExc_Exception, OSError,
2134
OSError, OSError_new,
2135
OSError_methods, OSError_members, OSError_getset,
2136
OSError_str,
2137
"Base class for I/O related errors.");
2138
2139
2140
/*
2141
* Various OSError subclasses
2142
*/
2143
MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
2144
"I/O operation would block.");
2145
MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
2146
"Connection error.");
2147
MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
2148
"Child process error.");
2149
MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
2150
"Broken pipe.");
2151
MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
2152
"Connection aborted.");
2153
MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
2154
"Connection refused.");
2155
MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
2156
"Connection reset.");
2157
MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
2158
"File already exists.");
2159
MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
2160
"File not found.");
2161
MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
2162
"Operation doesn't work on directories.");
2163
MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
2164
"Operation only works on directories.");
2165
MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
2166
"Interrupted by signal.");
2167
MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
2168
"Not enough permissions.");
2169
MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
2170
"Process not found.");
2171
MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
2172
"Timeout expired.");
2173
2174
/*
2175
* EOFError extends Exception
2176
*/
2177
SimpleExtendsException(PyExc_Exception, EOFError,
2178
"Read beyond end of file.");
2179
2180
2181
/*
2182
* RuntimeError extends Exception
2183
*/
2184
SimpleExtendsException(PyExc_Exception, RuntimeError,
2185
"Unspecified run-time error.");
2186
2187
/*
2188
* RecursionError extends RuntimeError
2189
*/
2190
SimpleExtendsException(PyExc_RuntimeError, RecursionError,
2191
"Recursion limit exceeded.");
2192
2193
/*
2194
* NotImplementedError extends RuntimeError
2195
*/
2196
SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
2197
"Method or function hasn't been implemented yet.");
2198
2199
/*
2200
* NameError extends Exception
2201
*/
2202
2203
static int
2204
NameError_init(PyNameErrorObject *self, PyObject *args, PyObject *kwds)
2205
{
2206
static char *kwlist[] = {"name", NULL};
2207
PyObject *name = NULL;
2208
2209
if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1) {
2210
return -1;
2211
}
2212
2213
PyObject *empty_tuple = PyTuple_New(0);
2214
if (!empty_tuple) {
2215
return -1;
2216
}
2217
if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$O:NameError", kwlist,
2218
&name)) {
2219
Py_DECREF(empty_tuple);
2220
return -1;
2221
}
2222
Py_DECREF(empty_tuple);
2223
2224
Py_XSETREF(self->name, Py_XNewRef(name));
2225
2226
return 0;
2227
}
2228
2229
static int
2230
NameError_clear(PyNameErrorObject *self)
2231
{
2232
Py_CLEAR(self->name);
2233
return BaseException_clear((PyBaseExceptionObject *)self);
2234
}
2235
2236
static void
2237
NameError_dealloc(PyNameErrorObject *self)
2238
{
2239
_PyObject_GC_UNTRACK(self);
2240
NameError_clear(self);
2241
Py_TYPE(self)->tp_free((PyObject *)self);
2242
}
2243
2244
static int
2245
NameError_traverse(PyNameErrorObject *self, visitproc visit, void *arg)
2246
{
2247
Py_VISIT(self->name);
2248
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
2249
}
2250
2251
static PyMemberDef NameError_members[] = {
2252
{"name", T_OBJECT, offsetof(PyNameErrorObject, name), 0, PyDoc_STR("name")},
2253
{NULL} /* Sentinel */
2254
};
2255
2256
static PyMethodDef NameError_methods[] = {
2257
{NULL} /* Sentinel */
2258
};
2259
2260
ComplexExtendsException(PyExc_Exception, NameError,
2261
NameError, 0,
2262
NameError_methods, NameError_members,
2263
0, BaseException_str, "Name not found globally.");
2264
2265
/*
2266
* UnboundLocalError extends NameError
2267
*/
2268
2269
MiddlingExtendsException(PyExc_NameError, UnboundLocalError, NameError,
2270
"Local name referenced but not bound to a value.");
2271
2272
/*
2273
* AttributeError extends Exception
2274
*/
2275
2276
static int
2277
AttributeError_init(PyAttributeErrorObject *self, PyObject *args, PyObject *kwds)
2278
{
2279
static char *kwlist[] = {"name", "obj", NULL};
2280
PyObject *name = NULL;
2281
PyObject *obj = NULL;
2282
2283
if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1) {
2284
return -1;
2285
}
2286
2287
PyObject *empty_tuple = PyTuple_New(0);
2288
if (!empty_tuple) {
2289
return -1;
2290
}
2291
if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OO:AttributeError", kwlist,
2292
&name, &obj)) {
2293
Py_DECREF(empty_tuple);
2294
return -1;
2295
}
2296
Py_DECREF(empty_tuple);
2297
2298
Py_XSETREF(self->name, Py_XNewRef(name));
2299
Py_XSETREF(self->obj, Py_XNewRef(obj));
2300
2301
return 0;
2302
}
2303
2304
static int
2305
AttributeError_clear(PyAttributeErrorObject *self)
2306
{
2307
Py_CLEAR(self->obj);
2308
Py_CLEAR(self->name);
2309
return BaseException_clear((PyBaseExceptionObject *)self);
2310
}
2311
2312
static void
2313
AttributeError_dealloc(PyAttributeErrorObject *self)
2314
{
2315
_PyObject_GC_UNTRACK(self);
2316
AttributeError_clear(self);
2317
Py_TYPE(self)->tp_free((PyObject *)self);
2318
}
2319
2320
static int
2321
AttributeError_traverse(PyAttributeErrorObject *self, visitproc visit, void *arg)
2322
{
2323
Py_VISIT(self->obj);
2324
Py_VISIT(self->name);
2325
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
2326
}
2327
2328
/* Pickling support */
2329
static PyObject *
2330
AttributeError_getstate(PyAttributeErrorObject *self, PyObject *Py_UNUSED(ignored))
2331
{
2332
PyObject *dict = ((PyAttributeErrorObject *)self)->dict;
2333
if (self->name || self->args) {
2334
dict = dict ? PyDict_Copy(dict) : PyDict_New();
2335
if (dict == NULL) {
2336
return NULL;
2337
}
2338
if (self->name && PyDict_SetItemString(dict, "name", self->name) < 0) {
2339
Py_DECREF(dict);
2340
return NULL;
2341
}
2342
/* We specifically are not pickling the obj attribute since there are many
2343
cases where it is unlikely to be picklable. See GH-103352.
2344
*/
2345
if (self->args && PyDict_SetItemString(dict, "args", self->args) < 0) {
2346
Py_DECREF(dict);
2347
return NULL;
2348
}
2349
return dict;
2350
}
2351
else if (dict) {
2352
return Py_NewRef(dict);
2353
}
2354
Py_RETURN_NONE;
2355
}
2356
2357
static PyObject *
2358
AttributeError_reduce(PyAttributeErrorObject *self, PyObject *Py_UNUSED(ignored))
2359
{
2360
PyObject *state = AttributeError_getstate(self, NULL);
2361
if (state == NULL) {
2362
return NULL;
2363
}
2364
2365
PyObject *return_value = PyTuple_Pack(3, Py_TYPE(self), self->args, state);
2366
Py_DECREF(state);
2367
return return_value;
2368
}
2369
2370
static PyMemberDef AttributeError_members[] = {
2371
{"name", T_OBJECT, offsetof(PyAttributeErrorObject, name), 0, PyDoc_STR("attribute name")},
2372
{"obj", T_OBJECT, offsetof(PyAttributeErrorObject, obj), 0, PyDoc_STR("object")},
2373
{NULL} /* Sentinel */
2374
};
2375
2376
static PyMethodDef AttributeError_methods[] = {
2377
{"__getstate__", (PyCFunction)AttributeError_getstate, METH_NOARGS},
2378
{"__reduce__", (PyCFunction)AttributeError_reduce, METH_NOARGS },
2379
{NULL}
2380
};
2381
2382
ComplexExtendsException(PyExc_Exception, AttributeError,
2383
AttributeError, 0,
2384
AttributeError_methods, AttributeError_members,
2385
0, BaseException_str, "Attribute not found.");
2386
2387
/*
2388
* SyntaxError extends Exception
2389
*/
2390
2391
static int
2392
SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
2393
{
2394
PyObject *info = NULL;
2395
Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
2396
2397
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2398
return -1;
2399
2400
if (lenargs >= 1) {
2401
Py_XSETREF(self->msg, Py_NewRef(PyTuple_GET_ITEM(args, 0)));
2402
}
2403
if (lenargs == 2) {
2404
info = PyTuple_GET_ITEM(args, 1);
2405
info = PySequence_Tuple(info);
2406
if (!info) {
2407
return -1;
2408
}
2409
2410
self->end_lineno = NULL;
2411
self->end_offset = NULL;
2412
if (!PyArg_ParseTuple(info, "OOOO|OO",
2413
&self->filename, &self->lineno,
2414
&self->offset, &self->text,
2415
&self->end_lineno, &self->end_offset)) {
2416
Py_DECREF(info);
2417
return -1;
2418
}
2419
2420
Py_INCREF(self->filename);
2421
Py_INCREF(self->lineno);
2422
Py_INCREF(self->offset);
2423
Py_INCREF(self->text);
2424
Py_XINCREF(self->end_lineno);
2425
Py_XINCREF(self->end_offset);
2426
Py_DECREF(info);
2427
2428
if (self->end_lineno != NULL && self->end_offset == NULL) {
2429
PyErr_SetString(PyExc_TypeError, "end_offset must be provided when end_lineno is provided");
2430
return -1;
2431
}
2432
}
2433
return 0;
2434
}
2435
2436
static int
2437
SyntaxError_clear(PySyntaxErrorObject *self)
2438
{
2439
Py_CLEAR(self->msg);
2440
Py_CLEAR(self->filename);
2441
Py_CLEAR(self->lineno);
2442
Py_CLEAR(self->offset);
2443
Py_CLEAR(self->end_lineno);
2444
Py_CLEAR(self->end_offset);
2445
Py_CLEAR(self->text);
2446
Py_CLEAR(self->print_file_and_line);
2447
return BaseException_clear((PyBaseExceptionObject *)self);
2448
}
2449
2450
static void
2451
SyntaxError_dealloc(PySyntaxErrorObject *self)
2452
{
2453
_PyObject_GC_UNTRACK(self);
2454
SyntaxError_clear(self);
2455
Py_TYPE(self)->tp_free((PyObject *)self);
2456
}
2457
2458
static int
2459
SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
2460
{
2461
Py_VISIT(self->msg);
2462
Py_VISIT(self->filename);
2463
Py_VISIT(self->lineno);
2464
Py_VISIT(self->offset);
2465
Py_VISIT(self->end_lineno);
2466
Py_VISIT(self->end_offset);
2467
Py_VISIT(self->text);
2468
Py_VISIT(self->print_file_and_line);
2469
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
2470
}
2471
2472
/* This is called "my_basename" instead of just "basename" to avoid name
2473
conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
2474
defined, and Python does define that. */
2475
static PyObject*
2476
my_basename(PyObject *name)
2477
{
2478
Py_ssize_t i, size, offset;
2479
int kind;
2480
const void *data;
2481
2482
kind = PyUnicode_KIND(name);
2483
data = PyUnicode_DATA(name);
2484
size = PyUnicode_GET_LENGTH(name);
2485
offset = 0;
2486
for(i=0; i < size; i++) {
2487
if (PyUnicode_READ(kind, data, i) == SEP) {
2488
offset = i + 1;
2489
}
2490
}
2491
if (offset != 0) {
2492
return PyUnicode_Substring(name, offset, size);
2493
}
2494
else {
2495
return Py_NewRef(name);
2496
}
2497
}
2498
2499
2500
static PyObject *
2501
SyntaxError_str(PySyntaxErrorObject *self)
2502
{
2503
int have_lineno = 0;
2504
PyObject *filename;
2505
PyObject *result;
2506
/* Below, we always ignore overflow errors, just printing -1.
2507
Still, we cannot allow an OverflowError to be raised, so
2508
we need to call PyLong_AsLongAndOverflow. */
2509
int overflow;
2510
2511
/* XXX -- do all the additional formatting with filename and
2512
lineno here */
2513
2514
if (self->filename && PyUnicode_Check(self->filename)) {
2515
filename = my_basename(self->filename);
2516
if (filename == NULL)
2517
return NULL;
2518
} else {
2519
filename = NULL;
2520
}
2521
have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
2522
2523
if (!filename && !have_lineno)
2524
return PyObject_Str(self->msg ? self->msg : Py_None);
2525
2526
if (filename && have_lineno)
2527
result = PyUnicode_FromFormat("%S (%U, line %ld)",
2528
self->msg ? self->msg : Py_None,
2529
filename,
2530
PyLong_AsLongAndOverflow(self->lineno, &overflow));
2531
else if (filename)
2532
result = PyUnicode_FromFormat("%S (%U)",
2533
self->msg ? self->msg : Py_None,
2534
filename);
2535
else /* only have_lineno */
2536
result = PyUnicode_FromFormat("%S (line %ld)",
2537
self->msg ? self->msg : Py_None,
2538
PyLong_AsLongAndOverflow(self->lineno, &overflow));
2539
Py_XDECREF(filename);
2540
return result;
2541
}
2542
2543
static PyMemberDef SyntaxError_members[] = {
2544
{"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
2545
PyDoc_STR("exception msg")},
2546
{"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
2547
PyDoc_STR("exception filename")},
2548
{"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
2549
PyDoc_STR("exception lineno")},
2550
{"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
2551
PyDoc_STR("exception offset")},
2552
{"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
2553
PyDoc_STR("exception text")},
2554
{"end_lineno", T_OBJECT, offsetof(PySyntaxErrorObject, end_lineno), 0,
2555
PyDoc_STR("exception end lineno")},
2556
{"end_offset", T_OBJECT, offsetof(PySyntaxErrorObject, end_offset), 0,
2557
PyDoc_STR("exception end offset")},
2558
{"print_file_and_line", T_OBJECT,
2559
offsetof(PySyntaxErrorObject, print_file_and_line), 0,
2560
PyDoc_STR("exception print_file_and_line")},
2561
{NULL} /* Sentinel */
2562
};
2563
2564
ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
2565
0, 0, SyntaxError_members, 0,
2566
SyntaxError_str, "Invalid syntax.");
2567
2568
2569
/*
2570
* IndentationError extends SyntaxError
2571
*/
2572
MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
2573
"Improper indentation.");
2574
2575
2576
/*
2577
* TabError extends IndentationError
2578
*/
2579
MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
2580
"Improper mixture of spaces and tabs.");
2581
2582
2583
/*
2584
* LookupError extends Exception
2585
*/
2586
SimpleExtendsException(PyExc_Exception, LookupError,
2587
"Base class for lookup errors.");
2588
2589
2590
/*
2591
* IndexError extends LookupError
2592
*/
2593
SimpleExtendsException(PyExc_LookupError, IndexError,
2594
"Sequence index out of range.");
2595
2596
2597
/*
2598
* KeyError extends LookupError
2599
*/
2600
static PyObject *
2601
KeyError_str(PyBaseExceptionObject *self)
2602
{
2603
/* If args is a tuple of exactly one item, apply repr to args[0].
2604
This is done so that e.g. the exception raised by {}[''] prints
2605
KeyError: ''
2606
rather than the confusing
2607
KeyError
2608
alone. The downside is that if KeyError is raised with an explanatory
2609
string, that string will be displayed in quotes. Too bad.
2610
If args is anything else, use the default BaseException__str__().
2611
*/
2612
if (PyTuple_GET_SIZE(self->args) == 1) {
2613
return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
2614
}
2615
return BaseException_str(self);
2616
}
2617
2618
ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
2619
0, 0, 0, 0, KeyError_str, "Mapping key not found.");
2620
2621
2622
/*
2623
* ValueError extends Exception
2624
*/
2625
SimpleExtendsException(PyExc_Exception, ValueError,
2626
"Inappropriate argument value (of correct type).");
2627
2628
/*
2629
* UnicodeError extends ValueError
2630
*/
2631
2632
SimpleExtendsException(PyExc_ValueError, UnicodeError,
2633
"Unicode related error.");
2634
2635
static PyObject *
2636
get_string(PyObject *attr, const char *name)
2637
{
2638
if (!attr) {
2639
PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
2640
return NULL;
2641
}
2642
2643
if (!PyBytes_Check(attr)) {
2644
PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
2645
return NULL;
2646
}
2647
return Py_NewRef(attr);
2648
}
2649
2650
static PyObject *
2651
get_unicode(PyObject *attr, const char *name)
2652
{
2653
if (!attr) {
2654
PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
2655
return NULL;
2656
}
2657
2658
if (!PyUnicode_Check(attr)) {
2659
PyErr_Format(PyExc_TypeError,
2660
"%.200s attribute must be unicode", name);
2661
return NULL;
2662
}
2663
return Py_NewRef(attr);
2664
}
2665
2666
static int
2667
set_unicodefromstring(PyObject **attr, const char *value)
2668
{
2669
PyObject *obj = PyUnicode_FromString(value);
2670
if (!obj)
2671
return -1;
2672
Py_XSETREF(*attr, obj);
2673
return 0;
2674
}
2675
2676
PyObject *
2677
PyUnicodeEncodeError_GetEncoding(PyObject *exc)
2678
{
2679
return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
2680
}
2681
2682
PyObject *
2683
PyUnicodeDecodeError_GetEncoding(PyObject *exc)
2684
{
2685
return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
2686
}
2687
2688
PyObject *
2689
PyUnicodeEncodeError_GetObject(PyObject *exc)
2690
{
2691
return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
2692
}
2693
2694
PyObject *
2695
PyUnicodeDecodeError_GetObject(PyObject *exc)
2696
{
2697
return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
2698
}
2699
2700
PyObject *
2701
PyUnicodeTranslateError_GetObject(PyObject *exc)
2702
{
2703
return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
2704
}
2705
2706
int
2707
PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
2708
{
2709
Py_ssize_t size;
2710
PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
2711
"object");
2712
if (!obj)
2713
return -1;
2714
*start = ((PyUnicodeErrorObject *)exc)->start;
2715
size = PyUnicode_GET_LENGTH(obj);
2716
if (*start<0)
2717
*start = 0; /*XXX check for values <0*/
2718
if (*start>=size)
2719
*start = size-1;
2720
Py_DECREF(obj);
2721
return 0;
2722
}
2723
2724
2725
int
2726
PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
2727
{
2728
Py_ssize_t size;
2729
PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
2730
if (!obj)
2731
return -1;
2732
size = PyBytes_GET_SIZE(obj);
2733
*start = ((PyUnicodeErrorObject *)exc)->start;
2734
if (*start<0)
2735
*start = 0;
2736
if (*start>=size)
2737
*start = size-1;
2738
Py_DECREF(obj);
2739
return 0;
2740
}
2741
2742
2743
int
2744
PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
2745
{
2746
return PyUnicodeEncodeError_GetStart(exc, start);
2747
}
2748
2749
2750
int
2751
PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
2752
{
2753
((PyUnicodeErrorObject *)exc)->start = start;
2754
return 0;
2755
}
2756
2757
2758
int
2759
PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
2760
{
2761
((PyUnicodeErrorObject *)exc)->start = start;
2762
return 0;
2763
}
2764
2765
2766
int
2767
PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
2768
{
2769
((PyUnicodeErrorObject *)exc)->start = start;
2770
return 0;
2771
}
2772
2773
2774
int
2775
PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
2776
{
2777
Py_ssize_t size;
2778
PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
2779
"object");
2780
if (!obj)
2781
return -1;
2782
*end = ((PyUnicodeErrorObject *)exc)->end;
2783
size = PyUnicode_GET_LENGTH(obj);
2784
if (*end<1)
2785
*end = 1;
2786
if (*end>size)
2787
*end = size;
2788
Py_DECREF(obj);
2789
return 0;
2790
}
2791
2792
2793
int
2794
PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
2795
{
2796
Py_ssize_t size;
2797
PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
2798
if (!obj)
2799
return -1;
2800
size = PyBytes_GET_SIZE(obj);
2801
*end = ((PyUnicodeErrorObject *)exc)->end;
2802
if (*end<1)
2803
*end = 1;
2804
if (*end>size)
2805
*end = size;
2806
Py_DECREF(obj);
2807
return 0;
2808
}
2809
2810
2811
int
2812
PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
2813
{
2814
return PyUnicodeEncodeError_GetEnd(exc, end);
2815
}
2816
2817
2818
int
2819
PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
2820
{
2821
((PyUnicodeErrorObject *)exc)->end = end;
2822
return 0;
2823
}
2824
2825
2826
int
2827
PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
2828
{
2829
((PyUnicodeErrorObject *)exc)->end = end;
2830
return 0;
2831
}
2832
2833
2834
int
2835
PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
2836
{
2837
((PyUnicodeErrorObject *)exc)->end = end;
2838
return 0;
2839
}
2840
2841
PyObject *
2842
PyUnicodeEncodeError_GetReason(PyObject *exc)
2843
{
2844
return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
2845
}
2846
2847
2848
PyObject *
2849
PyUnicodeDecodeError_GetReason(PyObject *exc)
2850
{
2851
return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
2852
}
2853
2854
2855
PyObject *
2856
PyUnicodeTranslateError_GetReason(PyObject *exc)
2857
{
2858
return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
2859
}
2860
2861
2862
int
2863
PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
2864
{
2865
return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
2866
reason);
2867
}
2868
2869
2870
int
2871
PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
2872
{
2873
return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
2874
reason);
2875
}
2876
2877
2878
int
2879
PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
2880
{
2881
return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
2882
reason);
2883
}
2884
2885
2886
static int
2887
UnicodeError_clear(PyUnicodeErrorObject *self)
2888
{
2889
Py_CLEAR(self->encoding);
2890
Py_CLEAR(self->object);
2891
Py_CLEAR(self->reason);
2892
return BaseException_clear((PyBaseExceptionObject *)self);
2893
}
2894
2895
static void
2896
UnicodeError_dealloc(PyUnicodeErrorObject *self)
2897
{
2898
_PyObject_GC_UNTRACK(self);
2899
UnicodeError_clear(self);
2900
Py_TYPE(self)->tp_free((PyObject *)self);
2901
}
2902
2903
static int
2904
UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
2905
{
2906
Py_VISIT(self->encoding);
2907
Py_VISIT(self->object);
2908
Py_VISIT(self->reason);
2909
return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
2910
}
2911
2912
static PyMemberDef UnicodeError_members[] = {
2913
{"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
2914
PyDoc_STR("exception encoding")},
2915
{"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
2916
PyDoc_STR("exception object")},
2917
{"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
2918
PyDoc_STR("exception start")},
2919
{"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
2920
PyDoc_STR("exception end")},
2921
{"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
2922
PyDoc_STR("exception reason")},
2923
{NULL} /* Sentinel */
2924
};
2925
2926
2927
/*
2928
* UnicodeEncodeError extends UnicodeError
2929
*/
2930
2931
static int
2932
UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
2933
{
2934
PyUnicodeErrorObject *err;
2935
2936
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2937
return -1;
2938
2939
err = (PyUnicodeErrorObject *)self;
2940
2941
Py_CLEAR(err->encoding);
2942
Py_CLEAR(err->object);
2943
Py_CLEAR(err->reason);
2944
2945
if (!PyArg_ParseTuple(args, "UUnnU",
2946
&err->encoding, &err->object,
2947
&err->start, &err->end, &err->reason)) {
2948
err->encoding = err->object = err->reason = NULL;
2949
return -1;
2950
}
2951
2952
Py_INCREF(err->encoding);
2953
Py_INCREF(err->object);
2954
Py_INCREF(err->reason);
2955
2956
return 0;
2957
}
2958
2959
static PyObject *
2960
UnicodeEncodeError_str(PyObject *self)
2961
{
2962
PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
2963
PyObject *result = NULL;
2964
PyObject *reason_str = NULL;
2965
PyObject *encoding_str = NULL;
2966
2967
if (!uself->object)
2968
/* Not properly initialized. */
2969
return PyUnicode_FromString("");
2970
2971
/* Get reason and encoding as strings, which they might not be if
2972
they've been modified after we were constructed. */
2973
reason_str = PyObject_Str(uself->reason);
2974
if (reason_str == NULL)
2975
goto done;
2976
encoding_str = PyObject_Str(uself->encoding);
2977
if (encoding_str == NULL)
2978
goto done;
2979
2980
if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2981
Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
2982
const char *fmt;
2983
if (badchar <= 0xff)
2984
fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
2985
else if (badchar <= 0xffff)
2986
fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
2987
else
2988
fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
2989
result = PyUnicode_FromFormat(
2990
fmt,
2991
encoding_str,
2992
(int)badchar,
2993
uself->start,
2994
reason_str);
2995
}
2996
else {
2997
result = PyUnicode_FromFormat(
2998
"'%U' codec can't encode characters in position %zd-%zd: %U",
2999
encoding_str,
3000
uself->start,
3001
uself->end-1,
3002
reason_str);
3003
}
3004
done:
3005
Py_XDECREF(reason_str);
3006
Py_XDECREF(encoding_str);
3007
return result;
3008
}
3009
3010
static PyTypeObject _PyExc_UnicodeEncodeError = {
3011
PyVarObject_HEAD_INIT(NULL, 0)
3012
"UnicodeEncodeError",
3013
sizeof(PyUnicodeErrorObject), 0,
3014
(destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3015
(reprfunc)UnicodeEncodeError_str, 0, 0, 0,
3016
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
3017
PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
3018
(inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
3019
0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
3020
(initproc)UnicodeEncodeError_init, 0, BaseException_new,
3021
};
3022
PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
3023
3024
3025
/*
3026
* UnicodeDecodeError extends UnicodeError
3027
*/
3028
3029
static int
3030
UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
3031
{
3032
PyUnicodeErrorObject *ude;
3033
3034
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
3035
return -1;
3036
3037
ude = (PyUnicodeErrorObject *)self;
3038
3039
Py_CLEAR(ude->encoding);
3040
Py_CLEAR(ude->object);
3041
Py_CLEAR(ude->reason);
3042
3043
if (!PyArg_ParseTuple(args, "UOnnU",
3044
&ude->encoding, &ude->object,
3045
&ude->start, &ude->end, &ude->reason)) {
3046
ude->encoding = ude->object = ude->reason = NULL;
3047
return -1;
3048
}
3049
3050
Py_INCREF(ude->encoding);
3051
Py_INCREF(ude->object);
3052
Py_INCREF(ude->reason);
3053
3054
if (!PyBytes_Check(ude->object)) {
3055
Py_buffer view;
3056
if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
3057
goto error;
3058
Py_XSETREF(ude->object, PyBytes_FromStringAndSize(view.buf, view.len));
3059
PyBuffer_Release(&view);
3060
if (!ude->object)
3061
goto error;
3062
}
3063
return 0;
3064
3065
error:
3066
Py_CLEAR(ude->encoding);
3067
Py_CLEAR(ude->object);
3068
Py_CLEAR(ude->reason);
3069
return -1;
3070
}
3071
3072
static PyObject *
3073
UnicodeDecodeError_str(PyObject *self)
3074
{
3075
PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
3076
PyObject *result = NULL;
3077
PyObject *reason_str = NULL;
3078
PyObject *encoding_str = NULL;
3079
3080
if (!uself->object)
3081
/* Not properly initialized. */
3082
return PyUnicode_FromString("");
3083
3084
/* Get reason and encoding as strings, which they might not be if
3085
they've been modified after we were constructed. */
3086
reason_str = PyObject_Str(uself->reason);
3087
if (reason_str == NULL)
3088
goto done;
3089
encoding_str = PyObject_Str(uself->encoding);
3090
if (encoding_str == NULL)
3091
goto done;
3092
3093
if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
3094
int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
3095
result = PyUnicode_FromFormat(
3096
"'%U' codec can't decode byte 0x%02x in position %zd: %U",
3097
encoding_str,
3098
byte,
3099
uself->start,
3100
reason_str);
3101
}
3102
else {
3103
result = PyUnicode_FromFormat(
3104
"'%U' codec can't decode bytes in position %zd-%zd: %U",
3105
encoding_str,
3106
uself->start,
3107
uself->end-1,
3108
reason_str
3109
);
3110
}
3111
done:
3112
Py_XDECREF(reason_str);
3113
Py_XDECREF(encoding_str);
3114
return result;
3115
}
3116
3117
static PyTypeObject _PyExc_UnicodeDecodeError = {
3118
PyVarObject_HEAD_INIT(NULL, 0)
3119
"UnicodeDecodeError",
3120
sizeof(PyUnicodeErrorObject), 0,
3121
(destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3122
(reprfunc)UnicodeDecodeError_str, 0, 0, 0,
3123
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
3124
PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
3125
(inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
3126
0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
3127
(initproc)UnicodeDecodeError_init, 0, BaseException_new,
3128
};
3129
PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
3130
3131
PyObject *
3132
PyUnicodeDecodeError_Create(
3133
const char *encoding, const char *object, Py_ssize_t length,
3134
Py_ssize_t start, Py_ssize_t end, const char *reason)
3135
{
3136
return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3137
encoding, object, length, start, end, reason);
3138
}
3139
3140
3141
/*
3142
* UnicodeTranslateError extends UnicodeError
3143
*/
3144
3145
static int
3146
UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
3147
PyObject *kwds)
3148
{
3149
if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
3150
return -1;
3151
3152
Py_CLEAR(self->object);
3153
Py_CLEAR(self->reason);
3154
3155
if (!PyArg_ParseTuple(args, "UnnU",
3156
&self->object,
3157
&self->start, &self->end, &self->reason)) {
3158
self->object = self->reason = NULL;
3159
return -1;
3160
}
3161
3162
Py_INCREF(self->object);
3163
Py_INCREF(self->reason);
3164
3165
return 0;
3166
}
3167
3168
3169
static PyObject *
3170
UnicodeTranslateError_str(PyObject *self)
3171
{
3172
PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
3173
PyObject *result = NULL;
3174
PyObject *reason_str = NULL;
3175
3176
if (!uself->object)
3177
/* Not properly initialized. */
3178
return PyUnicode_FromString("");
3179
3180
/* Get reason as a string, which it might not be if it's been
3181
modified after we were constructed. */
3182
reason_str = PyObject_Str(uself->reason);
3183
if (reason_str == NULL)
3184
goto done;
3185
3186
if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
3187
Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
3188
const char *fmt;
3189
if (badchar <= 0xff)
3190
fmt = "can't translate character '\\x%02x' in position %zd: %U";
3191
else if (badchar <= 0xffff)
3192
fmt = "can't translate character '\\u%04x' in position %zd: %U";
3193
else
3194
fmt = "can't translate character '\\U%08x' in position %zd: %U";
3195
result = PyUnicode_FromFormat(
3196
fmt,
3197
(int)badchar,
3198
uself->start,
3199
reason_str
3200
);
3201
} else {
3202
result = PyUnicode_FromFormat(
3203
"can't translate characters in position %zd-%zd: %U",
3204
uself->start,
3205
uself->end-1,
3206
reason_str
3207
);
3208
}
3209
done:
3210
Py_XDECREF(reason_str);
3211
return result;
3212
}
3213
3214
static PyTypeObject _PyExc_UnicodeTranslateError = {
3215
PyVarObject_HEAD_INIT(NULL, 0)
3216
"UnicodeTranslateError",
3217
sizeof(PyUnicodeErrorObject), 0,
3218
(destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3219
(reprfunc)UnicodeTranslateError_str, 0, 0, 0,
3220
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
3221
PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
3222
(inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
3223
0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
3224
(initproc)UnicodeTranslateError_init, 0, BaseException_new,
3225
};
3226
PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
3227
3228
PyObject *
3229
_PyUnicodeTranslateError_Create(
3230
PyObject *object,
3231
Py_ssize_t start, Py_ssize_t end, const char *reason)
3232
{
3233
return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
3234
object, start, end, reason);
3235
}
3236
3237
/*
3238
* AssertionError extends Exception
3239
*/
3240
SimpleExtendsException(PyExc_Exception, AssertionError,
3241
"Assertion failed.");
3242
3243
3244
/*
3245
* ArithmeticError extends Exception
3246
*/
3247
SimpleExtendsException(PyExc_Exception, ArithmeticError,
3248
"Base class for arithmetic errors.");
3249
3250
3251
/*
3252
* FloatingPointError extends ArithmeticError
3253
*/
3254
SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
3255
"Floating point operation failed.");
3256
3257
3258
/*
3259
* OverflowError extends ArithmeticError
3260
*/
3261
SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
3262
"Result too large to be represented.");
3263
3264
3265
/*
3266
* ZeroDivisionError extends ArithmeticError
3267
*/
3268
SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
3269
"Second argument to a division or modulo operation was zero.");
3270
3271
3272
/*
3273
* SystemError extends Exception
3274
*/
3275
SimpleExtendsException(PyExc_Exception, SystemError,
3276
"Internal error in the Python interpreter.\n"
3277
"\n"
3278
"Please report this to the Python maintainer, along with the traceback,\n"
3279
"the Python version, and the hardware/OS platform and version.");
3280
3281
3282
/*
3283
* ReferenceError extends Exception
3284
*/
3285
SimpleExtendsException(PyExc_Exception, ReferenceError,
3286
"Weak ref proxy used after referent went away.");
3287
3288
3289
/*
3290
* MemoryError extends Exception
3291
*/
3292
3293
#define MEMERRORS_SAVE 16
3294
3295
static PyObject *
3296
get_memory_error(int allow_allocation, PyObject *args, PyObject *kwds)
3297
{
3298
PyBaseExceptionObject *self;
3299
struct _Py_exc_state *state = get_exc_state();
3300
if (state->memerrors_freelist == NULL) {
3301
if (!allow_allocation) {
3302
PyInterpreterState *interp = _PyInterpreterState_GET();
3303
return Py_NewRef(
3304
&_Py_INTERP_SINGLETON(interp, last_resort_memory_error));
3305
}
3306
PyObject *result = BaseException_new((PyTypeObject *)PyExc_MemoryError, args, kwds);
3307
return result;
3308
}
3309
3310
/* Fetch object from freelist and revive it */
3311
self = state->memerrors_freelist;
3312
self->args = PyTuple_New(0);
3313
/* This shouldn't happen since the empty tuple is persistent */
3314
3315
if (self->args == NULL) {
3316
return NULL;
3317
}
3318
3319
state->memerrors_freelist = (PyBaseExceptionObject *) self->dict;
3320
state->memerrors_numfree--;
3321
self->dict = NULL;
3322
_Py_NewReference((PyObject *)self);
3323
_PyObject_GC_TRACK(self);
3324
return (PyObject *)self;
3325
}
3326
3327
static PyObject *
3328
MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3329
{
3330
/* If this is a subclass of MemoryError, don't use the freelist
3331
* and just return a fresh object */
3332
if (type != (PyTypeObject *) PyExc_MemoryError) {
3333
return BaseException_new(type, args, kwds);
3334
}
3335
return get_memory_error(1, args, kwds);
3336
}
3337
3338
PyObject *
3339
_PyErr_NoMemory(PyThreadState *tstate)
3340
{
3341
if (Py_IS_TYPE(PyExc_MemoryError, NULL)) {
3342
/* PyErr_NoMemory() has been called before PyExc_MemoryError has been
3343
initialized by _PyExc_Init() */
3344
Py_FatalError("Out of memory and PyExc_MemoryError is not "
3345
"initialized yet");
3346
}
3347
PyObject *err = get_memory_error(0, NULL, NULL);
3348
if (err != NULL) {
3349
_PyErr_SetRaisedException(tstate, err);
3350
}
3351
return NULL;
3352
}
3353
3354
static void
3355
MemoryError_dealloc(PyBaseExceptionObject *self)
3356
{
3357
_PyObject_GC_UNTRACK(self);
3358
3359
BaseException_clear(self);
3360
3361
/* If this is a subclass of MemoryError, we don't need to
3362
* do anything in the free-list*/
3363
if (!Py_IS_TYPE(self, (PyTypeObject *) PyExc_MemoryError)) {
3364
Py_TYPE(self)->tp_free((PyObject *)self);
3365
return;
3366
}
3367
3368
struct _Py_exc_state *state = get_exc_state();
3369
if (state->memerrors_numfree >= MEMERRORS_SAVE) {
3370
Py_TYPE(self)->tp_free((PyObject *)self);
3371
}
3372
else {
3373
self->dict = (PyObject *) state->memerrors_freelist;
3374
state->memerrors_freelist = self;
3375
state->memerrors_numfree++;
3376
}
3377
}
3378
3379
static int
3380
preallocate_memerrors(void)
3381
{
3382
/* We create enough MemoryErrors and then decref them, which will fill
3383
up the freelist. */
3384
int i;
3385
3386
PyObject *errors[MEMERRORS_SAVE];
3387
for (i = 0; i < MEMERRORS_SAVE; i++) {
3388
errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
3389
NULL, NULL);
3390
if (!errors[i]) {
3391
return -1;
3392
}
3393
}
3394
for (i = 0; i < MEMERRORS_SAVE; i++) {
3395
Py_DECREF(errors[i]);
3396
}
3397
return 0;
3398
}
3399
3400
static void
3401
free_preallocated_memerrors(struct _Py_exc_state *state)
3402
{
3403
while (state->memerrors_freelist != NULL) {
3404
PyObject *self = (PyObject *) state->memerrors_freelist;
3405
state->memerrors_freelist = (PyBaseExceptionObject *)state->memerrors_freelist->dict;
3406
Py_TYPE(self)->tp_free((PyObject *)self);
3407
}
3408
}
3409
3410
3411
PyTypeObject _PyExc_MemoryError = {
3412
PyVarObject_HEAD_INIT(NULL, 0)
3413
"MemoryError",
3414
sizeof(PyBaseExceptionObject),
3415
0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
3416
0, 0, 0, 0, 0, 0, 0,
3417
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
3418
PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
3419
(inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
3420
0, 0, 0, offsetof(PyBaseExceptionObject, dict),
3421
(initproc)BaseException_init, 0, MemoryError_new
3422
};
3423
PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
3424
3425
3426
/*
3427
* BufferError extends Exception
3428
*/
3429
SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
3430
3431
3432
/* Warning category docstrings */
3433
3434
/*
3435
* Warning extends Exception
3436
*/
3437
SimpleExtendsException(PyExc_Exception, Warning,
3438
"Base class for warning categories.");
3439
3440
3441
/*
3442
* UserWarning extends Warning
3443
*/
3444
SimpleExtendsException(PyExc_Warning, UserWarning,
3445
"Base class for warnings generated by user code.");
3446
3447
3448
/*
3449
* DeprecationWarning extends Warning
3450
*/
3451
SimpleExtendsException(PyExc_Warning, DeprecationWarning,
3452
"Base class for warnings about deprecated features.");
3453
3454
3455
/*
3456
* PendingDeprecationWarning extends Warning
3457
*/
3458
SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
3459
"Base class for warnings about features which will be deprecated\n"
3460
"in the future.");
3461
3462
3463
/*
3464
* SyntaxWarning extends Warning
3465
*/
3466
SimpleExtendsException(PyExc_Warning, SyntaxWarning,
3467
"Base class for warnings about dubious syntax.");
3468
3469
3470
/*
3471
* RuntimeWarning extends Warning
3472
*/
3473
SimpleExtendsException(PyExc_Warning, RuntimeWarning,
3474
"Base class for warnings about dubious runtime behavior.");
3475
3476
3477
/*
3478
* FutureWarning extends Warning
3479
*/
3480
SimpleExtendsException(PyExc_Warning, FutureWarning,
3481
"Base class for warnings about constructs that will change semantically\n"
3482
"in the future.");
3483
3484
3485
/*
3486
* ImportWarning extends Warning
3487
*/
3488
SimpleExtendsException(PyExc_Warning, ImportWarning,
3489
"Base class for warnings about probable mistakes in module imports");
3490
3491
3492
/*
3493
* UnicodeWarning extends Warning
3494
*/
3495
SimpleExtendsException(PyExc_Warning, UnicodeWarning,
3496
"Base class for warnings about Unicode related problems, mostly\n"
3497
"related to conversion problems.");
3498
3499
3500
/*
3501
* BytesWarning extends Warning
3502
*/
3503
SimpleExtendsException(PyExc_Warning, BytesWarning,
3504
"Base class for warnings about bytes and buffer related problems, mostly\n"
3505
"related to conversion from str or comparing to str.");
3506
3507
3508
/*
3509
* EncodingWarning extends Warning
3510
*/
3511
SimpleExtendsException(PyExc_Warning, EncodingWarning,
3512
"Base class for warnings about encodings.");
3513
3514
3515
/*
3516
* ResourceWarning extends Warning
3517
*/
3518
SimpleExtendsException(PyExc_Warning, ResourceWarning,
3519
"Base class for warnings about resource usage.");
3520
3521
3522
3523
#ifdef MS_WINDOWS
3524
#include <winsock2.h>
3525
/* The following constants were added to errno.h in VS2010 but have
3526
preferred WSA equivalents. */
3527
#undef EADDRINUSE
3528
#undef EADDRNOTAVAIL
3529
#undef EAFNOSUPPORT
3530
#undef EALREADY
3531
#undef ECONNABORTED
3532
#undef ECONNREFUSED
3533
#undef ECONNRESET
3534
#undef EDESTADDRREQ
3535
#undef EHOSTUNREACH
3536
#undef EINPROGRESS
3537
#undef EISCONN
3538
#undef ELOOP
3539
#undef EMSGSIZE
3540
#undef ENETDOWN
3541
#undef ENETRESET
3542
#undef ENETUNREACH
3543
#undef ENOBUFS
3544
#undef ENOPROTOOPT
3545
#undef ENOTCONN
3546
#undef ENOTSOCK
3547
#undef EOPNOTSUPP
3548
#undef EPROTONOSUPPORT
3549
#undef EPROTOTYPE
3550
#undef ETIMEDOUT
3551
#undef EWOULDBLOCK
3552
3553
#if defined(WSAEALREADY) && !defined(EALREADY)
3554
#define EALREADY WSAEALREADY
3555
#endif
3556
#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
3557
#define ECONNABORTED WSAECONNABORTED
3558
#endif
3559
#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
3560
#define ECONNREFUSED WSAECONNREFUSED
3561
#endif
3562
#if defined(WSAECONNRESET) && !defined(ECONNRESET)
3563
#define ECONNRESET WSAECONNRESET
3564
#endif
3565
#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
3566
#define EINPROGRESS WSAEINPROGRESS
3567
#endif
3568
#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
3569
#define ESHUTDOWN WSAESHUTDOWN
3570
#endif
3571
#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
3572
#define ETIMEDOUT WSAETIMEDOUT
3573
#endif
3574
#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
3575
#define EWOULDBLOCK WSAEWOULDBLOCK
3576
#endif
3577
#endif /* MS_WINDOWS */
3578
3579
struct static_exception {
3580
PyTypeObject *exc;
3581
const char *name;
3582
};
3583
3584
static struct static_exception static_exceptions[] = {
3585
#define ITEM(NAME) {&_PyExc_##NAME, #NAME}
3586
// Level 1
3587
ITEM(BaseException),
3588
3589
// Level 2: BaseException subclasses
3590
ITEM(BaseExceptionGroup),
3591
ITEM(Exception),
3592
ITEM(GeneratorExit),
3593
ITEM(KeyboardInterrupt),
3594
ITEM(SystemExit),
3595
3596
// Level 3: Exception(BaseException) subclasses
3597
ITEM(ArithmeticError),
3598
ITEM(AssertionError),
3599
ITEM(AttributeError),
3600
ITEM(BufferError),
3601
ITEM(EOFError),
3602
//ITEM(ExceptionGroup),
3603
ITEM(ImportError),
3604
ITEM(LookupError),
3605
ITEM(MemoryError),
3606
ITEM(NameError),
3607
ITEM(OSError),
3608
ITEM(ReferenceError),
3609
ITEM(RuntimeError),
3610
ITEM(StopAsyncIteration),
3611
ITEM(StopIteration),
3612
ITEM(SyntaxError),
3613
ITEM(SystemError),
3614
ITEM(TypeError),
3615
ITEM(ValueError),
3616
ITEM(Warning),
3617
3618
// Level 4: ArithmeticError(Exception) subclasses
3619
ITEM(FloatingPointError),
3620
ITEM(OverflowError),
3621
ITEM(ZeroDivisionError),
3622
3623
// Level 4: Warning(Exception) subclasses
3624
ITEM(BytesWarning),
3625
ITEM(DeprecationWarning),
3626
ITEM(EncodingWarning),
3627
ITEM(FutureWarning),
3628
ITEM(ImportWarning),
3629
ITEM(PendingDeprecationWarning),
3630
ITEM(ResourceWarning),
3631
ITEM(RuntimeWarning),
3632
ITEM(SyntaxWarning),
3633
ITEM(UnicodeWarning),
3634
ITEM(UserWarning),
3635
3636
// Level 4: OSError(Exception) subclasses
3637
ITEM(BlockingIOError),
3638
ITEM(ChildProcessError),
3639
ITEM(ConnectionError),
3640
ITEM(FileExistsError),
3641
ITEM(FileNotFoundError),
3642
ITEM(InterruptedError),
3643
ITEM(IsADirectoryError),
3644
ITEM(NotADirectoryError),
3645
ITEM(PermissionError),
3646
ITEM(ProcessLookupError),
3647
ITEM(TimeoutError),
3648
3649
// Level 4: Other subclasses
3650
ITEM(IndentationError), // base: SyntaxError(Exception)
3651
ITEM(IndexError), // base: LookupError(Exception)
3652
ITEM(KeyError), // base: LookupError(Exception)
3653
ITEM(ModuleNotFoundError), // base: ImportError(Exception)
3654
ITEM(NotImplementedError), // base: RuntimeError(Exception)
3655
ITEM(RecursionError), // base: RuntimeError(Exception)
3656
ITEM(UnboundLocalError), // base: NameError(Exception)
3657
ITEM(UnicodeError), // base: ValueError(Exception)
3658
3659
// Level 5: ConnectionError(OSError) subclasses
3660
ITEM(BrokenPipeError),
3661
ITEM(ConnectionAbortedError),
3662
ITEM(ConnectionRefusedError),
3663
ITEM(ConnectionResetError),
3664
3665
// Level 5: IndentationError(SyntaxError) subclasses
3666
ITEM(TabError), // base: IndentationError
3667
3668
// Level 5: UnicodeError(ValueError) subclasses
3669
ITEM(UnicodeDecodeError),
3670
ITEM(UnicodeEncodeError),
3671
ITEM(UnicodeTranslateError),
3672
#undef ITEM
3673
};
3674
3675
3676
int
3677
_PyExc_InitTypes(PyInterpreterState *interp)
3678
{
3679
for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) {
3680
PyTypeObject *exc = static_exceptions[i].exc;
3681
if (_PyStaticType_InitBuiltin(interp, exc) < 0) {
3682
return -1;
3683
}
3684
}
3685
return 0;
3686
}
3687
3688
3689
static void
3690
_PyExc_FiniTypes(PyInterpreterState *interp)
3691
{
3692
for (Py_ssize_t i=Py_ARRAY_LENGTH(static_exceptions) - 1; i >= 0; i--) {
3693
PyTypeObject *exc = static_exceptions[i].exc;
3694
_PyStaticType_Dealloc(interp, exc);
3695
}
3696
}
3697
3698
3699
PyStatus
3700
_PyExc_InitGlobalObjects(PyInterpreterState *interp)
3701
{
3702
if (!_Py_IsMainInterpreter(interp)) {
3703
return _PyStatus_OK();
3704
}
3705
3706
if (preallocate_memerrors() < 0) {
3707
return _PyStatus_NO_MEMORY();
3708
}
3709
return _PyStatus_OK();
3710
}
3711
3712
PyStatus
3713
_PyExc_InitState(PyInterpreterState *interp)
3714
{
3715
struct _Py_exc_state *state = &interp->exc_state;
3716
3717
#define ADD_ERRNO(TYPE, CODE) \
3718
do { \
3719
PyObject *_code = PyLong_FromLong(CODE); \
3720
assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
3721
if (!_code || PyDict_SetItem(state->errnomap, _code, PyExc_ ## TYPE)) { \
3722
Py_XDECREF(_code); \
3723
return _PyStatus_ERR("errmap insertion problem."); \
3724
} \
3725
Py_DECREF(_code); \
3726
} while (0)
3727
3728
/* Add exceptions to errnomap */
3729
assert(state->errnomap == NULL);
3730
state->errnomap = PyDict_New();
3731
if (!state->errnomap) {
3732
return _PyStatus_NO_MEMORY();
3733
}
3734
3735
ADD_ERRNO(BlockingIOError, EAGAIN);
3736
ADD_ERRNO(BlockingIOError, EALREADY);
3737
ADD_ERRNO(BlockingIOError, EINPROGRESS);
3738
ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
3739
ADD_ERRNO(BrokenPipeError, EPIPE);
3740
#ifdef ESHUTDOWN
3741
ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
3742
#endif
3743
ADD_ERRNO(ChildProcessError, ECHILD);
3744
ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
3745
ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
3746
ADD_ERRNO(ConnectionResetError, ECONNRESET);
3747
ADD_ERRNO(FileExistsError, EEXIST);
3748
ADD_ERRNO(FileNotFoundError, ENOENT);
3749
ADD_ERRNO(IsADirectoryError, EISDIR);
3750
ADD_ERRNO(NotADirectoryError, ENOTDIR);
3751
ADD_ERRNO(InterruptedError, EINTR);
3752
ADD_ERRNO(PermissionError, EACCES);
3753
ADD_ERRNO(PermissionError, EPERM);
3754
#ifdef ENOTCAPABLE
3755
// Extension for WASI capability-based security. Process lacks
3756
// capability to access a resource.
3757
ADD_ERRNO(PermissionError, ENOTCAPABLE);
3758
#endif
3759
ADD_ERRNO(ProcessLookupError, ESRCH);
3760
ADD_ERRNO(TimeoutError, ETIMEDOUT);
3761
3762
return _PyStatus_OK();
3763
3764
#undef ADD_ERRNO
3765
}
3766
3767
3768
/* Add exception types to the builtins module */
3769
int
3770
_PyBuiltins_AddExceptions(PyObject *bltinmod)
3771
{
3772
PyObject *mod_dict = PyModule_GetDict(bltinmod);
3773
if (mod_dict == NULL) {
3774
return -1;
3775
}
3776
3777
for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) {
3778
struct static_exception item = static_exceptions[i];
3779
3780
if (PyDict_SetItemString(mod_dict, item.name, (PyObject*)item.exc)) {
3781
return -1;
3782
}
3783
}
3784
3785
PyObject *PyExc_ExceptionGroup = create_exception_group_class();
3786
if (!PyExc_ExceptionGroup) {
3787
return -1;
3788
}
3789
if (PyDict_SetItemString(mod_dict, "ExceptionGroup", PyExc_ExceptionGroup)) {
3790
return -1;
3791
}
3792
3793
#define INIT_ALIAS(NAME, TYPE) \
3794
do { \
3795
PyExc_ ## NAME = PyExc_ ## TYPE; \
3796
if (PyDict_SetItemString(mod_dict, # NAME, PyExc_ ## TYPE)) { \
3797
return -1; \
3798
} \
3799
} while (0)
3800
3801
INIT_ALIAS(EnvironmentError, OSError);
3802
INIT_ALIAS(IOError, OSError);
3803
#ifdef MS_WINDOWS
3804
INIT_ALIAS(WindowsError, OSError);
3805
#endif
3806
3807
#undef INIT_ALIAS
3808
3809
return 0;
3810
}
3811
3812
void
3813
_PyExc_ClearExceptionGroupType(PyInterpreterState *interp)
3814
{
3815
struct _Py_exc_state *state = &interp->exc_state;
3816
Py_CLEAR(state->PyExc_ExceptionGroup);
3817
}
3818
3819
void
3820
_PyExc_Fini(PyInterpreterState *interp)
3821
{
3822
struct _Py_exc_state *state = &interp->exc_state;
3823
free_preallocated_memerrors(state);
3824
Py_CLEAR(state->errnomap);
3825
3826
_PyExc_FiniTypes(interp);
3827
}
3828
3829
int
3830
_PyException_AddNote(PyObject *exc, PyObject *note)
3831
{
3832
if (!PyExceptionInstance_Check(exc)) {
3833
PyErr_Format(PyExc_TypeError,
3834
"exc must be an exception, not '%s'",
3835
Py_TYPE(exc)->tp_name);
3836
return -1;
3837
}
3838
PyObject *r = BaseException_add_note(exc, note);
3839
int res = r == NULL ? -1 : 0;
3840
Py_XDECREF(r);
3841
return res;
3842
}
3843
3844
3845