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