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