1
2 /* Error handling */
3
4 #include "Python.h"
5 #include "pycore_call.h" // _PyObject_CallNoArgs()
6 #include "pycore_initconfig.h" // _PyStatus_ERR()
7 #include "pycore_pyerrors.h" // _PyErr_Format()
8 #include "pycore_pystate.h" // _PyThreadState_GET()
9 #include "pycore_structseq.h" // _PyStructSequence_FiniBuiltin()
10 #include "pycore_sysmodule.h" // _PySys_Audit()
11 #include "pycore_traceback.h" // _PyTraceBack_FromFrame()
12
13 #ifdef MS_WINDOWS
14 # include <windows.h>
15 # include <winbase.h>
16 # include <stdlib.h> // _sys_nerr
17 #endif
18
19 /* Forward declarations */
20 static PyObject *
21 _PyErr_FormatV(PyThreadState *tstate, PyObject *exception,
22 const char *format, va_list vargs);
23
24 void
_PyErr_SetRaisedException(PyThreadState * tstate,PyObject * exc)25 _PyErr_SetRaisedException(PyThreadState *tstate, PyObject *exc)
26 {
27 PyObject *old_exc = tstate->current_exception;
28 tstate->current_exception = exc;
29 Py_XDECREF(old_exc);
30 }
31
32 static PyObject*
_PyErr_CreateException(PyObject * exception_type,PyObject * value)33 _PyErr_CreateException(PyObject *exception_type, PyObject *value)
34 {
35 PyObject *exc;
36
37 if (value == NULL || value == Py_None) {
38 exc = _PyObject_CallNoArgs(exception_type);
39 }
40 else if (PyTuple_Check(value)) {
41 exc = PyObject_Call(exception_type, value, NULL);
42 }
43 else {
44 exc = PyObject_CallOneArg(exception_type, value);
45 }
46
47 if (exc != NULL && !PyExceptionInstance_Check(exc)) {
48 PyErr_Format(PyExc_TypeError,
49 "calling %R should have returned an instance of "
50 "BaseException, not %s",
51 exception_type, Py_TYPE(exc)->tp_name);
52 Py_CLEAR(exc);
53 }
54
55 return exc;
56 }
57
58 void
_PyErr_Restore(PyThreadState * tstate,PyObject * type,PyObject * value,PyObject * traceback)59 _PyErr_Restore(PyThreadState *tstate, PyObject *type, PyObject *value,
60 PyObject *traceback)
61 {
62 if (type == NULL) {
63 assert(value == NULL);
64 assert(traceback == NULL);
65 _PyErr_SetRaisedException(tstate, NULL);
66 return;
67 }
68 assert(PyExceptionClass_Check(type));
69 if (value != NULL && type == (PyObject *)Py_TYPE(value)) {
70 /* Already normalized */
71 assert(((PyBaseExceptionObject *)value)->traceback != Py_None);
72 }
73 else {
74 PyObject *exc = _PyErr_CreateException(type, value);
75 Py_XDECREF(value);
76 if (exc == NULL) {
77 Py_DECREF(type);
78 Py_XDECREF(traceback);
79 return;
80 }
81 value = exc;
82 }
83 assert(PyExceptionInstance_Check(value));
84 if (traceback != NULL && !PyTraceBack_Check(traceback)) {
85 if (traceback == Py_None) {
86 Py_DECREF(Py_None);
87 traceback = NULL;
88 }
89 else {
90 PyErr_SetString(PyExc_TypeError, "traceback must be a Traceback or None");
91 Py_XDECREF(value);
92 Py_DECREF(type);
93 Py_XDECREF(traceback);
94 return;
95 }
96 }
97 PyObject *old_traceback = ((PyBaseExceptionObject *)value)->traceback;
98 ((PyBaseExceptionObject *)value)->traceback = traceback;
99 Py_XDECREF(old_traceback);
100 _PyErr_SetRaisedException(tstate, value);
101 Py_DECREF(type);
102 }
103
104 void
PyErr_Restore(PyObject * type,PyObject * value,PyObject * traceback)105 PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
106 {
107 PyThreadState *tstate = _PyThreadState_GET();
108 _PyErr_Restore(tstate, type, value, traceback);
109 }
110
111 void
PyErr_SetRaisedException(PyObject * exc)112 PyErr_SetRaisedException(PyObject *exc)
113 {
114 PyThreadState *tstate = _PyThreadState_GET();
115 _PyErr_SetRaisedException(tstate, exc);
116 }
117
118 _PyErr_StackItem *
_PyErr_GetTopmostException(PyThreadState * tstate)119 _PyErr_GetTopmostException(PyThreadState *tstate)
120 {
121 _PyErr_StackItem *exc_info = tstate->exc_info;
122 assert(exc_info);
123
124 while (exc_info->exc_value == NULL && exc_info->previous_item != NULL)
125 {
126 exc_info = exc_info->previous_item;
127 }
128 assert(!Py_IsNone(exc_info->exc_value));
129 return exc_info;
130 }
131
132 static PyObject *
get_normalization_failure_note(PyThreadState * tstate,PyObject * exception,PyObject * value)133 get_normalization_failure_note(PyThreadState *tstate, PyObject *exception, PyObject *value)
134 {
135 PyObject *args = PyObject_Repr(value);
136 if (args == NULL) {
137 _PyErr_Clear(tstate);
138 args = PyUnicode_FromFormat("<unknown>");
139 }
140 PyObject *note;
141 const char *tpname = ((PyTypeObject*)exception)->tp_name;
142 if (args == NULL) {
143 _PyErr_Clear(tstate);
144 note = PyUnicode_FromFormat("Normalization failed: type=%s", tpname);
145 }
146 else {
147 note = PyUnicode_FromFormat("Normalization failed: type=%s args=%S",
148 tpname, args);
149 Py_DECREF(args);
150 }
151 return note;
152 }
153
154 void
_PyErr_SetObject(PyThreadState * tstate,PyObject * exception,PyObject * value)155 _PyErr_SetObject(PyThreadState *tstate, PyObject *exception, PyObject *value)
156 {
157 PyObject *exc_value;
158 PyObject *tb = NULL;
159
160 if (exception != NULL &&
161 !PyExceptionClass_Check(exception)) {
162 _PyErr_Format(tstate, PyExc_SystemError,
163 "_PyErr_SetObject: "
164 "exception %R is not a BaseException subclass",
165 exception);
166 return;
167 }
168 /* Normalize the exception */
169 int is_subclass = 0;
170 if (value != NULL && PyExceptionInstance_Check(value)) {
171 is_subclass = PyObject_IsSubclass((PyObject *)Py_TYPE(value), exception);
172 if (is_subclass < 0) {
173 return;
174 }
175 }
176 Py_XINCREF(value);
177 if (!is_subclass) {
178 /* We must normalize the value right now */
179
180 /* Issue #23571: functions must not be called with an
181 exception set */
182 _PyErr_Clear(tstate);
183
184 PyObject *fixed_value = _PyErr_CreateException(exception, value);
185 if (fixed_value == NULL) {
186 PyObject *exc = _PyErr_GetRaisedException(tstate);
187 assert(PyExceptionInstance_Check(exc));
188
189 PyObject *note = get_normalization_failure_note(tstate, exception, value);
190 Py_XDECREF(value);
191 if (note != NULL) {
192 /* ignore errors in _PyException_AddNote - they will be overwritten below */
193 _PyException_AddNote(exc, note);
194 Py_DECREF(note);
195 }
196 _PyErr_SetRaisedException(tstate, exc);
197 return;
198 }
199 Py_XSETREF(value, fixed_value);
200 }
201
202 exc_value = _PyErr_GetTopmostException(tstate)->exc_value;
203 if (exc_value != NULL && exc_value != Py_None) {
204 /* Implicit exception chaining */
205 Py_INCREF(exc_value);
206 /* Avoid creating new reference cycles through the
207 context chain, while taking care not to hang on
208 pre-existing ones.
209 This is O(chain length) but context chains are
210 usually very short. Sensitive readers may try
211 to inline the call to PyException_GetContext. */
212 if (exc_value != value) {
213 PyObject *o = exc_value, *context;
214 PyObject *slow_o = o; /* Floyd's cycle detection algo */
215 int slow_update_toggle = 0;
216 while ((context = PyException_GetContext(o))) {
217 Py_DECREF(context);
218 if (context == value) {
219 PyException_SetContext(o, NULL);
220 break;
221 }
222 o = context;
223 if (o == slow_o) {
224 /* pre-existing cycle - all exceptions on the
225 path were visited and checked. */
226 break;
227 }
228 if (slow_update_toggle) {
229 slow_o = PyException_GetContext(slow_o);
230 Py_DECREF(slow_o);
231 }
232 slow_update_toggle = !slow_update_toggle;
233 }
234 PyException_SetContext(value, exc_value);
235 }
236 else {
237 Py_DECREF(exc_value);
238 }
239 }
240 assert(value != NULL);
241 if (PyExceptionInstance_Check(value))
242 tb = PyException_GetTraceback(value);
243 _PyErr_Restore(tstate, Py_NewRef(Py_TYPE(value)), value, tb);
244 }
245
246 void
PyErr_SetObject(PyObject * exception,PyObject * value)247 PyErr_SetObject(PyObject *exception, PyObject *value)
248 {
249 PyThreadState *tstate = _PyThreadState_GET();
250 _PyErr_SetObject(tstate, exception, value);
251 }
252
253 /* Set a key error with the specified argument, wrapping it in a
254 * tuple automatically so that tuple keys are not unpacked as the
255 * exception arguments. */
256 void
_PyErr_SetKeyError(PyObject * arg)257 _PyErr_SetKeyError(PyObject *arg)
258 {
259 PyThreadState *tstate = _PyThreadState_GET();
260 PyObject *tup = PyTuple_Pack(1, arg);
261 if (!tup) {
262 /* caller will expect error to be set anyway */
263 return;
264 }
265 _PyErr_SetObject(tstate, PyExc_KeyError, tup);
266 Py_DECREF(tup);
267 }
268
269 void
_PyErr_SetNone(PyThreadState * tstate,PyObject * exception)270 _PyErr_SetNone(PyThreadState *tstate, PyObject *exception)
271 {
272 _PyErr_SetObject(tstate, exception, (PyObject *)NULL);
273 }
274
275
276 void
PyErr_SetNone(PyObject * exception)277 PyErr_SetNone(PyObject *exception)
278 {
279 PyThreadState *tstate = _PyThreadState_GET();
280 _PyErr_SetNone(tstate, exception);
281 }
282
283
284 void
_PyErr_SetString(PyThreadState * tstate,PyObject * exception,const char * string)285 _PyErr_SetString(PyThreadState *tstate, PyObject *exception,
286 const char *string)
287 {
288 PyObject *value = PyUnicode_FromString(string);
289 if (value != NULL) {
290 _PyErr_SetObject(tstate, exception, value);
291 Py_DECREF(value);
292 }
293 }
294
295 void
PyErr_SetString(PyObject * exception,const char * string)296 PyErr_SetString(PyObject *exception, const char *string)
297 {
298 PyThreadState *tstate = _PyThreadState_GET();
299 _PyErr_SetString(tstate, exception, string);
300 }
301
302
303 PyObject* _Py_HOT_FUNCTION
PyErr_Occurred(void)304 PyErr_Occurred(void)
305 {
306 /* The caller must hold the GIL. */
307 assert(PyGILState_Check());
308
309 PyThreadState *tstate = _PyThreadState_GET();
310 return _PyErr_Occurred(tstate);
311 }
312
313
314 int
PyErr_GivenExceptionMatches(PyObject * err,PyObject * exc)315 PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
316 {
317 if (err == NULL || exc == NULL) {
318 /* maybe caused by "import exceptions" that failed early on */
319 return 0;
320 }
321 if (PyTuple_Check(exc)) {
322 Py_ssize_t i, n;
323 n = PyTuple_Size(exc);
324 for (i = 0; i < n; i++) {
325 /* Test recursively */
326 if (PyErr_GivenExceptionMatches(
327 err, PyTuple_GET_ITEM(exc, i)))
328 {
329 return 1;
330 }
331 }
332 return 0;
333 }
334 /* err might be an instance, so check its class. */
335 if (PyExceptionInstance_Check(err))
336 err = PyExceptionInstance_Class(err);
337
338 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
339 return PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
340 }
341
342 return err == exc;
343 }
344
345
346 int
_PyErr_ExceptionMatches(PyThreadState * tstate,PyObject * exc)347 _PyErr_ExceptionMatches(PyThreadState *tstate, PyObject *exc)
348 {
349 return PyErr_GivenExceptionMatches(_PyErr_Occurred(tstate), exc);
350 }
351
352
353 int
PyErr_ExceptionMatches(PyObject * exc)354 PyErr_ExceptionMatches(PyObject *exc)
355 {
356 PyThreadState *tstate = _PyThreadState_GET();
357 return _PyErr_ExceptionMatches(tstate, exc);
358 }
359
360
361 #ifndef Py_NORMALIZE_RECURSION_LIMIT
362 #define Py_NORMALIZE_RECURSION_LIMIT 32
363 #endif
364
365 /* Used in many places to normalize a raised exception, including in
366 eval_code2(), do_raise(), and PyErr_Print()
367
368 XXX: should PyErr_NormalizeException() also call
369 PyException_SetTraceback() with the resulting value and tb?
370 */
371 void
_PyErr_NormalizeException(PyThreadState * tstate,PyObject ** exc,PyObject ** val,PyObject ** tb)372 _PyErr_NormalizeException(PyThreadState *tstate, PyObject **exc,
373 PyObject **val, PyObject **tb)
374 {
375 int recursion_depth = 0;
376 tstate->recursion_headroom++;
377 PyObject *type, *value, *initial_tb;
378
379 restart:
380 type = *exc;
381 if (type == NULL) {
382 /* There was no exception, so nothing to do. */
383 tstate->recursion_headroom--;
384 return;
385 }
386
387 value = *val;
388 /* If PyErr_SetNone() was used, the value will have been actually
389 set to NULL.
390 */
391 if (!value) {
392 value = Py_NewRef(Py_None);
393 }
394
395 /* Normalize the exception so that if the type is a class, the
396 value will be an instance.
397 */
398 if (PyExceptionClass_Check(type)) {
399 PyObject *inclass = NULL;
400 int is_subclass = 0;
401
402 if (PyExceptionInstance_Check(value)) {
403 inclass = PyExceptionInstance_Class(value);
404 is_subclass = PyObject_IsSubclass(inclass, type);
405 if (is_subclass < 0) {
406 goto error;
407 }
408 }
409
410 /* If the value was not an instance, or is not an instance
411 whose class is (or is derived from) type, then use the
412 value as an argument to instantiation of the type
413 class.
414 */
415 if (!is_subclass) {
416 PyObject *fixed_value = _PyErr_CreateException(type, value);
417 if (fixed_value == NULL) {
418 goto error;
419 }
420 Py_SETREF(value, fixed_value);
421 }
422 /* If the class of the instance doesn't exactly match the
423 class of the type, believe the instance.
424 */
425 else if (inclass != type) {
426 Py_SETREF(type, Py_NewRef(inclass));
427 }
428 }
429 *exc = type;
430 *val = value;
431 tstate->recursion_headroom--;
432 return;
433
434 error:
435 Py_DECREF(type);
436 Py_DECREF(value);
437 recursion_depth++;
438 if (recursion_depth == Py_NORMALIZE_RECURSION_LIMIT) {
439 _PyErr_SetString(tstate, PyExc_RecursionError,
440 "maximum recursion depth exceeded "
441 "while normalizing an exception");
442 }
443 /* If the new exception doesn't set a traceback and the old
444 exception had a traceback, use the old traceback for the
445 new exception. It's better than nothing.
446 */
447 initial_tb = *tb;
448 _PyErr_Fetch(tstate, exc, val, tb);
449 assert(*exc != NULL);
450 if (initial_tb != NULL) {
451 if (*tb == NULL)
452 *tb = initial_tb;
453 else
454 Py_DECREF(initial_tb);
455 }
456 /* Abort when Py_NORMALIZE_RECURSION_LIMIT has been exceeded, and the
457 corresponding RecursionError could not be normalized, and the
458 MemoryError raised when normalize this RecursionError could not be
459 normalized. */
460 if (recursion_depth >= Py_NORMALIZE_RECURSION_LIMIT + 2) {
461 if (PyErr_GivenExceptionMatches(*exc, PyExc_MemoryError)) {
462 Py_FatalError("Cannot recover from MemoryErrors "
463 "while normalizing exceptions.");
464 }
465 else {
466 Py_FatalError("Cannot recover from the recursive normalization "
467 "of an exception.");
468 }
469 }
470 goto restart;
471 }
472
473
474 void
PyErr_NormalizeException(PyObject ** exc,PyObject ** val,PyObject ** tb)475 PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
476 {
477 PyThreadState *tstate = _PyThreadState_GET();
478 _PyErr_NormalizeException(tstate, exc, val, tb);
479 }
480
481
482 PyObject *
_PyErr_GetRaisedException(PyThreadState * tstate)483 _PyErr_GetRaisedException(PyThreadState *tstate) {
484 PyObject *exc = tstate->current_exception;
485 tstate->current_exception = NULL;
486 return exc;
487 }
488
489 PyObject *
PyErr_GetRaisedException(void)490 PyErr_GetRaisedException(void)
491 {
492 PyThreadState *tstate = _PyThreadState_GET();
493 return _PyErr_GetRaisedException(tstate);
494 }
495
496 void
_PyErr_Fetch(PyThreadState * tstate,PyObject ** p_type,PyObject ** p_value,PyObject ** p_traceback)497 _PyErr_Fetch(PyThreadState *tstate, PyObject **p_type, PyObject **p_value,
498 PyObject **p_traceback)
499 {
500 PyObject *exc = _PyErr_GetRaisedException(tstate);
501 *p_value = exc;
502 if (exc == NULL) {
503 *p_type = NULL;
504 *p_traceback = NULL;
505 }
506 else {
507 *p_type = Py_NewRef(Py_TYPE(exc));
508 *p_traceback = Py_XNewRef(((PyBaseExceptionObject *)exc)->traceback);
509 }
510 }
511
512
513 void
PyErr_Fetch(PyObject ** p_type,PyObject ** p_value,PyObject ** p_traceback)514 PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
515 {
516 PyThreadState *tstate = _PyThreadState_GET();
517 _PyErr_Fetch(tstate, p_type, p_value, p_traceback);
518 }
519
520
521 void
_PyErr_Clear(PyThreadState * tstate)522 _PyErr_Clear(PyThreadState *tstate)
523 {
524 _PyErr_Restore(tstate, NULL, NULL, NULL);
525 }
526
527
528 void
PyErr_Clear(void)529 PyErr_Clear(void)
530 {
531 PyThreadState *tstate = _PyThreadState_GET();
532 _PyErr_Clear(tstate);
533 }
534
535 static PyObject*
get_exc_type(PyObject * exc_value)536 get_exc_type(PyObject *exc_value) /* returns a borrowed ref */
537 {
538 if (exc_value == NULL || exc_value == Py_None) {
539 return Py_None;
540 }
541 else {
542 assert(PyExceptionInstance_Check(exc_value));
543 PyObject *type = PyExceptionInstance_Class(exc_value);
544 assert(type != NULL);
545 return type;
546 }
547 }
548
549 static PyObject*
get_exc_traceback(PyObject * exc_value)550 get_exc_traceback(PyObject *exc_value) /* returns a borrowed ref */
551 {
552 if (exc_value == NULL || exc_value == Py_None) {
553 return Py_None;
554 }
555 else {
556 assert(PyExceptionInstance_Check(exc_value));
557 PyObject *tb = PyException_GetTraceback(exc_value);
558 Py_XDECREF(tb);
559 return tb ? tb : Py_None;
560 }
561 }
562
563 void
_PyErr_GetExcInfo(PyThreadState * tstate,PyObject ** p_type,PyObject ** p_value,PyObject ** p_traceback)564 _PyErr_GetExcInfo(PyThreadState *tstate,
565 PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
566 {
567 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
568
569 *p_type = Py_XNewRef(get_exc_type(exc_info->exc_value));
570 *p_value = Py_XNewRef(exc_info->exc_value);
571 *p_traceback = Py_XNewRef(get_exc_traceback(exc_info->exc_value));
572 }
573
574 PyObject*
_PyErr_GetHandledException(PyThreadState * tstate)575 _PyErr_GetHandledException(PyThreadState *tstate)
576 {
577 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
578 PyObject *exc = exc_info->exc_value;
579 if (exc == NULL || exc == Py_None) {
580 return NULL;
581 }
582 return Py_NewRef(exc);
583 }
584
585 PyObject*
PyErr_GetHandledException(void)586 PyErr_GetHandledException(void)
587 {
588 PyThreadState *tstate = _PyThreadState_GET();
589 return _PyErr_GetHandledException(tstate);
590 }
591
592 void
_PyErr_SetHandledException(PyThreadState * tstate,PyObject * exc)593 _PyErr_SetHandledException(PyThreadState *tstate, PyObject *exc)
594 {
595 Py_XSETREF(tstate->exc_info->exc_value, Py_XNewRef(exc == Py_None ? NULL : exc));
596 }
597
598 void
PyErr_SetHandledException(PyObject * exc)599 PyErr_SetHandledException(PyObject *exc)
600 {
601 PyThreadState *tstate = _PyThreadState_GET();
602 _PyErr_SetHandledException(tstate, exc);
603 }
604
605 void
PyErr_GetExcInfo(PyObject ** p_type,PyObject ** p_value,PyObject ** p_traceback)606 PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
607 {
608 PyThreadState *tstate = _PyThreadState_GET();
609 _PyErr_GetExcInfo(tstate, p_type, p_value, p_traceback);
610 }
611
612 void
PyErr_SetExcInfo(PyObject * type,PyObject * value,PyObject * traceback)613 PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
614 {
615 PyErr_SetHandledException(value);
616 Py_XDECREF(value);
617 /* These args are no longer used, but we still need to steal a ref */
618 Py_XDECREF(type);
619 Py_XDECREF(traceback);
620 }
621
622
623 PyObject*
_PyErr_StackItemToExcInfoTuple(_PyErr_StackItem * err_info)624 _PyErr_StackItemToExcInfoTuple(_PyErr_StackItem *err_info)
625 {
626 PyObject *exc_value = err_info->exc_value;
627
628 assert(exc_value == NULL ||
629 exc_value == Py_None ||
630 PyExceptionInstance_Check(exc_value));
631
632 PyObject *exc_type = get_exc_type(exc_value);
633 PyObject *exc_traceback = get_exc_traceback(exc_value);
634
635 return PyTuple_Pack(
636 3,
637 exc_type ? exc_type : Py_None,
638 exc_value ? exc_value : Py_None,
639 exc_traceback ? exc_traceback : Py_None);
640 }
641
642
643 /* Like PyErr_Restore(), but if an exception is already set,
644 set the context associated with it.
645
646 The caller is responsible for ensuring that this call won't create
647 any cycles in the exception context chain. */
648 void
_PyErr_ChainExceptions(PyObject * typ,PyObject * val,PyObject * tb)649 _PyErr_ChainExceptions(PyObject *typ, PyObject *val, PyObject *tb)
650 {
651 if (typ == NULL)
652 return;
653
654 PyThreadState *tstate = _PyThreadState_GET();
655
656 if (!PyExceptionClass_Check(typ)) {
657 _PyErr_Format(tstate, PyExc_SystemError,
658 "_PyErr_ChainExceptions: "
659 "exception %R is not a BaseException subclass",
660 typ);
661 return;
662 }
663
664 if (_PyErr_Occurred(tstate)) {
665 _PyErr_NormalizeException(tstate, &typ, &val, &tb);
666 if (tb != NULL) {
667 PyException_SetTraceback(val, tb);
668 Py_DECREF(tb);
669 }
670 Py_DECREF(typ);
671 PyObject *exc2 = _PyErr_GetRaisedException(tstate);
672 PyException_SetContext(exc2, val);
673 _PyErr_SetRaisedException(tstate, exc2);
674 }
675 else {
676 _PyErr_Restore(tstate, typ, val, tb);
677 }
678 }
679
680 /* Like PyErr_SetRaisedException(), but if an exception is already set,
681 set the context associated with it.
682
683 The caller is responsible for ensuring that this call won't create
684 any cycles in the exception context chain. */
685 void
_PyErr_ChainExceptions1(PyObject * exc)686 _PyErr_ChainExceptions1(PyObject *exc)
687 {
688 if (exc == NULL) {
689 return;
690 }
691 PyThreadState *tstate = _PyThreadState_GET();
692 if (_PyErr_Occurred(tstate)) {
693 PyObject *exc2 = _PyErr_GetRaisedException(tstate);
694 PyException_SetContext(exc2, exc);
695 _PyErr_SetRaisedException(tstate, exc2);
696 }
697 else {
698 _PyErr_SetRaisedException(tstate, exc);
699 }
700 }
701
702 /* If the current thread is handling an exception (exc_info is ), set this
703 exception as the context of the current raised exception.
704
705 This function can only be called when _PyErr_Occurred() is true.
706 Also, this function won't create any cycles in the exception context
707 chain to the extent that _PyErr_SetObject ensures this. */
708 void
_PyErr_ChainStackItem(void)709 _PyErr_ChainStackItem(void)
710 {
711 PyThreadState *tstate = _PyThreadState_GET();
712 assert(_PyErr_Occurred(tstate));
713
714 _PyErr_StackItem *exc_info = tstate->exc_info;
715 if (exc_info->exc_value == NULL || exc_info->exc_value == Py_None) {
716 return;
717 }
718
719 PyObject *exc = _PyErr_GetRaisedException(tstate);
720
721 /* _PyErr_SetObject sets the context from PyThreadState. */
722 _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(exc), exc);
723 Py_DECREF(exc); // since _PyErr_Occurred was true
724 }
725
726 static PyObject *
_PyErr_FormatVFromCause(PyThreadState * tstate,PyObject * exception,const char * format,va_list vargs)727 _PyErr_FormatVFromCause(PyThreadState *tstate, PyObject *exception,
728 const char *format, va_list vargs)
729 {
730 assert(_PyErr_Occurred(tstate));
731 PyObject *exc = _PyErr_GetRaisedException(tstate);
732 assert(!_PyErr_Occurred(tstate));
733 _PyErr_FormatV(tstate, exception, format, vargs);
734 PyObject *exc2 = _PyErr_GetRaisedException(tstate);
735 PyException_SetCause(exc2, Py_NewRef(exc));
736 PyException_SetContext(exc2, Py_NewRef(exc));
737 Py_DECREF(exc);
738 _PyErr_SetRaisedException(tstate, exc2);
739 return NULL;
740 }
741
742 PyObject *
_PyErr_FormatFromCauseTstate(PyThreadState * tstate,PyObject * exception,const char * format,...)743 _PyErr_FormatFromCauseTstate(PyThreadState *tstate, PyObject *exception,
744 const char *format, ...)
745 {
746 va_list vargs;
747 va_start(vargs, format);
748 _PyErr_FormatVFromCause(tstate, exception, format, vargs);
749 va_end(vargs);
750 return NULL;
751 }
752
753 PyObject *
_PyErr_FormatFromCause(PyObject * exception,const char * format,...)754 _PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
755 {
756 PyThreadState *tstate = _PyThreadState_GET();
757 va_list vargs;
758 va_start(vargs, format);
759 _PyErr_FormatVFromCause(tstate, exception, format, vargs);
760 va_end(vargs);
761 return NULL;
762 }
763
764 /* Convenience functions to set a type error exception and return 0 */
765
766 int
PyErr_BadArgument(void)767 PyErr_BadArgument(void)
768 {
769 PyThreadState *tstate = _PyThreadState_GET();
770 _PyErr_SetString(tstate, PyExc_TypeError,
771 "bad argument type for built-in operation");
772 return 0;
773 }
774
775 PyObject *
PyErr_NoMemory(void)776 PyErr_NoMemory(void)
777 {
778 PyThreadState *tstate = _PyThreadState_GET();
779 return _PyErr_NoMemory(tstate);
780 }
781
782 PyObject *
PyErr_SetFromErrnoWithFilenameObject(PyObject * exc,PyObject * filenameObject)783 PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
784 {
785 return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
786 }
787
788 PyObject *
PyErr_SetFromErrnoWithFilenameObjects(PyObject * exc,PyObject * filenameObject,PyObject * filenameObject2)789 PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
790 {
791 PyThreadState *tstate = _PyThreadState_GET();
792 PyObject *message;
793 PyObject *v, *args;
794 int i = errno;
795 #ifdef MS_WINDOWS
796 WCHAR *s_buf = NULL;
797 #endif /* Unix/Windows */
798
799 #ifdef EINTR
800 if (i == EINTR && PyErr_CheckSignals())
801 return NULL;
802 #endif
803
804 #ifndef MS_WINDOWS
805 if (i != 0) {
806 const char *s = strerror(i);
807 message = PyUnicode_DecodeLocale(s, "surrogateescape");
808 }
809 else {
810 /* Sometimes errno didn't get set */
811 message = PyUnicode_FromString("Error");
812 }
813 #else
814 if (i == 0)
815 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
816 else
817 {
818 /* Note that the Win32 errors do not lineup with the
819 errno error. So if the error is in the MSVC error
820 table, we use it, otherwise we assume it really _is_
821 a Win32 error code
822 */
823 if (i > 0 && i < _sys_nerr) {
824 message = PyUnicode_FromString(_sys_errlist[i]);
825 }
826 else {
827 int len = FormatMessageW(
828 FORMAT_MESSAGE_ALLOCATE_BUFFER |
829 FORMAT_MESSAGE_FROM_SYSTEM |
830 FORMAT_MESSAGE_IGNORE_INSERTS,
831 NULL, /* no message source */
832 i,
833 MAKELANGID(LANG_NEUTRAL,
834 SUBLANG_DEFAULT),
835 /* Default language */
836 (LPWSTR) &s_buf,
837 0, /* size not used */
838 NULL); /* no args */
839 if (len==0) {
840 /* Only ever seen this in out-of-mem
841 situations */
842 s_buf = NULL;
843 message = PyUnicode_FromFormat("Windows Error 0x%x", i);
844 } else {
845 /* remove trailing cr/lf and dots */
846 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
847 s_buf[--len] = L'\0';
848 message = PyUnicode_FromWideChar(s_buf, len);
849 }
850 }
851 }
852 #endif /* Unix/Windows */
853
854 if (message == NULL)
855 {
856 #ifdef MS_WINDOWS
857 LocalFree(s_buf);
858 #endif
859 return NULL;
860 }
861
862 if (filenameObject != NULL) {
863 if (filenameObject2 != NULL)
864 args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
865 else
866 args = Py_BuildValue("(iOO)", i, message, filenameObject);
867 } else {
868 assert(filenameObject2 == NULL);
869 args = Py_BuildValue("(iO)", i, message);
870 }
871 Py_DECREF(message);
872
873 if (args != NULL) {
874 v = PyObject_Call(exc, args, NULL);
875 Py_DECREF(args);
876 if (v != NULL) {
877 _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(v), v);
878 Py_DECREF(v);
879 }
880 }
881 #ifdef MS_WINDOWS
882 LocalFree(s_buf);
883 #endif
884 return NULL;
885 }
886
887 PyObject *
PyErr_SetFromErrnoWithFilename(PyObject * exc,const char * filename)888 PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
889 {
890 PyObject *name = NULL;
891 if (filename) {
892 int i = errno;
893 name = PyUnicode_DecodeFSDefault(filename);
894 if (name == NULL) {
895 return NULL;
896 }
897 errno = i;
898 }
899 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
900 Py_XDECREF(name);
901 return result;
902 }
903
904 PyObject *
PyErr_SetFromErrno(PyObject * exc)905 PyErr_SetFromErrno(PyObject *exc)
906 {
907 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
908 }
909
910 #ifdef MS_WINDOWS
911 /* Windows specific error code handling */
PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject * exc,int ierr,PyObject * filenameObject)912 PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
913 PyObject *exc,
914 int ierr,
915 PyObject *filenameObject)
916 {
917 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
918 filenameObject, NULL);
919 }
920
PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject * exc,int ierr,PyObject * filenameObject,PyObject * filenameObject2)921 PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
922 PyObject *exc,
923 int ierr,
924 PyObject *filenameObject,
925 PyObject *filenameObject2)
926 {
927 PyThreadState *tstate = _PyThreadState_GET();
928 int len;
929 WCHAR *s_buf = NULL; /* Free via LocalFree */
930 PyObject *message;
931 PyObject *args, *v;
932
933 DWORD err = (DWORD)ierr;
934 if (err==0) {
935 err = GetLastError();
936 }
937
938 len = FormatMessageW(
939 /* Error API error */
940 FORMAT_MESSAGE_ALLOCATE_BUFFER |
941 FORMAT_MESSAGE_FROM_SYSTEM |
942 FORMAT_MESSAGE_IGNORE_INSERTS,
943 NULL, /* no message source */
944 err,
945 MAKELANGID(LANG_NEUTRAL,
946 SUBLANG_DEFAULT), /* Default language */
947 (LPWSTR) &s_buf,
948 0, /* size not used */
949 NULL); /* no args */
950 if (len==0) {
951 /* Only seen this in out of mem situations */
952 message = PyUnicode_FromFormat("Windows Error 0x%x", err);
953 s_buf = NULL;
954 } else {
955 /* remove trailing cr/lf and dots */
956 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
957 s_buf[--len] = L'\0';
958 message = PyUnicode_FromWideChar(s_buf, len);
959 }
960
961 if (message == NULL)
962 {
963 LocalFree(s_buf);
964 return NULL;
965 }
966
967 if (filenameObject == NULL) {
968 assert(filenameObject2 == NULL);
969 filenameObject = filenameObject2 = Py_None;
970 }
971 else if (filenameObject2 == NULL)
972 filenameObject2 = Py_None;
973 /* This is the constructor signature for OSError.
974 The POSIX translation will be figured out by the constructor. */
975 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
976 Py_DECREF(message);
977
978 if (args != NULL) {
979 v = PyObject_Call(exc, args, NULL);
980 Py_DECREF(args);
981 if (v != NULL) {
982 _PyErr_SetObject(tstate, (PyObject *) Py_TYPE(v), v);
983 Py_DECREF(v);
984 }
985 }
986 LocalFree(s_buf);
987 return NULL;
988 }
989
PyErr_SetExcFromWindowsErrWithFilename(PyObject * exc,int ierr,const char * filename)990 PyObject *PyErr_SetExcFromWindowsErrWithFilename(
991 PyObject *exc,
992 int ierr,
993 const char *filename)
994 {
995 PyObject *name = NULL;
996 if (filename) {
997 if ((DWORD)ierr == 0) {
998 ierr = (int)GetLastError();
999 }
1000 name = PyUnicode_DecodeFSDefault(filename);
1001 if (name == NULL) {
1002 return NULL;
1003 }
1004 }
1005 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
1006 ierr,
1007 name,
1008 NULL);
1009 Py_XDECREF(name);
1010 return ret;
1011 }
1012
PyErr_SetExcFromWindowsErr(PyObject * exc,int ierr)1013 PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
1014 {
1015 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
1016 }
1017
PyErr_SetFromWindowsErr(int ierr)1018 PyObject *PyErr_SetFromWindowsErr(int ierr)
1019 {
1020 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
1021 ierr, NULL);
1022 }
1023
PyErr_SetFromWindowsErrWithFilename(int ierr,const char * filename)1024 PyObject *PyErr_SetFromWindowsErrWithFilename(
1025 int ierr,
1026 const char *filename)
1027 {
1028 PyObject *name = NULL;
1029 if (filename) {
1030 if ((DWORD)ierr == 0) {
1031 ierr = (int)GetLastError();
1032 }
1033 name = PyUnicode_DecodeFSDefault(filename);
1034 if (name == NULL) {
1035 return NULL;
1036 }
1037 }
1038 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
1039 PyExc_OSError,
1040 ierr, name, NULL);
1041 Py_XDECREF(name);
1042 return result;
1043 }
1044
1045 #endif /* MS_WINDOWS */
1046
1047 static PyObject *
_PyErr_SetImportErrorSubclassWithNameFrom(PyObject * exception,PyObject * msg,PyObject * name,PyObject * path,PyObject * from_name)1048 _PyErr_SetImportErrorSubclassWithNameFrom(
1049 PyObject *exception, PyObject *msg,
1050 PyObject *name, PyObject *path, PyObject* from_name)
1051 {
1052 PyThreadState *tstate = _PyThreadState_GET();
1053 int issubclass;
1054 PyObject *kwargs, *error;
1055
1056 issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
1057 if (issubclass < 0) {
1058 return NULL;
1059 }
1060 else if (!issubclass) {
1061 _PyErr_SetString(tstate, PyExc_TypeError,
1062 "expected a subclass of ImportError");
1063 return NULL;
1064 }
1065
1066 if (msg == NULL) {
1067 _PyErr_SetString(tstate, PyExc_TypeError,
1068 "expected a message argument");
1069 return NULL;
1070 }
1071
1072 if (name == NULL) {
1073 name = Py_None;
1074 }
1075 if (path == NULL) {
1076 path = Py_None;
1077 }
1078 if (from_name == NULL) {
1079 from_name = Py_None;
1080 }
1081
1082
1083 kwargs = PyDict_New();
1084 if (kwargs == NULL) {
1085 return NULL;
1086 }
1087 if (PyDict_SetItemString(kwargs, "name", name) < 0) {
1088 goto done;
1089 }
1090 if (PyDict_SetItemString(kwargs, "path", path) < 0) {
1091 goto done;
1092 }
1093 if (PyDict_SetItemString(kwargs, "name_from", from_name) < 0) {
1094 goto done;
1095 }
1096
1097 error = PyObject_VectorcallDict(exception, &msg, 1, kwargs);
1098 if (error != NULL) {
1099 _PyErr_SetObject(tstate, (PyObject *)Py_TYPE(error), error);
1100 Py_DECREF(error);
1101 }
1102
1103 done:
1104 Py_DECREF(kwargs);
1105 return NULL;
1106 }
1107
1108
1109 PyObject *
PyErr_SetImportErrorSubclass(PyObject * exception,PyObject * msg,PyObject * name,PyObject * path)1110 PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
1111 PyObject *name, PyObject *path)
1112 {
1113 return _PyErr_SetImportErrorSubclassWithNameFrom(exception, msg, name, path, NULL);
1114 }
1115
1116 PyObject *
_PyErr_SetImportErrorWithNameFrom(PyObject * msg,PyObject * name,PyObject * path,PyObject * from_name)1117 _PyErr_SetImportErrorWithNameFrom(PyObject *msg, PyObject *name, PyObject *path, PyObject* from_name)
1118 {
1119 return _PyErr_SetImportErrorSubclassWithNameFrom(PyExc_ImportError, msg, name, path, from_name);
1120 }
1121
1122 PyObject *
PyErr_SetImportError(PyObject * msg,PyObject * name,PyObject * path)1123 PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
1124 {
1125 return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
1126 }
1127
1128 void
_PyErr_BadInternalCall(const char * filename,int lineno)1129 _PyErr_BadInternalCall(const char *filename, int lineno)
1130 {
1131 PyThreadState *tstate = _PyThreadState_GET();
1132 _PyErr_Format(tstate, PyExc_SystemError,
1133 "%s:%d: bad argument to internal function",
1134 filename, lineno);
1135 }
1136
1137 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
1138 export the entry point for existing object code: */
1139 #undef PyErr_BadInternalCall
1140 void
PyErr_BadInternalCall(void)1141 PyErr_BadInternalCall(void)
1142 {
1143 assert(0 && "bad argument to internal function");
1144 PyThreadState *tstate = _PyThreadState_GET();
1145 _PyErr_SetString(tstate, PyExc_SystemError,
1146 "bad argument to internal function");
1147 }
1148 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
1149
1150
1151 static PyObject *
_PyErr_FormatV(PyThreadState * tstate,PyObject * exception,const char * format,va_list vargs)1152 _PyErr_FormatV(PyThreadState *tstate, PyObject *exception,
1153 const char *format, va_list vargs)
1154 {
1155 PyObject* string;
1156
1157 /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
1158 exception set, it calls arbitrary Python code like PyObject_Repr() */
1159 _PyErr_Clear(tstate);
1160
1161 string = PyUnicode_FromFormatV(format, vargs);
1162 if (string != NULL) {
1163 _PyErr_SetObject(tstate, exception, string);
1164 Py_DECREF(string);
1165 }
1166 return NULL;
1167 }
1168
1169
1170 PyObject *
PyErr_FormatV(PyObject * exception,const char * format,va_list vargs)1171 PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
1172 {
1173 PyThreadState *tstate = _PyThreadState_GET();
1174 return _PyErr_FormatV(tstate, exception, format, vargs);
1175 }
1176
1177
1178 PyObject *
_PyErr_Format(PyThreadState * tstate,PyObject * exception,const char * format,...)1179 _PyErr_Format(PyThreadState *tstate, PyObject *exception,
1180 const char *format, ...)
1181 {
1182 va_list vargs;
1183 va_start(vargs, format);
1184 _PyErr_FormatV(tstate, exception, format, vargs);
1185 va_end(vargs);
1186 return NULL;
1187 }
1188
1189
1190 PyObject *
PyErr_Format(PyObject * exception,const char * format,...)1191 PyErr_Format(PyObject *exception, const char *format, ...)
1192 {
1193 PyThreadState *tstate = _PyThreadState_GET();
1194 va_list vargs;
1195 va_start(vargs, format);
1196 _PyErr_FormatV(tstate, exception, format, vargs);
1197 va_end(vargs);
1198 return NULL;
1199 }
1200
1201
1202 /* Adds a note to the current exception (if any) */
1203 void
_PyErr_FormatNote(const char * format,...)1204 _PyErr_FormatNote(const char *format, ...)
1205 {
1206 PyObject *exc = PyErr_GetRaisedException();
1207 if (exc == NULL) {
1208 return;
1209 }
1210 va_list vargs;
1211 va_start(vargs, format);
1212 PyObject *note = PyUnicode_FromFormatV(format, vargs);
1213 va_end(vargs);
1214 if (note == NULL) {
1215 goto error;
1216 }
1217 int res = _PyException_AddNote(exc, note);
1218 Py_DECREF(note);
1219 if (res < 0) {
1220 goto error;
1221 }
1222 PyErr_SetRaisedException(exc);
1223 return;
1224 error:
1225 _PyErr_ChainExceptions1(exc);
1226 }
1227
1228
1229 PyObject *
PyErr_NewException(const char * name,PyObject * base,PyObject * dict)1230 PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
1231 {
1232 PyThreadState *tstate = _PyThreadState_GET();
1233 PyObject *modulename = NULL;
1234 PyObject *mydict = NULL;
1235 PyObject *bases = NULL;
1236 PyObject *result = NULL;
1237
1238 const char *dot = strrchr(name, '.');
1239 if (dot == NULL) {
1240 _PyErr_SetString(tstate, PyExc_SystemError,
1241 "PyErr_NewException: name must be module.class");
1242 return NULL;
1243 }
1244 if (base == NULL) {
1245 base = PyExc_Exception;
1246 }
1247 if (dict == NULL) {
1248 dict = mydict = PyDict_New();
1249 if (dict == NULL)
1250 goto failure;
1251 }
1252
1253 int r = PyDict_Contains(dict, &_Py_ID(__module__));
1254 if (r < 0) {
1255 goto failure;
1256 }
1257 if (r == 0) {
1258 modulename = PyUnicode_FromStringAndSize(name,
1259 (Py_ssize_t)(dot-name));
1260 if (modulename == NULL)
1261 goto failure;
1262 if (PyDict_SetItem(dict, &_Py_ID(__module__), modulename) != 0)
1263 goto failure;
1264 }
1265 if (PyTuple_Check(base)) {
1266 bases = Py_NewRef(base);
1267 } else {
1268 bases = PyTuple_Pack(1, base);
1269 if (bases == NULL)
1270 goto failure;
1271 }
1272 /* Create a real class. */
1273 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
1274 dot+1, bases, dict);
1275 failure:
1276 Py_XDECREF(bases);
1277 Py_XDECREF(mydict);
1278 Py_XDECREF(modulename);
1279 return result;
1280 }
1281
1282
1283 /* Create an exception with docstring */
1284 PyObject *
PyErr_NewExceptionWithDoc(const char * name,const char * doc,PyObject * base,PyObject * dict)1285 PyErr_NewExceptionWithDoc(const char *name, const char *doc,
1286 PyObject *base, PyObject *dict)
1287 {
1288 int result;
1289 PyObject *ret = NULL;
1290 PyObject *mydict = NULL; /* points to the dict only if we create it */
1291 PyObject *docobj;
1292
1293 if (dict == NULL) {
1294 dict = mydict = PyDict_New();
1295 if (dict == NULL) {
1296 return NULL;
1297 }
1298 }
1299
1300 if (doc != NULL) {
1301 docobj = PyUnicode_FromString(doc);
1302 if (docobj == NULL)
1303 goto failure;
1304 result = PyDict_SetItemString(dict, "__doc__", docobj);
1305 Py_DECREF(docobj);
1306 if (result < 0)
1307 goto failure;
1308 }
1309
1310 ret = PyErr_NewException(name, base, dict);
1311 failure:
1312 Py_XDECREF(mydict);
1313 return ret;
1314 }
1315
1316
1317 PyDoc_STRVAR(UnraisableHookArgs__doc__,
1318 "UnraisableHookArgs\n\
1319 \n\
1320 Type used to pass arguments to sys.unraisablehook.");
1321
1322 static PyTypeObject UnraisableHookArgsType;
1323
1324 static PyStructSequence_Field UnraisableHookArgs_fields[] = {
1325 {"exc_type", "Exception type"},
1326 {"exc_value", "Exception value"},
1327 {"exc_traceback", "Exception traceback"},
1328 {"err_msg", "Error message"},
1329 {"object", "Object causing the exception"},
1330 {0}
1331 };
1332
1333 static PyStructSequence_Desc UnraisableHookArgs_desc = {
1334 .name = "UnraisableHookArgs",
1335 .doc = UnraisableHookArgs__doc__,
1336 .fields = UnraisableHookArgs_fields,
1337 .n_in_sequence = 5
1338 };
1339
1340
1341 PyStatus
_PyErr_InitTypes(PyInterpreterState * interp)1342 _PyErr_InitTypes(PyInterpreterState *interp)
1343 {
1344 if (_PyStructSequence_InitBuiltin(interp, &UnraisableHookArgsType,
1345 &UnraisableHookArgs_desc) < 0)
1346 {
1347 return _PyStatus_ERR("failed to initialize UnraisableHookArgs type");
1348 }
1349 return _PyStatus_OK();
1350 }
1351
1352
1353 void
_PyErr_FiniTypes(PyInterpreterState * interp)1354 _PyErr_FiniTypes(PyInterpreterState *interp)
1355 {
1356 _PyStructSequence_FiniBuiltin(interp, &UnraisableHookArgsType);
1357 }
1358
1359
1360 static PyObject *
make_unraisable_hook_args(PyThreadState * tstate,PyObject * exc_type,PyObject * exc_value,PyObject * exc_tb,PyObject * err_msg,PyObject * obj)1361 make_unraisable_hook_args(PyThreadState *tstate, PyObject *exc_type,
1362 PyObject *exc_value, PyObject *exc_tb,
1363 PyObject *err_msg, PyObject *obj)
1364 {
1365 PyObject *args = PyStructSequence_New(&UnraisableHookArgsType);
1366 if (args == NULL) {
1367 return NULL;
1368 }
1369
1370 Py_ssize_t pos = 0;
1371 #define ADD_ITEM(exc_type) \
1372 do { \
1373 if (exc_type == NULL) { \
1374 exc_type = Py_None; \
1375 } \
1376 PyStructSequence_SET_ITEM(args, pos++, Py_NewRef(exc_type)); \
1377 } while (0)
1378
1379
1380 ADD_ITEM(exc_type);
1381 ADD_ITEM(exc_value);
1382 ADD_ITEM(exc_tb);
1383 ADD_ITEM(err_msg);
1384 ADD_ITEM(obj);
1385 #undef ADD_ITEM
1386
1387 if (_PyErr_Occurred(tstate)) {
1388 Py_DECREF(args);
1389 return NULL;
1390 }
1391 return args;
1392 }
1393
1394
1395
1396 /* Default implementation of sys.unraisablehook.
1397
1398 It can be called to log the exception of a custom sys.unraisablehook.
1399
1400 Do nothing if sys.stderr attribute doesn't exist or is set to None. */
1401 static int
write_unraisable_exc_file(PyThreadState * tstate,PyObject * exc_type,PyObject * exc_value,PyObject * exc_tb,PyObject * err_msg,PyObject * obj,PyObject * file)1402 write_unraisable_exc_file(PyThreadState *tstate, PyObject *exc_type,
1403 PyObject *exc_value, PyObject *exc_tb,
1404 PyObject *err_msg, PyObject *obj, PyObject *file)
1405 {
1406 if (obj != NULL && obj != Py_None) {
1407 if (err_msg != NULL && err_msg != Py_None) {
1408 if (PyFile_WriteObject(err_msg, file, Py_PRINT_RAW) < 0) {
1409 return -1;
1410 }
1411 if (PyFile_WriteString(": ", file) < 0) {
1412 return -1;
1413 }
1414 }
1415 else {
1416 if (PyFile_WriteString("Exception ignored in: ", file) < 0) {
1417 return -1;
1418 }
1419 }
1420
1421 if (PyFile_WriteObject(obj, file, 0) < 0) {
1422 _PyErr_Clear(tstate);
1423 if (PyFile_WriteString("<object repr() failed>", file) < 0) {
1424 return -1;
1425 }
1426 }
1427 if (PyFile_WriteString("\n", file) < 0) {
1428 return -1;
1429 }
1430 }
1431 else if (err_msg != NULL && err_msg != Py_None) {
1432 if (PyFile_WriteObject(err_msg, file, Py_PRINT_RAW) < 0) {
1433 return -1;
1434 }
1435 if (PyFile_WriteString(":\n", file) < 0) {
1436 return -1;
1437 }
1438 }
1439
1440 if (exc_tb != NULL && exc_tb != Py_None) {
1441 if (PyTraceBack_Print(exc_tb, file) < 0) {
1442 /* continue even if writing the traceback failed */
1443 _PyErr_Clear(tstate);
1444 }
1445 }
1446
1447 if (exc_type == NULL || exc_type == Py_None) {
1448 return -1;
1449 }
1450
1451 assert(PyExceptionClass_Check(exc_type));
1452
1453 PyObject *modulename = PyObject_GetAttr(exc_type, &_Py_ID(__module__));
1454 if (modulename == NULL || !PyUnicode_Check(modulename)) {
1455 Py_XDECREF(modulename);
1456 _PyErr_Clear(tstate);
1457 if (PyFile_WriteString("<unknown>", file) < 0) {
1458 return -1;
1459 }
1460 }
1461 else {
1462 if (!_PyUnicode_Equal(modulename, &_Py_ID(builtins)) &&
1463 !_PyUnicode_Equal(modulename, &_Py_ID(__main__))) {
1464 if (PyFile_WriteObject(modulename, file, Py_PRINT_RAW) < 0) {
1465 Py_DECREF(modulename);
1466 return -1;
1467 }
1468 Py_DECREF(modulename);
1469 if (PyFile_WriteString(".", file) < 0) {
1470 return -1;
1471 }
1472 }
1473 else {
1474 Py_DECREF(modulename);
1475 }
1476 }
1477
1478 PyObject *qualname = PyType_GetQualName((PyTypeObject *)exc_type);
1479 if (qualname == NULL || !PyUnicode_Check(qualname)) {
1480 Py_XDECREF(qualname);
1481 _PyErr_Clear(tstate);
1482 if (PyFile_WriteString("<unknown>", file) < 0) {
1483 return -1;
1484 }
1485 }
1486 else {
1487 if (PyFile_WriteObject(qualname, file, Py_PRINT_RAW) < 0) {
1488 Py_DECREF(qualname);
1489 return -1;
1490 }
1491 Py_DECREF(qualname);
1492 }
1493
1494 if (exc_value && exc_value != Py_None) {
1495 if (PyFile_WriteString(": ", file) < 0) {
1496 return -1;
1497 }
1498 if (PyFile_WriteObject(exc_value, file, Py_PRINT_RAW) < 0) {
1499 _PyErr_Clear(tstate);
1500 if (PyFile_WriteString("<exception str() failed>", file) < 0) {
1501 return -1;
1502 }
1503 }
1504 }
1505
1506 if (PyFile_WriteString("\n", file) < 0) {
1507 return -1;
1508 }
1509
1510 /* Explicitly call file.flush() */
1511 if (_PyFile_Flush(file) < 0) {
1512 return -1;
1513 }
1514
1515 return 0;
1516 }
1517
1518
1519 static int
write_unraisable_exc(PyThreadState * tstate,PyObject * exc_type,PyObject * exc_value,PyObject * exc_tb,PyObject * err_msg,PyObject * obj)1520 write_unraisable_exc(PyThreadState *tstate, PyObject *exc_type,
1521 PyObject *exc_value, PyObject *exc_tb, PyObject *err_msg,
1522 PyObject *obj)
1523 {
1524 PyObject *file = _PySys_GetAttr(tstate, &_Py_ID(stderr));
1525 if (file == NULL || file == Py_None) {
1526 return 0;
1527 }
1528
1529 /* Hold a strong reference to ensure that sys.stderr doesn't go away
1530 while we use it */
1531 Py_INCREF(file);
1532 int res = write_unraisable_exc_file(tstate, exc_type, exc_value, exc_tb,
1533 err_msg, obj, file);
1534 Py_DECREF(file);
1535
1536 return res;
1537 }
1538
1539
1540 PyObject*
_PyErr_WriteUnraisableDefaultHook(PyObject * args)1541 _PyErr_WriteUnraisableDefaultHook(PyObject *args)
1542 {
1543 PyThreadState *tstate = _PyThreadState_GET();
1544
1545 if (!Py_IS_TYPE(args, &UnraisableHookArgsType)) {
1546 _PyErr_SetString(tstate, PyExc_TypeError,
1547 "sys.unraisablehook argument type "
1548 "must be UnraisableHookArgs");
1549 return NULL;
1550 }
1551
1552 /* Borrowed references */
1553 PyObject *exc_type = PyStructSequence_GET_ITEM(args, 0);
1554 PyObject *exc_value = PyStructSequence_GET_ITEM(args, 1);
1555 PyObject *exc_tb = PyStructSequence_GET_ITEM(args, 2);
1556 PyObject *err_msg = PyStructSequence_GET_ITEM(args, 3);
1557 PyObject *obj = PyStructSequence_GET_ITEM(args, 4);
1558
1559 if (write_unraisable_exc(tstate, exc_type, exc_value, exc_tb, err_msg, obj) < 0) {
1560 return NULL;
1561 }
1562 Py_RETURN_NONE;
1563 }
1564
1565
1566 /* Call sys.unraisablehook().
1567
1568 This function can be used when an exception has occurred but there is no way
1569 for Python to handle it. For example, when a destructor raises an exception
1570 or during garbage collection (gc.collect()).
1571
1572 If format is non-NULL, the error message is formatted using format and
1573 variable arguments as in PyUnicode_FromFormat().
1574 Otherwise, use "Exception ignored in" error message.
1575
1576 An exception must be set when calling this function. */
1577
1578 static void
format_unraisable_v(const char * format,va_list va,PyObject * obj)1579 format_unraisable_v(const char *format, va_list va, PyObject *obj)
1580 {
1581 const char *err_msg_str;
1582 PyThreadState *tstate = _PyThreadState_GET();
1583 _Py_EnsureTstateNotNULL(tstate);
1584
1585 PyObject *err_msg = NULL;
1586 PyObject *exc_type, *exc_value, *exc_tb;
1587 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
1588
1589 assert(exc_type != NULL);
1590
1591 if (exc_type == NULL) {
1592 /* sys.unraisablehook requires that at least exc_type is set */
1593 goto default_hook;
1594 }
1595
1596 if (exc_tb == NULL) {
1597 PyFrameObject *frame = PyThreadState_GetFrame(tstate);
1598 if (frame != NULL) {
1599 exc_tb = _PyTraceBack_FromFrame(NULL, frame);
1600 if (exc_tb == NULL) {
1601 _PyErr_Clear(tstate);
1602 }
1603 Py_DECREF(frame);
1604 }
1605 }
1606
1607 _PyErr_NormalizeException(tstate, &exc_type, &exc_value, &exc_tb);
1608
1609 if (exc_tb != NULL && exc_tb != Py_None && PyTraceBack_Check(exc_tb)) {
1610 if (PyException_SetTraceback(exc_value, exc_tb) < 0) {
1611 _PyErr_Clear(tstate);
1612 }
1613 }
1614
1615 if (format != NULL) {
1616 err_msg = PyUnicode_FromFormatV(format, va);
1617 if (err_msg == NULL) {
1618 PyErr_Clear();
1619 }
1620 }
1621
1622 PyObject *hook_args = make_unraisable_hook_args(
1623 tstate, exc_type, exc_value, exc_tb, err_msg, obj);
1624 if (hook_args == NULL) {
1625 err_msg_str = ("Exception ignored on building "
1626 "sys.unraisablehook arguments");
1627 goto error;
1628 }
1629
1630 PyObject *hook = _PySys_GetAttr(tstate, &_Py_ID(unraisablehook));
1631 if (hook == NULL) {
1632 Py_DECREF(hook_args);
1633 goto default_hook;
1634 }
1635
1636 if (_PySys_Audit(tstate, "sys.unraisablehook", "OO", hook, hook_args) < 0) {
1637 Py_DECREF(hook_args);
1638 err_msg_str = "Exception ignored in audit hook";
1639 obj = NULL;
1640 goto error;
1641 }
1642
1643 if (hook == Py_None) {
1644 Py_DECREF(hook_args);
1645 goto default_hook;
1646 }
1647
1648 PyObject *res = PyObject_CallOneArg(hook, hook_args);
1649 Py_DECREF(hook_args);
1650 if (res != NULL) {
1651 Py_DECREF(res);
1652 goto done;
1653 }
1654
1655 /* sys.unraisablehook failed: log its error using default hook */
1656 obj = hook;
1657 err_msg_str = NULL;
1658
1659 error:
1660 /* err_msg_str and obj have been updated and we have a new exception */
1661 Py_XSETREF(err_msg, PyUnicode_FromString(err_msg_str ?
1662 err_msg_str : "Exception ignored in sys.unraisablehook"));
1663 Py_XDECREF(exc_type);
1664 Py_XDECREF(exc_value);
1665 Py_XDECREF(exc_tb);
1666 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
1667
1668 default_hook:
1669 /* Call the default unraisable hook (ignore failure) */
1670 (void)write_unraisable_exc(tstate, exc_type, exc_value, exc_tb,
1671 err_msg, obj);
1672
1673 done:
1674 Py_XDECREF(exc_type);
1675 Py_XDECREF(exc_value);
1676 Py_XDECREF(exc_tb);
1677 Py_XDECREF(err_msg);
1678 _PyErr_Clear(tstate); /* Just in case */
1679 }
1680
1681 void
PyErr_FormatUnraisable(const char * format,...)1682 PyErr_FormatUnraisable(const char *format, ...)
1683 {
1684 va_list va;
1685
1686 va_start(va, format);
1687 format_unraisable_v(format, va, NULL);
1688 va_end(va);
1689 }
1690
1691 static void
format_unraisable(PyObject * obj,const char * format,...)1692 format_unraisable(PyObject *obj, const char *format, ...)
1693 {
1694 va_list va;
1695
1696 va_start(va, format);
1697 format_unraisable_v(format, va, obj);
1698 va_end(va);
1699 }
1700
1701 void
PyErr_WriteUnraisable(PyObject * obj)1702 PyErr_WriteUnraisable(PyObject *obj)
1703 {
1704 format_unraisable(obj, NULL);
1705 }
1706
1707
1708 void
PyErr_SyntaxLocation(const char * filename,int lineno)1709 PyErr_SyntaxLocation(const char *filename, int lineno)
1710 {
1711 PyErr_SyntaxLocationEx(filename, lineno, -1);
1712 }
1713
1714
1715 /* Set file and line information for the current exception.
1716 If the exception is not a SyntaxError, also sets additional attributes
1717 to make printing of exceptions believe it is a syntax error. */
1718
1719 static void
PyErr_SyntaxLocationObjectEx(PyObject * filename,int lineno,int col_offset,int end_lineno,int end_col_offset)1720 PyErr_SyntaxLocationObjectEx(PyObject *filename, int lineno, int col_offset,
1721 int end_lineno, int end_col_offset)
1722 {
1723 PyThreadState *tstate = _PyThreadState_GET();
1724
1725 /* add attributes for the line number and filename for the error */
1726 PyObject *exc = _PyErr_GetRaisedException(tstate);
1727 /* XXX check that it is, indeed, a syntax error. It might not
1728 * be, though. */
1729 PyObject *tmp = PyLong_FromLong(lineno);
1730 if (tmp == NULL) {
1731 _PyErr_Clear(tstate);
1732 }
1733 else {
1734 if (PyObject_SetAttr(exc, &_Py_ID(lineno), tmp)) {
1735 _PyErr_Clear(tstate);
1736 }
1737 Py_DECREF(tmp);
1738 }
1739 tmp = NULL;
1740 if (col_offset >= 0) {
1741 tmp = PyLong_FromLong(col_offset);
1742 if (tmp == NULL) {
1743 _PyErr_Clear(tstate);
1744 }
1745 }
1746 if (PyObject_SetAttr(exc, &_Py_ID(offset), tmp ? tmp : Py_None)) {
1747 _PyErr_Clear(tstate);
1748 }
1749 Py_XDECREF(tmp);
1750
1751 tmp = NULL;
1752 if (end_lineno >= 0) {
1753 tmp = PyLong_FromLong(end_lineno);
1754 if (tmp == NULL) {
1755 _PyErr_Clear(tstate);
1756 }
1757 }
1758 if (PyObject_SetAttr(exc, &_Py_ID(end_lineno), tmp ? tmp : Py_None)) {
1759 _PyErr_Clear(tstate);
1760 }
1761 Py_XDECREF(tmp);
1762
1763 tmp = NULL;
1764 if (end_col_offset >= 0) {
1765 tmp = PyLong_FromLong(end_col_offset);
1766 if (tmp == NULL) {
1767 _PyErr_Clear(tstate);
1768 }
1769 }
1770 if (PyObject_SetAttr(exc, &_Py_ID(end_offset), tmp ? tmp : Py_None)) {
1771 _PyErr_Clear(tstate);
1772 }
1773 Py_XDECREF(tmp);
1774
1775 tmp = NULL;
1776 if (filename != NULL) {
1777 if (PyObject_SetAttr(exc, &_Py_ID(filename), filename)) {
1778 _PyErr_Clear(tstate);
1779 }
1780
1781 tmp = PyErr_ProgramTextObject(filename, lineno);
1782 if (tmp) {
1783 if (PyObject_SetAttr(exc, &_Py_ID(text), tmp)) {
1784 _PyErr_Clear(tstate);
1785 }
1786 Py_DECREF(tmp);
1787 }
1788 else {
1789 _PyErr_Clear(tstate);
1790 }
1791 }
1792 if ((PyObject *)Py_TYPE(exc) != PyExc_SyntaxError) {
1793 int rc = PyObject_HasAttrWithError(exc, &_Py_ID(msg));
1794 if (rc < 0) {
1795 _PyErr_Clear(tstate);
1796 }
1797 else if (!rc) {
1798 tmp = PyObject_Str(exc);
1799 if (tmp) {
1800 if (PyObject_SetAttr(exc, &_Py_ID(msg), tmp)) {
1801 _PyErr_Clear(tstate);
1802 }
1803 Py_DECREF(tmp);
1804 }
1805 else {
1806 _PyErr_Clear(tstate);
1807 }
1808 }
1809
1810 rc = PyObject_HasAttrWithError(exc, &_Py_ID(print_file_and_line));
1811 if (rc < 0) {
1812 _PyErr_Clear(tstate);
1813 }
1814 else if (!rc) {
1815 if (PyObject_SetAttr(exc, &_Py_ID(print_file_and_line), Py_None)) {
1816 _PyErr_Clear(tstate);
1817 }
1818 }
1819 }
1820 _PyErr_SetRaisedException(tstate, exc);
1821 }
1822
1823 void
PyErr_SyntaxLocationObject(PyObject * filename,int lineno,int col_offset)1824 PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) {
1825 PyErr_SyntaxLocationObjectEx(filename, lineno, col_offset, lineno, -1);
1826 }
1827
1828 void
PyErr_RangedSyntaxLocationObject(PyObject * filename,int lineno,int col_offset,int end_lineno,int end_col_offset)1829 PyErr_RangedSyntaxLocationObject(PyObject *filename, int lineno, int col_offset,
1830 int end_lineno, int end_col_offset) {
1831 PyErr_SyntaxLocationObjectEx(filename, lineno, col_offset, end_lineno, end_col_offset);
1832 }
1833
1834 void
PyErr_SyntaxLocationEx(const char * filename,int lineno,int col_offset)1835 PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1836 {
1837 PyThreadState *tstate = _PyThreadState_GET();
1838 PyObject *fileobj;
1839 if (filename != NULL) {
1840 fileobj = PyUnicode_DecodeFSDefault(filename);
1841 if (fileobj == NULL) {
1842 _PyErr_Clear(tstate);
1843 }
1844 }
1845 else {
1846 fileobj = NULL;
1847 }
1848 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1849 Py_XDECREF(fileobj);
1850 }
1851
1852 /* Attempt to load the line of text that the exception refers to. If it
1853 fails, it will return NULL but will not set an exception.
1854
1855 XXX The functionality of this function is quite similar to the
1856 functionality in tb_displayline() in traceback.c. */
1857
1858 static PyObject *
err_programtext(FILE * fp,int lineno,const char * encoding)1859 err_programtext(FILE *fp, int lineno, const char* encoding)
1860 {
1861 char linebuf[1000];
1862 size_t line_size = 0;
1863
1864 for (int i = 0; i < lineno; ) {
1865 line_size = 0;
1866 if (_Py_UniversalNewlineFgetsWithSize(linebuf, sizeof(linebuf),
1867 fp, NULL, &line_size) == NULL)
1868 {
1869 /* Error or EOF. */
1870 return NULL;
1871 }
1872 /* fgets read *something*; if it didn't fill the
1873 whole buffer, it must have found a newline
1874 or hit the end of the file; if the last character is \n,
1875 it obviously found a newline; else we haven't
1876 yet seen a newline, so must continue */
1877 if (i + 1 < lineno
1878 && line_size == sizeof(linebuf) - 1
1879 && linebuf[sizeof(linebuf) - 2] != '\n')
1880 {
1881 continue;
1882 }
1883 i++;
1884 }
1885
1886 const char *line = linebuf;
1887 /* Skip BOM. */
1888 if (lineno == 1 && line_size >= 3 && memcmp(line, "\xef\xbb\xbf", 3) == 0) {
1889 line += 3;
1890 line_size -= 3;
1891 }
1892 PyObject *res = PyUnicode_Decode(line, line_size, encoding, "replace");
1893 if (res == NULL) {
1894 PyErr_Clear();
1895 }
1896 return res;
1897 }
1898
1899 PyObject *
PyErr_ProgramText(const char * filename,int lineno)1900 PyErr_ProgramText(const char *filename, int lineno)
1901 {
1902 if (filename == NULL) {
1903 return NULL;
1904 }
1905
1906 PyObject *filename_obj = PyUnicode_DecodeFSDefault(filename);
1907 if (filename_obj == NULL) {
1908 PyErr_Clear();
1909 return NULL;
1910 }
1911 PyObject *res = PyErr_ProgramTextObject(filename_obj, lineno);
1912 Py_DECREF(filename_obj);
1913 return res;
1914 }
1915
1916 /* Function from Parser/tokenizer/file_tokenizer.c */
1917 extern char* _PyTokenizer_FindEncodingFilename(int, PyObject *);
1918
1919 PyObject *
_PyErr_ProgramDecodedTextObject(PyObject * filename,int lineno,const char * encoding)1920 _PyErr_ProgramDecodedTextObject(PyObject *filename, int lineno, const char* encoding)
1921 {
1922 char *found_encoding = NULL;
1923 if (filename == NULL || lineno <= 0) {
1924 return NULL;
1925 }
1926
1927 FILE *fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
1928 if (fp == NULL) {
1929 PyErr_Clear();
1930 return NULL;
1931 }
1932 if (encoding == NULL) {
1933 int fd = fileno(fp);
1934 found_encoding = _PyTokenizer_FindEncodingFilename(fd, filename);
1935 encoding = found_encoding;
1936 if (encoding == NULL) {
1937 PyErr_Clear();
1938 encoding = "utf-8";
1939 }
1940 /* Reset position */
1941 if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
1942 fclose(fp);
1943 PyMem_Free(found_encoding);
1944 return NULL;
1945 }
1946 }
1947 PyObject *res = err_programtext(fp, lineno, encoding);
1948 fclose(fp);
1949 PyMem_Free(found_encoding);
1950 return res;
1951 }
1952
1953 PyObject *
PyErr_ProgramTextObject(PyObject * filename,int lineno)1954 PyErr_ProgramTextObject(PyObject *filename, int lineno)
1955 {
1956 return _PyErr_ProgramDecodedTextObject(filename, lineno, NULL);
1957 }
1958