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