/src/cpython/Objects/exceptions.c
Line | Count | Source |
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_exceptions.h" // struct _Py_exc_state |
12 | | #include "pycore_initconfig.h" |
13 | | #include "pycore_modsupport.h" // _PyArg_NoKeywords() |
14 | | #include "pycore_moduleobject.h" // _PyModule_CAST() |
15 | | #include "pycore_object.h" |
16 | | #include "pycore_pyerrors.h" // struct _PyErr_SetRaisedException |
17 | | #include "pycore_tuple.h" // _PyTuple_FromPair |
18 | | #include "pycore_unicodeobject.h" // _PyUnicode_Equal() |
19 | | |
20 | | #include "osdefs.h" // SEP |
21 | | #include "clinic/exceptions.c.h" |
22 | | |
23 | | |
24 | | /*[clinic input] |
25 | | class BaseException "PyBaseExceptionObject *" "&PyExc_BaseException" |
26 | | class BaseExceptionGroup "PyBaseExceptionGroupObject *" "&PyExc_BaseExceptionGroup" |
27 | | class ImportError "PyImportErrorObject *" "&PyExc_ImportError" |
28 | | class NameError "PyNameErrorObject *" "&PyExc_NameError" |
29 | | class AttributeError "PyAttributeErrorObject *" "&PyExc_AttributeError" |
30 | | [clinic start generated code]*/ |
31 | | /*[clinic end generated code: output=da39a3ee5e6b4b0d input=fce4682940ab8948]*/ |
32 | | |
33 | | |
34 | | static struct _Py_exc_state* |
35 | | get_exc_state(void) |
36 | 236k | { |
37 | 236k | PyInterpreterState *interp = _PyInterpreterState_GET(); |
38 | 236k | return &interp->exc_state; |
39 | 236k | } |
40 | | |
41 | | |
42 | | /* NOTE: If the exception class hierarchy changes, don't forget to update |
43 | | * Lib/test/exception_hierarchy.txt |
44 | | */ |
45 | | |
46 | | static inline PyBaseExceptionObject * |
47 | | PyBaseExceptionObject_CAST(PyObject *exc) |
48 | 317M | { |
49 | 317M | assert(PyExceptionInstance_Check(exc)); |
50 | 317M | return (PyBaseExceptionObject *)exc; |
51 | 317M | } |
52 | | |
53 | | /* |
54 | | * BaseException |
55 | | */ |
56 | | static PyObject * |
57 | | BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
58 | 41.0M | { |
59 | 41.0M | PyBaseExceptionObject *self; |
60 | | |
61 | 41.0M | self = (PyBaseExceptionObject *)type->tp_alloc(type, 0); |
62 | 41.0M | if (!self) |
63 | 0 | return NULL; |
64 | | /* the dict is created on the fly in PyObject_GenericSetAttr */ |
65 | 41.0M | self->dict = NULL; |
66 | 41.0M | self->notes = NULL; |
67 | 41.0M | self->traceback = self->cause = self->context = NULL; |
68 | 41.0M | self->suppress_context = 0; |
69 | | |
70 | 41.0M | if (args) { |
71 | 41.0M | self->args = Py_NewRef(args); |
72 | 41.0M | return (PyObject *)self; |
73 | 41.0M | } |
74 | | |
75 | 592 | self->args = PyTuple_New(0); |
76 | 592 | if (!self->args) { |
77 | 0 | Py_DECREF(self); |
78 | 0 | return NULL; |
79 | 0 | } |
80 | | |
81 | 592 | return (PyObject *)self; |
82 | 592 | } |
83 | | |
84 | | static int |
85 | | BaseException_init(PyObject *op, PyObject *args, PyObject *kwds) |
86 | 39.6M | { |
87 | 39.6M | PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); |
88 | 39.6M | if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) |
89 | 0 | return -1; |
90 | | |
91 | 39.6M | Py_XSETREF(self->args, Py_NewRef(args)); |
92 | 39.6M | return 0; |
93 | 39.6M | } |
94 | | |
95 | | |
96 | | static PyObject * |
97 | | BaseException_vectorcall(PyObject *type_obj, PyObject * const*args, |
98 | | size_t nargsf, PyObject *kwnames) |
99 | 17.4M | { |
100 | 17.4M | PyTypeObject *type = _PyType_CAST(type_obj); |
101 | 17.4M | if (!_PyArg_NoKwnames(type->tp_name, kwnames)) { |
102 | 0 | return NULL; |
103 | 0 | } |
104 | | |
105 | 17.4M | PyBaseExceptionObject *self; |
106 | 17.4M | self = (PyBaseExceptionObject *)type->tp_alloc(type, 0); |
107 | 17.4M | if (!self) { |
108 | 0 | return NULL; |
109 | 0 | } |
110 | | |
111 | | // The dict is created on the fly in PyObject_GenericSetAttr() |
112 | 17.4M | self->dict = NULL; |
113 | 17.4M | self->notes = NULL; |
114 | 17.4M | self->traceback = NULL; |
115 | 17.4M | self->cause = NULL; |
116 | 17.4M | self->context = NULL; |
117 | 17.4M | self->suppress_context = 0; |
118 | | |
119 | 17.4M | self->args = PyTuple_FromArray(args, PyVectorcall_NARGS(nargsf)); |
120 | 17.4M | if (!self->args) { |
121 | 0 | Py_DECREF(self); |
122 | 0 | return NULL; |
123 | 0 | } |
124 | | |
125 | 17.4M | return (PyObject *)self; |
126 | 17.4M | } |
127 | | |
128 | | |
129 | | static int |
130 | | BaseException_clear(PyObject *op) |
131 | 58.7M | { |
132 | 58.7M | PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); |
133 | 58.7M | Py_CLEAR(self->dict); |
134 | 58.7M | Py_CLEAR(self->args); |
135 | 58.7M | Py_CLEAR(self->notes); |
136 | 58.7M | Py_CLEAR(self->traceback); |
137 | 58.7M | Py_CLEAR(self->cause); |
138 | 58.7M | Py_CLEAR(self->context); |
139 | 58.7M | return 0; |
140 | 58.7M | } |
141 | | |
142 | | static void |
143 | | BaseException_dealloc(PyObject *op) |
144 | 36.3M | { |
145 | 36.3M | PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); |
146 | 36.3M | PyObject_GC_UnTrack(self); |
147 | | // bpo-44348: The trashcan mechanism prevents stack overflow when deleting |
148 | | // long chains of exceptions. For example, exceptions can be chained |
149 | | // through the __context__ attributes or the __traceback__ attribute. |
150 | 36.3M | (void)BaseException_clear(op); |
151 | 36.3M | Py_TYPE(self)->tp_free(self); |
152 | 36.3M | } |
153 | | |
154 | | static int |
155 | | BaseException_traverse(PyObject *op, visitproc visit, void *arg) |
156 | 40.9M | { |
157 | 40.9M | PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); |
158 | 40.9M | Py_VISIT(self->dict); |
159 | 40.9M | Py_VISIT(self->args); |
160 | 40.9M | Py_VISIT(self->notes); |
161 | 40.9M | Py_VISIT(self->traceback); |
162 | 40.9M | Py_VISIT(self->cause); |
163 | 40.9M | Py_VISIT(self->context); |
164 | 40.9M | return 0; |
165 | 40.9M | } |
166 | | |
167 | | /*[clinic input] |
168 | | @critical_section |
169 | | BaseException.__str__ |
170 | | [clinic start generated code]*/ |
171 | | |
172 | | static PyObject * |
173 | | BaseException_str_impl(PyBaseExceptionObject *self) |
174 | | /*[clinic end generated code: output=f9cf63c6d14a73fe input=cd946062d6786776]*/ |
175 | 4.99M | { |
176 | 4.99M | switch (PyTuple_GET_SIZE(self->args)) { |
177 | 0 | case 0: |
178 | 0 | return Py_GetConstant(Py_CONSTANT_EMPTY_STR); |
179 | 4.99M | case 1: |
180 | 4.99M | return PyObject_Str(PyTuple_GET_ITEM(self->args, 0)); |
181 | 0 | default: |
182 | 0 | return PyObject_Str(self->args); |
183 | 4.99M | } |
184 | 4.99M | } |
185 | | |
186 | | /*[clinic input] |
187 | | @critical_section |
188 | | BaseException.__repr__ |
189 | | [clinic start generated code]*/ |
190 | | |
191 | | static PyObject * |
192 | | BaseException_repr_impl(PyBaseExceptionObject *self) |
193 | | /*[clinic end generated code: output=c885549a153a6007 input=20941168ad0ab577]*/ |
194 | 4.90k | { |
195 | 4.90k | const char *name = _PyType_Name(Py_TYPE(self)); |
196 | 4.90k | if (PyTuple_GET_SIZE(self->args) == 1) { |
197 | 4.90k | return PyUnicode_FromFormat("%s(%R)", name, |
198 | 4.90k | PyTuple_GET_ITEM(self->args, 0)); |
199 | 4.90k | } |
200 | 0 | return PyUnicode_FromFormat("%s%R", name, self->args); |
201 | 4.90k | } |
202 | | |
203 | | /* Pickling support */ |
204 | | |
205 | | /*[clinic input] |
206 | | @critical_section |
207 | | BaseException.__reduce__ |
208 | | [clinic start generated code]*/ |
209 | | |
210 | | static PyObject * |
211 | | BaseException___reduce___impl(PyBaseExceptionObject *self) |
212 | | /*[clinic end generated code: output=af87c1247ef98748 input=283be5a10d9c964f]*/ |
213 | 0 | { |
214 | 0 | if (self->args && self->dict) |
215 | 0 | return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict); |
216 | 0 | else |
217 | 0 | return _PyTuple_FromPair((PyObject *)Py_TYPE(self), self->args); |
218 | 0 | } |
219 | | |
220 | | /* |
221 | | * Needed for backward compatibility, since exceptions used to store |
222 | | * all their attributes in the __dict__. Code is taken from cPickle's |
223 | | * load_build function. |
224 | | */ |
225 | | |
226 | | /*[clinic input] |
227 | | @critical_section state |
228 | | BaseException.__setstate__ |
229 | | state: object |
230 | | / |
231 | | [clinic start generated code]*/ |
232 | | |
233 | | static PyObject * |
234 | | BaseException___setstate___impl(PyBaseExceptionObject *self, PyObject *state) |
235 | | /*[clinic end generated code: output=f3834889950453ab input=f9b1aea70382cdb6]*/ |
236 | 0 | { |
237 | 0 | PyObject *d_key, *d_value; |
238 | 0 | Py_ssize_t i = 0; |
239 | |
|
240 | 0 | if (state != Py_None) { |
241 | 0 | if (!PyDict_Check(state)) { |
242 | 0 | PyErr_SetString(PyExc_TypeError, "state is not a dictionary"); |
243 | 0 | return NULL; |
244 | 0 | } |
245 | 0 | while (PyDict_Next(state, &i, &d_key, &d_value)) { |
246 | 0 | Py_INCREF(d_key); |
247 | 0 | Py_INCREF(d_value); |
248 | 0 | int res = PyObject_SetAttr((PyObject *)self, d_key, d_value); |
249 | 0 | Py_DECREF(d_value); |
250 | 0 | Py_DECREF(d_key); |
251 | 0 | if (res < 0) { |
252 | 0 | return NULL; |
253 | 0 | } |
254 | 0 | } |
255 | 0 | } |
256 | 0 | Py_RETURN_NONE; |
257 | 0 | } |
258 | | |
259 | | |
260 | | /*[clinic input] |
261 | | @critical_section |
262 | | BaseException.with_traceback |
263 | | tb: object |
264 | | / |
265 | | |
266 | | Set self.__traceback__ to tb and return self. |
267 | | [clinic start generated code]*/ |
268 | | |
269 | | static PyObject * |
270 | | BaseException_with_traceback_impl(PyBaseExceptionObject *self, PyObject *tb) |
271 | | /*[clinic end generated code: output=81e92f2387927f10 input=b5fb64d834717e36]*/ |
272 | 0 | { |
273 | 0 | if (BaseException___traceback___set_impl(self, tb) < 0){ |
274 | 0 | return NULL; |
275 | 0 | } |
276 | 0 | return Py_NewRef(self); |
277 | 0 | } |
278 | | |
279 | | /*[clinic input] |
280 | | @critical_section |
281 | | BaseException.add_note |
282 | | note: object(subclass_of="&PyUnicode_Type") |
283 | | / |
284 | | |
285 | | Add a note to the exception |
286 | | [clinic start generated code]*/ |
287 | | |
288 | | static PyObject * |
289 | | BaseException_add_note_impl(PyBaseExceptionObject *self, PyObject *note) |
290 | | /*[clinic end generated code: output=fb7cbcba611c187b input=e60a6b6e9596acaf]*/ |
291 | 53.6k | { |
292 | 53.6k | PyObject *notes; |
293 | 53.6k | if (PyObject_GetOptionalAttr((PyObject *)self, &_Py_ID(__notes__), ¬es) < 0) { |
294 | 0 | return NULL; |
295 | 0 | } |
296 | 53.6k | if (notes == NULL) { |
297 | 53.6k | notes = PyList_New(0); |
298 | 53.6k | if (notes == NULL) { |
299 | 0 | return NULL; |
300 | 0 | } |
301 | 53.6k | if (PyObject_SetAttr((PyObject *)self, &_Py_ID(__notes__), notes) < 0) { |
302 | 0 | Py_DECREF(notes); |
303 | 0 | return NULL; |
304 | 0 | } |
305 | 53.6k | } |
306 | 47 | else if (!PyList_Check(notes)) { |
307 | 0 | Py_DECREF(notes); |
308 | 0 | PyErr_SetString(PyExc_TypeError, "Cannot add note: __notes__ is not a list"); |
309 | 0 | return NULL; |
310 | 0 | } |
311 | 53.6k | if (PyList_Append(notes, note) < 0) { |
312 | 0 | Py_DECREF(notes); |
313 | 0 | return NULL; |
314 | 0 | } |
315 | 53.6k | Py_DECREF(notes); |
316 | 53.6k | Py_RETURN_NONE; |
317 | 53.6k | } |
318 | | |
319 | | static PyMethodDef BaseException_methods[] = { |
320 | | BASEEXCEPTION___REDUCE___METHODDEF |
321 | | BASEEXCEPTION___SETSTATE___METHODDEF |
322 | | BASEEXCEPTION_WITH_TRACEBACK_METHODDEF |
323 | | BASEEXCEPTION_ADD_NOTE_METHODDEF |
324 | | {NULL, NULL, 0, NULL}, |
325 | | }; |
326 | | |
327 | | /*[clinic input] |
328 | | @critical_section |
329 | | @getter |
330 | | BaseException.args |
331 | | [clinic start generated code]*/ |
332 | | |
333 | | static PyObject * |
334 | | BaseException_args_get_impl(PyBaseExceptionObject *self) |
335 | | /*[clinic end generated code: output=e02e34e35cf4d677 input=64282386e4d7822d]*/ |
336 | 0 | { |
337 | 0 | if (self->args == NULL) { |
338 | 0 | Py_RETURN_NONE; |
339 | 0 | } |
340 | 0 | return Py_NewRef(self->args); |
341 | 0 | } |
342 | | |
343 | | /*[clinic input] |
344 | | @critical_section |
345 | | @setter |
346 | | BaseException.args |
347 | | [clinic start generated code]*/ |
348 | | |
349 | | static int |
350 | | BaseException_args_set_impl(PyBaseExceptionObject *self, PyObject *value) |
351 | | /*[clinic end generated code: output=331137e11d8f9e80 input=2400047ea5970a84]*/ |
352 | 6.21M | { |
353 | 6.21M | PyObject *seq; |
354 | 6.21M | seq = PySequence_Tuple(value); |
355 | 6.21M | if (!seq) |
356 | 0 | return -1; |
357 | 6.21M | Py_XSETREF(self->args, seq); |
358 | 6.21M | return 0; |
359 | 6.21M | } |
360 | | |
361 | | /*[clinic input] |
362 | | @critical_section |
363 | | @getter |
364 | | BaseException.__traceback__ |
365 | | [clinic start generated code]*/ |
366 | | |
367 | | static PyObject * |
368 | | BaseException___traceback___get_impl(PyBaseExceptionObject *self) |
369 | | /*[clinic end generated code: output=17cf874a52339398 input=a2277f0de62170cf]*/ |
370 | 0 | { |
371 | 0 | if (self->traceback == NULL) { |
372 | 0 | Py_RETURN_NONE; |
373 | 0 | } |
374 | 0 | return Py_NewRef(self->traceback); |
375 | 0 | } |
376 | | |
377 | | |
378 | | /*[clinic input] |
379 | | @critical_section |
380 | | @setter |
381 | | BaseException.__traceback__ |
382 | | [clinic start generated code]*/ |
383 | | |
384 | | static int |
385 | | BaseException___traceback___set_impl(PyBaseExceptionObject *self, |
386 | | PyObject *value) |
387 | | /*[clinic end generated code: output=a82c86d9f29f48f0 input=12676035676badad]*/ |
388 | 66.0M | { |
389 | 66.0M | if (PyTraceBack_Check(value)) { |
390 | 66.0M | Py_XSETREF(self->traceback, Py_NewRef(value)); |
391 | 66.0M | } |
392 | 1.92k | else if (value == Py_None) { |
393 | 1.92k | Py_CLEAR(self->traceback); |
394 | 1.92k | } |
395 | 0 | else { |
396 | 0 | PyErr_SetString(PyExc_TypeError, |
397 | 0 | "__traceback__ must be a traceback or None"); |
398 | 0 | return -1; |
399 | 0 | } |
400 | 66.0M | return 0; |
401 | 66.0M | } |
402 | | |
403 | | /*[clinic input] |
404 | | @critical_section |
405 | | @getter |
406 | | BaseException.__context__ |
407 | | [clinic start generated code]*/ |
408 | | |
409 | | static PyObject * |
410 | | BaseException___context___get_impl(PyBaseExceptionObject *self) |
411 | | /*[clinic end generated code: output=6ec5d296ce8d1c93 input=b2d22687937e66ab]*/ |
412 | 0 | { |
413 | 0 | if (self->context == NULL) { |
414 | 0 | Py_RETURN_NONE; |
415 | 0 | } |
416 | 0 | return Py_NewRef(self->context); |
417 | 0 | } |
418 | | |
419 | | /*[clinic input] |
420 | | @critical_section |
421 | | @setter |
422 | | BaseException.__context__ |
423 | | [clinic start generated code]*/ |
424 | | |
425 | | static int |
426 | | BaseException___context___set_impl(PyBaseExceptionObject *self, |
427 | | PyObject *value) |
428 | | /*[clinic end generated code: output=b4cb52dcca1da3bd input=c0971adf47fa1858]*/ |
429 | 0 | { |
430 | 0 | if (value == Py_None) { |
431 | 0 | value = NULL; |
432 | 0 | } else if (!PyExceptionInstance_Check(value)) { |
433 | 0 | PyErr_SetString(PyExc_TypeError, "exception context must be None " |
434 | 0 | "or derive from BaseException"); |
435 | 0 | return -1; |
436 | 0 | } else { |
437 | 0 | Py_INCREF(value); |
438 | 0 | } |
439 | 0 | Py_XSETREF(self->context, value); |
440 | 0 | return 0; |
441 | 0 | } |
442 | | |
443 | | /*[clinic input] |
444 | | @critical_section |
445 | | @getter |
446 | | BaseException.__cause__ |
447 | | [clinic start generated code]*/ |
448 | | |
449 | | static PyObject * |
450 | | BaseException___cause___get_impl(PyBaseExceptionObject *self) |
451 | | /*[clinic end generated code: output=987f6c4d8a0bdbab input=40e0eac427b6e602]*/ |
452 | 0 | { |
453 | 0 | if (self->cause == NULL) { |
454 | 0 | Py_RETURN_NONE; |
455 | 0 | } |
456 | 0 | return Py_NewRef(self->cause); |
457 | 0 | } |
458 | | |
459 | | /*[clinic input] |
460 | | @critical_section |
461 | | @setter |
462 | | BaseException.__cause__ |
463 | | [clinic start generated code]*/ |
464 | | |
465 | | static int |
466 | | BaseException___cause___set_impl(PyBaseExceptionObject *self, |
467 | | PyObject *value) |
468 | | /*[clinic end generated code: output=6161315398aaf541 input=e1b403c0bde3f62a]*/ |
469 | 0 | { |
470 | 0 | if (value == Py_None) { |
471 | 0 | value = NULL; |
472 | 0 | } else if (!PyExceptionInstance_Check(value)) { |
473 | 0 | PyErr_SetString(PyExc_TypeError, "exception cause must be None " |
474 | 0 | "or derive from BaseException"); |
475 | 0 | return -1; |
476 | 0 | } else { |
477 | | /* PyException_SetCause steals this reference */ |
478 | 0 | Py_INCREF(value); |
479 | 0 | } |
480 | 0 | PyException_SetCause((PyObject *)self, value); |
481 | 0 | return 0; |
482 | 0 | } |
483 | | |
484 | | |
485 | | static PyGetSetDef BaseException_getset[] = { |
486 | | {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, |
487 | | BASEEXCEPTION_ARGS_GETSETDEF |
488 | | BASEEXCEPTION___TRACEBACK___GETSETDEF |
489 | | BASEEXCEPTION___CONTEXT___GETSETDEF |
490 | | BASEEXCEPTION___CAUSE___GETSETDEF |
491 | | {NULL}, |
492 | | }; |
493 | | |
494 | | |
495 | | PyObject * |
496 | | PyException_GetTraceback(PyObject *self) |
497 | 66.1M | { |
498 | 66.1M | PyObject *traceback; |
499 | 66.1M | Py_BEGIN_CRITICAL_SECTION(self); |
500 | 66.1M | traceback = Py_XNewRef(PyBaseExceptionObject_CAST(self)->traceback); |
501 | 66.1M | Py_END_CRITICAL_SECTION(); |
502 | 66.1M | return traceback; |
503 | 66.1M | } |
504 | | |
505 | | |
506 | | int |
507 | | PyException_SetTraceback(PyObject *self, PyObject *tb) |
508 | 66.0M | { |
509 | 66.0M | int res; |
510 | 66.0M | Py_BEGIN_CRITICAL_SECTION(self); |
511 | 66.0M | res = BaseException___traceback___set_impl(PyBaseExceptionObject_CAST(self), tb); |
512 | 66.0M | Py_END_CRITICAL_SECTION(); |
513 | 66.0M | return res; |
514 | 66.0M | } |
515 | | |
516 | | PyObject * |
517 | | PyException_GetCause(PyObject *self) |
518 | 0 | { |
519 | 0 | PyObject *cause; |
520 | 0 | Py_BEGIN_CRITICAL_SECTION(self); |
521 | 0 | cause = Py_XNewRef(PyBaseExceptionObject_CAST(self)->cause); |
522 | 0 | Py_END_CRITICAL_SECTION(); |
523 | 0 | return cause; |
524 | 0 | } |
525 | | |
526 | | /* Steals a reference to cause */ |
527 | | void |
528 | | PyException_SetCause(PyObject *self, PyObject *cause) |
529 | 9.93k | { |
530 | 9.93k | Py_BEGIN_CRITICAL_SECTION(self); |
531 | 9.93k | PyBaseExceptionObject *base_self = PyBaseExceptionObject_CAST(self); |
532 | 9.93k | base_self->suppress_context = 1; |
533 | 9.93k | Py_XSETREF(base_self->cause, cause); |
534 | 9.93k | Py_END_CRITICAL_SECTION(); |
535 | 9.93k | } |
536 | | |
537 | | PyObject * |
538 | | PyException_GetContext(PyObject *self) |
539 | 4.89M | { |
540 | 4.89M | PyObject *context; |
541 | 4.89M | Py_BEGIN_CRITICAL_SECTION(self); |
542 | 4.89M | context = Py_XNewRef(PyBaseExceptionObject_CAST(self)->context); |
543 | 4.89M | Py_END_CRITICAL_SECTION(); |
544 | 4.89M | return context; |
545 | 4.89M | } |
546 | | |
547 | | /* Steals a reference to context */ |
548 | | void |
549 | | PyException_SetContext(PyObject *self, PyObject *context) |
550 | 4.29M | { |
551 | 4.29M | Py_BEGIN_CRITICAL_SECTION(self); |
552 | 4.29M | Py_XSETREF(PyBaseExceptionObject_CAST(self)->context, context); |
553 | 4.29M | Py_END_CRITICAL_SECTION(); |
554 | 4.29M | } |
555 | | |
556 | | PyObject * |
557 | | PyException_GetArgs(PyObject *self) |
558 | 0 | { |
559 | 0 | PyObject *args; |
560 | 0 | Py_BEGIN_CRITICAL_SECTION(self); |
561 | 0 | args = Py_NewRef(PyBaseExceptionObject_CAST(self)->args); |
562 | 0 | Py_END_CRITICAL_SECTION(); |
563 | 0 | return args; |
564 | 0 | } |
565 | | |
566 | | void |
567 | | PyException_SetArgs(PyObject *self, PyObject *args) |
568 | 0 | { |
569 | 0 | Py_BEGIN_CRITICAL_SECTION(self); |
570 | 0 | Py_INCREF(args); |
571 | 0 | Py_XSETREF(PyBaseExceptionObject_CAST(self)->args, args); |
572 | 0 | Py_END_CRITICAL_SECTION(); |
573 | 0 | } |
574 | | |
575 | | const char * |
576 | | PyExceptionClass_Name(PyObject *ob) |
577 | 0 | { |
578 | 0 | assert(PyExceptionClass_Check(ob)); |
579 | 0 | return ((PyTypeObject*)ob)->tp_name; |
580 | 0 | } |
581 | | |
582 | | static struct PyMemberDef BaseException_members[] = { |
583 | | {"__suppress_context__", Py_T_BOOL, |
584 | | offsetof(PyBaseExceptionObject, suppress_context)}, |
585 | | {NULL} |
586 | | }; |
587 | | |
588 | | |
589 | | static PyTypeObject _PyExc_BaseException = { |
590 | | PyVarObject_HEAD_INIT(NULL, 0) |
591 | | "BaseException", /*tp_name*/ |
592 | | sizeof(PyBaseExceptionObject), /*tp_basicsize*/ |
593 | | 0, /*tp_itemsize*/ |
594 | | BaseException_dealloc, /*tp_dealloc*/ |
595 | | 0, /*tp_vectorcall_offset*/ |
596 | | 0, /*tp_getattr*/ |
597 | | 0, /*tp_setattr*/ |
598 | | 0, /*tp_as_async*/ |
599 | | BaseException_repr, /*tp_repr*/ |
600 | | 0, /*tp_as_number*/ |
601 | | 0, /*tp_as_sequence*/ |
602 | | 0, /*tp_as_mapping*/ |
603 | | 0, /*tp_hash */ |
604 | | 0, /*tp_call*/ |
605 | | BaseException_str, /*tp_str*/ |
606 | | PyObject_GenericGetAttr, /*tp_getattro*/ |
607 | | PyObject_GenericSetAttr, /*tp_setattro*/ |
608 | | 0, /*tp_as_buffer*/ |
609 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | |
610 | | Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ |
611 | | PyDoc_STR("Common base class for all exceptions"), /* tp_doc */ |
612 | | BaseException_traverse, /* tp_traverse */ |
613 | | BaseException_clear, /* tp_clear */ |
614 | | 0, /* tp_richcompare */ |
615 | | 0, /* tp_weaklistoffset */ |
616 | | 0, /* tp_iter */ |
617 | | 0, /* tp_iternext */ |
618 | | BaseException_methods, /* tp_methods */ |
619 | | BaseException_members, /* tp_members */ |
620 | | BaseException_getset, /* tp_getset */ |
621 | | 0, /* tp_base */ |
622 | | 0, /* tp_dict */ |
623 | | 0, /* tp_descr_get */ |
624 | | 0, /* tp_descr_set */ |
625 | | offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */ |
626 | | BaseException_init, /* tp_init */ |
627 | | 0, /* tp_alloc */ |
628 | | BaseException_new, /* tp_new */ |
629 | | .tp_vectorcall = BaseException_vectorcall, |
630 | | }; |
631 | | /* the CPython API expects exceptions to be (PyObject *) - both a hold-over |
632 | | from the previous implementation and also allowing Python objects to be used |
633 | | in the API */ |
634 | | PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException; |
635 | | |
636 | | /* note these macros omit the last semicolon so the macro invocation may |
637 | | * include it and not look strange. |
638 | | */ |
639 | | #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \ |
640 | | static PyTypeObject _PyExc_ ## EXCNAME = { \ |
641 | | PyVarObject_HEAD_INIT(NULL, 0) \ |
642 | | # EXCNAME, \ |
643 | | sizeof(PyBaseExceptionObject), \ |
644 | | 0, BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \ |
645 | | 0, 0, 0, 0, 0, 0, 0, \ |
646 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ |
647 | | PyDoc_STR(EXCDOC), BaseException_traverse, \ |
648 | | BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \ |
649 | | 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \ |
650 | | BaseException_init, 0, BaseException_new,\ |
651 | | }; \ |
652 | | PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME |
653 | | |
654 | | #define MiddlingExtendsExceptionEx(EXCBASE, EXCNAME, PYEXCNAME, EXCSTORE, EXCDOC) \ |
655 | | PyTypeObject _PyExc_ ## EXCNAME = { \ |
656 | | PyVarObject_HEAD_INIT(NULL, 0) \ |
657 | | # PYEXCNAME, \ |
658 | | sizeof(Py ## EXCSTORE ## Object), \ |
659 | | 0, EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \ |
660 | | 0, 0, 0, 0, 0, \ |
661 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ |
662 | | PyDoc_STR(EXCDOC), EXCSTORE ## _traverse, \ |
663 | | EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \ |
664 | | 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \ |
665 | | EXCSTORE ## _init, 0, 0, \ |
666 | | }; |
667 | | |
668 | | #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \ |
669 | | static MiddlingExtendsExceptionEx( \ |
670 | | EXCBASE, EXCNAME, EXCNAME, EXCSTORE, EXCDOC); \ |
671 | | PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME |
672 | | |
673 | | #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \ |
674 | | EXCMETHODS, EXCMEMBERS, EXCGETSET, \ |
675 | | EXCSTR, EXCREPR, EXCDOC) \ |
676 | | static PyTypeObject _PyExc_ ## EXCNAME = { \ |
677 | | PyVarObject_HEAD_INIT(NULL, 0) \ |
678 | | # EXCNAME, \ |
679 | | sizeof(Py ## EXCSTORE ## Object), 0, \ |
680 | | EXCSTORE ## _dealloc, 0, 0, 0, 0, EXCREPR, 0, 0, 0, 0, 0, \ |
681 | | EXCSTR, 0, 0, 0, \ |
682 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ |
683 | | PyDoc_STR(EXCDOC), EXCSTORE ## _traverse, \ |
684 | | EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \ |
685 | | EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \ |
686 | | 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \ |
687 | | EXCSTORE ## _init, 0, EXCNEW,\ |
688 | | }; \ |
689 | | PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME |
690 | | |
691 | | |
692 | | /* |
693 | | * Exception extends BaseException |
694 | | */ |
695 | | SimpleExtendsException(PyExc_BaseException, Exception, |
696 | | "Common base class for all non-exit exceptions."); |
697 | | |
698 | | |
699 | | /* |
700 | | * TypeError extends Exception |
701 | | */ |
702 | | SimpleExtendsException(PyExc_Exception, TypeError, |
703 | | "Inappropriate argument type."); |
704 | | |
705 | | |
706 | | /* |
707 | | * StopAsyncIteration extends Exception |
708 | | */ |
709 | | SimpleExtendsException(PyExc_Exception, StopAsyncIteration, |
710 | | "Signal the end from iterator.__anext__()."); |
711 | | |
712 | | |
713 | | /* |
714 | | * StopIteration extends Exception |
715 | | */ |
716 | | |
717 | | static PyMemberDef StopIteration_members[] = { |
718 | | {"value", _Py_T_OBJECT, offsetof(PyStopIterationObject, value), 0, |
719 | | PyDoc_STR("generator return value")}, |
720 | | {NULL} /* Sentinel */ |
721 | | }; |
722 | | |
723 | | static inline PyStopIterationObject * |
724 | | PyStopIterationObject_CAST(PyObject *self) |
725 | 30.8M | { |
726 | 30.8M | assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_StopIteration)); |
727 | 30.8M | return (PyStopIterationObject *)self; |
728 | 30.8M | } |
729 | | |
730 | | static int |
731 | | StopIteration_init(PyObject *op, PyObject *args, PyObject *kwds) |
732 | 15.4M | { |
733 | 15.4M | Py_ssize_t size = PyTuple_GET_SIZE(args); |
734 | 15.4M | PyObject *value; |
735 | | |
736 | 15.4M | if (BaseException_init(op, args, kwds) == -1) |
737 | 0 | return -1; |
738 | 15.4M | PyStopIterationObject *self = PyStopIterationObject_CAST(op); |
739 | 15.4M | Py_CLEAR(self->value); |
740 | 15.4M | if (size > 0) |
741 | 2.15k | value = PyTuple_GET_ITEM(args, 0); |
742 | 15.4M | else |
743 | 15.4M | value = Py_None; |
744 | 15.4M | self->value = Py_NewRef(value); |
745 | 15.4M | return 0; |
746 | 15.4M | } |
747 | | |
748 | | static int |
749 | | StopIteration_clear(PyObject *op) |
750 | 15.4M | { |
751 | 15.4M | PyStopIterationObject *self = PyStopIterationObject_CAST(op); |
752 | 15.4M | Py_CLEAR(self->value); |
753 | 15.4M | return BaseException_clear(op); |
754 | 15.4M | } |
755 | | |
756 | | static void |
757 | | StopIteration_dealloc(PyObject *self) |
758 | 15.4M | { |
759 | 15.4M | PyObject_GC_UnTrack(self); |
760 | 15.4M | (void)StopIteration_clear(self); |
761 | 15.4M | Py_TYPE(self)->tp_free(self); |
762 | 15.4M | } |
763 | | |
764 | | static int |
765 | | StopIteration_traverse(PyObject *op, visitproc visit, void *arg) |
766 | 0 | { |
767 | 0 | PyStopIterationObject *self = PyStopIterationObject_CAST(op); |
768 | 0 | Py_VISIT(self->value); |
769 | 0 | return BaseException_traverse(op, visit, arg); |
770 | 0 | } |
771 | | |
772 | | ComplexExtendsException(PyExc_Exception, StopIteration, StopIteration, |
773 | | 0, 0, StopIteration_members, 0, 0, 0, |
774 | | "Signal the end from iterator.__next__()."); |
775 | | |
776 | | |
777 | | /* |
778 | | * GeneratorExit extends BaseException |
779 | | */ |
780 | | SimpleExtendsException(PyExc_BaseException, GeneratorExit, |
781 | | "Request that a generator exit."); |
782 | | |
783 | | |
784 | | /* |
785 | | * SystemExit extends BaseException |
786 | | */ |
787 | | |
788 | | static inline PySystemExitObject * |
789 | | PySystemExitObject_CAST(PyObject *self) |
790 | 0 | { |
791 | 0 | assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_SystemExit)); |
792 | 0 | return (PySystemExitObject *)self; |
793 | 0 | } |
794 | | |
795 | | static int |
796 | | SystemExit_init(PyObject *op, PyObject *args, PyObject *kwds) |
797 | 0 | { |
798 | 0 | Py_ssize_t size = PyTuple_GET_SIZE(args); |
799 | |
|
800 | 0 | if (BaseException_init(op, args, kwds) == -1) |
801 | 0 | return -1; |
802 | | |
803 | 0 | PySystemExitObject *self = PySystemExitObject_CAST(op); |
804 | 0 | if (size == 0) |
805 | 0 | return 0; |
806 | 0 | if (size == 1) { |
807 | 0 | Py_XSETREF(self->code, Py_NewRef(PyTuple_GET_ITEM(args, 0))); |
808 | 0 | } |
809 | 0 | else { /* size > 1 */ |
810 | 0 | Py_XSETREF(self->code, Py_NewRef(args)); |
811 | 0 | } |
812 | 0 | return 0; |
813 | 0 | } |
814 | | |
815 | | static int |
816 | | SystemExit_clear(PyObject *op) |
817 | 0 | { |
818 | 0 | PySystemExitObject *self = PySystemExitObject_CAST(op); |
819 | 0 | Py_CLEAR(self->code); |
820 | 0 | return BaseException_clear(op); |
821 | 0 | } |
822 | | |
823 | | static void |
824 | | SystemExit_dealloc(PyObject *self) |
825 | 0 | { |
826 | 0 | _PyObject_GC_UNTRACK(self); |
827 | 0 | (void)SystemExit_clear(self); |
828 | 0 | Py_TYPE(self)->tp_free(self); |
829 | 0 | } |
830 | | |
831 | | static int |
832 | | SystemExit_traverse(PyObject *op, visitproc visit, void *arg) |
833 | 0 | { |
834 | 0 | PySystemExitObject *self = PySystemExitObject_CAST(op); |
835 | 0 | Py_VISIT(self->code); |
836 | 0 | return BaseException_traverse(op, visit, arg); |
837 | 0 | } |
838 | | |
839 | | static PyMemberDef SystemExit_members[] = { |
840 | | {"code", _Py_T_OBJECT, offsetof(PySystemExitObject, code), 0, |
841 | | PyDoc_STR("exception code")}, |
842 | | {NULL} /* Sentinel */ |
843 | | }; |
844 | | |
845 | | ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit, |
846 | | 0, 0, SystemExit_members, 0, 0, 0, |
847 | | "Request to exit from the interpreter."); |
848 | | |
849 | | /* |
850 | | * BaseExceptionGroup extends BaseException |
851 | | * ExceptionGroup extends BaseExceptionGroup and Exception |
852 | | */ |
853 | | |
854 | | |
855 | | static inline PyBaseExceptionGroupObject* |
856 | | PyBaseExceptionGroupObject_CAST(PyObject *exc) |
857 | 0 | { |
858 | 0 | assert(_PyBaseExceptionGroup_Check(exc)); |
859 | 0 | return (PyBaseExceptionGroupObject *)exc; |
860 | 0 | } |
861 | | |
862 | | static PyObject * |
863 | | BaseExceptionGroup_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
864 | 0 | { |
865 | 0 | struct _Py_exc_state *state = get_exc_state(); |
866 | 0 | PyTypeObject *PyExc_ExceptionGroup = |
867 | 0 | (PyTypeObject*)state->PyExc_ExceptionGroup; |
868 | |
|
869 | 0 | PyObject *message = NULL; |
870 | 0 | PyObject *exceptions = NULL; |
871 | 0 | PyObject *exceptions_str = NULL; |
872 | |
|
873 | 0 | if (!PyArg_ParseTuple(args, |
874 | 0 | "UO:BaseExceptionGroup.__new__", |
875 | 0 | &message, |
876 | 0 | &exceptions)) { |
877 | 0 | return NULL; |
878 | 0 | } |
879 | | |
880 | 0 | if (!PySequence_Check(exceptions)) { |
881 | 0 | PyErr_SetString( |
882 | 0 | PyExc_TypeError, |
883 | 0 | "second argument (exceptions) must be a sequence"); |
884 | 0 | return NULL; |
885 | 0 | } |
886 | | |
887 | | /* Save initial exceptions sequence as a string in case sequence is mutated */ |
888 | 0 | if (!PyList_Check(exceptions) && !PyTuple_Check(exceptions)) { |
889 | 0 | exceptions_str = PyObject_Repr(exceptions); |
890 | 0 | if (exceptions_str == NULL) { |
891 | | /* We don't hold a reference to exceptions, so clear it before |
892 | | * attempting a decref in the cleanup. |
893 | | */ |
894 | 0 | exceptions = NULL; |
895 | 0 | goto error; |
896 | 0 | } |
897 | 0 | } |
898 | | |
899 | 0 | exceptions = PySequence_Tuple(exceptions); |
900 | 0 | if (!exceptions) { |
901 | 0 | goto error; |
902 | 0 | } |
903 | | |
904 | | /* We are now holding a ref to the exceptions tuple */ |
905 | | |
906 | 0 | Py_ssize_t numexcs = PyTuple_GET_SIZE(exceptions); |
907 | 0 | if (numexcs == 0) { |
908 | 0 | PyErr_SetString( |
909 | 0 | PyExc_ValueError, |
910 | 0 | "second argument (exceptions) must be a non-empty sequence"); |
911 | 0 | goto error; |
912 | 0 | } |
913 | | |
914 | 0 | bool nested_base_exceptions = false; |
915 | 0 | for (Py_ssize_t i = 0; i < numexcs; i++) { |
916 | 0 | PyObject *exc = PyTuple_GET_ITEM(exceptions, i); |
917 | 0 | if (!exc) { |
918 | 0 | goto error; |
919 | 0 | } |
920 | 0 | if (!PyExceptionInstance_Check(exc)) { |
921 | 0 | PyErr_Format( |
922 | 0 | PyExc_ValueError, |
923 | 0 | "Item %zd of second argument (exceptions) is not an exception", |
924 | 0 | i); |
925 | 0 | goto error; |
926 | 0 | } |
927 | 0 | int is_nonbase_exception = PyObject_IsInstance(exc, PyExc_Exception); |
928 | 0 | if (is_nonbase_exception < 0) { |
929 | 0 | goto error; |
930 | 0 | } |
931 | 0 | else if (is_nonbase_exception == 0) { |
932 | 0 | nested_base_exceptions = true; |
933 | 0 | } |
934 | 0 | } |
935 | | |
936 | 0 | PyTypeObject *cls = type; |
937 | 0 | if (cls == PyExc_ExceptionGroup) { |
938 | 0 | if (nested_base_exceptions) { |
939 | 0 | PyErr_SetString(PyExc_TypeError, |
940 | 0 | "Cannot nest BaseExceptions in an ExceptionGroup"); |
941 | 0 | goto error; |
942 | 0 | } |
943 | 0 | } |
944 | 0 | else if (cls == (PyTypeObject*)PyExc_BaseExceptionGroup) { |
945 | 0 | if (!nested_base_exceptions) { |
946 | | /* All nested exceptions are Exception subclasses, |
947 | | * wrap them in an ExceptionGroup |
948 | | */ |
949 | 0 | cls = PyExc_ExceptionGroup; |
950 | 0 | } |
951 | 0 | } |
952 | 0 | else { |
953 | | /* user-defined subclass */ |
954 | 0 | if (nested_base_exceptions) { |
955 | 0 | int nonbase = PyObject_IsSubclass((PyObject*)cls, PyExc_Exception); |
956 | 0 | if (nonbase == -1) { |
957 | 0 | goto error; |
958 | 0 | } |
959 | 0 | else if (nonbase == 1) { |
960 | 0 | PyErr_Format(PyExc_TypeError, |
961 | 0 | "Cannot nest BaseExceptions in '%.200s'", |
962 | 0 | cls->tp_name); |
963 | 0 | goto error; |
964 | 0 | } |
965 | 0 | } |
966 | 0 | } |
967 | | |
968 | 0 | if (!cls) { |
969 | | /* Don't crash during interpreter shutdown |
970 | | * (PyExc_ExceptionGroup may have been cleared) |
971 | | */ |
972 | 0 | cls = (PyTypeObject*)PyExc_BaseExceptionGroup; |
973 | 0 | } |
974 | 0 | PyObject *op = BaseException_new(cls, args, kwds); |
975 | 0 | if (!op) { |
976 | 0 | goto error; |
977 | 0 | } |
978 | 0 | PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op); |
979 | |
|
980 | 0 | self->msg = Py_NewRef(message); |
981 | 0 | self->excs = exceptions; |
982 | 0 | self->excs_str = exceptions_str; |
983 | 0 | return (PyObject*)self; |
984 | 0 | error: |
985 | 0 | Py_XDECREF(exceptions); |
986 | 0 | Py_XDECREF(exceptions_str); |
987 | 0 | return NULL; |
988 | 0 | } |
989 | | |
990 | | PyObject * |
991 | | _PyExc_CreateExceptionGroup(const char *msg_str, PyObject *excs) |
992 | 0 | { |
993 | 0 | PyObject *msg = PyUnicode_FromString(msg_str); |
994 | 0 | if (!msg) { |
995 | 0 | return NULL; |
996 | 0 | } |
997 | 0 | PyObject *args = _PyTuple_FromPairSteal(msg, Py_NewRef(excs)); |
998 | 0 | if (!args) { |
999 | 0 | return NULL; |
1000 | 0 | } |
1001 | 0 | PyObject *result = PyObject_CallObject(PyExc_BaseExceptionGroup, args); |
1002 | 0 | Py_DECREF(args); |
1003 | 0 | return result; |
1004 | 0 | } |
1005 | | |
1006 | | static int |
1007 | | BaseExceptionGroup_init(PyObject *self, PyObject *args, PyObject *kwds) |
1008 | 0 | { |
1009 | 0 | if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) { |
1010 | 0 | return -1; |
1011 | 0 | } |
1012 | 0 | if (BaseException_init(self, args, kwds) == -1) { |
1013 | 0 | return -1; |
1014 | 0 | } |
1015 | 0 | return 0; |
1016 | 0 | } |
1017 | | |
1018 | | static int |
1019 | | BaseExceptionGroup_clear(PyObject *op) |
1020 | 0 | { |
1021 | 0 | PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op); |
1022 | 0 | Py_CLEAR(self->msg); |
1023 | 0 | Py_CLEAR(self->excs); |
1024 | 0 | Py_CLEAR(self->excs_str); |
1025 | 0 | return BaseException_clear(op); |
1026 | 0 | } |
1027 | | |
1028 | | static void |
1029 | | BaseExceptionGroup_dealloc(PyObject *self) |
1030 | 0 | { |
1031 | 0 | _PyObject_GC_UNTRACK(self); |
1032 | 0 | (void)BaseExceptionGroup_clear(self); |
1033 | 0 | Py_TYPE(self)->tp_free(self); |
1034 | 0 | } |
1035 | | |
1036 | | static int |
1037 | | BaseExceptionGroup_traverse(PyObject *op, visitproc visit, void *arg) |
1038 | 0 | { |
1039 | 0 | PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op); |
1040 | 0 | Py_VISIT(self->msg); |
1041 | 0 | Py_VISIT(self->excs); |
1042 | 0 | Py_VISIT(self->excs_str); |
1043 | 0 | return BaseException_traverse(op, visit, arg); |
1044 | 0 | } |
1045 | | |
1046 | | static PyObject * |
1047 | | BaseExceptionGroup_str(PyObject *op) |
1048 | 0 | { |
1049 | 0 | PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op); |
1050 | 0 | assert(self->msg); |
1051 | 0 | assert(PyUnicode_Check(self->msg)); |
1052 | |
|
1053 | 0 | assert(PyTuple_CheckExact(self->excs)); |
1054 | 0 | Py_ssize_t num_excs = PyTuple_Size(self->excs); |
1055 | 0 | return PyUnicode_FromFormat( |
1056 | 0 | "%S (%zd sub-exception%s)", |
1057 | 0 | self->msg, num_excs, num_excs > 1 ? "s" : ""); |
1058 | 0 | } |
1059 | | |
1060 | | static PyObject * |
1061 | | BaseExceptionGroup_repr(PyObject *op) |
1062 | 0 | { |
1063 | 0 | PyBaseExceptionGroupObject *self = PyBaseExceptionGroupObject_CAST(op); |
1064 | 0 | assert(self->msg); |
1065 | |
|
1066 | 0 | PyObject *exceptions_str = NULL; |
1067 | | |
1068 | | /* Use the saved exceptions string for custom sequences. */ |
1069 | 0 | if (self->excs_str) { |
1070 | 0 | exceptions_str = Py_NewRef(self->excs_str); |
1071 | 0 | } |
1072 | 0 | else { |
1073 | 0 | assert(self->excs); |
1074 | | |
1075 | | /* Older versions delegated to BaseException, inserting the current |
1076 | | * value of self.args[1]; but this can be mutable and go out-of-sync |
1077 | | * with self.exceptions. Instead, use self.exceptions for accuracy, |
1078 | | * making it look like self.args[1] for backwards compatibility. */ |
1079 | 0 | assert(PyTuple_Check(self->args)); |
1080 | 0 | if (PyTuple_GET_SIZE(self->args) == 2 && PyList_Check(PyTuple_GET_ITEM(self->args, 1))) { |
1081 | 0 | PyObject *exceptions_list = PySequence_List(self->excs); |
1082 | 0 | if (!exceptions_list) { |
1083 | 0 | return NULL; |
1084 | 0 | } |
1085 | | |
1086 | 0 | exceptions_str = PyObject_Repr(exceptions_list); |
1087 | 0 | Py_DECREF(exceptions_list); |
1088 | 0 | } |
1089 | 0 | else { |
1090 | 0 | exceptions_str = PyObject_Repr(self->excs); |
1091 | 0 | } |
1092 | | |
1093 | 0 | if (!exceptions_str) { |
1094 | 0 | return NULL; |
1095 | 0 | } |
1096 | 0 | } |
1097 | | |
1098 | 0 | assert(exceptions_str != NULL); |
1099 | |
|
1100 | 0 | const char *name = _PyType_Name(Py_TYPE(self)); |
1101 | 0 | PyObject *repr = PyUnicode_FromFormat( |
1102 | 0 | "%s(%R, %U)", name, |
1103 | 0 | self->msg, exceptions_str); |
1104 | |
|
1105 | 0 | Py_DECREF(exceptions_str); |
1106 | 0 | return repr; |
1107 | 0 | } |
1108 | | |
1109 | | /*[clinic input] |
1110 | | @critical_section |
1111 | | BaseExceptionGroup.derive |
1112 | | excs: object |
1113 | | / |
1114 | | [clinic start generated code]*/ |
1115 | | |
1116 | | static PyObject * |
1117 | | BaseExceptionGroup_derive_impl(PyBaseExceptionGroupObject *self, |
1118 | | PyObject *excs) |
1119 | | /*[clinic end generated code: output=4307564218dfbf06 input=f72009d38e98cec1]*/ |
1120 | 0 | { |
1121 | 0 | PyObject *init_args = _PyTuple_FromPair(self->msg, excs); |
1122 | 0 | if (!init_args) { |
1123 | 0 | return NULL; |
1124 | 0 | } |
1125 | 0 | PyObject *eg = PyObject_CallObject( |
1126 | 0 | PyExc_BaseExceptionGroup, init_args); |
1127 | 0 | Py_DECREF(init_args); |
1128 | 0 | return eg; |
1129 | 0 | } |
1130 | | |
1131 | | static int |
1132 | | exceptiongroup_subset( |
1133 | | PyBaseExceptionGroupObject *_orig, PyObject *excs, PyObject **result) |
1134 | 0 | { |
1135 | | /* Sets *result to an ExceptionGroup wrapping excs with metadata from |
1136 | | * _orig. If excs is empty, sets *result to NULL. |
1137 | | * Returns 0 on success and -1 on error. |
1138 | | |
1139 | | * This function is used by split() to construct the match/rest parts, |
1140 | | * so excs is the matching or non-matching sub-sequence of orig->excs |
1141 | | * (this function does not verify that it is a subsequence). |
1142 | | */ |
1143 | 0 | PyObject *orig = (PyObject *)_orig; |
1144 | |
|
1145 | 0 | *result = NULL; |
1146 | 0 | Py_ssize_t num_excs = PySequence_Size(excs); |
1147 | 0 | if (num_excs < 0) { |
1148 | 0 | return -1; |
1149 | 0 | } |
1150 | 0 | else if (num_excs == 0) { |
1151 | 0 | return 0; |
1152 | 0 | } |
1153 | | |
1154 | 0 | PyObject *eg = PyObject_CallMethod( |
1155 | 0 | orig, "derive", "(O)", excs); |
1156 | 0 | if (!eg) { |
1157 | 0 | return -1; |
1158 | 0 | } |
1159 | | |
1160 | 0 | if (!_PyBaseExceptionGroup_Check(eg)) { |
1161 | 0 | PyErr_SetString(PyExc_TypeError, |
1162 | 0 | "derive must return an instance of BaseExceptionGroup"); |
1163 | 0 | goto error; |
1164 | 0 | } |
1165 | | |
1166 | | /* Now we hold a reference to the new eg */ |
1167 | | |
1168 | 0 | PyObject *tb = PyException_GetTraceback(orig); |
1169 | 0 | if (tb) { |
1170 | 0 | int res = PyException_SetTraceback(eg, tb); |
1171 | 0 | Py_DECREF(tb); |
1172 | 0 | if (res < 0) { |
1173 | 0 | goto error; |
1174 | 0 | } |
1175 | 0 | } |
1176 | 0 | PyException_SetContext(eg, PyException_GetContext(orig)); |
1177 | 0 | PyException_SetCause(eg, PyException_GetCause(orig)); |
1178 | |
|
1179 | 0 | PyObject *notes; |
1180 | 0 | if (PyObject_GetOptionalAttr(orig, &_Py_ID(__notes__), ¬es) < 0) { |
1181 | 0 | goto error; |
1182 | 0 | } |
1183 | 0 | if (notes) { |
1184 | 0 | if (PySequence_Check(notes)) { |
1185 | | /* Make a copy so the parts have independent notes lists. */ |
1186 | 0 | PyObject *notes_copy = PySequence_List(notes); |
1187 | 0 | Py_DECREF(notes); |
1188 | 0 | if (notes_copy == NULL) { |
1189 | 0 | goto error; |
1190 | 0 | } |
1191 | 0 | int res = PyObject_SetAttr(eg, &_Py_ID(__notes__), notes_copy); |
1192 | 0 | Py_DECREF(notes_copy); |
1193 | 0 | if (res < 0) { |
1194 | 0 | goto error; |
1195 | 0 | } |
1196 | 0 | } |
1197 | 0 | else { |
1198 | | /* __notes__ is supposed to be a list, and split() is not a |
1199 | | * good place to report earlier user errors, so we just ignore |
1200 | | * notes of non-sequence type. |
1201 | | */ |
1202 | 0 | Py_DECREF(notes); |
1203 | 0 | } |
1204 | 0 | } |
1205 | | |
1206 | 0 | *result = eg; |
1207 | 0 | return 0; |
1208 | 0 | error: |
1209 | 0 | Py_DECREF(eg); |
1210 | 0 | return -1; |
1211 | 0 | } |
1212 | | |
1213 | | typedef enum { |
1214 | | /* Exception type or tuple of thereof */ |
1215 | | EXCEPTION_GROUP_MATCH_BY_TYPE = 0, |
1216 | | /* A PyFunction returning True for matching exceptions */ |
1217 | | EXCEPTION_GROUP_MATCH_BY_PREDICATE = 1, |
1218 | | /* A set of the IDs of leaf exceptions to include in the result. |
1219 | | * This matcher type is used internally by the interpreter |
1220 | | * to construct reraised exceptions. |
1221 | | */ |
1222 | | EXCEPTION_GROUP_MATCH_INSTANCE_IDS = 2 |
1223 | | } _exceptiongroup_split_matcher_type; |
1224 | | |
1225 | | static int |
1226 | | get_matcher_type(PyObject *value, |
1227 | | _exceptiongroup_split_matcher_type *type) |
1228 | 0 | { |
1229 | 0 | assert(value); |
1230 | |
|
1231 | 0 | if (PyCallable_Check(value) && !PyType_Check(value)) { |
1232 | 0 | *type = EXCEPTION_GROUP_MATCH_BY_PREDICATE; |
1233 | 0 | return 0; |
1234 | 0 | } |
1235 | | |
1236 | 0 | if (PyExceptionClass_Check(value)) { |
1237 | 0 | *type = EXCEPTION_GROUP_MATCH_BY_TYPE; |
1238 | 0 | return 0; |
1239 | 0 | } |
1240 | | |
1241 | 0 | if (PyTuple_CheckExact(value)) { |
1242 | 0 | Py_ssize_t n = PyTuple_GET_SIZE(value); |
1243 | 0 | for (Py_ssize_t i=0; i<n; i++) { |
1244 | 0 | if (!PyExceptionClass_Check(PyTuple_GET_ITEM(value, i))) { |
1245 | 0 | goto error; |
1246 | 0 | } |
1247 | 0 | } |
1248 | 0 | *type = EXCEPTION_GROUP_MATCH_BY_TYPE; |
1249 | 0 | return 0; |
1250 | 0 | } |
1251 | | |
1252 | 0 | error: |
1253 | 0 | PyErr_SetString( |
1254 | 0 | PyExc_TypeError, |
1255 | 0 | "expected an exception type, a tuple of exception types, or a callable (other than a class)"); |
1256 | 0 | return -1; |
1257 | 0 | } |
1258 | | |
1259 | | static int |
1260 | | exceptiongroup_split_check_match(PyObject *exc, |
1261 | | _exceptiongroup_split_matcher_type matcher_type, |
1262 | | PyObject *matcher_value) |
1263 | 0 | { |
1264 | 0 | switch (matcher_type) { |
1265 | 0 | case EXCEPTION_GROUP_MATCH_BY_TYPE: { |
1266 | 0 | assert(PyExceptionClass_Check(matcher_value) || |
1267 | 0 | PyTuple_CheckExact(matcher_value)); |
1268 | 0 | return PyErr_GivenExceptionMatches(exc, matcher_value); |
1269 | 0 | } |
1270 | 0 | case EXCEPTION_GROUP_MATCH_BY_PREDICATE: { |
1271 | 0 | assert(PyCallable_Check(matcher_value) && !PyType_Check(matcher_value)); |
1272 | 0 | PyObject *exc_matches = PyObject_CallOneArg(matcher_value, exc); |
1273 | 0 | if (exc_matches == NULL) { |
1274 | 0 | return -1; |
1275 | 0 | } |
1276 | 0 | int is_true = PyObject_IsTrue(exc_matches); |
1277 | 0 | Py_DECREF(exc_matches); |
1278 | 0 | return is_true; |
1279 | 0 | } |
1280 | 0 | case EXCEPTION_GROUP_MATCH_INSTANCE_IDS: { |
1281 | 0 | assert(PySet_Check(matcher_value)); |
1282 | 0 | if (!_PyBaseExceptionGroup_Check(exc)) { |
1283 | 0 | PyObject *exc_id = PyLong_FromVoidPtr(exc); |
1284 | 0 | if (exc_id == NULL) { |
1285 | 0 | return -1; |
1286 | 0 | } |
1287 | 0 | int res = PySet_Contains(matcher_value, exc_id); |
1288 | 0 | Py_DECREF(exc_id); |
1289 | 0 | return res; |
1290 | 0 | } |
1291 | 0 | return 0; |
1292 | 0 | } |
1293 | 0 | } |
1294 | 0 | return 0; |
1295 | 0 | } |
1296 | | |
1297 | | typedef struct { |
1298 | | PyObject *match; |
1299 | | PyObject *rest; |
1300 | | } _exceptiongroup_split_result; |
1301 | | |
1302 | | static int |
1303 | | exceptiongroup_split_recursive(PyObject *exc, |
1304 | | _exceptiongroup_split_matcher_type matcher_type, |
1305 | | PyObject *matcher_value, |
1306 | | bool construct_rest, |
1307 | | _exceptiongroup_split_result *result) |
1308 | 0 | { |
1309 | 0 | result->match = NULL; |
1310 | 0 | result->rest = NULL; |
1311 | |
|
1312 | 0 | int is_match = exceptiongroup_split_check_match( |
1313 | 0 | exc, matcher_type, matcher_value); |
1314 | 0 | if (is_match < 0) { |
1315 | 0 | return -1; |
1316 | 0 | } |
1317 | | |
1318 | 0 | if (is_match) { |
1319 | | /* Full match */ |
1320 | 0 | result->match = Py_NewRef(exc); |
1321 | 0 | return 0; |
1322 | 0 | } |
1323 | 0 | else if (!_PyBaseExceptionGroup_Check(exc)) { |
1324 | | /* Leaf exception and no match */ |
1325 | 0 | if (construct_rest) { |
1326 | 0 | result->rest = Py_NewRef(exc); |
1327 | 0 | } |
1328 | 0 | return 0; |
1329 | 0 | } |
1330 | | |
1331 | | /* Partial match */ |
1332 | | |
1333 | 0 | PyBaseExceptionGroupObject *eg = PyBaseExceptionGroupObject_CAST(exc); |
1334 | 0 | assert(PyTuple_CheckExact(eg->excs)); |
1335 | 0 | Py_ssize_t num_excs = PyTuple_Size(eg->excs); |
1336 | 0 | if (num_excs < 0) { |
1337 | 0 | return -1; |
1338 | 0 | } |
1339 | 0 | assert(num_excs > 0); /* checked in constructor, and excs is read-only */ |
1340 | |
|
1341 | 0 | int retval = -1; |
1342 | 0 | PyObject *match_list = PyList_New(0); |
1343 | 0 | if (!match_list) { |
1344 | 0 | return -1; |
1345 | 0 | } |
1346 | | |
1347 | 0 | PyObject *rest_list = NULL; |
1348 | 0 | if (construct_rest) { |
1349 | 0 | rest_list = PyList_New(0); |
1350 | 0 | if (!rest_list) { |
1351 | 0 | goto done; |
1352 | 0 | } |
1353 | 0 | } |
1354 | | /* recursive calls */ |
1355 | 0 | for (Py_ssize_t i = 0; i < num_excs; i++) { |
1356 | 0 | PyObject *e = PyTuple_GET_ITEM(eg->excs, i); |
1357 | 0 | _exceptiongroup_split_result rec_result; |
1358 | 0 | if (_Py_EnterRecursiveCall(" in exceptiongroup_split_recursive")) { |
1359 | 0 | goto done; |
1360 | 0 | } |
1361 | 0 | if (exceptiongroup_split_recursive( |
1362 | 0 | e, matcher_type, matcher_value, |
1363 | 0 | construct_rest, &rec_result) < 0) { |
1364 | 0 | assert(!rec_result.match); |
1365 | 0 | assert(!rec_result.rest); |
1366 | 0 | _Py_LeaveRecursiveCall(); |
1367 | 0 | goto done; |
1368 | 0 | } |
1369 | 0 | _Py_LeaveRecursiveCall(); |
1370 | 0 | if (rec_result.match) { |
1371 | 0 | assert(PyList_CheckExact(match_list)); |
1372 | 0 | if (PyList_Append(match_list, rec_result.match) < 0) { |
1373 | 0 | Py_DECREF(rec_result.match); |
1374 | 0 | Py_XDECREF(rec_result.rest); |
1375 | 0 | goto done; |
1376 | 0 | } |
1377 | 0 | Py_DECREF(rec_result.match); |
1378 | 0 | } |
1379 | 0 | if (rec_result.rest) { |
1380 | 0 | assert(construct_rest); |
1381 | 0 | assert(PyList_CheckExact(rest_list)); |
1382 | 0 | if (PyList_Append(rest_list, rec_result.rest) < 0) { |
1383 | 0 | Py_DECREF(rec_result.rest); |
1384 | 0 | goto done; |
1385 | 0 | } |
1386 | 0 | Py_DECREF(rec_result.rest); |
1387 | 0 | } |
1388 | 0 | } |
1389 | | |
1390 | | /* construct result */ |
1391 | 0 | if (exceptiongroup_subset(eg, match_list, &result->match) < 0) { |
1392 | 0 | goto done; |
1393 | 0 | } |
1394 | | |
1395 | 0 | if (construct_rest) { |
1396 | 0 | assert(PyList_CheckExact(rest_list)); |
1397 | 0 | if (exceptiongroup_subset(eg, rest_list, &result->rest) < 0) { |
1398 | 0 | Py_CLEAR(result->match); |
1399 | 0 | goto done; |
1400 | 0 | } |
1401 | 0 | } |
1402 | 0 | retval = 0; |
1403 | 0 | done: |
1404 | 0 | Py_DECREF(match_list); |
1405 | 0 | Py_XDECREF(rest_list); |
1406 | 0 | if (retval < 0) { |
1407 | 0 | Py_CLEAR(result->match); |
1408 | 0 | Py_CLEAR(result->rest); |
1409 | 0 | } |
1410 | 0 | return retval; |
1411 | 0 | } |
1412 | | |
1413 | | /*[clinic input] |
1414 | | @critical_section |
1415 | | BaseExceptionGroup.split |
1416 | | matcher_value: object |
1417 | | / |
1418 | | [clinic start generated code]*/ |
1419 | | |
1420 | | static PyObject * |
1421 | | BaseExceptionGroup_split_impl(PyBaseExceptionGroupObject *self, |
1422 | | PyObject *matcher_value) |
1423 | | /*[clinic end generated code: output=d74db579da4df6e2 input=0c5cfbfed57e0052]*/ |
1424 | 0 | { |
1425 | 0 | _exceptiongroup_split_matcher_type matcher_type; |
1426 | 0 | if (get_matcher_type(matcher_value, &matcher_type) < 0) { |
1427 | 0 | return NULL; |
1428 | 0 | } |
1429 | | |
1430 | 0 | _exceptiongroup_split_result split_result; |
1431 | 0 | bool construct_rest = true; |
1432 | 0 | if (exceptiongroup_split_recursive( |
1433 | 0 | (PyObject *)self, matcher_type, matcher_value, |
1434 | 0 | construct_rest, &split_result) < 0) { |
1435 | 0 | return NULL; |
1436 | 0 | } |
1437 | | |
1438 | 0 | assert(_Py_IsStaticImmortal(Py_None)); |
1439 | 0 | PyObject *result = _PyTuple_FromPairSteal( |
1440 | 0 | split_result.match ? split_result.match : Py_None, |
1441 | 0 | split_result.rest ? split_result.rest : Py_None); |
1442 | |
|
1443 | 0 | return result; |
1444 | 0 | } |
1445 | | |
1446 | | /*[clinic input] |
1447 | | @critical_section |
1448 | | BaseExceptionGroup.subgroup |
1449 | | matcher_value: object |
1450 | | / |
1451 | | [clinic start generated code]*/ |
1452 | | |
1453 | | static PyObject * |
1454 | | BaseExceptionGroup_subgroup_impl(PyBaseExceptionGroupObject *self, |
1455 | | PyObject *matcher_value) |
1456 | | /*[clinic end generated code: output=07dbec8f77d4dd8e input=988ffdd755a151ce]*/ |
1457 | 0 | { |
1458 | 0 | _exceptiongroup_split_matcher_type matcher_type; |
1459 | 0 | if (get_matcher_type(matcher_value, &matcher_type) < 0) { |
1460 | 0 | return NULL; |
1461 | 0 | } |
1462 | | |
1463 | 0 | _exceptiongroup_split_result split_result; |
1464 | 0 | bool construct_rest = false; |
1465 | 0 | if (exceptiongroup_split_recursive( |
1466 | 0 | (PyObject *)self, matcher_type, matcher_value, |
1467 | 0 | construct_rest, &split_result) < 0) { |
1468 | 0 | return NULL; |
1469 | 0 | } |
1470 | | |
1471 | 0 | PyObject *result = Py_NewRef( |
1472 | 0 | split_result.match ? split_result.match : Py_None); |
1473 | |
|
1474 | 0 | Py_XDECREF(split_result.match); |
1475 | 0 | assert(!split_result.rest); |
1476 | 0 | return result; |
1477 | 0 | } |
1478 | | |
1479 | | static int |
1480 | | collect_exception_group_leaf_ids(PyObject *exc, PyObject *leaf_ids) |
1481 | 0 | { |
1482 | 0 | if (Py_IsNone(exc)) { |
1483 | 0 | return 0; |
1484 | 0 | } |
1485 | | |
1486 | 0 | assert(PyExceptionInstance_Check(exc)); |
1487 | 0 | assert(PySet_Check(leaf_ids)); |
1488 | | |
1489 | | /* Add IDs of all leaf exceptions in exc to the leaf_ids set */ |
1490 | |
|
1491 | 0 | if (!_PyBaseExceptionGroup_Check(exc)) { |
1492 | 0 | PyObject *exc_id = PyLong_FromVoidPtr(exc); |
1493 | 0 | if (exc_id == NULL) { |
1494 | 0 | return -1; |
1495 | 0 | } |
1496 | 0 | int res = PySet_Add(leaf_ids, exc_id); |
1497 | 0 | Py_DECREF(exc_id); |
1498 | 0 | return res; |
1499 | 0 | } |
1500 | 0 | PyBaseExceptionGroupObject *eg = PyBaseExceptionGroupObject_CAST(exc); |
1501 | 0 | Py_ssize_t num_excs = PyTuple_GET_SIZE(eg->excs); |
1502 | | /* recursive calls */ |
1503 | 0 | for (Py_ssize_t i = 0; i < num_excs; i++) { |
1504 | 0 | PyObject *e = PyTuple_GET_ITEM(eg->excs, i); |
1505 | 0 | if (_Py_EnterRecursiveCall(" in collect_exception_group_leaf_ids")) { |
1506 | 0 | return -1; |
1507 | 0 | } |
1508 | 0 | int res = collect_exception_group_leaf_ids(e, leaf_ids); |
1509 | 0 | _Py_LeaveRecursiveCall(); |
1510 | 0 | if (res < 0) { |
1511 | 0 | return -1; |
1512 | 0 | } |
1513 | 0 | } |
1514 | 0 | return 0; |
1515 | 0 | } |
1516 | | |
1517 | | /* This function is used by the interpreter to construct reraised |
1518 | | * exception groups. It takes an exception group eg and a list |
1519 | | * of exception groups keep and returns the sub-exception group |
1520 | | * of eg which contains all leaf exceptions that are contained |
1521 | | * in any exception group in keep. |
1522 | | */ |
1523 | | static PyObject * |
1524 | | exception_group_projection(PyObject *eg, PyObject *keep) |
1525 | 0 | { |
1526 | 0 | assert(_PyBaseExceptionGroup_Check(eg)); |
1527 | 0 | assert(PyList_CheckExact(keep)); |
1528 | |
|
1529 | 0 | PyObject *leaf_ids = PySet_New(NULL); |
1530 | 0 | if (!leaf_ids) { |
1531 | 0 | return NULL; |
1532 | 0 | } |
1533 | | |
1534 | 0 | Py_ssize_t n = PyList_GET_SIZE(keep); |
1535 | 0 | for (Py_ssize_t i = 0; i < n; i++) { |
1536 | 0 | PyObject *e = PyList_GET_ITEM(keep, i); |
1537 | 0 | assert(e != NULL); |
1538 | 0 | assert(_PyBaseExceptionGroup_Check(e)); |
1539 | 0 | if (collect_exception_group_leaf_ids(e, leaf_ids) < 0) { |
1540 | 0 | Py_DECREF(leaf_ids); |
1541 | 0 | return NULL; |
1542 | 0 | } |
1543 | 0 | } |
1544 | | |
1545 | 0 | _exceptiongroup_split_result split_result; |
1546 | 0 | bool construct_rest = false; |
1547 | 0 | int err = exceptiongroup_split_recursive( |
1548 | 0 | eg, EXCEPTION_GROUP_MATCH_INSTANCE_IDS, leaf_ids, |
1549 | 0 | construct_rest, &split_result); |
1550 | 0 | Py_DECREF(leaf_ids); |
1551 | 0 | if (err < 0) { |
1552 | 0 | return NULL; |
1553 | 0 | } |
1554 | | |
1555 | 0 | PyObject *result = split_result.match ? |
1556 | 0 | split_result.match : Py_NewRef(Py_None); |
1557 | 0 | assert(split_result.rest == NULL); |
1558 | 0 | return result; |
1559 | 0 | } |
1560 | | |
1561 | | static bool |
1562 | | is_same_exception_metadata(PyObject *exc1, PyObject *exc2) |
1563 | 0 | { |
1564 | 0 | assert(PyExceptionInstance_Check(exc1)); |
1565 | 0 | assert(PyExceptionInstance_Check(exc2)); |
1566 | |
|
1567 | 0 | PyBaseExceptionObject *e1 = (PyBaseExceptionObject *)exc1; |
1568 | 0 | PyBaseExceptionObject *e2 = (PyBaseExceptionObject *)exc2; |
1569 | |
|
1570 | 0 | return (e1->notes == e2->notes && |
1571 | 0 | e1->traceback == e2->traceback && |
1572 | 0 | e1->cause == e2->cause && |
1573 | 0 | e1->context == e2->context); |
1574 | 0 | } |
1575 | | |
1576 | | /* |
1577 | | This function is used by the interpreter to calculate |
1578 | | the exception group to be raised at the end of a |
1579 | | try-except* construct. |
1580 | | |
1581 | | orig: the original except that was caught. |
1582 | | excs: a list of exceptions that were raised/reraised |
1583 | | in the except* clauses. |
1584 | | |
1585 | | Calculates an exception group to raise. It contains |
1586 | | all exceptions in excs, where those that were reraised |
1587 | | have same nesting structure as in orig, and those that |
1588 | | were raised (if any) are added as siblings in a new EG. |
1589 | | |
1590 | | Returns NULL and sets an exception on failure. |
1591 | | */ |
1592 | | PyObject * |
1593 | | _PyExc_PrepReraiseStar(PyObject *orig, PyObject *excs) |
1594 | 0 | { |
1595 | | /* orig must be a raised & caught exception, so it has a traceback */ |
1596 | 0 | assert(PyExceptionInstance_Check(orig)); |
1597 | 0 | assert(PyBaseExceptionObject_CAST(orig)->traceback != NULL); |
1598 | |
|
1599 | 0 | assert(PyList_Check(excs)); |
1600 | |
|
1601 | 0 | Py_ssize_t numexcs = PyList_GET_SIZE(excs); |
1602 | |
|
1603 | 0 | if (numexcs == 0) { |
1604 | 0 | return Py_NewRef(Py_None); |
1605 | 0 | } |
1606 | | |
1607 | 0 | if (!_PyBaseExceptionGroup_Check(orig)) { |
1608 | | /* a naked exception was caught and wrapped. Only one except* clause |
1609 | | * could have executed,so there is at most one exception to raise. |
1610 | | */ |
1611 | |
|
1612 | 0 | assert(numexcs == 1 || (numexcs == 2 && PyList_GET_ITEM(excs, 1) == Py_None)); |
1613 | |
|
1614 | 0 | PyObject *e = PyList_GET_ITEM(excs, 0); |
1615 | 0 | assert(e != NULL); |
1616 | 0 | return Py_NewRef(e); |
1617 | 0 | } |
1618 | | |
1619 | 0 | PyObject *raised_list = PyList_New(0); |
1620 | 0 | if (raised_list == NULL) { |
1621 | 0 | return NULL; |
1622 | 0 | } |
1623 | 0 | PyObject* reraised_list = PyList_New(0); |
1624 | 0 | if (reraised_list == NULL) { |
1625 | 0 | Py_DECREF(raised_list); |
1626 | 0 | return NULL; |
1627 | 0 | } |
1628 | | |
1629 | | /* Now we are holding refs to raised_list and reraised_list */ |
1630 | | |
1631 | 0 | PyObject *result = NULL; |
1632 | | |
1633 | | /* Split excs into raised and reraised by comparing metadata with orig */ |
1634 | 0 | for (Py_ssize_t i = 0; i < numexcs; i++) { |
1635 | 0 | PyObject *e = PyList_GET_ITEM(excs, i); |
1636 | 0 | assert(e != NULL); |
1637 | 0 | if (Py_IsNone(e)) { |
1638 | 0 | continue; |
1639 | 0 | } |
1640 | 0 | bool is_reraise = is_same_exception_metadata(e, orig); |
1641 | 0 | PyObject *append_list = is_reraise ? reraised_list : raised_list; |
1642 | 0 | if (PyList_Append(append_list, e) < 0) { |
1643 | 0 | goto done; |
1644 | 0 | } |
1645 | 0 | } |
1646 | | |
1647 | 0 | PyObject *reraised_eg = exception_group_projection(orig, reraised_list); |
1648 | 0 | if (reraised_eg == NULL) { |
1649 | 0 | goto done; |
1650 | 0 | } |
1651 | | |
1652 | 0 | if (!Py_IsNone(reraised_eg)) { |
1653 | 0 | assert(is_same_exception_metadata(reraised_eg, orig)); |
1654 | 0 | } |
1655 | 0 | Py_ssize_t num_raised = PyList_GET_SIZE(raised_list); |
1656 | 0 | if (num_raised == 0) { |
1657 | 0 | result = reraised_eg; |
1658 | 0 | } |
1659 | 0 | else if (num_raised > 0) { |
1660 | 0 | int res = 0; |
1661 | 0 | if (!Py_IsNone(reraised_eg)) { |
1662 | 0 | res = PyList_Append(raised_list, reraised_eg); |
1663 | 0 | } |
1664 | 0 | Py_DECREF(reraised_eg); |
1665 | 0 | if (res < 0) { |
1666 | 0 | goto done; |
1667 | 0 | } |
1668 | 0 | if (PyList_GET_SIZE(raised_list) > 1) { |
1669 | 0 | result = _PyExc_CreateExceptionGroup("", raised_list); |
1670 | 0 | } |
1671 | 0 | else { |
1672 | 0 | result = Py_NewRef(PyList_GetItem(raised_list, 0)); |
1673 | 0 | } |
1674 | 0 | if (result == NULL) { |
1675 | 0 | goto done; |
1676 | 0 | } |
1677 | 0 | } |
1678 | | |
1679 | 0 | done: |
1680 | 0 | Py_XDECREF(raised_list); |
1681 | 0 | Py_XDECREF(reraised_list); |
1682 | 0 | return result; |
1683 | 0 | } |
1684 | | |
1685 | | PyObject * |
1686 | | PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs) |
1687 | 0 | { |
1688 | 0 | if (orig == NULL || !PyExceptionInstance_Check(orig)) { |
1689 | 0 | PyErr_SetString(PyExc_TypeError, "orig must be an exception instance"); |
1690 | 0 | return NULL; |
1691 | 0 | } |
1692 | 0 | if (excs == NULL || !PyList_Check(excs)) { |
1693 | 0 | PyErr_SetString(PyExc_TypeError, |
1694 | 0 | "excs must be a list of exception instances"); |
1695 | 0 | return NULL; |
1696 | 0 | } |
1697 | 0 | Py_ssize_t numexcs = PyList_GET_SIZE(excs); |
1698 | 0 | for (Py_ssize_t i = 0; i < numexcs; i++) { |
1699 | 0 | PyObject *exc = PyList_GET_ITEM(excs, i); |
1700 | 0 | if (exc == NULL || !(PyExceptionInstance_Check(exc) || Py_IsNone(exc))) { |
1701 | 0 | PyErr_Format(PyExc_TypeError, |
1702 | 0 | "item %zd of excs is not an exception", i); |
1703 | 0 | return NULL; |
1704 | 0 | } |
1705 | 0 | } |
1706 | | |
1707 | | /* Make sure that orig has something as traceback, in the interpreter |
1708 | | * it always does because it's a raised exception. |
1709 | | */ |
1710 | 0 | PyObject *tb = PyException_GetTraceback(orig); |
1711 | |
|
1712 | 0 | if (tb == NULL) { |
1713 | 0 | PyErr_Format(PyExc_ValueError, "orig must be a raised exception"); |
1714 | 0 | return NULL; |
1715 | 0 | } |
1716 | 0 | Py_DECREF(tb); |
1717 | |
|
1718 | 0 | return _PyExc_PrepReraiseStar(orig, excs); |
1719 | 0 | } |
1720 | | |
1721 | | static PyMemberDef BaseExceptionGroup_members[] = { |
1722 | | {"message", _Py_T_OBJECT, offsetof(PyBaseExceptionGroupObject, msg), Py_READONLY, |
1723 | | PyDoc_STR("exception message")}, |
1724 | | {"exceptions", _Py_T_OBJECT, offsetof(PyBaseExceptionGroupObject, excs), Py_READONLY, |
1725 | | PyDoc_STR("nested exceptions")}, |
1726 | | {NULL} /* Sentinel */ |
1727 | | }; |
1728 | | |
1729 | | static PyMethodDef BaseExceptionGroup_methods[] = { |
1730 | | {"__class_getitem__", Py_GenericAlias, |
1731 | | METH_O|METH_CLASS, |
1732 | | PyDoc_STR("Exception groups are generic over the type of their contained exceptions")}, |
1733 | | BASEEXCEPTIONGROUP_DERIVE_METHODDEF |
1734 | | BASEEXCEPTIONGROUP_SPLIT_METHODDEF |
1735 | | BASEEXCEPTIONGROUP_SUBGROUP_METHODDEF |
1736 | | {NULL} |
1737 | | }; |
1738 | | |
1739 | | ComplexExtendsException(PyExc_BaseException, BaseExceptionGroup, |
1740 | | BaseExceptionGroup, BaseExceptionGroup_new /* new */, |
1741 | | BaseExceptionGroup_methods, BaseExceptionGroup_members, |
1742 | | 0 /* getset */, BaseExceptionGroup_str, BaseExceptionGroup_repr, |
1743 | | "A combination of multiple unrelated exceptions."); |
1744 | | |
1745 | | /* |
1746 | | * ExceptionGroup extends BaseExceptionGroup, Exception |
1747 | | */ |
1748 | | static PyObject* |
1749 | 37 | create_exception_group_class(void) { |
1750 | 37 | struct _Py_exc_state *state = get_exc_state(); |
1751 | | |
1752 | 37 | PyObject *bases = _PyTuple_FromPair( |
1753 | 37 | PyExc_BaseExceptionGroup, PyExc_Exception); |
1754 | 37 | if (bases == NULL) { |
1755 | 0 | return NULL; |
1756 | 0 | } |
1757 | | |
1758 | 37 | assert(!state->PyExc_ExceptionGroup); |
1759 | 37 | state->PyExc_ExceptionGroup = PyErr_NewException( |
1760 | 37 | "builtins.ExceptionGroup", bases, NULL); |
1761 | | |
1762 | 37 | Py_DECREF(bases); |
1763 | 37 | return state->PyExc_ExceptionGroup; |
1764 | 37 | } |
1765 | | |
1766 | | /* |
1767 | | * KeyboardInterrupt extends BaseException |
1768 | | */ |
1769 | | SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt, |
1770 | | "Program interrupted by user."); |
1771 | | |
1772 | | |
1773 | | /* |
1774 | | * ImportError extends Exception |
1775 | | */ |
1776 | | |
1777 | | static inline PyImportErrorObject * |
1778 | | PyImportErrorObject_CAST(PyObject *self) |
1779 | 2.48k | { |
1780 | 2.48k | assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_ImportError)); |
1781 | 2.48k | return (PyImportErrorObject *)self; |
1782 | 2.48k | } |
1783 | | |
1784 | | /*[clinic input] |
1785 | | @vectorcall |
1786 | | ImportError.__init__ as ImportError_init |
1787 | | |
1788 | | *args: tuple |
1789 | | name: object = NULL |
1790 | | path: object = NULL |
1791 | | name_from: object = NULL |
1792 | | |
1793 | | [clinic start generated code]*/ |
1794 | | |
1795 | | static int |
1796 | | ImportError_init_impl(PyImportErrorObject *self, PyObject *args, |
1797 | | PyObject *name, PyObject *path, PyObject *name_from) |
1798 | | /*[clinic end generated code: output=4917add0f9473bd2 input=4e94a3b530f9be97]*/ |
1799 | 2.48k | { |
1800 | 2.48k | PyObject *msg = NULL; |
1801 | | |
1802 | 2.48k | if (BaseException_init((PyObject *)self, args, NULL) == -1) { |
1803 | 0 | return -1; |
1804 | 0 | } |
1805 | | |
1806 | 2.48k | Py_XSETREF(self->name, Py_XNewRef(name)); |
1807 | 2.48k | Py_XSETREF(self->path, Py_XNewRef(path)); |
1808 | 2.48k | Py_XSETREF(self->name_from, Py_XNewRef(name_from)); |
1809 | | |
1810 | 2.48k | if (PyTuple_GET_SIZE(args) == 1) { |
1811 | 2.48k | msg = Py_NewRef(PyTuple_GET_ITEM(args, 0)); |
1812 | 2.48k | } |
1813 | 2.48k | Py_XSETREF(self->msg, msg); |
1814 | | |
1815 | 2.48k | return 0; |
1816 | 2.48k | } |
1817 | | |
1818 | | |
1819 | | static int |
1820 | | ImportError_clear(PyObject *op) |
1821 | 2.48k | { |
1822 | 2.48k | PyImportErrorObject *self = PyImportErrorObject_CAST(op); |
1823 | 2.48k | Py_CLEAR(self->msg); |
1824 | 2.48k | Py_CLEAR(self->name); |
1825 | 2.48k | Py_CLEAR(self->path); |
1826 | 2.48k | Py_CLEAR(self->name_from); |
1827 | 2.48k | return BaseException_clear(op); |
1828 | 2.48k | } |
1829 | | |
1830 | | static void |
1831 | | ImportError_dealloc(PyObject *self) |
1832 | 2.48k | { |
1833 | 2.48k | _PyObject_GC_UNTRACK(self); |
1834 | 2.48k | (void)ImportError_clear(self); |
1835 | 2.48k | Py_TYPE(self)->tp_free(self); |
1836 | 2.48k | } |
1837 | | |
1838 | | static int |
1839 | | ImportError_traverse(PyObject *op, visitproc visit, void *arg) |
1840 | 4 | { |
1841 | 4 | PyImportErrorObject *self = PyImportErrorObject_CAST(op); |
1842 | 4 | Py_VISIT(self->msg); |
1843 | 4 | Py_VISIT(self->name); |
1844 | 4 | Py_VISIT(self->path); |
1845 | 4 | Py_VISIT(self->name_from); |
1846 | 4 | return BaseException_traverse(op, visit, arg); |
1847 | 4 | } |
1848 | | |
1849 | | static PyObject * |
1850 | | ImportError_str(PyObject *op) |
1851 | 0 | { |
1852 | 0 | PyImportErrorObject *self = PyImportErrorObject_CAST(op); |
1853 | 0 | if (self->msg && PyUnicode_CheckExact(self->msg)) { |
1854 | 0 | return Py_NewRef(self->msg); |
1855 | 0 | } |
1856 | 0 | return BaseException_str(op); |
1857 | 0 | } |
1858 | | |
1859 | | static PyObject * |
1860 | | ImportError_getstate(PyObject *op) |
1861 | 0 | { |
1862 | 0 | PyImportErrorObject *self = PyImportErrorObject_CAST(op); |
1863 | 0 | PyObject *dict = self->dict; |
1864 | 0 | if (self->name || self->path || self->name_from) { |
1865 | 0 | dict = dict ? PyDict_Copy(dict) : PyDict_New(); |
1866 | 0 | if (dict == NULL) |
1867 | 0 | return NULL; |
1868 | 0 | if (self->name && PyDict_SetItem(dict, &_Py_ID(name), self->name) < 0) { |
1869 | 0 | Py_DECREF(dict); |
1870 | 0 | return NULL; |
1871 | 0 | } |
1872 | 0 | if (self->path && PyDict_SetItem(dict, &_Py_ID(path), self->path) < 0) { |
1873 | 0 | Py_DECREF(dict); |
1874 | 0 | return NULL; |
1875 | 0 | } |
1876 | 0 | if (self->name_from && PyDict_SetItem(dict, &_Py_ID(name_from), self->name_from) < 0) { |
1877 | 0 | Py_DECREF(dict); |
1878 | 0 | return NULL; |
1879 | 0 | } |
1880 | 0 | return dict; |
1881 | 0 | } |
1882 | 0 | else if (dict) { |
1883 | 0 | return Py_NewRef(dict); |
1884 | 0 | } |
1885 | 0 | else { |
1886 | 0 | Py_RETURN_NONE; |
1887 | 0 | } |
1888 | 0 | } |
1889 | | |
1890 | | /* Pickling support */ |
1891 | | static PyObject * |
1892 | | ImportError_reduce(PyObject *self, PyObject *Py_UNUSED(ignored)) |
1893 | 0 | { |
1894 | 0 | PyObject *res; |
1895 | 0 | PyObject *state = ImportError_getstate(self); |
1896 | 0 | if (state == NULL) |
1897 | 0 | return NULL; |
1898 | 0 | PyBaseExceptionObject *exc = PyBaseExceptionObject_CAST(self); |
1899 | 0 | if (state == Py_None) |
1900 | 0 | res = _PyTuple_FromPair((PyObject *)Py_TYPE(self), exc->args); |
1901 | 0 | else |
1902 | 0 | res = PyTuple_Pack(3, Py_TYPE(self), exc->args, state); |
1903 | 0 | Py_DECREF(state); |
1904 | 0 | return res; |
1905 | 0 | } |
1906 | | |
1907 | | static PyObject * |
1908 | | ImportError_repr(PyObject *self) |
1909 | 0 | { |
1910 | 0 | int hasargs = PyTuple_GET_SIZE(((PyBaseExceptionObject *)self)->args) != 0; |
1911 | 0 | PyImportErrorObject *exc = PyImportErrorObject_CAST(self); |
1912 | 0 | if (exc->name == NULL && exc->path == NULL) { |
1913 | 0 | return BaseException_repr(self); |
1914 | 0 | } |
1915 | 0 | PyUnicodeWriter *writer = PyUnicodeWriter_Create(0); |
1916 | 0 | if (writer == NULL) { |
1917 | 0 | goto error; |
1918 | 0 | } |
1919 | 0 | PyObject *r = BaseException_repr(self); |
1920 | 0 | if (r == NULL) { |
1921 | 0 | goto error; |
1922 | 0 | } |
1923 | 0 | if (PyUnicodeWriter_WriteSubstring( |
1924 | 0 | writer, r, 0, PyUnicode_GET_LENGTH(r) - 1) < 0) |
1925 | 0 | { |
1926 | 0 | Py_DECREF(r); |
1927 | 0 | goto error; |
1928 | 0 | } |
1929 | 0 | Py_DECREF(r); |
1930 | 0 | if (exc->name) { |
1931 | 0 | if (hasargs) { |
1932 | 0 | if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) { |
1933 | 0 | goto error; |
1934 | 0 | } |
1935 | 0 | } |
1936 | 0 | if (PyUnicodeWriter_Format(writer, "name=%R", exc->name) < 0) { |
1937 | 0 | goto error; |
1938 | 0 | } |
1939 | 0 | hasargs = 1; |
1940 | 0 | } |
1941 | 0 | if (exc->path) { |
1942 | 0 | if (hasargs) { |
1943 | 0 | if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) { |
1944 | 0 | goto error; |
1945 | 0 | } |
1946 | 0 | } |
1947 | 0 | if (PyUnicodeWriter_Format(writer, "path=%R", exc->path) < 0) { |
1948 | 0 | goto error; |
1949 | 0 | } |
1950 | 0 | } |
1951 | | |
1952 | 0 | if (PyUnicodeWriter_WriteChar(writer, ')') < 0) { |
1953 | 0 | goto error; |
1954 | 0 | } |
1955 | | |
1956 | 0 | return PyUnicodeWriter_Finish(writer); |
1957 | | |
1958 | 0 | error: |
1959 | 0 | PyUnicodeWriter_Discard(writer); |
1960 | 0 | return NULL; |
1961 | 0 | } |
1962 | | |
1963 | | static PyMemberDef ImportError_members[] = { |
1964 | | {"msg", _Py_T_OBJECT, offsetof(PyImportErrorObject, msg), 0, |
1965 | | PyDoc_STR("exception message")}, |
1966 | | {"name", _Py_T_OBJECT, offsetof(PyImportErrorObject, name), 0, |
1967 | | PyDoc_STR("module name")}, |
1968 | | {"path", _Py_T_OBJECT, offsetof(PyImportErrorObject, path), 0, |
1969 | | PyDoc_STR("module path")}, |
1970 | | {"name_from", _Py_T_OBJECT, offsetof(PyImportErrorObject, name_from), 0, |
1971 | | PyDoc_STR("name imported from module")}, |
1972 | | {NULL} /* Sentinel */ |
1973 | | }; |
1974 | | |
1975 | | static PyMethodDef ImportError_methods[] = { |
1976 | | {"__reduce__", ImportError_reduce, METH_NOARGS}, |
1977 | | {NULL} |
1978 | | }; |
1979 | | |
1980 | | static PyTypeObject _PyExc_ImportError = { |
1981 | | PyVarObject_HEAD_INIT(NULL, 0) |
1982 | | .tp_name = "ImportError", |
1983 | | .tp_basicsize = sizeof(PyImportErrorObject), |
1984 | | .tp_dealloc = ImportError_dealloc, |
1985 | | .tp_repr = ImportError_repr, |
1986 | | .tp_str = ImportError_str, |
1987 | | .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, |
1988 | | .tp_doc = PyDoc_STR( |
1989 | | "Import can't find module, " |
1990 | | "or can't find name in module."), |
1991 | | .tp_traverse = ImportError_traverse, |
1992 | | .tp_clear = ImportError_clear, |
1993 | | .tp_methods = ImportError_methods, |
1994 | | .tp_members = ImportError_members, |
1995 | | .tp_base = &_PyExc_Exception, |
1996 | | .tp_dictoffset = offsetof(PyImportErrorObject, dict), |
1997 | | .tp_init = ImportError_init, |
1998 | | }; |
1999 | | PyObject *PyExc_ImportError = (PyObject *)&_PyExc_ImportError; |
2000 | | |
2001 | | /* |
2002 | | * ImportCycleError extends ImportError |
2003 | | */ |
2004 | | |
2005 | | MiddlingExtendsException(PyExc_ImportError, ImportCycleError, ImportError, |
2006 | | "Import produces a cycle."); |
2007 | | /* |
2008 | | * ModuleNotFoundError extends ImportError |
2009 | | */ |
2010 | | |
2011 | | MiddlingExtendsException(PyExc_ImportError, ModuleNotFoundError, ImportError, |
2012 | | "Module not found."); |
2013 | | |
2014 | | /* |
2015 | | * OSError extends Exception |
2016 | | */ |
2017 | | |
2018 | | static inline PyOSErrorObject * |
2019 | | PyOSErrorObject_CAST(PyObject *self) |
2020 | 470k | { |
2021 | 470k | assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_OSError)); |
2022 | 470k | return (PyOSErrorObject *)self; |
2023 | 470k | } |
2024 | | |
2025 | | #ifdef MS_WINDOWS |
2026 | | #include "errmap.h" |
2027 | | #endif |
2028 | | |
2029 | | /* Where a function has a single filename, such as open() or some |
2030 | | * of the os module functions, PyErr_SetFromErrnoWithFilename() is |
2031 | | * called, giving a third argument which is the filename. But, so |
2032 | | * that old code using in-place unpacking doesn't break, e.g.: |
2033 | | * |
2034 | | * except OSError, (errno, strerror): |
2035 | | * |
2036 | | * we hack args so that it only contains two items. This also |
2037 | | * means we need our own __str__() which prints out the filename |
2038 | | * when it was supplied. |
2039 | | * |
2040 | | * (If a function has two filenames, such as rename(), symlink(), |
2041 | | * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called, |
2042 | | * which allows passing in a second filename.) |
2043 | | */ |
2044 | | |
2045 | | /* This function doesn't cleanup on error, the caller should */ |
2046 | | static int |
2047 | | oserror_parse_args(PyObject **p_args, |
2048 | | PyObject **myerrno, PyObject **strerror, |
2049 | | PyObject **filename, PyObject **filename2 |
2050 | | #ifdef MS_WINDOWS |
2051 | | , PyObject **winerror |
2052 | | #endif |
2053 | | ) |
2054 | 235k | { |
2055 | 235k | Py_ssize_t nargs; |
2056 | 235k | PyObject *args = *p_args; |
2057 | 235k | #ifndef MS_WINDOWS |
2058 | | /* |
2059 | | * ignored on non-Windows platforms, |
2060 | | * but parsed so OSError has a consistent signature |
2061 | | */ |
2062 | 235k | PyObject *_winerror = NULL; |
2063 | 235k | PyObject **winerror = &_winerror; |
2064 | 235k | #endif /* MS_WINDOWS */ |
2065 | | |
2066 | 235k | nargs = PyTuple_GET_SIZE(args); |
2067 | | |
2068 | 235k | if (nargs >= 2 && nargs <= 5) { |
2069 | 232k | if (!PyArg_UnpackTuple(args, "OSError", 2, 5, |
2070 | 232k | myerrno, strerror, |
2071 | 232k | filename, winerror, filename2)) |
2072 | 0 | return -1; |
2073 | | #ifdef MS_WINDOWS |
2074 | | if (*winerror && PyLong_Check(*winerror)) { |
2075 | | long errcode, winerrcode; |
2076 | | PyObject *newargs; |
2077 | | Py_ssize_t i; |
2078 | | |
2079 | | winerrcode = PyLong_AsLong(*winerror); |
2080 | | if (winerrcode == -1 && PyErr_Occurred()) |
2081 | | return -1; |
2082 | | errcode = winerror_to_errno(winerrcode); |
2083 | | *myerrno = PyLong_FromLong(errcode); |
2084 | | if (!*myerrno) |
2085 | | return -1; |
2086 | | newargs = PyTuple_New(nargs); |
2087 | | if (!newargs) |
2088 | | return -1; |
2089 | | PyTuple_SET_ITEM(newargs, 0, *myerrno); |
2090 | | for (i = 1; i < nargs; i++) { |
2091 | | PyObject *val = PyTuple_GET_ITEM(args, i); |
2092 | | PyTuple_SET_ITEM(newargs, i, Py_NewRef(val)); |
2093 | | } |
2094 | | Py_DECREF(args); |
2095 | | args = *p_args = newargs; |
2096 | | } |
2097 | | #endif /* MS_WINDOWS */ |
2098 | 232k | } |
2099 | | |
2100 | 235k | return 0; |
2101 | 235k | } |
2102 | | |
2103 | | static int |
2104 | | oserror_init(PyOSErrorObject *self, PyObject **p_args, |
2105 | | PyObject *myerrno, PyObject *strerror, |
2106 | | PyObject *filename, PyObject *filename2 |
2107 | | #ifdef MS_WINDOWS |
2108 | | , PyObject *winerror |
2109 | | #endif |
2110 | | ) |
2111 | 235k | { |
2112 | 235k | PyObject *args = *p_args; |
2113 | 235k | Py_ssize_t nargs = PyTuple_GET_SIZE(args); |
2114 | | |
2115 | | /* self->filename will remain Py_None otherwise */ |
2116 | 235k | if (filename && filename != Py_None) { |
2117 | 232k | if (Py_IS_TYPE(self, (PyTypeObject *) PyExc_BlockingIOError) && |
2118 | 0 | PyNumber_Check(filename)) { |
2119 | | /* BlockingIOError's 3rd argument can be the number of |
2120 | | * characters written. |
2121 | | */ |
2122 | 0 | self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError); |
2123 | 0 | if (self->written == -1 && PyErr_Occurred()) |
2124 | 0 | return -1; |
2125 | 0 | } |
2126 | 232k | else { |
2127 | 232k | Py_XSETREF(self->filename, Py_NewRef(filename)); |
2128 | | |
2129 | 232k | if (filename2 && filename2 != Py_None) { |
2130 | 0 | Py_XSETREF(self->filename2, Py_NewRef(filename2)); |
2131 | 0 | } |
2132 | | |
2133 | 232k | if (nargs >= 2 && nargs <= 5) { |
2134 | | /* filename, filename2, and winerror are removed from the args tuple |
2135 | | (for compatibility purposes, see test_exceptions.py) */ |
2136 | 232k | PyObject *subslice = PyTuple_GetSlice(args, 0, 2); |
2137 | 232k | if (!subslice) |
2138 | 0 | return -1; |
2139 | | |
2140 | 232k | Py_DECREF(args); /* replacing args */ |
2141 | 232k | *p_args = args = subslice; |
2142 | 232k | } |
2143 | 232k | } |
2144 | 232k | } |
2145 | 235k | Py_XSETREF(self->myerrno, Py_XNewRef(myerrno)); |
2146 | 235k | Py_XSETREF(self->strerror, Py_XNewRef(strerror)); |
2147 | | #ifdef MS_WINDOWS |
2148 | | Py_XSETREF(self->winerror, Py_XNewRef(winerror)); |
2149 | | #endif |
2150 | | |
2151 | | /* Steals the reference to args */ |
2152 | 235k | Py_XSETREF(self->args, args); |
2153 | 235k | *p_args = args = NULL; |
2154 | | |
2155 | 235k | return 0; |
2156 | 235k | } |
2157 | | |
2158 | | static PyObject * |
2159 | | OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds); |
2160 | | static int |
2161 | | OSError_init(PyObject *self, PyObject *args, PyObject *kwds); |
2162 | | |
2163 | | static int |
2164 | | oserror_use_init(PyTypeObject *type) |
2165 | 705k | { |
2166 | | /* When __init__ is defined in an OSError subclass, we want any |
2167 | | extraneous argument to __new__ to be ignored. The only reasonable |
2168 | | solution, given __new__ takes a variable number of arguments, |
2169 | | is to defer arg parsing and initialization to __init__. |
2170 | | |
2171 | | But when __new__ is overridden as well, it should call our __new__ |
2172 | | with the right arguments. |
2173 | | |
2174 | | (see http://bugs.python.org/issue12555#msg148829 ) |
2175 | | */ |
2176 | 705k | if (type->tp_init != OSError_init && type->tp_new == OSError_new) { |
2177 | 123 | assert((PyObject *) type != PyExc_OSError); |
2178 | 123 | return 1; |
2179 | 123 | } |
2180 | 704k | return 0; |
2181 | 705k | } |
2182 | | |
2183 | | static PyObject * |
2184 | | OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
2185 | 235k | { |
2186 | 235k | PyOSErrorObject *self = NULL; |
2187 | 235k | PyObject *myerrno = NULL, *strerror = NULL; |
2188 | 235k | PyObject *filename = NULL, *filename2 = NULL; |
2189 | | #ifdef MS_WINDOWS |
2190 | | PyObject *winerror = NULL; |
2191 | | #endif |
2192 | | |
2193 | 235k | Py_INCREF(args); |
2194 | | |
2195 | 235k | if (!oserror_use_init(type)) { |
2196 | 234k | if (!_PyArg_NoKeywords(type->tp_name, kwds)) |
2197 | 0 | goto error; |
2198 | | |
2199 | 234k | if (oserror_parse_args(&args, &myerrno, &strerror, |
2200 | 234k | &filename, &filename2 |
2201 | | #ifdef MS_WINDOWS |
2202 | | , &winerror |
2203 | | #endif |
2204 | 234k | )) |
2205 | 0 | goto error; |
2206 | | |
2207 | 234k | struct _Py_exc_state *state = get_exc_state(); |
2208 | 234k | if (myerrno && PyLong_Check(myerrno) && |
2209 | 232k | state->errnomap && (PyObject *) type == PyExc_OSError) { |
2210 | 232k | PyObject *newtype; |
2211 | 232k | newtype = PyDict_GetItemWithError(state->errnomap, myerrno); |
2212 | 232k | if (newtype) { |
2213 | 201k | type = _PyType_CAST(newtype); |
2214 | 201k | } |
2215 | 30.9k | else if (PyErr_Occurred()) |
2216 | 0 | goto error; |
2217 | 232k | } |
2218 | 234k | } |
2219 | | |
2220 | 235k | self = (PyOSErrorObject *) type->tp_alloc(type, 0); |
2221 | 235k | if (!self) |
2222 | 0 | goto error; |
2223 | | |
2224 | 235k | self->dict = NULL; |
2225 | 235k | self->traceback = self->cause = self->context = NULL; |
2226 | 235k | self->written = -1; |
2227 | | |
2228 | 235k | if (!oserror_use_init(type)) { |
2229 | 234k | if (oserror_init(self, &args, myerrno, strerror, filename, filename2 |
2230 | | #ifdef MS_WINDOWS |
2231 | | , winerror |
2232 | | #endif |
2233 | 234k | )) |
2234 | 0 | goto error; |
2235 | 234k | } |
2236 | 41 | else { |
2237 | 41 | self->args = PyTuple_New(0); |
2238 | 41 | if (self->args == NULL) |
2239 | 0 | goto error; |
2240 | 41 | } |
2241 | | |
2242 | 235k | Py_XDECREF(args); |
2243 | 235k | return (PyObject *) self; |
2244 | | |
2245 | 0 | error: |
2246 | 0 | Py_XDECREF(args); |
2247 | 0 | Py_XDECREF(self); |
2248 | 0 | return NULL; |
2249 | 235k | } |
2250 | | |
2251 | | static int |
2252 | | OSError_init(PyObject *op, PyObject *args, PyObject *kwds) |
2253 | 235k | { |
2254 | 235k | PyOSErrorObject *self = PyOSErrorObject_CAST(op); |
2255 | 235k | PyObject *myerrno = NULL, *strerror = NULL; |
2256 | 235k | PyObject *filename = NULL, *filename2 = NULL; |
2257 | | #ifdef MS_WINDOWS |
2258 | | PyObject *winerror = NULL; |
2259 | | #endif |
2260 | | |
2261 | 235k | if (!oserror_use_init(Py_TYPE(self))) |
2262 | | /* Everything already done in OSError_new */ |
2263 | 234k | return 0; |
2264 | | |
2265 | 41 | if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) |
2266 | 0 | return -1; |
2267 | | |
2268 | 41 | Py_INCREF(args); |
2269 | 41 | if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2 |
2270 | | #ifdef MS_WINDOWS |
2271 | | , &winerror |
2272 | | #endif |
2273 | 41 | )) |
2274 | 0 | goto error; |
2275 | | |
2276 | 41 | if (oserror_init(self, &args, myerrno, strerror, filename, filename2 |
2277 | | #ifdef MS_WINDOWS |
2278 | | , winerror |
2279 | | #endif |
2280 | 41 | )) |
2281 | 0 | goto error; |
2282 | | |
2283 | 41 | return 0; |
2284 | | |
2285 | 0 | error: |
2286 | 0 | Py_DECREF(args); |
2287 | 0 | return -1; |
2288 | 41 | } |
2289 | | |
2290 | | static int |
2291 | | OSError_clear(PyObject *op) |
2292 | 235k | { |
2293 | 235k | PyOSErrorObject *self = PyOSErrorObject_CAST(op); |
2294 | 235k | Py_CLEAR(self->myerrno); |
2295 | 235k | Py_CLEAR(self->strerror); |
2296 | 235k | Py_CLEAR(self->filename); |
2297 | 235k | Py_CLEAR(self->filename2); |
2298 | | #ifdef MS_WINDOWS |
2299 | | Py_CLEAR(self->winerror); |
2300 | | #endif |
2301 | 235k | return BaseException_clear(op); |
2302 | 235k | } |
2303 | | |
2304 | | static void |
2305 | | OSError_dealloc(PyObject *self) |
2306 | 235k | { |
2307 | 235k | _PyObject_GC_UNTRACK(self); |
2308 | 235k | (void)OSError_clear(self); |
2309 | 235k | Py_TYPE(self)->tp_free(self); |
2310 | 235k | } |
2311 | | |
2312 | | static int |
2313 | | OSError_traverse(PyObject *op, visitproc visit, void *arg) |
2314 | 10 | { |
2315 | 10 | PyOSErrorObject *self = PyOSErrorObject_CAST(op); |
2316 | 10 | Py_VISIT(self->myerrno); |
2317 | 10 | Py_VISIT(self->strerror); |
2318 | 10 | Py_VISIT(self->filename); |
2319 | 10 | Py_VISIT(self->filename2); |
2320 | | #ifdef MS_WINDOWS |
2321 | | Py_VISIT(self->winerror); |
2322 | | #endif |
2323 | 10 | return BaseException_traverse(op, visit, arg); |
2324 | 10 | } |
2325 | | |
2326 | | static PyObject * |
2327 | | OSError_str(PyObject *op) |
2328 | 832 | { |
2329 | 832 | PyOSErrorObject *self = PyOSErrorObject_CAST(op); |
2330 | 832 | PyObject *res; |
2331 | | /* Hold strong references: formatting may run arbitrary code |
2332 | | which modifies the attributes. */ |
2333 | 832 | PyObject *myerrno = Py_XNewRef(self->myerrno); |
2334 | 832 | PyObject *strerror = Py_XNewRef(self->strerror); |
2335 | 832 | PyObject *filename = Py_XNewRef(self->filename); |
2336 | 832 | PyObject *filename2 = Py_XNewRef(self->filename2); |
2337 | | #ifdef MS_WINDOWS |
2338 | | PyObject *winerror = Py_XNewRef(self->winerror); |
2339 | | #endif |
2340 | 1.64k | #define OR_NONE(x) ((x)?(x):Py_None) |
2341 | | #ifdef MS_WINDOWS |
2342 | | /* If available, winerror has the priority over myerrno */ |
2343 | | if (winerror && filename) { |
2344 | | if (filename2) { |
2345 | | res = PyUnicode_FromFormat("[WinError %S] %S: %R -> %R", |
2346 | | OR_NONE(winerror), |
2347 | | OR_NONE(strerror), |
2348 | | filename, |
2349 | | filename2); |
2350 | | } else { |
2351 | | res = PyUnicode_FromFormat("[WinError %S] %S: %R", |
2352 | | OR_NONE(winerror), |
2353 | | OR_NONE(strerror), |
2354 | | filename); |
2355 | | } |
2356 | | goto done; |
2357 | | } |
2358 | | if (winerror && strerror) { |
2359 | | res = PyUnicode_FromFormat("[WinError %S] %S", |
2360 | | winerror, strerror); |
2361 | | goto done; |
2362 | | } |
2363 | | #endif |
2364 | 832 | if (filename) { |
2365 | 824 | if (filename2) { |
2366 | 0 | res = PyUnicode_FromFormat("[Errno %S] %S: %R -> %R", |
2367 | 0 | OR_NONE(myerrno), |
2368 | 0 | OR_NONE(strerror), |
2369 | 0 | filename, |
2370 | 0 | filename2); |
2371 | 824 | } else { |
2372 | 824 | res = PyUnicode_FromFormat("[Errno %S] %S: %R", |
2373 | 824 | OR_NONE(myerrno), |
2374 | 824 | OR_NONE(strerror), |
2375 | 824 | filename); |
2376 | 824 | } |
2377 | 824 | goto done; |
2378 | 824 | } |
2379 | 8 | if (myerrno && strerror) { |
2380 | 0 | res = PyUnicode_FromFormat("[Errno %S] %S", |
2381 | 0 | myerrno, strerror); |
2382 | 0 | goto done; |
2383 | 0 | } |
2384 | 8 | res = BaseException_str(op); |
2385 | 832 | done: |
2386 | 832 | Py_XDECREF(myerrno); |
2387 | 832 | Py_XDECREF(strerror); |
2388 | 832 | Py_XDECREF(filename); |
2389 | 832 | Py_XDECREF(filename2); |
2390 | | #ifdef MS_WINDOWS |
2391 | | Py_XDECREF(winerror); |
2392 | | #endif |
2393 | 832 | return res; |
2394 | 8 | } |
2395 | | |
2396 | | static PyObject * |
2397 | | OSError_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) |
2398 | 0 | { |
2399 | 0 | PyOSErrorObject *self = PyOSErrorObject_CAST(op); |
2400 | 0 | PyObject *args = self->args; |
2401 | 0 | PyObject *res = NULL; |
2402 | | |
2403 | | /* self->args is only the first two real arguments if there was a |
2404 | | * file name given to OSError. */ |
2405 | 0 | if (PyTuple_GET_SIZE(args) == 2 && self->filename) { |
2406 | 0 | Py_ssize_t size = self->filename2 ? 5 : 3; |
2407 | 0 | args = PyTuple_New(size); |
2408 | 0 | if (!args) |
2409 | 0 | return NULL; |
2410 | | |
2411 | 0 | PyTuple_SET_ITEM(args, 0, Py_NewRef(PyTuple_GET_ITEM(self->args, 0))); |
2412 | 0 | PyTuple_SET_ITEM(args, 1, Py_NewRef(PyTuple_GET_ITEM(self->args, 1))); |
2413 | 0 | PyTuple_SET_ITEM(args, 2, Py_NewRef(self->filename)); |
2414 | |
|
2415 | 0 | if (self->filename2) { |
2416 | | /* |
2417 | | * This tuple is essentially used as OSError(*args). |
2418 | | * So, to recreate filename2, we need to pass in |
2419 | | * winerror as well. |
2420 | | */ |
2421 | 0 | PyTuple_SET_ITEM(args, 3, Py_NewRef(Py_None)); |
2422 | | |
2423 | | /* filename2 */ |
2424 | 0 | PyTuple_SET_ITEM(args, 4, Py_NewRef(self->filename2)); |
2425 | 0 | } |
2426 | 0 | } else |
2427 | 0 | Py_INCREF(args); |
2428 | | |
2429 | 0 | if (self->dict) |
2430 | 0 | res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict); |
2431 | 0 | else |
2432 | 0 | res = _PyTuple_FromPair((PyObject *)Py_TYPE(self), args); |
2433 | 0 | Py_DECREF(args); |
2434 | 0 | return res; |
2435 | 0 | } |
2436 | | |
2437 | | static PyObject * |
2438 | | OSError_written_get(PyObject *op, void *context) |
2439 | 0 | { |
2440 | 0 | PyOSErrorObject *self = PyOSErrorObject_CAST(op); |
2441 | 0 | if (self->written == -1) { |
2442 | 0 | PyErr_SetString(PyExc_AttributeError, "characters_written"); |
2443 | 0 | return NULL; |
2444 | 0 | } |
2445 | 0 | return PyLong_FromSsize_t(self->written); |
2446 | 0 | } |
2447 | | |
2448 | | static int |
2449 | | OSError_written_set(PyObject *op, PyObject *arg, void *context) |
2450 | 0 | { |
2451 | 0 | PyOSErrorObject *self = PyOSErrorObject_CAST(op); |
2452 | 0 | if (arg == NULL) { |
2453 | 0 | if (self->written == -1) { |
2454 | 0 | PyErr_SetString(PyExc_AttributeError, "characters_written"); |
2455 | 0 | return -1; |
2456 | 0 | } |
2457 | 0 | self->written = -1; |
2458 | 0 | return 0; |
2459 | 0 | } |
2460 | 0 | Py_ssize_t n; |
2461 | 0 | n = PyNumber_AsSsize_t(arg, PyExc_ValueError); |
2462 | 0 | if (n == -1 && PyErr_Occurred()) |
2463 | 0 | return -1; |
2464 | 0 | self->written = n; |
2465 | 0 | return 0; |
2466 | 0 | } |
2467 | | |
2468 | | static PyMemberDef OSError_members[] = { |
2469 | | {"errno", _Py_T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0, |
2470 | | PyDoc_STR("POSIX exception code")}, |
2471 | | {"strerror", _Py_T_OBJECT, offsetof(PyOSErrorObject, strerror), 0, |
2472 | | PyDoc_STR("exception strerror")}, |
2473 | | {"filename", _Py_T_OBJECT, offsetof(PyOSErrorObject, filename), 0, |
2474 | | PyDoc_STR("exception filename")}, |
2475 | | {"filename2", _Py_T_OBJECT, offsetof(PyOSErrorObject, filename2), 0, |
2476 | | PyDoc_STR("second exception filename")}, |
2477 | | #ifdef MS_WINDOWS |
2478 | | {"winerror", _Py_T_OBJECT, offsetof(PyOSErrorObject, winerror), 0, |
2479 | | PyDoc_STR("Win32 exception code")}, |
2480 | | #endif |
2481 | | {NULL} /* Sentinel */ |
2482 | | }; |
2483 | | |
2484 | | static PyMethodDef OSError_methods[] = { |
2485 | | {"__reduce__", OSError_reduce, METH_NOARGS}, |
2486 | | {NULL} |
2487 | | }; |
2488 | | |
2489 | | static PyGetSetDef OSError_getset[] = { |
2490 | | {"characters_written", OSError_written_get, |
2491 | | OSError_written_set, NULL}, |
2492 | | {NULL} |
2493 | | }; |
2494 | | |
2495 | | |
2496 | | ComplexExtendsException(PyExc_Exception, OSError, |
2497 | | OSError, OSError_new, |
2498 | | OSError_methods, OSError_members, OSError_getset, |
2499 | | OSError_str, 0, |
2500 | | "Base class for I/O related errors."); |
2501 | | |
2502 | | |
2503 | | /* |
2504 | | * Various OSError subclasses |
2505 | | */ |
2506 | | MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError, |
2507 | | "I/O operation would block."); |
2508 | | MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError, |
2509 | | "Connection error."); |
2510 | | MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError, |
2511 | | "Child process error."); |
2512 | | MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError, |
2513 | | "Broken pipe."); |
2514 | | MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError, |
2515 | | "Connection aborted."); |
2516 | | MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError, |
2517 | | "Connection refused."); |
2518 | | MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError, |
2519 | | "Connection reset."); |
2520 | | MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError, |
2521 | | "File already exists."); |
2522 | | MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError, |
2523 | | "File not found."); |
2524 | | MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError, |
2525 | | "Operation doesn't work on directories."); |
2526 | | MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError, |
2527 | | "Operation only works on directories."); |
2528 | | MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError, |
2529 | | "Interrupted by signal."); |
2530 | | MiddlingExtendsException(PyExc_OSError, PermissionError, OSError, |
2531 | | "Not enough permissions."); |
2532 | | MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError, |
2533 | | "Process not found."); |
2534 | | MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError, |
2535 | | "Timeout expired."); |
2536 | | |
2537 | | /* Compatibility aliases */ |
2538 | | PyObject *PyExc_EnvironmentError = (PyObject *)&_PyExc_OSError; // borrowed ref |
2539 | | PyObject *PyExc_IOError = (PyObject *)&_PyExc_OSError; // borrowed ref |
2540 | | #ifdef MS_WINDOWS |
2541 | | PyObject *PyExc_WindowsError = (PyObject *)&_PyExc_OSError; // borrowed ref |
2542 | | #endif |
2543 | | |
2544 | | /* |
2545 | | * EOFError extends Exception |
2546 | | */ |
2547 | | SimpleExtendsException(PyExc_Exception, EOFError, |
2548 | | "Read beyond end of file."); |
2549 | | |
2550 | | |
2551 | | /* |
2552 | | * RuntimeError extends Exception |
2553 | | */ |
2554 | | SimpleExtendsException(PyExc_Exception, RuntimeError, |
2555 | | "Unspecified run-time error."); |
2556 | | |
2557 | | /* |
2558 | | * RecursionError extends RuntimeError |
2559 | | */ |
2560 | | SimpleExtendsException(PyExc_RuntimeError, RecursionError, |
2561 | | "Recursion limit exceeded."); |
2562 | | |
2563 | | // PythonFinalizationError extends RuntimeError |
2564 | | SimpleExtendsException(PyExc_RuntimeError, PythonFinalizationError, |
2565 | | "Operation blocked during Python finalization."); |
2566 | | |
2567 | | /* |
2568 | | * NotImplementedError extends RuntimeError |
2569 | | */ |
2570 | | SimpleExtendsException(PyExc_RuntimeError, NotImplementedError, |
2571 | | "Method or function hasn't been implemented yet."); |
2572 | | |
2573 | | /* |
2574 | | * NameError extends Exception |
2575 | | */ |
2576 | | |
2577 | | static inline PyNameErrorObject * |
2578 | | PyNameErrorObject_CAST(PyObject *self) |
2579 | 7 | { |
2580 | 7 | assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_NameError)); |
2581 | 7 | return (PyNameErrorObject *)self; |
2582 | 7 | } |
2583 | | |
2584 | | /*[clinic input] |
2585 | | @vectorcall |
2586 | | NameError.__init__ as NameError_init |
2587 | | |
2588 | | *args: tuple |
2589 | | name: object = NULL |
2590 | | |
2591 | | [clinic start generated code]*/ |
2592 | | |
2593 | | static int |
2594 | | NameError_init_impl(PyNameErrorObject *self, PyObject *args, PyObject *name) |
2595 | | /*[clinic end generated code: output=f15305075d9aa272 input=2e2b7e781ae146b1]*/ |
2596 | 5 | { |
2597 | 5 | if (BaseException_init((PyObject *)self, args, NULL) == -1) { |
2598 | 0 | return -1; |
2599 | 0 | } |
2600 | | |
2601 | 5 | Py_XSETREF(self->name, Py_XNewRef(name)); |
2602 | | |
2603 | 5 | return 0; |
2604 | 5 | } |
2605 | | |
2606 | | |
2607 | | static int |
2608 | | NameError_clear(PyObject *op) |
2609 | 5 | { |
2610 | 5 | PyNameErrorObject *self = PyNameErrorObject_CAST(op); |
2611 | 5 | Py_CLEAR(self->name); |
2612 | 5 | return BaseException_clear(op); |
2613 | 5 | } |
2614 | | |
2615 | | static void |
2616 | | NameError_dealloc(PyObject *self) |
2617 | 5 | { |
2618 | 5 | _PyObject_GC_UNTRACK(self); |
2619 | 5 | (void)NameError_clear(self); |
2620 | 5 | Py_TYPE(self)->tp_free(self); |
2621 | 5 | } |
2622 | | |
2623 | | static int |
2624 | | NameError_traverse(PyObject *op, visitproc visit, void *arg) |
2625 | 2 | { |
2626 | 2 | PyNameErrorObject *self = PyNameErrorObject_CAST(op); |
2627 | 2 | Py_VISIT(self->name); |
2628 | 2 | return BaseException_traverse(op, visit, arg); |
2629 | 2 | } |
2630 | | |
2631 | | static PyMemberDef NameError_members[] = { |
2632 | | {"name", _Py_T_OBJECT, offsetof(PyNameErrorObject, name), 0, PyDoc_STR("name")}, |
2633 | | {NULL} /* Sentinel */ |
2634 | | }; |
2635 | | |
2636 | | static PyMethodDef NameError_methods[] = { |
2637 | | {NULL} /* Sentinel */ |
2638 | | }; |
2639 | | |
2640 | | ComplexExtendsException(PyExc_Exception, NameError, |
2641 | | NameError, 0, |
2642 | | NameError_methods, NameError_members, |
2643 | | 0, BaseException_str, 0, "Name not found globally."); |
2644 | | |
2645 | | /* |
2646 | | * UnboundLocalError extends NameError |
2647 | | */ |
2648 | | |
2649 | | MiddlingExtendsException(PyExc_NameError, UnboundLocalError, NameError, |
2650 | | "Local name referenced but not bound to a value."); |
2651 | | |
2652 | | /* |
2653 | | * AttributeError extends Exception |
2654 | | */ |
2655 | | |
2656 | | static inline PyAttributeErrorObject * |
2657 | | PyAttributeErrorObject_CAST(PyObject *self) |
2658 | 1.35M | { |
2659 | 1.35M | assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_AttributeError)); |
2660 | 1.35M | return (PyAttributeErrorObject *)self; |
2661 | 1.35M | } |
2662 | | |
2663 | | /*[clinic input] |
2664 | | @vectorcall |
2665 | | AttributeError.__init__ as AttributeError_init |
2666 | | |
2667 | | *args: tuple |
2668 | | name: object = NULL |
2669 | | obj: object = NULL |
2670 | | |
2671 | | [clinic start generated code]*/ |
2672 | | |
2673 | | static int |
2674 | | AttributeError_init_impl(PyAttributeErrorObject *self, PyObject *args, |
2675 | | PyObject *name, PyObject *obj) |
2676 | | /*[clinic end generated code: output=3d346f9a389f60fa input=bed43aafea47f1a0]*/ |
2677 | 1.35M | { |
2678 | 1.35M | if (BaseException_init((PyObject *)self, args, NULL) == -1) { |
2679 | 0 | return -1; |
2680 | 0 | } |
2681 | | |
2682 | 1.35M | Py_XSETREF(self->name, Py_XNewRef(name)); |
2683 | 1.35M | Py_XSETREF(self->obj, Py_XNewRef(obj)); |
2684 | | |
2685 | 1.35M | return 0; |
2686 | 1.35M | } |
2687 | | |
2688 | | |
2689 | | static int |
2690 | | AttributeError_clear(PyObject *op) |
2691 | 1.35M | { |
2692 | 1.35M | PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); |
2693 | 1.35M | Py_CLEAR(self->obj); |
2694 | 1.35M | Py_CLEAR(self->name); |
2695 | 1.35M | return BaseException_clear(op); |
2696 | 1.35M | } |
2697 | | |
2698 | | static void |
2699 | | AttributeError_dealloc(PyObject *self) |
2700 | 1.35M | { |
2701 | 1.35M | _PyObject_GC_UNTRACK(self); |
2702 | 1.35M | (void)AttributeError_clear(self); |
2703 | 1.35M | Py_TYPE(self)->tp_free(self); |
2704 | 1.35M | } |
2705 | | |
2706 | | static PyObject * |
2707 | | AttributeError_str(PyObject *op) |
2708 | 0 | { |
2709 | 0 | PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); |
2710 | 0 | PyObject *arg; // borrowed ref |
2711 | 0 | PyObject *obj = NULL, *name = NULL; |
2712 | | |
2713 | | /* .name and .obj are set automatically when attribute lookup fails, so |
2714 | | synthesize a more informative message from them when the caller |
2715 | | didn't supply a meaningful one of their own -- that is, when args is |
2716 | | empty, or contains only the attribute name. Otherwise, use the |
2717 | | message the caller gave. */ |
2718 | |
|
2719 | 0 | Py_BEGIN_CRITICAL_SECTION(self); |
2720 | 0 | if ( |
2721 | 0 | self->obj && self->name && PyUnicode_Check(self->name) |
2722 | 0 | && ((PyTuple_GET_SIZE(self->args) == 1 |
2723 | 0 | && PyUnicode_Check(arg = PyTuple_GET_ITEM(self->args, 0)) |
2724 | 0 | && _PyUnicode_Equal(arg, self->name)) |
2725 | 0 | || PyTuple_GET_SIZE(self->args) == 0) |
2726 | 0 | ) { |
2727 | 0 | obj = Py_NewRef(self->obj); |
2728 | 0 | name = Py_NewRef(self->name); |
2729 | 0 | } |
2730 | 0 | Py_END_CRITICAL_SECTION(); |
2731 | |
|
2732 | 0 | if (!obj) { |
2733 | 0 | assert(!name); |
2734 | 0 | return BaseException_str(op); /* re-acquires lock */ |
2735 | 0 | } |
2736 | | |
2737 | 0 | PyObject *result = NULL; |
2738 | 0 | if (PyModule_Check(obj)) { |
2739 | 0 | PyModuleObject *mod = _PyModule_CAST(obj); |
2740 | 0 | PyObject *modname; |
2741 | 0 | if (PyDict_GetItemRef(mod->md_dict, &_Py_ID(__name__), &modname) < 0) { |
2742 | 0 | goto done; |
2743 | 0 | } |
2744 | 0 | if (modname && PyUnicode_Check(modname)) { |
2745 | 0 | result = PyUnicode_FromFormat("module %R has no attribute %R", |
2746 | 0 | modname, name); |
2747 | 0 | Py_DECREF(modname); |
2748 | 0 | } else { |
2749 | 0 | Py_XDECREF(modname); |
2750 | 0 | result = PyUnicode_FromFormat("module has no attribute %R", name); |
2751 | 0 | } |
2752 | 0 | } else if (PyType_Check(obj)) { |
2753 | 0 | result = PyUnicode_FromFormat("type object '%N' has no attribute %R", |
2754 | 0 | obj, name); |
2755 | 0 | } else { |
2756 | 0 | result = PyUnicode_FromFormat("'%T' object has no attribute %R", |
2757 | 0 | obj, name); |
2758 | 0 | } |
2759 | 0 | done: |
2760 | 0 | Py_DECREF(obj); |
2761 | 0 | Py_DECREF(name); |
2762 | 0 | return result; |
2763 | 0 | } |
2764 | | |
2765 | | static int |
2766 | | AttributeError_traverse(PyObject *op, visitproc visit, void *arg) |
2767 | 88 | { |
2768 | 88 | PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); |
2769 | 88 | Py_VISIT(self->obj); |
2770 | 88 | Py_VISIT(self->name); |
2771 | 88 | return BaseException_traverse(op, visit, arg); |
2772 | 88 | } |
2773 | | |
2774 | | /* Pickling support */ |
2775 | | static PyObject * |
2776 | | AttributeError_getstate(PyObject *op, PyObject *Py_UNUSED(ignored)) |
2777 | 0 | { |
2778 | 0 | PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); |
2779 | 0 | PyObject *dict = self->dict; |
2780 | 0 | if (self->name || self->args) { |
2781 | 0 | dict = dict ? PyDict_Copy(dict) : PyDict_New(); |
2782 | 0 | if (dict == NULL) { |
2783 | 0 | return NULL; |
2784 | 0 | } |
2785 | 0 | if (self->name && PyDict_SetItemString(dict, "name", self->name) < 0) { |
2786 | 0 | Py_DECREF(dict); |
2787 | 0 | return NULL; |
2788 | 0 | } |
2789 | | /* We specifically are not pickling the obj attribute since there are many |
2790 | | cases where it is unlikely to be picklable. See GH-103352. |
2791 | | */ |
2792 | 0 | if (self->args && PyDict_SetItemString(dict, "args", self->args) < 0) { |
2793 | 0 | Py_DECREF(dict); |
2794 | 0 | return NULL; |
2795 | 0 | } |
2796 | 0 | return dict; |
2797 | 0 | } |
2798 | 0 | else if (dict) { |
2799 | 0 | return Py_NewRef(dict); |
2800 | 0 | } |
2801 | 0 | Py_RETURN_NONE; |
2802 | 0 | } |
2803 | | |
2804 | | static PyObject * |
2805 | | AttributeError_reduce(PyObject *op, PyObject *Py_UNUSED(ignored)) |
2806 | 0 | { |
2807 | 0 | PyObject *state = AttributeError_getstate(op, NULL); |
2808 | 0 | if (state == NULL) { |
2809 | 0 | return NULL; |
2810 | 0 | } |
2811 | | |
2812 | 0 | PyAttributeErrorObject *self = PyAttributeErrorObject_CAST(op); |
2813 | 0 | PyObject *return_value = PyTuple_Pack(3, Py_TYPE(self), self->args, state); |
2814 | 0 | Py_DECREF(state); |
2815 | 0 | return return_value; |
2816 | 0 | } |
2817 | | |
2818 | | static PyMemberDef AttributeError_members[] = { |
2819 | | {"name", _Py_T_OBJECT, offsetof(PyAttributeErrorObject, name), 0, PyDoc_STR("attribute name")}, |
2820 | | {"obj", _Py_T_OBJECT, offsetof(PyAttributeErrorObject, obj), 0, PyDoc_STR("object")}, |
2821 | | {NULL} /* Sentinel */ |
2822 | | }; |
2823 | | |
2824 | | static PyMethodDef AttributeError_methods[] = { |
2825 | | {"__getstate__", AttributeError_getstate, METH_NOARGS}, |
2826 | | {"__reduce__", AttributeError_reduce, METH_NOARGS }, |
2827 | | {NULL} |
2828 | | }; |
2829 | | |
2830 | | ComplexExtendsException(PyExc_Exception, AttributeError, |
2831 | | AttributeError, 0, |
2832 | | AttributeError_methods, AttributeError_members, |
2833 | | 0, AttributeError_str, 0, "Attribute not found."); |
2834 | | |
2835 | | /* |
2836 | | * SyntaxError extends Exception |
2837 | | */ |
2838 | | |
2839 | | static inline PySyntaxErrorObject * |
2840 | | PySyntaxErrorObject_CAST(PyObject *self) |
2841 | 163k | { |
2842 | 163k | assert(PyObject_TypeCheck(self, (PyTypeObject *)PyExc_SyntaxError)); |
2843 | 163k | return (PySyntaxErrorObject *)self; |
2844 | 163k | } |
2845 | | |
2846 | | static int |
2847 | | SyntaxError_init(PyObject *op, PyObject *args, PyObject *kwds) |
2848 | 81.5k | { |
2849 | 81.5k | PyObject *info = NULL; |
2850 | 81.5k | Py_ssize_t lenargs = PyTuple_GET_SIZE(args); |
2851 | | |
2852 | 81.5k | if (BaseException_init(op, args, kwds) == -1) |
2853 | 0 | return -1; |
2854 | | |
2855 | 81.5k | PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op); |
2856 | 81.5k | if (lenargs >= 1) { |
2857 | 81.5k | Py_XSETREF(self->msg, Py_NewRef(PyTuple_GET_ITEM(args, 0))); |
2858 | 81.5k | } |
2859 | 81.5k | if (lenargs == 2) { |
2860 | 59.2k | info = PyTuple_GET_ITEM(args, 1); |
2861 | 59.2k | info = PySequence_Tuple(info); |
2862 | 59.2k | if (!info) { |
2863 | 0 | return -1; |
2864 | 0 | } |
2865 | | |
2866 | 59.2k | PyObject *filename, *lineno, *offset, *text; |
2867 | 59.2k | PyObject *end_lineno = NULL; |
2868 | 59.2k | PyObject *end_offset = NULL; |
2869 | 59.2k | PyObject *metadata = NULL; |
2870 | 59.2k | if (!PyArg_ParseTuple(info, "OOOO|OOO", |
2871 | 59.2k | &filename, &lineno, |
2872 | 59.2k | &offset, &text, |
2873 | 59.2k | &end_lineno, &end_offset, &metadata)) { |
2874 | 0 | Py_DECREF(info); |
2875 | 0 | return -1; |
2876 | 0 | } |
2877 | | |
2878 | 59.2k | Py_XSETREF(self->filename, Py_NewRef(filename)); |
2879 | 59.2k | Py_XSETREF(self->lineno, Py_NewRef(lineno)); |
2880 | 59.2k | Py_XSETREF(self->offset, Py_NewRef(offset)); |
2881 | 59.2k | Py_XSETREF(self->text, Py_NewRef(text)); |
2882 | 59.2k | Py_XSETREF(self->end_lineno, Py_XNewRef(end_lineno)); |
2883 | 59.2k | Py_XSETREF(self->end_offset, Py_XNewRef(end_offset)); |
2884 | 59.2k | Py_XSETREF(self->metadata, Py_XNewRef(metadata)); |
2885 | 59.2k | Py_DECREF(info); |
2886 | | |
2887 | 59.2k | if (self->end_lineno != NULL && self->end_offset == NULL) { |
2888 | 0 | PyErr_SetString(PyExc_TypeError, "end_offset must be provided when end_lineno is provided"); |
2889 | 0 | return -1; |
2890 | 0 | } |
2891 | 59.2k | } |
2892 | 81.5k | return 0; |
2893 | 81.5k | } |
2894 | | |
2895 | | static int |
2896 | | SyntaxError_clear(PyObject *op) |
2897 | 81.5k | { |
2898 | 81.5k | PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op); |
2899 | 81.5k | Py_CLEAR(self->msg); |
2900 | 81.5k | Py_CLEAR(self->filename); |
2901 | 81.5k | Py_CLEAR(self->lineno); |
2902 | 81.5k | Py_CLEAR(self->offset); |
2903 | 81.5k | Py_CLEAR(self->end_lineno); |
2904 | 81.5k | Py_CLEAR(self->end_offset); |
2905 | 81.5k | Py_CLEAR(self->text); |
2906 | 81.5k | Py_CLEAR(self->print_file_and_line); |
2907 | 81.5k | Py_CLEAR(self->metadata); |
2908 | 81.5k | return BaseException_clear(op); |
2909 | 81.5k | } |
2910 | | |
2911 | | static void |
2912 | | SyntaxError_dealloc(PyObject *self) |
2913 | 81.5k | { |
2914 | 81.5k | _PyObject_GC_UNTRACK(self); |
2915 | 81.5k | (void)SyntaxError_clear(self); |
2916 | 81.5k | Py_TYPE(self)->tp_free(self); |
2917 | 81.5k | } |
2918 | | |
2919 | | static int |
2920 | | SyntaxError_traverse(PyObject *op, visitproc visit, void *arg) |
2921 | 0 | { |
2922 | 0 | PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op); |
2923 | 0 | Py_VISIT(self->msg); |
2924 | 0 | Py_VISIT(self->filename); |
2925 | 0 | Py_VISIT(self->lineno); |
2926 | 0 | Py_VISIT(self->offset); |
2927 | 0 | Py_VISIT(self->end_lineno); |
2928 | 0 | Py_VISIT(self->end_offset); |
2929 | 0 | Py_VISIT(self->text); |
2930 | 0 | Py_VISIT(self->print_file_and_line); |
2931 | 0 | Py_VISIT(self->metadata); |
2932 | 0 | return BaseException_traverse(op, visit, arg); |
2933 | 0 | } |
2934 | | |
2935 | | /* This is called "my_basename" instead of just "basename" to avoid name |
2936 | | conflicts with glibc; basename is already prototyped if _GNU_SOURCE is |
2937 | | defined, and Python does define that. */ |
2938 | | static PyObject* |
2939 | | my_basename(PyObject *name) |
2940 | 0 | { |
2941 | 0 | Py_ssize_t i, size, offset; |
2942 | 0 | int kind; |
2943 | 0 | const void *data; |
2944 | |
|
2945 | 0 | kind = PyUnicode_KIND(name); |
2946 | 0 | data = PyUnicode_DATA(name); |
2947 | 0 | size = PyUnicode_GET_LENGTH(name); |
2948 | 0 | offset = 0; |
2949 | 0 | for(i=0; i < size; i++) { |
2950 | 0 | if (PyUnicode_READ(kind, data, i) == SEP) { |
2951 | 0 | offset = i + 1; |
2952 | 0 | } |
2953 | 0 | } |
2954 | 0 | if (offset != 0) { |
2955 | 0 | return PyUnicode_Substring(name, offset, size); |
2956 | 0 | } |
2957 | 0 | else { |
2958 | 0 | return Py_NewRef(name); |
2959 | 0 | } |
2960 | 0 | } |
2961 | | |
2962 | | |
2963 | | static PyObject * |
2964 | | SyntaxError_str(PyObject *op) |
2965 | 0 | { |
2966 | 0 | PySyntaxErrorObject *self = PySyntaxErrorObject_CAST(op); |
2967 | 0 | int have_lineno = 0; |
2968 | 0 | PyObject *filename; |
2969 | 0 | PyObject *result; |
2970 | | /* Below, we always ignore overflow errors, just printing -1. |
2971 | | Still, we cannot allow an OverflowError to be raised, so |
2972 | | we need to call PyLong_AsLongAndOverflow. */ |
2973 | 0 | int overflow; |
2974 | | |
2975 | | /* XXX -- do all the additional formatting with filename and |
2976 | | lineno here */ |
2977 | |
|
2978 | 0 | if (self->filename && PyUnicode_Check(self->filename)) { |
2979 | 0 | filename = my_basename(self->filename); |
2980 | 0 | if (filename == NULL) |
2981 | 0 | return NULL; |
2982 | 0 | } else { |
2983 | 0 | filename = NULL; |
2984 | 0 | } |
2985 | 0 | have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno); |
2986 | |
|
2987 | 0 | if (!filename && !have_lineno) |
2988 | 0 | return PyObject_Str(self->msg ? self->msg : Py_None); |
2989 | | |
2990 | | // Even if 'filename' can be an instance of a subclass of 'str', |
2991 | | // we only render its "true" content and do not use str(filename). |
2992 | 0 | if (filename && have_lineno) |
2993 | 0 | result = PyUnicode_FromFormat("%S (%U, line %ld)", |
2994 | 0 | self->msg ? self->msg : Py_None, |
2995 | 0 | filename, |
2996 | 0 | PyLong_AsLongAndOverflow(self->lineno, &overflow)); |
2997 | 0 | else if (filename) |
2998 | 0 | result = PyUnicode_FromFormat("%S (%U)", |
2999 | 0 | self->msg ? self->msg : Py_None, |
3000 | 0 | filename); |
3001 | 0 | else /* only have_lineno */ |
3002 | 0 | result = PyUnicode_FromFormat("%S (line %ld)", |
3003 | 0 | self->msg ? self->msg : Py_None, |
3004 | 0 | PyLong_AsLongAndOverflow(self->lineno, &overflow)); |
3005 | 0 | Py_XDECREF(filename); |
3006 | 0 | return result; |
3007 | 0 | } |
3008 | | |
3009 | | static PyMemberDef SyntaxError_members[] = { |
3010 | | {"msg", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0, |
3011 | | PyDoc_STR("exception msg")}, |
3012 | | {"filename", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0, |
3013 | | PyDoc_STR("exception filename")}, |
3014 | | {"lineno", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0, |
3015 | | PyDoc_STR("exception lineno")}, |
3016 | | {"offset", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0, |
3017 | | PyDoc_STR("exception offset")}, |
3018 | | {"text", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, text), 0, |
3019 | | PyDoc_STR("exception text")}, |
3020 | | {"end_lineno", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, end_lineno), 0, |
3021 | | PyDoc_STR("exception end lineno")}, |
3022 | | {"end_offset", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, end_offset), 0, |
3023 | | PyDoc_STR("exception end offset")}, |
3024 | | {"print_file_and_line", _Py_T_OBJECT, |
3025 | | offsetof(PySyntaxErrorObject, print_file_and_line), 0, |
3026 | | PyDoc_STR("exception print_file_and_line")}, |
3027 | | {"_metadata", _Py_T_OBJECT, offsetof(PySyntaxErrorObject, metadata), 0, |
3028 | | PyDoc_STR("exception private metadata")}, |
3029 | | {NULL} /* Sentinel */ |
3030 | | }; |
3031 | | |
3032 | | ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError, |
3033 | | 0, 0, SyntaxError_members, 0, |
3034 | | SyntaxError_str, 0, "Invalid syntax."); |
3035 | | |
3036 | | |
3037 | | /* |
3038 | | * IndentationError extends SyntaxError |
3039 | | */ |
3040 | | MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError, |
3041 | | "Improper indentation."); |
3042 | | |
3043 | | |
3044 | | /* |
3045 | | * TabError extends IndentationError |
3046 | | */ |
3047 | | MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError, |
3048 | | "Improper mixture of spaces and tabs."); |
3049 | | |
3050 | | /* |
3051 | | * IncompleteInputError extends SyntaxError |
3052 | | */ |
3053 | | MiddlingExtendsExceptionEx(PyExc_SyntaxError, IncompleteInputError, _IncompleteInputError, |
3054 | | SyntaxError, "incomplete input."); |
3055 | | |
3056 | | /* |
3057 | | * LookupError extends Exception |
3058 | | */ |
3059 | | SimpleExtendsException(PyExc_Exception, LookupError, |
3060 | | "Base class for lookup errors."); |
3061 | | |
3062 | | |
3063 | | /* |
3064 | | * IndexError extends LookupError |
3065 | | */ |
3066 | | SimpleExtendsException(PyExc_LookupError, IndexError, |
3067 | | "Sequence index out of range."); |
3068 | | |
3069 | | |
3070 | | /* |
3071 | | * KeyError extends LookupError |
3072 | | */ |
3073 | | |
3074 | | static PyObject * |
3075 | | KeyError_str(PyObject *op) |
3076 | 0 | { |
3077 | | /* If args is a tuple of exactly one item, apply repr to args[0]. |
3078 | | This is done so that e.g. the exception raised by {}[''] prints |
3079 | | KeyError: '' |
3080 | | rather than the confusing |
3081 | | KeyError |
3082 | | alone. The downside is that if KeyError is raised with an explanatory |
3083 | | string, that string will be displayed in quotes. Too bad. |
3084 | | If args is anything else, use the default BaseException__str__(). |
3085 | | */ |
3086 | 0 | PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); |
3087 | 0 | if (PyTuple_GET_SIZE(self->args) == 1) { |
3088 | 0 | return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0)); |
3089 | 0 | } |
3090 | 0 | return BaseException_str(op); |
3091 | 0 | } |
3092 | | |
3093 | | ComplexExtendsException(PyExc_LookupError, KeyError, BaseException, |
3094 | | 0, 0, 0, 0, KeyError_str, 0, "Mapping key not found."); |
3095 | | |
3096 | | |
3097 | | /* |
3098 | | * ValueError extends Exception |
3099 | | */ |
3100 | | SimpleExtendsException(PyExc_Exception, ValueError, |
3101 | | "Inappropriate argument value (of correct type)."); |
3102 | | |
3103 | | /* |
3104 | | * UnicodeError extends ValueError |
3105 | | */ |
3106 | | |
3107 | | SimpleExtendsException(PyExc_ValueError, UnicodeError, |
3108 | | "Unicode related error."); |
3109 | | |
3110 | | |
3111 | | /* |
3112 | | * Check the validity of 'attr' as a unicode or bytes object depending |
3113 | | * on 'as_bytes'. |
3114 | | * |
3115 | | * The 'name' is the attribute name and is only used for error reporting. |
3116 | | * |
3117 | | * On success, this returns 0. |
3118 | | * On failure, this sets a TypeError and returns -1. |
3119 | | */ |
3120 | | static int |
3121 | | check_unicode_error_attribute(PyObject *attr, const char *name, int as_bytes) |
3122 | 1.30M | { |
3123 | 1.30M | assert(as_bytes == 0 || as_bytes == 1); |
3124 | 1.30M | if (attr == NULL) { |
3125 | 0 | PyErr_Format(PyExc_TypeError, |
3126 | 0 | "UnicodeError '%s' attribute is not set", |
3127 | 0 | name); |
3128 | 0 | return -1; |
3129 | 0 | } |
3130 | 1.30M | if (!(as_bytes ? PyBytes_Check(attr) : PyUnicode_Check(attr))) { |
3131 | 0 | PyErr_Format(PyExc_TypeError, |
3132 | 0 | "UnicodeError '%s' attribute must be a %s", |
3133 | 0 | name, as_bytes ? "bytes" : "string"); |
3134 | 0 | return -1; |
3135 | 0 | } |
3136 | 1.30M | return 0; |
3137 | 1.30M | } |
3138 | | |
3139 | | |
3140 | | /* |
3141 | | * Check the validity of 'attr' as a unicode or bytes object depending |
3142 | | * on 'as_bytes' and return a new reference on it if it is the case. |
3143 | | * |
3144 | | * The 'name' is the attribute name and is only used for error reporting. |
3145 | | * |
3146 | | * On success, this returns a strong reference on 'attr'. |
3147 | | * On failure, this sets a TypeError and returns NULL. |
3148 | | */ |
3149 | | static PyObject * |
3150 | | as_unicode_error_attribute(PyObject *attr, const char *name, int as_bytes) |
3151 | 1.30M | { |
3152 | 1.30M | int rc = check_unicode_error_attribute(attr, name, as_bytes); |
3153 | 1.30M | return rc < 0 ? NULL : Py_NewRef(attr); |
3154 | 1.30M | } |
3155 | | |
3156 | | |
3157 | | #define PyUnicodeError_Check(PTR) \ |
3158 | 2.72M | PyObject_TypeCheck((PTR), (PyTypeObject *)PyExc_UnicodeError) |
3159 | | #define PyUnicodeError_CAST(PTR) \ |
3160 | 3.07M | (assert(PyUnicodeError_Check(PTR)), ((PyUnicodeErrorObject *)(PTR))) |
3161 | | |
3162 | | |
3163 | | /* class names to use when reporting errors */ |
3164 | 0 | #define Py_UNICODE_ENCODE_ERROR_NAME "UnicodeEncodeError" |
3165 | 2.72M | #define Py_UNICODE_DECODE_ERROR_NAME "UnicodeDecodeError" |
3166 | 0 | #define Py_UNICODE_TRANSLATE_ERROR_NAME "UnicodeTranslateError" |
3167 | | |
3168 | | |
3169 | | /* |
3170 | | * Check that 'self' is a UnicodeError object. |
3171 | | * |
3172 | | * On success, this returns 0. |
3173 | | * On failure, this sets a TypeError exception and returns -1. |
3174 | | * |
3175 | | * The 'expect_type' is the name of the expected type, which is |
3176 | | * only used for error reporting. |
3177 | | * |
3178 | | * As an implementation detail, the `PyUnicode*Error_*` functions |
3179 | | * currently allow *any* subclass of UnicodeError as 'self'. |
3180 | | * |
3181 | | * Use one of the `Py_UNICODE_*_ERROR_NAME` macros to avoid typos. |
3182 | | */ |
3183 | | static inline int |
3184 | | check_unicode_error_type(PyObject *self, const char *expect_type) |
3185 | 2.72M | { |
3186 | 2.72M | assert(self != NULL); |
3187 | 2.72M | if (!PyUnicodeError_Check(self)) { |
3188 | 0 | PyErr_Format(PyExc_TypeError, |
3189 | 0 | "expecting a %s object, got %T", expect_type, self); |
3190 | 0 | return -1; |
3191 | 0 | } |
3192 | 2.72M | return 0; |
3193 | 2.72M | } |
3194 | | |
3195 | | |
3196 | | // --- PyUnicodeEncodeObject: internal helpers -------------------------------- |
3197 | | // |
3198 | | // In the helpers below, the caller is responsible to ensure that 'self' |
3199 | | // is a PyUnicodeErrorObject, although this is verified on DEBUG builds |
3200 | | // through PyUnicodeError_CAST(). |
3201 | | |
3202 | | /* |
3203 | | * Return the underlying (str) 'encoding' attribute of a UnicodeError object. |
3204 | | */ |
3205 | | static inline PyObject * |
3206 | | unicode_error_get_encoding_impl(PyObject *self) |
3207 | 8 | { |
3208 | 8 | assert(self != NULL); |
3209 | 8 | PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); |
3210 | 8 | return as_unicode_error_attribute(exc->encoding, "encoding", false); |
3211 | 8 | } |
3212 | | |
3213 | | |
3214 | | /* |
3215 | | * Return the underlying 'object' attribute of a UnicodeError object |
3216 | | * as a bytes or a string instance, depending on the 'as_bytes' flag. |
3217 | | */ |
3218 | | static inline PyObject * |
3219 | | unicode_error_get_object_impl(PyObject *self, int as_bytes) |
3220 | 637k | { |
3221 | 637k | assert(self != NULL); |
3222 | 637k | PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); |
3223 | 637k | return as_unicode_error_attribute(exc->object, "object", as_bytes); |
3224 | 637k | } |
3225 | | |
3226 | | |
3227 | | /* |
3228 | | * Return the underlying (str) 'reason' attribute of a UnicodeError object. |
3229 | | */ |
3230 | | static inline PyObject * |
3231 | | unicode_error_get_reason_impl(PyObject *self) |
3232 | 0 | { |
3233 | 0 | assert(self != NULL); |
3234 | 0 | PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); |
3235 | 0 | return as_unicode_error_attribute(exc->reason, "reason", false); |
3236 | 0 | } |
3237 | | |
3238 | | |
3239 | | /* |
3240 | | * Set the underlying (str) 'reason' attribute of a UnicodeError object. |
3241 | | * |
3242 | | * Return 0 on success and -1 on failure. |
3243 | | */ |
3244 | | static inline int |
3245 | | unicode_error_set_reason_impl(PyObject *self, const char *reason) |
3246 | 590k | { |
3247 | 590k | assert(self != NULL); |
3248 | 590k | PyObject *value = PyUnicode_FromString(reason); |
3249 | 590k | if (value == NULL) { |
3250 | 0 | return -1; |
3251 | 0 | } |
3252 | 590k | PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); |
3253 | 590k | Py_XSETREF(exc->reason, value); |
3254 | 590k | return 0; |
3255 | 590k | } |
3256 | | |
3257 | | |
3258 | | /* |
3259 | | * Set the 'start' attribute of a UnicodeError object. |
3260 | | * |
3261 | | * Return 0 on success and -1 on failure. |
3262 | | */ |
3263 | | static inline int |
3264 | | unicode_error_set_start_impl(PyObject *self, Py_ssize_t start) |
3265 | 590k | { |
3266 | 590k | assert(self != NULL); |
3267 | 590k | PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); |
3268 | 590k | exc->start = start; |
3269 | 590k | return 0; |
3270 | 590k | } |
3271 | | |
3272 | | |
3273 | | /* |
3274 | | * Set the 'end' attribute of a UnicodeError object. |
3275 | | * |
3276 | | * Return 0 on success and -1 on failure. |
3277 | | */ |
3278 | | static inline int |
3279 | | unicode_error_set_end_impl(PyObject *self, Py_ssize_t end) |
3280 | 590k | { |
3281 | 590k | assert(self != NULL); |
3282 | 590k | PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); |
3283 | 590k | exc->end = end; |
3284 | 590k | return 0; |
3285 | 590k | } |
3286 | | |
3287 | | // --- PyUnicodeEncodeObject: internal getters -------------------------------- |
3288 | | |
3289 | | /* |
3290 | | * Adjust the (inclusive) 'start' value of a UnicodeError object. |
3291 | | * |
3292 | | * The 'start' can be negative or not, but when adjusting the value, |
3293 | | * we clip it in [0, max(0, objlen - 1)] and do not interpret it as |
3294 | | * a relative offset. |
3295 | | * |
3296 | | * This function always succeeds. |
3297 | | */ |
3298 | | static Py_ssize_t |
3299 | | unicode_error_adjust_start(Py_ssize_t start, Py_ssize_t objlen) |
3300 | 344k | { |
3301 | 344k | assert(objlen >= 0); |
3302 | 344k | if (start < 0) { |
3303 | 0 | start = 0; |
3304 | 0 | } |
3305 | 344k | if (start >= objlen) { |
3306 | 0 | start = objlen == 0 ? 0 : objlen - 1; |
3307 | 0 | } |
3308 | 344k | return start; |
3309 | 344k | } |
3310 | | |
3311 | | |
3312 | | /* Assert some properties of the adjusted 'start' value. */ |
3313 | | #ifndef NDEBUG |
3314 | | static void |
3315 | | assert_adjusted_unicode_error_start(Py_ssize_t start, Py_ssize_t objlen) |
3316 | | { |
3317 | | assert(objlen >= 0); |
3318 | | /* in the future, `min_start` may be something else */ |
3319 | | Py_ssize_t min_start = 0; |
3320 | | assert(start >= min_start); |
3321 | | /* in the future, `max_start` may be something else */ |
3322 | | Py_ssize_t max_start = Py_MAX(min_start, objlen - 1); |
3323 | | assert(start <= max_start); |
3324 | | } |
3325 | | #else |
3326 | | #define assert_adjusted_unicode_error_start(...) |
3327 | | #endif |
3328 | | |
3329 | | |
3330 | | /* |
3331 | | * Adjust the (exclusive) 'end' value of a UnicodeError object. |
3332 | | * |
3333 | | * The 'end' can be negative or not, but when adjusting the value, |
3334 | | * we clip it in [min(1, objlen), max(min(1, objlen), objlen)] and |
3335 | | * do not interpret it as a relative offset. |
3336 | | * |
3337 | | * This function always succeeds. |
3338 | | */ |
3339 | | static Py_ssize_t |
3340 | | unicode_error_adjust_end(Py_ssize_t end, Py_ssize_t objlen) |
3341 | 662k | { |
3342 | 662k | assert(objlen >= 0); |
3343 | 662k | if (end < 1) { |
3344 | 0 | end = 1; |
3345 | 0 | } |
3346 | 662k | if (end > objlen) { |
3347 | 0 | end = objlen; |
3348 | 0 | } |
3349 | 662k | return end; |
3350 | 662k | } |
3351 | | |
3352 | | #define PyUnicodeError_Check(PTR) \ |
3353 | | PyObject_TypeCheck((PTR), (PyTypeObject *)PyExc_UnicodeError) |
3354 | | #define PyUnicodeErrorObject_CAST(op) \ |
3355 | 10.7M | (assert(PyUnicodeError_Check(op)), ((PyUnicodeErrorObject *)(op))) |
3356 | | |
3357 | | /* Assert some properties of the adjusted 'end' value. */ |
3358 | | #ifndef NDEBUG |
3359 | | static void |
3360 | | assert_adjusted_unicode_error_end(Py_ssize_t end, Py_ssize_t objlen) |
3361 | | { |
3362 | | assert(objlen >= 0); |
3363 | | /* in the future, `min_end` may be something else */ |
3364 | | Py_ssize_t min_end = Py_MIN(1, objlen); |
3365 | | assert(end >= min_end); |
3366 | | /* in the future, `max_end` may be something else */ |
3367 | | Py_ssize_t max_end = Py_MAX(min_end, objlen); |
3368 | | assert(end <= max_end); |
3369 | | } |
3370 | | #else |
3371 | | #define assert_adjusted_unicode_error_end(...) |
3372 | | #endif |
3373 | | |
3374 | | |
3375 | | /* |
3376 | | * Adjust the length of the range described by a UnicodeError object. |
3377 | | * |
3378 | | * The 'start' and 'end' arguments must have been obtained by |
3379 | | * unicode_error_adjust_start() and unicode_error_adjust_end(). |
3380 | | * |
3381 | | * The result is clipped in [0, objlen]. By construction, it |
3382 | | * will always be smaller than 'objlen' as 'start' and 'end' |
3383 | | * are smaller than 'objlen'. |
3384 | | */ |
3385 | | static Py_ssize_t |
3386 | | unicode_error_adjust_len(Py_ssize_t start, Py_ssize_t end, Py_ssize_t objlen) |
3387 | 344k | { |
3388 | 344k | assert_adjusted_unicode_error_start(start, objlen); |
3389 | 344k | assert_adjusted_unicode_error_end(end, objlen); |
3390 | 344k | Py_ssize_t ranlen = end - start; |
3391 | 344k | assert(ranlen <= objlen); |
3392 | 344k | return ranlen < 0 ? 0 : ranlen; |
3393 | 344k | } |
3394 | | |
3395 | | |
3396 | | /* Assert some properties of the adjusted range 'len' value. */ |
3397 | | #ifndef NDEBUG |
3398 | | static void |
3399 | | assert_adjusted_unicode_error_len(Py_ssize_t ranlen, Py_ssize_t objlen) |
3400 | | { |
3401 | | assert(objlen >= 0); |
3402 | | assert(ranlen >= 0); |
3403 | | assert(ranlen <= objlen); |
3404 | | } |
3405 | | #else |
3406 | | #define assert_adjusted_unicode_error_len(...) |
3407 | | #endif |
3408 | | |
3409 | | |
3410 | | /* |
3411 | | * Get various common parameters of a UnicodeError object. |
3412 | | * |
3413 | | * The caller is responsible to ensure that 'self' is a PyUnicodeErrorObject, |
3414 | | * although this condition is verified by this function on DEBUG builds. |
3415 | | * |
3416 | | * Return 0 on success and -1 on failure. |
3417 | | * |
3418 | | * Output parameters: |
3419 | | * |
3420 | | * obj A strong reference to the 'object' attribute. |
3421 | | * objlen The 'object' length. |
3422 | | * start The clipped 'start' attribute. |
3423 | | * end The clipped 'end' attribute. |
3424 | | * slen The length of the slice described by the clipped 'start' |
3425 | | * and 'end' values. It always lies in [0, objlen]. |
3426 | | * |
3427 | | * An output parameter can be NULL to indicate that |
3428 | | * the corresponding value does not need to be stored. |
3429 | | * |
3430 | | * Input parameter: |
3431 | | * |
3432 | | * as_bytes If true, the error's 'object' attribute must be a `bytes`, |
3433 | | * i.e. 'self' is a `UnicodeDecodeError` instance. Otherwise, |
3434 | | * the 'object' attribute must be a string. |
3435 | | * |
3436 | | * A TypeError is raised if the 'object' type is incompatible. |
3437 | | */ |
3438 | | int |
3439 | | _PyUnicodeError_GetParams(PyObject *self, |
3440 | | PyObject **obj, Py_ssize_t *objlen, |
3441 | | Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t *slen, |
3442 | | int as_bytes) |
3443 | 662k | { |
3444 | 662k | assert(self != NULL); |
3445 | 662k | assert(as_bytes == 0 || as_bytes == 1); |
3446 | 662k | PyUnicodeErrorObject *exc = PyUnicodeError_CAST(self); |
3447 | 662k | PyObject *r = as_unicode_error_attribute(exc->object, "object", as_bytes); |
3448 | 662k | if (r == NULL) { |
3449 | 0 | return -1; |
3450 | 0 | } |
3451 | | |
3452 | 662k | Py_ssize_t n = as_bytes ? PyBytes_GET_SIZE(r) : PyUnicode_GET_LENGTH(r); |
3453 | 662k | if (objlen != NULL) { |
3454 | 8 | *objlen = n; |
3455 | 8 | } |
3456 | | |
3457 | 662k | Py_ssize_t start_value = -1; |
3458 | 662k | if (start != NULL || slen != NULL) { |
3459 | 344k | start_value = unicode_error_adjust_start(exc->start, n); |
3460 | 344k | } |
3461 | 662k | if (start != NULL) { |
3462 | 344k | assert_adjusted_unicode_error_start(start_value, n); |
3463 | 344k | *start = start_value; |
3464 | 344k | } |
3465 | | |
3466 | 662k | Py_ssize_t end_value = -1; |
3467 | 662k | if (end != NULL || slen != NULL) { |
3468 | 662k | end_value = unicode_error_adjust_end(exc->end, n); |
3469 | 662k | } |
3470 | 662k | if (end != NULL) { |
3471 | 662k | assert_adjusted_unicode_error_end(end_value, n); |
3472 | 662k | *end = end_value; |
3473 | 662k | } |
3474 | | |
3475 | 662k | if (slen != NULL) { |
3476 | 344k | *slen = unicode_error_adjust_len(start_value, end_value, n); |
3477 | 344k | assert_adjusted_unicode_error_len(*slen, n); |
3478 | 344k | } |
3479 | | |
3480 | 662k | if (obj != NULL) { |
3481 | 344k | *obj = r; |
3482 | 344k | } |
3483 | 317k | else { |
3484 | 317k | Py_DECREF(r); |
3485 | 317k | } |
3486 | 662k | return 0; |
3487 | 662k | } |
3488 | | |
3489 | | |
3490 | | // --- PyUnicodeEncodeObject: 'encoding' getters ------------------------------ |
3491 | | // Note: PyUnicodeTranslateError does not have an 'encoding' attribute. |
3492 | | |
3493 | | PyObject * |
3494 | | PyUnicodeEncodeError_GetEncoding(PyObject *self) |
3495 | 0 | { |
3496 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); |
3497 | 0 | return rc < 0 ? NULL : unicode_error_get_encoding_impl(self); |
3498 | 0 | } |
3499 | | |
3500 | | |
3501 | | PyObject * |
3502 | | PyUnicodeDecodeError_GetEncoding(PyObject *self) |
3503 | 8 | { |
3504 | 8 | int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); |
3505 | 8 | return rc < 0 ? NULL : unicode_error_get_encoding_impl(self); |
3506 | 8 | } |
3507 | | |
3508 | | |
3509 | | // --- PyUnicodeEncodeObject: 'object' getters -------------------------------- |
3510 | | |
3511 | | PyObject * |
3512 | | PyUnicodeEncodeError_GetObject(PyObject *self) |
3513 | 0 | { |
3514 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); |
3515 | 0 | return rc < 0 ? NULL : unicode_error_get_object_impl(self, false); |
3516 | 0 | } |
3517 | | |
3518 | | |
3519 | | PyObject * |
3520 | | PyUnicodeDecodeError_GetObject(PyObject *self) |
3521 | 637k | { |
3522 | 637k | int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); |
3523 | 637k | return rc < 0 ? NULL : unicode_error_get_object_impl(self, true); |
3524 | 637k | } |
3525 | | |
3526 | | |
3527 | | PyObject * |
3528 | | PyUnicodeTranslateError_GetObject(PyObject *self) |
3529 | 0 | { |
3530 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); |
3531 | 0 | return rc < 0 ? NULL : unicode_error_get_object_impl(self, false); |
3532 | 0 | } |
3533 | | |
3534 | | |
3535 | | // --- PyUnicodeEncodeObject: 'start' getters --------------------------------- |
3536 | | |
3537 | | /* |
3538 | | * Specialization of _PyUnicodeError_GetParams() for the 'start' attribute. |
3539 | | * |
3540 | | * The caller is responsible to ensure that 'self' is a PyUnicodeErrorObject, |
3541 | | * although this condition is verified by this function on DEBUG builds. |
3542 | | */ |
3543 | | static inline int |
3544 | | unicode_error_get_start_impl(PyObject *self, Py_ssize_t *start, int as_bytes) |
3545 | 0 | { |
3546 | 0 | assert(self != NULL); |
3547 | 0 | return _PyUnicodeError_GetParams(self, NULL, NULL, |
3548 | 0 | start, NULL, NULL, |
3549 | 0 | as_bytes); |
3550 | 0 | } |
3551 | | |
3552 | | |
3553 | | int |
3554 | | PyUnicodeEncodeError_GetStart(PyObject *self, Py_ssize_t *start) |
3555 | 0 | { |
3556 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); |
3557 | 0 | return rc < 0 ? -1 : unicode_error_get_start_impl(self, start, false); |
3558 | 0 | } |
3559 | | |
3560 | | |
3561 | | int |
3562 | | PyUnicodeDecodeError_GetStart(PyObject *self, Py_ssize_t *start) |
3563 | 0 | { |
3564 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); |
3565 | 0 | return rc < 0 ? -1 : unicode_error_get_start_impl(self, start, true); |
3566 | 0 | } |
3567 | | |
3568 | | |
3569 | | int |
3570 | | PyUnicodeTranslateError_GetStart(PyObject *self, Py_ssize_t *start) |
3571 | 0 | { |
3572 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); |
3573 | 0 | return rc < 0 ? -1 : unicode_error_get_start_impl(self, start, false); |
3574 | 0 | } |
3575 | | |
3576 | | |
3577 | | // --- PyUnicodeEncodeObject: 'start' setters --------------------------------- |
3578 | | |
3579 | | int |
3580 | | PyUnicodeEncodeError_SetStart(PyObject *self, Py_ssize_t start) |
3581 | 0 | { |
3582 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); |
3583 | 0 | return rc < 0 ? -1 : unicode_error_set_start_impl(self, start); |
3584 | 0 | } |
3585 | | |
3586 | | |
3587 | | int |
3588 | | PyUnicodeDecodeError_SetStart(PyObject *self, Py_ssize_t start) |
3589 | 590k | { |
3590 | 590k | int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); |
3591 | 590k | return rc < 0 ? -1 : unicode_error_set_start_impl(self, start); |
3592 | 590k | } |
3593 | | |
3594 | | |
3595 | | int |
3596 | | PyUnicodeTranslateError_SetStart(PyObject *self, Py_ssize_t start) |
3597 | 0 | { |
3598 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); |
3599 | 0 | return rc < 0 ? -1 : unicode_error_set_start_impl(self, start); |
3600 | 0 | } |
3601 | | |
3602 | | |
3603 | | // --- PyUnicodeEncodeObject: 'end' getters ----------------------------------- |
3604 | | |
3605 | | /* |
3606 | | * Specialization of _PyUnicodeError_GetParams() for the 'end' attribute. |
3607 | | * |
3608 | | * The caller is responsible to ensure that 'self' is a PyUnicodeErrorObject, |
3609 | | * although this condition is verified by this function on DEBUG builds. |
3610 | | */ |
3611 | | static inline int |
3612 | | unicode_error_get_end_impl(PyObject *self, Py_ssize_t *end, int as_bytes) |
3613 | 317k | { |
3614 | 317k | assert(self != NULL); |
3615 | 317k | return _PyUnicodeError_GetParams(self, NULL, NULL, |
3616 | 317k | NULL, end, NULL, |
3617 | 317k | as_bytes); |
3618 | 317k | } |
3619 | | |
3620 | | |
3621 | | int |
3622 | | PyUnicodeEncodeError_GetEnd(PyObject *self, Py_ssize_t *end) |
3623 | 0 | { |
3624 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); |
3625 | 0 | return rc < 0 ? -1 : unicode_error_get_end_impl(self, end, false); |
3626 | 0 | } |
3627 | | |
3628 | | |
3629 | | int |
3630 | | PyUnicodeDecodeError_GetEnd(PyObject *self, Py_ssize_t *end) |
3631 | 317k | { |
3632 | 317k | int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); |
3633 | 317k | return rc < 0 ? -1 : unicode_error_get_end_impl(self, end, true); |
3634 | 317k | } |
3635 | | |
3636 | | |
3637 | | int |
3638 | | PyUnicodeTranslateError_GetEnd(PyObject *self, Py_ssize_t *end) |
3639 | 0 | { |
3640 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); |
3641 | 0 | return rc < 0 ? -1 : unicode_error_get_end_impl(self, end, false); |
3642 | 0 | } |
3643 | | |
3644 | | |
3645 | | // --- PyUnicodeEncodeObject: 'end' setters ----------------------------------- |
3646 | | |
3647 | | int |
3648 | | PyUnicodeEncodeError_SetEnd(PyObject *self, Py_ssize_t end) |
3649 | 0 | { |
3650 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); |
3651 | 0 | return rc < 0 ? -1 : unicode_error_set_end_impl(self, end); |
3652 | 0 | } |
3653 | | |
3654 | | |
3655 | | int |
3656 | | PyUnicodeDecodeError_SetEnd(PyObject *self, Py_ssize_t end) |
3657 | 590k | { |
3658 | 590k | int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); |
3659 | 590k | return rc < 0 ? -1 : unicode_error_set_end_impl(self, end); |
3660 | 590k | } |
3661 | | |
3662 | | |
3663 | | int |
3664 | | PyUnicodeTranslateError_SetEnd(PyObject *self, Py_ssize_t end) |
3665 | 0 | { |
3666 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); |
3667 | 0 | return rc < 0 ? -1 : unicode_error_set_end_impl(self, end); |
3668 | 0 | } |
3669 | | |
3670 | | |
3671 | | // --- PyUnicodeEncodeObject: 'reason' getters -------------------------------- |
3672 | | |
3673 | | PyObject * |
3674 | | PyUnicodeEncodeError_GetReason(PyObject *self) |
3675 | 0 | { |
3676 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); |
3677 | 0 | return rc < 0 ? NULL : unicode_error_get_reason_impl(self); |
3678 | 0 | } |
3679 | | |
3680 | | |
3681 | | PyObject * |
3682 | | PyUnicodeDecodeError_GetReason(PyObject *self) |
3683 | 0 | { |
3684 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); |
3685 | 0 | return rc < 0 ? NULL : unicode_error_get_reason_impl(self); |
3686 | 0 | } |
3687 | | |
3688 | | |
3689 | | PyObject * |
3690 | | PyUnicodeTranslateError_GetReason(PyObject *self) |
3691 | 0 | { |
3692 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); |
3693 | 0 | return rc < 0 ? NULL : unicode_error_get_reason_impl(self); |
3694 | 0 | } |
3695 | | |
3696 | | |
3697 | | // --- PyUnicodeEncodeObject: 'reason' setters -------------------------------- |
3698 | | |
3699 | | int |
3700 | | PyUnicodeEncodeError_SetReason(PyObject *self, const char *reason) |
3701 | 0 | { |
3702 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_ENCODE_ERROR_NAME); |
3703 | 0 | return rc < 0 ? -1 : unicode_error_set_reason_impl(self, reason); |
3704 | 0 | } |
3705 | | |
3706 | | |
3707 | | int |
3708 | | PyUnicodeDecodeError_SetReason(PyObject *self, const char *reason) |
3709 | 590k | { |
3710 | 590k | int rc = check_unicode_error_type(self, Py_UNICODE_DECODE_ERROR_NAME); |
3711 | 590k | return rc < 0 ? -1 : unicode_error_set_reason_impl(self, reason); |
3712 | 590k | } |
3713 | | |
3714 | | |
3715 | | int |
3716 | | PyUnicodeTranslateError_SetReason(PyObject *self, const char *reason) |
3717 | 0 | { |
3718 | 0 | int rc = check_unicode_error_type(self, Py_UNICODE_TRANSLATE_ERROR_NAME); |
3719 | 0 | return rc < 0 ? -1 : unicode_error_set_reason_impl(self, reason); |
3720 | 0 | } |
3721 | | |
3722 | | |
3723 | | static int |
3724 | | UnicodeError_clear(PyObject *self) |
3725 | 5.38M | { |
3726 | 5.38M | PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); |
3727 | 5.38M | Py_CLEAR(exc->encoding); |
3728 | 5.38M | Py_CLEAR(exc->object); |
3729 | 5.38M | Py_CLEAR(exc->reason); |
3730 | 5.38M | return BaseException_clear(self); |
3731 | 5.38M | } |
3732 | | |
3733 | | static void |
3734 | | UnicodeError_dealloc(PyObject *self) |
3735 | 5.38M | { |
3736 | 5.38M | PyTypeObject *type = Py_TYPE(self); |
3737 | 5.38M | _PyObject_GC_UNTRACK(self); |
3738 | 5.38M | (void)UnicodeError_clear(self); |
3739 | 5.38M | type->tp_free(self); |
3740 | 5.38M | } |
3741 | | |
3742 | | static int |
3743 | | UnicodeError_traverse(PyObject *self, visitproc visit, void *arg) |
3744 | 540 | { |
3745 | 540 | PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); |
3746 | 540 | Py_VISIT(exc->encoding); |
3747 | 540 | Py_VISIT(exc->object); |
3748 | 540 | Py_VISIT(exc->reason); |
3749 | 540 | return BaseException_traverse(self, visit, arg); |
3750 | 540 | } |
3751 | | |
3752 | | static PyMemberDef UnicodeError_members[] = { |
3753 | | {"encoding", _Py_T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0, |
3754 | | PyDoc_STR("exception encoding")}, |
3755 | | {"object", _Py_T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0, |
3756 | | PyDoc_STR("exception object")}, |
3757 | | {"start", Py_T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0, |
3758 | | PyDoc_STR("exception start")}, |
3759 | | {"end", Py_T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0, |
3760 | | PyDoc_STR("exception end")}, |
3761 | | {"reason", _Py_T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0, |
3762 | | PyDoc_STR("exception reason")}, |
3763 | | {NULL} /* Sentinel */ |
3764 | | }; |
3765 | | |
3766 | | |
3767 | | /* |
3768 | | * UnicodeEncodeError extends UnicodeError |
3769 | | */ |
3770 | | |
3771 | | static int |
3772 | | UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds) |
3773 | 2.80M | { |
3774 | 2.80M | if (BaseException_init(self, args, kwds) == -1) { |
3775 | 0 | return -1; |
3776 | 0 | } |
3777 | | |
3778 | 2.80M | PyObject *encoding = NULL, *object = NULL, *reason = NULL; // borrowed |
3779 | 2.80M | Py_ssize_t start = -1, end = -1; |
3780 | | |
3781 | 2.80M | if (!PyArg_ParseTuple(args, "UUnnU", |
3782 | 2.80M | &encoding, &object, &start, &end, &reason)) |
3783 | 0 | { |
3784 | 0 | return -1; |
3785 | 0 | } |
3786 | | |
3787 | 2.80M | PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); |
3788 | 2.80M | Py_XSETREF(exc->encoding, Py_NewRef(encoding)); |
3789 | 2.80M | Py_XSETREF(exc->object, Py_NewRef(object)); |
3790 | 2.80M | exc->start = start; |
3791 | 2.80M | exc->end = end; |
3792 | 2.80M | Py_XSETREF(exc->reason, Py_NewRef(reason)); |
3793 | 2.80M | return 0; |
3794 | 2.80M | } |
3795 | | |
3796 | | static PyObject * |
3797 | | UnicodeEncodeError_str(PyObject *self) |
3798 | 65 | { |
3799 | 65 | PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); |
3800 | 65 | PyObject *result = NULL; |
3801 | 65 | PyObject *reason_str = NULL; |
3802 | 65 | PyObject *encoding_str = NULL; |
3803 | | |
3804 | 65 | if (exc->object == NULL) { |
3805 | | /* Not properly initialized. */ |
3806 | 0 | return Py_GetConstant(Py_CONSTANT_EMPTY_STR); |
3807 | 0 | } |
3808 | | |
3809 | | /* Get reason and encoding as strings, which they might not be if |
3810 | | they've been modified after we were constructed. */ |
3811 | 65 | reason_str = PyObject_Str(exc->reason); |
3812 | 65 | if (reason_str == NULL) { |
3813 | 0 | goto done; |
3814 | 0 | } |
3815 | 65 | encoding_str = PyObject_Str(exc->encoding); |
3816 | 65 | if (encoding_str == NULL) { |
3817 | 0 | goto done; |
3818 | 0 | } |
3819 | | // calls to PyObject_Str(...) above might mutate 'exc->object' |
3820 | 65 | if (check_unicode_error_attribute(exc->object, "object", false) < 0) { |
3821 | 0 | goto done; |
3822 | 0 | } |
3823 | 65 | Py_ssize_t len = PyUnicode_GET_LENGTH(exc->object); |
3824 | 65 | Py_ssize_t start = exc->start, end = exc->end; |
3825 | | |
3826 | 65 | if ((start >= 0 && start < len) && (end >= 0 && end <= len) && end == start + 1) { |
3827 | 38 | Py_UCS4 badchar = PyUnicode_ReadChar(exc->object, start); |
3828 | 38 | const char *fmt; |
3829 | 38 | if (badchar <= 0xff) { |
3830 | 0 | fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U"; |
3831 | 0 | } |
3832 | 38 | else if (badchar <= 0xffff) { |
3833 | 38 | fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U"; |
3834 | 38 | } |
3835 | 0 | else { |
3836 | 0 | fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U"; |
3837 | 0 | } |
3838 | 38 | result = PyUnicode_FromFormat( |
3839 | 38 | fmt, |
3840 | 38 | encoding_str, |
3841 | 38 | (int)badchar, |
3842 | 38 | start, |
3843 | 38 | reason_str); |
3844 | 38 | } |
3845 | 27 | else { |
3846 | 27 | result = PyUnicode_FromFormat( |
3847 | 27 | "'%U' codec can't encode characters in position %zd-%zd: %U", |
3848 | 27 | encoding_str, |
3849 | 27 | start, |
3850 | 27 | end - 1, |
3851 | 27 | reason_str); |
3852 | 27 | } |
3853 | 65 | done: |
3854 | 65 | Py_XDECREF(reason_str); |
3855 | 65 | Py_XDECREF(encoding_str); |
3856 | 65 | return result; |
3857 | 65 | } |
3858 | | |
3859 | | static PyTypeObject _PyExc_UnicodeEncodeError = { |
3860 | | PyVarObject_HEAD_INIT(NULL, 0) |
3861 | | "UnicodeEncodeError", |
3862 | | sizeof(PyUnicodeErrorObject), 0, |
3863 | | UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
3864 | | UnicodeEncodeError_str, 0, 0, 0, |
3865 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, |
3866 | | PyDoc_STR("Unicode encoding error."), UnicodeError_traverse, |
3867 | | UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, |
3868 | | 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), |
3869 | | UnicodeEncodeError_init, 0, BaseException_new, |
3870 | | }; |
3871 | | PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError; |
3872 | | |
3873 | | |
3874 | | /* |
3875 | | * UnicodeDecodeError extends UnicodeError |
3876 | | */ |
3877 | | |
3878 | | static int |
3879 | | UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds) |
3880 | 2.58M | { |
3881 | 2.58M | if (BaseException_init(self, args, kwds) == -1) { |
3882 | 0 | return -1; |
3883 | 0 | } |
3884 | | |
3885 | 2.58M | PyObject *encoding = NULL, *object = NULL, *reason = NULL; // borrowed |
3886 | 2.58M | Py_ssize_t start = -1, end = -1; |
3887 | | |
3888 | 2.58M | if (!PyArg_ParseTuple(args, "UOnnU", |
3889 | 2.58M | &encoding, &object, &start, &end, &reason)) |
3890 | 145 | { |
3891 | 145 | return -1; |
3892 | 145 | } |
3893 | | |
3894 | 2.58M | if (PyBytes_Check(object)) { |
3895 | 2.58M | Py_INCREF(object); // make 'object' a strong reference |
3896 | 2.58M | } |
3897 | 0 | else { |
3898 | 0 | Py_buffer view; |
3899 | 0 | if (PyObject_GetBuffer(object, &view, PyBUF_SIMPLE) != 0) { |
3900 | 0 | return -1; |
3901 | 0 | } |
3902 | | // 'object' is borrowed, so we can re-use the variable |
3903 | 0 | object = PyBytes_FromStringAndSize(view.buf, view.len); |
3904 | 0 | PyBuffer_Release(&view); |
3905 | 0 | if (object == NULL) { |
3906 | 0 | return -1; |
3907 | 0 | } |
3908 | 0 | } |
3909 | | |
3910 | 2.58M | PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); |
3911 | 2.58M | Py_XSETREF(exc->encoding, Py_NewRef(encoding)); |
3912 | 2.58M | Py_XSETREF(exc->object, object /* already a strong reference */); |
3913 | 2.58M | exc->start = start; |
3914 | 2.58M | exc->end = end; |
3915 | 2.58M | Py_XSETREF(exc->reason, Py_NewRef(reason)); |
3916 | 2.58M | return 0; |
3917 | 2.58M | } |
3918 | | |
3919 | | static PyObject * |
3920 | | UnicodeDecodeError_str(PyObject *self) |
3921 | 2.10k | { |
3922 | 2.10k | PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); |
3923 | 2.10k | PyObject *result = NULL; |
3924 | 2.10k | PyObject *reason_str = NULL; |
3925 | 2.10k | PyObject *encoding_str = NULL; |
3926 | | |
3927 | 2.10k | if (exc->object == NULL) { |
3928 | | /* Not properly initialized. */ |
3929 | 0 | return Py_GetConstant(Py_CONSTANT_EMPTY_STR); |
3930 | 0 | } |
3931 | | |
3932 | | /* Get reason and encoding as strings, which they might not be if |
3933 | | they've been modified after we were constructed. */ |
3934 | 2.10k | reason_str = PyObject_Str(exc->reason); |
3935 | 2.10k | if (reason_str == NULL) { |
3936 | 0 | goto done; |
3937 | 0 | } |
3938 | 2.10k | encoding_str = PyObject_Str(exc->encoding); |
3939 | 2.10k | if (encoding_str == NULL) { |
3940 | 0 | goto done; |
3941 | 0 | } |
3942 | | // calls to PyObject_Str(...) above might mutate 'exc->object' |
3943 | 2.10k | if (check_unicode_error_attribute(exc->object, "object", true) < 0) { |
3944 | 0 | goto done; |
3945 | 0 | } |
3946 | 2.10k | Py_ssize_t len = PyBytes_GET_SIZE(exc->object); |
3947 | 2.10k | Py_ssize_t start = exc->start, end = exc->end; |
3948 | | |
3949 | 2.10k | if ((start >= 0 && start < len) && (end >= 0 && end <= len) && end == start + 1) { |
3950 | 1.05k | int badbyte = (int)(PyBytes_AS_STRING(exc->object)[start] & 0xff); |
3951 | 1.05k | result = PyUnicode_FromFormat( |
3952 | 1.05k | "'%U' codec can't decode byte 0x%02x in position %zd: %U", |
3953 | 1.05k | encoding_str, |
3954 | 1.05k | badbyte, |
3955 | 1.05k | start, |
3956 | 1.05k | reason_str); |
3957 | 1.05k | } |
3958 | 1.05k | else { |
3959 | 1.05k | result = PyUnicode_FromFormat( |
3960 | 1.05k | "'%U' codec can't decode bytes in position %zd-%zd: %U", |
3961 | 1.05k | encoding_str, |
3962 | 1.05k | start, |
3963 | 1.05k | end - 1, |
3964 | 1.05k | reason_str); |
3965 | 1.05k | } |
3966 | 2.10k | done: |
3967 | 2.10k | Py_XDECREF(reason_str); |
3968 | 2.10k | Py_XDECREF(encoding_str); |
3969 | 2.10k | return result; |
3970 | 2.10k | } |
3971 | | |
3972 | | static PyTypeObject _PyExc_UnicodeDecodeError = { |
3973 | | PyVarObject_HEAD_INIT(NULL, 0) |
3974 | | "UnicodeDecodeError", |
3975 | | sizeof(PyUnicodeErrorObject), 0, |
3976 | | UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
3977 | | UnicodeDecodeError_str, 0, 0, 0, |
3978 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, |
3979 | | PyDoc_STR("Unicode decoding error."), UnicodeError_traverse, |
3980 | | UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, |
3981 | | 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), |
3982 | | UnicodeDecodeError_init, 0, BaseException_new, |
3983 | | }; |
3984 | | PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError; |
3985 | | |
3986 | | PyObject * |
3987 | | PyUnicodeDecodeError_Create( |
3988 | | const char *encoding, const char *object, Py_ssize_t length, |
3989 | | Py_ssize_t start, Py_ssize_t end, const char *reason) |
3990 | 2.57M | { |
3991 | 2.57M | return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns", |
3992 | 2.57M | encoding, object, length, start, end, reason); |
3993 | 2.57M | } |
3994 | | |
3995 | | |
3996 | | /* |
3997 | | * UnicodeTranslateError extends UnicodeError |
3998 | | */ |
3999 | | |
4000 | | static int |
4001 | | UnicodeTranslateError_init(PyObject *self, PyObject *args, PyObject *kwds) |
4002 | 0 | { |
4003 | 0 | if (BaseException_init(self, args, kwds) == -1) { |
4004 | 0 | return -1; |
4005 | 0 | } |
4006 | | |
4007 | 0 | PyObject *object = NULL, *reason = NULL; // borrowed |
4008 | 0 | Py_ssize_t start = -1, end = -1; |
4009 | |
|
4010 | 0 | if (!PyArg_ParseTuple(args, "UnnU", &object, &start, &end, &reason)) { |
4011 | 0 | return -1; |
4012 | 0 | } |
4013 | | |
4014 | 0 | PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); |
4015 | 0 | Py_XSETREF(exc->object, Py_NewRef(object)); |
4016 | 0 | exc->start = start; |
4017 | 0 | exc->end = end; |
4018 | 0 | Py_XSETREF(exc->reason, Py_NewRef(reason)); |
4019 | 0 | return 0; |
4020 | 0 | } |
4021 | | |
4022 | | |
4023 | | static PyObject * |
4024 | | UnicodeTranslateError_str(PyObject *self) |
4025 | 0 | { |
4026 | 0 | PyUnicodeErrorObject *exc = PyUnicodeErrorObject_CAST(self); |
4027 | 0 | PyObject *result = NULL; |
4028 | 0 | PyObject *reason_str = NULL; |
4029 | |
|
4030 | 0 | if (exc->object == NULL) { |
4031 | | /* Not properly initialized. */ |
4032 | 0 | return Py_GetConstant(Py_CONSTANT_EMPTY_STR); |
4033 | 0 | } |
4034 | | |
4035 | | /* Get reason as a string, which it might not be if it's been |
4036 | | modified after we were constructed. */ |
4037 | 0 | reason_str = PyObject_Str(exc->reason); |
4038 | 0 | if (reason_str == NULL) { |
4039 | 0 | goto done; |
4040 | 0 | } |
4041 | | // call to PyObject_Str(...) above might mutate 'exc->object' |
4042 | 0 | if (check_unicode_error_attribute(exc->object, "object", false) < 0) { |
4043 | 0 | goto done; |
4044 | 0 | } |
4045 | 0 | Py_ssize_t len = PyUnicode_GET_LENGTH(exc->object); |
4046 | 0 | Py_ssize_t start = exc->start, end = exc->end; |
4047 | |
|
4048 | 0 | if ((start >= 0 && start < len) && (end >= 0 && end <= len) && end == start + 1) { |
4049 | 0 | Py_UCS4 badchar = PyUnicode_ReadChar(exc->object, start); |
4050 | 0 | const char *fmt; |
4051 | 0 | if (badchar <= 0xff) { |
4052 | 0 | fmt = "can't translate character '\\x%02x' in position %zd: %U"; |
4053 | 0 | } |
4054 | 0 | else if (badchar <= 0xffff) { |
4055 | 0 | fmt = "can't translate character '\\u%04x' in position %zd: %U"; |
4056 | 0 | } |
4057 | 0 | else { |
4058 | 0 | fmt = "can't translate character '\\U%08x' in position %zd: %U"; |
4059 | 0 | } |
4060 | 0 | result = PyUnicode_FromFormat( |
4061 | 0 | fmt, |
4062 | 0 | (int)badchar, |
4063 | 0 | start, |
4064 | 0 | reason_str); |
4065 | 0 | } |
4066 | 0 | else { |
4067 | 0 | result = PyUnicode_FromFormat( |
4068 | 0 | "can't translate characters in position %zd-%zd: %U", |
4069 | 0 | start, |
4070 | 0 | end - 1, |
4071 | 0 | reason_str); |
4072 | 0 | } |
4073 | 0 | done: |
4074 | 0 | Py_XDECREF(reason_str); |
4075 | 0 | return result; |
4076 | 0 | } |
4077 | | |
4078 | | static PyTypeObject _PyExc_UnicodeTranslateError = { |
4079 | | PyVarObject_HEAD_INIT(NULL, 0) |
4080 | | "UnicodeTranslateError", |
4081 | | sizeof(PyUnicodeErrorObject), 0, |
4082 | | UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
4083 | | UnicodeTranslateError_str, 0, 0, 0, |
4084 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, |
4085 | | PyDoc_STR("Unicode translation error."), UnicodeError_traverse, |
4086 | | UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, |
4087 | | 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), |
4088 | | UnicodeTranslateError_init, 0, BaseException_new, |
4089 | | }; |
4090 | | PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError; |
4091 | | |
4092 | | PyObject * |
4093 | | _PyUnicodeTranslateError_Create( |
4094 | | PyObject *object, |
4095 | | Py_ssize_t start, Py_ssize_t end, const char *reason) |
4096 | 0 | { |
4097 | 0 | return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns", |
4098 | 0 | object, start, end, reason); |
4099 | 0 | } |
4100 | | |
4101 | | /* |
4102 | | * AssertionError extends Exception |
4103 | | */ |
4104 | | SimpleExtendsException(PyExc_Exception, AssertionError, |
4105 | | "Assertion failed."); |
4106 | | |
4107 | | |
4108 | | /* |
4109 | | * ArithmeticError extends Exception |
4110 | | */ |
4111 | | SimpleExtendsException(PyExc_Exception, ArithmeticError, |
4112 | | "Base class for arithmetic errors."); |
4113 | | |
4114 | | |
4115 | | /* |
4116 | | * FloatingPointError extends ArithmeticError |
4117 | | */ |
4118 | | SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError, |
4119 | | "Floating-point operation failed."); |
4120 | | |
4121 | | |
4122 | | /* |
4123 | | * OverflowError extends ArithmeticError |
4124 | | */ |
4125 | | SimpleExtendsException(PyExc_ArithmeticError, OverflowError, |
4126 | | "Result too large to be represented."); |
4127 | | |
4128 | | |
4129 | | /* |
4130 | | * ZeroDivisionError extends ArithmeticError |
4131 | | */ |
4132 | | SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError, |
4133 | | "Second argument to a division or modulo operation was zero."); |
4134 | | |
4135 | | |
4136 | | /* |
4137 | | * SystemError extends Exception |
4138 | | */ |
4139 | | SimpleExtendsException(PyExc_Exception, SystemError, |
4140 | | "Internal error in the Python interpreter.\n" |
4141 | | "\n" |
4142 | | "Please report this to the Python maintainer, along with the traceback,\n" |
4143 | | "the Python version, and the hardware/OS platform and version."); |
4144 | | |
4145 | | |
4146 | | /* |
4147 | | * ReferenceError extends Exception |
4148 | | */ |
4149 | | SimpleExtendsException(PyExc_Exception, ReferenceError, |
4150 | | "Weak ref proxy used after referent went away."); |
4151 | | |
4152 | | |
4153 | | /* |
4154 | | * MemoryError extends Exception |
4155 | | */ |
4156 | | |
4157 | 1.90k | #define MEMERRORS_SAVE 16 |
4158 | | |
4159 | | #ifdef Py_GIL_DISABLED |
4160 | | # define MEMERRORS_LOCK(state) PyMutex_LockFlags(&state->memerrors_lock, _Py_LOCK_DONT_DETACH) |
4161 | | # define MEMERRORS_UNLOCK(state) PyMutex_Unlock(&state->memerrors_lock) |
4162 | | #else |
4163 | 1.29k | # define MEMERRORS_LOCK(state) ((void)0) |
4164 | 1.29k | # define MEMERRORS_UNLOCK(state) ((void)0) |
4165 | | #endif |
4166 | | |
4167 | | static PyObject * |
4168 | | get_memory_error(int allow_allocation, PyObject *args, PyObject *kwds) |
4169 | 649 | { |
4170 | 649 | PyBaseExceptionObject *self = NULL; |
4171 | 649 | struct _Py_exc_state *state = get_exc_state(); |
4172 | | |
4173 | 649 | MEMERRORS_LOCK(state); |
4174 | 649 | if (state->memerrors_freelist != NULL) { |
4175 | | /* Fetch MemoryError from freelist and initialize it */ |
4176 | 57 | self = state->memerrors_freelist; |
4177 | 57 | state->memerrors_freelist = (PyBaseExceptionObject *) self->dict; |
4178 | 57 | state->memerrors_numfree--; |
4179 | 57 | self->dict = NULL; |
4180 | 57 | self->args = (PyObject *)&_Py_SINGLETON(tuple_empty); |
4181 | 57 | _Py_NewReference((PyObject *)self); |
4182 | 57 | _PyObject_GC_TRACK(self); |
4183 | 57 | } |
4184 | 649 | MEMERRORS_UNLOCK(state); |
4185 | | |
4186 | 649 | if (self != NULL) { |
4187 | 57 | return (PyObject *)self; |
4188 | 57 | } |
4189 | | |
4190 | 592 | if (!allow_allocation) { |
4191 | 0 | PyInterpreterState *interp = _PyInterpreterState_GET(); |
4192 | 0 | return Py_NewRef( |
4193 | 0 | &_Py_INTERP_SINGLETON(interp, last_resort_memory_error)); |
4194 | 0 | } |
4195 | 592 | return BaseException_new((PyTypeObject *)PyExc_MemoryError, args, kwds); |
4196 | 592 | } |
4197 | | |
4198 | | static PyObject * |
4199 | | MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
4200 | 649 | { |
4201 | | /* If this is a subclass of MemoryError, don't use the freelist |
4202 | | * and just return a fresh object */ |
4203 | 649 | if (type != (PyTypeObject *) PyExc_MemoryError) { |
4204 | 0 | return BaseException_new(type, args, kwds); |
4205 | 0 | } |
4206 | 649 | return get_memory_error(1, args, kwds); |
4207 | 649 | } |
4208 | | |
4209 | | PyObject * |
4210 | | _PyErr_NoMemory(PyThreadState *tstate) |
4211 | 0 | { |
4212 | 0 | if (Py_IS_TYPE(PyExc_MemoryError, NULL)) { |
4213 | | /* PyErr_NoMemory() has been called before PyExc_MemoryError has been |
4214 | | initialized by _PyExc_Init() */ |
4215 | 0 | Py_FatalError("Out of memory and PyExc_MemoryError is not " |
4216 | 0 | "initialized yet"); |
4217 | 0 | } |
4218 | 0 | PyObject *err = get_memory_error(0, NULL, NULL); |
4219 | 0 | if (err != NULL) { |
4220 | 0 | _PyErr_SetRaisedException(tstate, err); |
4221 | 0 | } |
4222 | 0 | return NULL; |
4223 | 0 | } |
4224 | | |
4225 | | static void |
4226 | | MemoryError_dealloc(PyObject *op) |
4227 | 649 | { |
4228 | 649 | PyBaseExceptionObject *self = PyBaseExceptionObject_CAST(op); |
4229 | 649 | _PyObject_GC_UNTRACK(self); |
4230 | | |
4231 | 649 | (void)BaseException_clear(op); |
4232 | | |
4233 | | /* If this is a subclass of MemoryError, we don't need to |
4234 | | * do anything in the free-list*/ |
4235 | 649 | if (!Py_IS_TYPE(self, (PyTypeObject *) PyExc_MemoryError)) { |
4236 | 0 | Py_TYPE(self)->tp_free(op); |
4237 | 0 | return; |
4238 | 0 | } |
4239 | | |
4240 | 649 | struct _Py_exc_state *state = get_exc_state(); |
4241 | 649 | MEMERRORS_LOCK(state); |
4242 | 649 | if (state->memerrors_numfree < MEMERRORS_SAVE) { |
4243 | 649 | self->dict = (PyObject *) state->memerrors_freelist; |
4244 | 649 | state->memerrors_freelist = self; |
4245 | 649 | state->memerrors_numfree++; |
4246 | 649 | MEMERRORS_UNLOCK(state); |
4247 | 649 | return; |
4248 | 649 | } |
4249 | 0 | MEMERRORS_UNLOCK(state); |
4250 | |
|
4251 | 0 | Py_TYPE(self)->tp_free((PyObject *)self); |
4252 | 0 | } |
4253 | | |
4254 | | static int |
4255 | | preallocate_memerrors(void) |
4256 | 37 | { |
4257 | | /* We create enough MemoryErrors and then decref them, which will fill |
4258 | | up the freelist. */ |
4259 | 37 | int i; |
4260 | | |
4261 | 37 | PyObject *errors[MEMERRORS_SAVE]; |
4262 | 629 | for (i = 0; i < MEMERRORS_SAVE; i++) { |
4263 | 592 | errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError, |
4264 | 592 | NULL, NULL); |
4265 | 592 | if (!errors[i]) { |
4266 | 0 | return -1; |
4267 | 0 | } |
4268 | 592 | } |
4269 | 629 | for (i = 0; i < MEMERRORS_SAVE; i++) { |
4270 | 592 | Py_DECREF(errors[i]); |
4271 | 592 | } |
4272 | 37 | return 0; |
4273 | 37 | } |
4274 | | |
4275 | | static void |
4276 | | free_preallocated_memerrors(struct _Py_exc_state *state) |
4277 | 0 | { |
4278 | 0 | while (state->memerrors_freelist != NULL) { |
4279 | 0 | PyObject *self = (PyObject *) state->memerrors_freelist; |
4280 | 0 | state->memerrors_freelist = (PyBaseExceptionObject *)state->memerrors_freelist->dict; |
4281 | 0 | Py_TYPE(self)->tp_free(self); |
4282 | 0 | } |
4283 | 0 | } |
4284 | | |
4285 | | |
4286 | | PyTypeObject _PyExc_MemoryError = { |
4287 | | PyVarObject_HEAD_INIT(NULL, 0) |
4288 | | "MemoryError", |
4289 | | sizeof(PyBaseExceptionObject), |
4290 | | 0, MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0, |
4291 | | 0, 0, 0, 0, 0, 0, 0, |
4292 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, |
4293 | | PyDoc_STR("Out of memory."), BaseException_traverse, |
4294 | | BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception, |
4295 | | 0, 0, 0, offsetof(PyBaseExceptionObject, dict), |
4296 | | BaseException_init, 0, MemoryError_new |
4297 | | }; |
4298 | | PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError; |
4299 | | |
4300 | | |
4301 | | /* |
4302 | | * BufferError extends Exception |
4303 | | */ |
4304 | | SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error."); |
4305 | | |
4306 | | |
4307 | | /* Warning category docstrings */ |
4308 | | |
4309 | | /* |
4310 | | * Warning extends Exception |
4311 | | */ |
4312 | | SimpleExtendsException(PyExc_Exception, Warning, |
4313 | | "Base class for warning categories."); |
4314 | | |
4315 | | |
4316 | | /* |
4317 | | * UserWarning extends Warning |
4318 | | */ |
4319 | | SimpleExtendsException(PyExc_Warning, UserWarning, |
4320 | | "Base class for warnings generated by user code."); |
4321 | | |
4322 | | |
4323 | | /* |
4324 | | * DeprecationWarning extends Warning |
4325 | | */ |
4326 | | SimpleExtendsException(PyExc_Warning, DeprecationWarning, |
4327 | | "Base class for warnings about deprecated features."); |
4328 | | |
4329 | | |
4330 | | /* |
4331 | | * PendingDeprecationWarning extends Warning |
4332 | | */ |
4333 | | SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning, |
4334 | | "Base class for warnings about features which will be deprecated\n" |
4335 | | "in the future."); |
4336 | | |
4337 | | |
4338 | | /* |
4339 | | * SyntaxWarning extends Warning |
4340 | | */ |
4341 | | SimpleExtendsException(PyExc_Warning, SyntaxWarning, |
4342 | | "Base class for warnings about dubious syntax."); |
4343 | | |
4344 | | |
4345 | | /* |
4346 | | * RuntimeWarning extends Warning |
4347 | | */ |
4348 | | SimpleExtendsException(PyExc_Warning, RuntimeWarning, |
4349 | | "Base class for warnings about dubious runtime behavior."); |
4350 | | |
4351 | | |
4352 | | /* |
4353 | | * FutureWarning extends Warning |
4354 | | */ |
4355 | | SimpleExtendsException(PyExc_Warning, FutureWarning, |
4356 | | "Base class for warnings about constructs that will change semantically\n" |
4357 | | "in the future."); |
4358 | | |
4359 | | |
4360 | | /* |
4361 | | * ImportWarning extends Warning |
4362 | | */ |
4363 | | SimpleExtendsException(PyExc_Warning, ImportWarning, |
4364 | | "Base class for warnings about probable mistakes in module imports"); |
4365 | | |
4366 | | |
4367 | | /* |
4368 | | * UnicodeWarning extends Warning |
4369 | | */ |
4370 | | SimpleExtendsException(PyExc_Warning, UnicodeWarning, |
4371 | | "Base class for warnings about Unicode related problems, mostly\n" |
4372 | | "related to conversion problems."); |
4373 | | |
4374 | | |
4375 | | /* |
4376 | | * BytesWarning extends Warning |
4377 | | */ |
4378 | | SimpleExtendsException(PyExc_Warning, BytesWarning, |
4379 | | "Base class for warnings about bytes and buffer related problems, mostly\n" |
4380 | | "related to conversion from str or comparing to str."); |
4381 | | |
4382 | | |
4383 | | /* |
4384 | | * EncodingWarning extends Warning |
4385 | | */ |
4386 | | SimpleExtendsException(PyExc_Warning, EncodingWarning, |
4387 | | "Base class for warnings about encodings."); |
4388 | | |
4389 | | |
4390 | | /* |
4391 | | * ResourceWarning extends Warning |
4392 | | */ |
4393 | | SimpleExtendsException(PyExc_Warning, ResourceWarning, |
4394 | | "Base class for warnings about resource usage."); |
4395 | | |
4396 | | |
4397 | | |
4398 | | #ifdef MS_WINDOWS |
4399 | | #include <winsock2.h> |
4400 | | /* The following constants were added to errno.h in VS2010 but have |
4401 | | preferred WSA equivalents. */ |
4402 | | #undef EADDRINUSE |
4403 | | #undef EADDRNOTAVAIL |
4404 | | #undef EAFNOSUPPORT |
4405 | | #undef EALREADY |
4406 | | #undef ECONNABORTED |
4407 | | #undef ECONNREFUSED |
4408 | | #undef ECONNRESET |
4409 | | #undef EDESTADDRREQ |
4410 | | #undef EHOSTUNREACH |
4411 | | #undef EINPROGRESS |
4412 | | #undef EISCONN |
4413 | | #undef ELOOP |
4414 | | #undef EMSGSIZE |
4415 | | #undef ENETDOWN |
4416 | | #undef ENETRESET |
4417 | | #undef ENETUNREACH |
4418 | | #undef ENOBUFS |
4419 | | #undef ENOPROTOOPT |
4420 | | #undef ENOTCONN |
4421 | | #undef ENOTSOCK |
4422 | | #undef EOPNOTSUPP |
4423 | | #undef EPROTONOSUPPORT |
4424 | | #undef EPROTOTYPE |
4425 | | #undef EWOULDBLOCK |
4426 | | |
4427 | | #if defined(WSAEALREADY) && !defined(EALREADY) |
4428 | | #define EALREADY WSAEALREADY |
4429 | | #endif |
4430 | | #if defined(WSAECONNABORTED) && !defined(ECONNABORTED) |
4431 | | #define ECONNABORTED WSAECONNABORTED |
4432 | | #endif |
4433 | | #if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED) |
4434 | | #define ECONNREFUSED WSAECONNREFUSED |
4435 | | #endif |
4436 | | #if defined(WSAECONNRESET) && !defined(ECONNRESET) |
4437 | | #define ECONNRESET WSAECONNRESET |
4438 | | #endif |
4439 | | #if defined(WSAEINPROGRESS) && !defined(EINPROGRESS) |
4440 | | #define EINPROGRESS WSAEINPROGRESS |
4441 | | #endif |
4442 | | #if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN) |
4443 | | #define ESHUTDOWN WSAESHUTDOWN |
4444 | | #endif |
4445 | | #if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK) |
4446 | | #define EWOULDBLOCK WSAEWOULDBLOCK |
4447 | | #endif |
4448 | | #endif /* MS_WINDOWS */ |
4449 | | |
4450 | | struct static_exception { |
4451 | | PyTypeObject *exc; |
4452 | | const char *name; |
4453 | | }; |
4454 | | |
4455 | | static struct static_exception static_exceptions[] = { |
4456 | | #define ITEM(NAME) {&_PyExc_##NAME, #NAME} |
4457 | | // Level 1 |
4458 | | ITEM(BaseException), |
4459 | | |
4460 | | // Level 2: BaseException subclasses |
4461 | | ITEM(BaseExceptionGroup), |
4462 | | ITEM(Exception), |
4463 | | ITEM(GeneratorExit), |
4464 | | ITEM(KeyboardInterrupt), |
4465 | | ITEM(SystemExit), |
4466 | | |
4467 | | // Level 3: Exception(BaseException) subclasses |
4468 | | ITEM(ArithmeticError), |
4469 | | ITEM(AssertionError), |
4470 | | ITEM(AttributeError), |
4471 | | ITEM(BufferError), |
4472 | | ITEM(EOFError), |
4473 | | //ITEM(ExceptionGroup), |
4474 | | ITEM(ImportError), |
4475 | | ITEM(LookupError), |
4476 | | ITEM(MemoryError), |
4477 | | ITEM(NameError), |
4478 | | ITEM(OSError), |
4479 | | ITEM(ReferenceError), |
4480 | | ITEM(RuntimeError), |
4481 | | ITEM(StopAsyncIteration), |
4482 | | ITEM(StopIteration), |
4483 | | ITEM(SyntaxError), |
4484 | | ITEM(SystemError), |
4485 | | ITEM(TypeError), |
4486 | | ITEM(ValueError), |
4487 | | ITEM(Warning), |
4488 | | |
4489 | | // Level 4: ArithmeticError(Exception) subclasses |
4490 | | ITEM(FloatingPointError), |
4491 | | ITEM(OverflowError), |
4492 | | ITEM(ZeroDivisionError), |
4493 | | |
4494 | | // Level 4: Warning(Exception) subclasses |
4495 | | ITEM(BytesWarning), |
4496 | | ITEM(DeprecationWarning), |
4497 | | ITEM(EncodingWarning), |
4498 | | ITEM(FutureWarning), |
4499 | | ITEM(ImportWarning), |
4500 | | ITEM(PendingDeprecationWarning), |
4501 | | ITEM(ResourceWarning), |
4502 | | ITEM(RuntimeWarning), |
4503 | | ITEM(SyntaxWarning), |
4504 | | ITEM(UnicodeWarning), |
4505 | | ITEM(UserWarning), |
4506 | | |
4507 | | // Level 4: OSError(Exception) subclasses |
4508 | | ITEM(BlockingIOError), |
4509 | | ITEM(ChildProcessError), |
4510 | | ITEM(ConnectionError), |
4511 | | ITEM(FileExistsError), |
4512 | | ITEM(FileNotFoundError), |
4513 | | ITEM(InterruptedError), |
4514 | | ITEM(IsADirectoryError), |
4515 | | ITEM(NotADirectoryError), |
4516 | | ITEM(PermissionError), |
4517 | | ITEM(ProcessLookupError), |
4518 | | ITEM(TimeoutError), |
4519 | | |
4520 | | // Level 4: Other subclasses |
4521 | | ITEM(IndentationError), // base: SyntaxError(Exception) |
4522 | | {&_PyExc_IncompleteInputError, "_IncompleteInputError"}, // base: SyntaxError(Exception) |
4523 | | ITEM(IndexError), // base: LookupError(Exception) |
4524 | | ITEM(KeyError), // base: LookupError(Exception) |
4525 | | ITEM(ImportCycleError), // base: ImportError(Exception) |
4526 | | ITEM(ModuleNotFoundError), // base: ImportError(Exception) |
4527 | | ITEM(NotImplementedError), // base: RuntimeError(Exception) |
4528 | | ITEM(PythonFinalizationError), // base: RuntimeError(Exception) |
4529 | | ITEM(RecursionError), // base: RuntimeError(Exception) |
4530 | | ITEM(UnboundLocalError), // base: NameError(Exception) |
4531 | | ITEM(UnicodeError), // base: ValueError(Exception) |
4532 | | |
4533 | | // Level 5: ConnectionError(OSError) subclasses |
4534 | | ITEM(BrokenPipeError), |
4535 | | ITEM(ConnectionAbortedError), |
4536 | | ITEM(ConnectionRefusedError), |
4537 | | ITEM(ConnectionResetError), |
4538 | | |
4539 | | // Level 5: IndentationError(SyntaxError) subclasses |
4540 | | ITEM(TabError), // base: IndentationError |
4541 | | |
4542 | | // Level 5: UnicodeError(ValueError) subclasses |
4543 | | ITEM(UnicodeDecodeError), |
4544 | | ITEM(UnicodeEncodeError), |
4545 | | ITEM(UnicodeTranslateError), |
4546 | | #undef ITEM |
4547 | | }; |
4548 | | |
4549 | | |
4550 | | int |
4551 | | _PyExc_InitTypes(PyInterpreterState *interp) |
4552 | 37 | { |
4553 | 2.59k | for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) { |
4554 | 2.55k | PyTypeObject *exc = static_exceptions[i].exc; |
4555 | 2.55k | if (_PyStaticType_InitBuiltin(interp, exc) < 0) { |
4556 | 0 | return -1; |
4557 | 0 | } |
4558 | 2.55k | if (exc->tp_new == BaseException_new |
4559 | 1.88k | && exc->tp_init == BaseException_init) |
4560 | 1.33k | { |
4561 | 1.33k | exc->tp_vectorcall = BaseException_vectorcall; |
4562 | 1.33k | } |
4563 | 1.22k | else if (exc->tp_init == ImportError_init) { |
4564 | 111 | exc->tp_vectorcall = ImportError_vectorcall; |
4565 | 111 | } |
4566 | 1.11k | else if (exc->tp_init == NameError_init) { |
4567 | 74 | exc->tp_vectorcall = NameError_vectorcall; |
4568 | 74 | } |
4569 | 1.03k | else if (exc->tp_init == AttributeError_init) { |
4570 | 37 | exc->tp_vectorcall = AttributeError_vectorcall; |
4571 | 37 | } |
4572 | 2.55k | } |
4573 | 37 | return 0; |
4574 | 37 | } |
4575 | | |
4576 | | |
4577 | | static void |
4578 | | _PyExc_FiniTypes(PyInterpreterState *interp) |
4579 | 0 | { |
4580 | 0 | for (Py_ssize_t i=Py_ARRAY_LENGTH(static_exceptions) - 1; i >= 0; i--) { |
4581 | 0 | PyTypeObject *exc = static_exceptions[i].exc; |
4582 | 0 | _PyStaticType_FiniBuiltin(interp, exc); |
4583 | 0 | } |
4584 | 0 | } |
4585 | | |
4586 | | |
4587 | | PyStatus |
4588 | | _PyExc_InitGlobalObjects(PyInterpreterState *interp) |
4589 | 37 | { |
4590 | 37 | if (preallocate_memerrors() < 0) { |
4591 | 0 | return _PyStatus_NO_MEMORY(); |
4592 | 0 | } |
4593 | 37 | return _PyStatus_OK(); |
4594 | 37 | } |
4595 | | |
4596 | | PyStatus |
4597 | | _PyExc_InitState(PyInterpreterState *interp) |
4598 | 37 | { |
4599 | 37 | struct _Py_exc_state *state = &interp->exc_state; |
4600 | | |
4601 | 37 | #define ADD_ERRNO(TYPE, CODE) \ |
4602 | 703 | do { \ |
4603 | 703 | PyObject *_code = PyLong_FromLong(CODE); \ |
4604 | 703 | assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \ |
4605 | 703 | if (!_code || PyDict_SetItem(state->errnomap, _code, PyExc_ ## TYPE)) { \ |
4606 | 0 | Py_XDECREF(_code); \ |
4607 | 0 | return _PyStatus_ERR("errmap insertion problem."); \ |
4608 | 0 | } \ |
4609 | 703 | Py_DECREF(_code); \ |
4610 | 703 | } while (0) |
4611 | | |
4612 | | /* Add exceptions to errnomap */ |
4613 | 37 | assert(state->errnomap == NULL); |
4614 | 37 | state->errnomap = PyDict_New(); |
4615 | 37 | if (!state->errnomap) { |
4616 | 0 | return _PyStatus_NO_MEMORY(); |
4617 | 0 | } |
4618 | | |
4619 | 37 | ADD_ERRNO(BlockingIOError, EAGAIN); |
4620 | 37 | ADD_ERRNO(BlockingIOError, EALREADY); |
4621 | 37 | ADD_ERRNO(BlockingIOError, EINPROGRESS); |
4622 | 37 | ADD_ERRNO(BlockingIOError, EWOULDBLOCK); |
4623 | 37 | ADD_ERRNO(BrokenPipeError, EPIPE); |
4624 | 37 | #ifdef ESHUTDOWN |
4625 | 37 | ADD_ERRNO(BrokenPipeError, ESHUTDOWN); |
4626 | 37 | #endif |
4627 | 37 | ADD_ERRNO(ChildProcessError, ECHILD); |
4628 | 37 | ADD_ERRNO(ConnectionAbortedError, ECONNABORTED); |
4629 | 37 | ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED); |
4630 | 37 | ADD_ERRNO(ConnectionResetError, ECONNRESET); |
4631 | 37 | ADD_ERRNO(FileExistsError, EEXIST); |
4632 | 37 | ADD_ERRNO(FileNotFoundError, ENOENT); |
4633 | 37 | ADD_ERRNO(IsADirectoryError, EISDIR); |
4634 | 37 | ADD_ERRNO(NotADirectoryError, ENOTDIR); |
4635 | 37 | ADD_ERRNO(InterruptedError, EINTR); |
4636 | 37 | ADD_ERRNO(PermissionError, EACCES); |
4637 | 37 | ADD_ERRNO(PermissionError, EPERM); |
4638 | | #ifdef ENOTCAPABLE |
4639 | | // Extension for WASI capability-based security. Process lacks |
4640 | | // capability to access a resource. |
4641 | | ADD_ERRNO(PermissionError, ENOTCAPABLE); |
4642 | | #endif |
4643 | 37 | ADD_ERRNO(ProcessLookupError, ESRCH); |
4644 | 37 | ADD_ERRNO(TimeoutError, ETIMEDOUT); |
4645 | | #ifdef WSAETIMEDOUT |
4646 | | ADD_ERRNO(TimeoutError, WSAETIMEDOUT); |
4647 | | #endif |
4648 | | |
4649 | 37 | return _PyStatus_OK(); |
4650 | | |
4651 | 37 | #undef ADD_ERRNO |
4652 | 37 | } |
4653 | | |
4654 | | |
4655 | | /* Add exception types to the builtins module */ |
4656 | | int |
4657 | | _PyBuiltins_AddExceptions(PyObject *bltinmod) |
4658 | 37 | { |
4659 | 37 | PyObject *mod_dict = PyModule_GetDict(bltinmod); |
4660 | 37 | if (mod_dict == NULL) { |
4661 | 0 | return -1; |
4662 | 0 | } |
4663 | | |
4664 | 2.59k | for (size_t i=0; i < Py_ARRAY_LENGTH(static_exceptions); i++) { |
4665 | 2.55k | struct static_exception item = static_exceptions[i]; |
4666 | | |
4667 | 2.55k | if (PyDict_SetItemString(mod_dict, item.name, (PyObject*)item.exc)) { |
4668 | 0 | return -1; |
4669 | 0 | } |
4670 | 2.55k | } |
4671 | | |
4672 | 37 | PyObject *PyExc_ExceptionGroup = create_exception_group_class(); |
4673 | 37 | if (!PyExc_ExceptionGroup) { |
4674 | 0 | return -1; |
4675 | 0 | } |
4676 | 37 | if (PyDict_SetItemString(mod_dict, "ExceptionGroup", PyExc_ExceptionGroup)) { |
4677 | 0 | return -1; |
4678 | 0 | } |
4679 | 37 | if (PyDict_SetItemString(mod_dict, "EnvironmentError", PyExc_OSError)) { |
4680 | 0 | return -1; |
4681 | 0 | } |
4682 | 37 | if (PyDict_SetItemString(mod_dict, "IOError", PyExc_OSError)) { |
4683 | 0 | return -1; |
4684 | 0 | } |
4685 | | #ifdef MS_WINDOWS |
4686 | | if (PyDict_SetItemString(mod_dict, "WindowsError", PyExc_OSError)) { |
4687 | | return -1; |
4688 | | } |
4689 | | #endif |
4690 | 37 | return 0; |
4691 | 37 | } |
4692 | | |
4693 | | void |
4694 | | _PyExc_ClearExceptionGroupType(PyInterpreterState *interp) |
4695 | 0 | { |
4696 | 0 | struct _Py_exc_state *state = &interp->exc_state; |
4697 | 0 | Py_CLEAR(state->PyExc_ExceptionGroup); |
4698 | 0 | } |
4699 | | |
4700 | | void |
4701 | | _PyExc_Fini(PyInterpreterState *interp) |
4702 | 0 | { |
4703 | 0 | struct _Py_exc_state *state = &interp->exc_state; |
4704 | 0 | free_preallocated_memerrors(state); |
4705 | 0 | Py_CLEAR(state->errnomap); |
4706 | |
|
4707 | 0 | _PyExc_FiniTypes(interp); |
4708 | 0 | } |
4709 | | |
4710 | | int |
4711 | | _PyException_AddNote(PyObject *exc, PyObject *note) |
4712 | 53.6k | { |
4713 | 53.6k | if (!PyExceptionInstance_Check(exc)) { |
4714 | 0 | PyErr_Format(PyExc_TypeError, |
4715 | 0 | "exc must be an exception, not '%s'", |
4716 | 0 | Py_TYPE(exc)->tp_name); |
4717 | 0 | return -1; |
4718 | 0 | } |
4719 | 53.6k | PyObject *r = BaseException_add_note(exc, note); |
4720 | 53.6k | int res = r == NULL ? -1 : 0; |
4721 | 53.6k | Py_XDECREF(r); |
4722 | 53.6k | return res; |
4723 | 53.6k | } |