• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /* Error handling */
3 
4 #include "Python.h"
5 #include "internal/pystate.h"
6 
7 #ifndef __STDC__
8 #ifndef MS_WINDOWS
9 extern char *strerror(int);
10 #endif
11 #endif
12 
13 #ifdef MS_WINDOWS
14 #include <windows.h>
15 #include <winbase.h>
16 #endif
17 
18 #include <ctype.h>
19 
20 #ifdef __cplusplus
21 extern "C" {
22 #endif
23 
24 _Py_IDENTIFIER(builtins);
25 _Py_IDENTIFIER(stderr);
26 
27 
28 void
PyErr_Restore(PyObject * type,PyObject * value,PyObject * traceback)29 PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
30 {
31     PyThreadState *tstate = PyThreadState_GET();
32     PyObject *oldtype, *oldvalue, *oldtraceback;
33 
34     if (traceback != NULL && !PyTraceBack_Check(traceback)) {
35         /* XXX Should never happen -- fatal error instead? */
36         /* Well, it could be None. */
37         Py_DECREF(traceback);
38         traceback = NULL;
39     }
40 
41     /* Save these in locals to safeguard against recursive
42        invocation through Py_XDECREF */
43     oldtype = tstate->curexc_type;
44     oldvalue = tstate->curexc_value;
45     oldtraceback = tstate->curexc_traceback;
46 
47     tstate->curexc_type = type;
48     tstate->curexc_value = value;
49     tstate->curexc_traceback = traceback;
50 
51     Py_XDECREF(oldtype);
52     Py_XDECREF(oldvalue);
53     Py_XDECREF(oldtraceback);
54 }
55 
56 _PyErr_StackItem *
_PyErr_GetTopmostException(PyThreadState * tstate)57 _PyErr_GetTopmostException(PyThreadState *tstate)
58 {
59     _PyErr_StackItem *exc_info = tstate->exc_info;
60     while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) &&
61            exc_info->previous_item != NULL)
62     {
63         exc_info = exc_info->previous_item;
64     }
65     return exc_info;
66 }
67 
68 static PyObject*
_PyErr_CreateException(PyObject * exception,PyObject * value)69 _PyErr_CreateException(PyObject *exception, PyObject *value)
70 {
71     if (value == NULL || value == Py_None) {
72         return _PyObject_CallNoArg(exception);
73     }
74     else if (PyTuple_Check(value)) {
75         return PyObject_Call(exception, value, NULL);
76     }
77     else {
78         return PyObject_CallFunctionObjArgs(exception, value, NULL);
79     }
80 }
81 
82 void
PyErr_SetObject(PyObject * exception,PyObject * value)83 PyErr_SetObject(PyObject *exception, PyObject *value)
84 {
85     PyThreadState *tstate = PyThreadState_GET();
86     PyObject *exc_value;
87     PyObject *tb = NULL;
88 
89     if (exception != NULL &&
90         !PyExceptionClass_Check(exception)) {
91         PyErr_Format(PyExc_SystemError,
92                      "exception %R not a BaseException subclass",
93                      exception);
94         return;
95     }
96 
97     Py_XINCREF(value);
98     exc_value = _PyErr_GetTopmostException(tstate)->exc_value;
99     if (exc_value != NULL && exc_value != Py_None) {
100         /* Implicit exception chaining */
101         Py_INCREF(exc_value);
102         if (value == NULL || !PyExceptionInstance_Check(value)) {
103             /* We must normalize the value right now */
104             PyObject *fixed_value;
105 
106             /* Issue #23571: functions must not be called with an
107                exception set */
108             PyErr_Clear();
109 
110             fixed_value = _PyErr_CreateException(exception, value);
111             Py_XDECREF(value);
112             if (fixed_value == NULL) {
113                 Py_DECREF(exc_value);
114                 return;
115             }
116 
117             value = fixed_value;
118         }
119 
120         /* Avoid reference cycles through the context chain.
121            This is O(chain length) but context chains are
122            usually very short. Sensitive readers may try
123            to inline the call to PyException_GetContext. */
124         if (exc_value != value) {
125             PyObject *o = exc_value, *context;
126             while ((context = PyException_GetContext(o))) {
127                 Py_DECREF(context);
128                 if (context == value) {
129                     PyException_SetContext(o, NULL);
130                     break;
131                 }
132                 o = context;
133             }
134             PyException_SetContext(value, exc_value);
135         }
136         else {
137             Py_DECREF(exc_value);
138         }
139     }
140     if (value != NULL && PyExceptionInstance_Check(value))
141         tb = PyException_GetTraceback(value);
142     Py_XINCREF(exception);
143     PyErr_Restore(exception, value, tb);
144 }
145 
146 /* Set a key error with the specified argument, wrapping it in a
147  * tuple automatically so that tuple keys are not unpacked as the
148  * exception arguments. */
149 void
_PyErr_SetKeyError(PyObject * arg)150 _PyErr_SetKeyError(PyObject *arg)
151 {
152     PyObject *tup;
153     tup = PyTuple_Pack(1, arg);
154     if (!tup)
155         return; /* caller will expect error to be set anyway */
156     PyErr_SetObject(PyExc_KeyError, tup);
157     Py_DECREF(tup);
158 }
159 
160 void
PyErr_SetNone(PyObject * exception)161 PyErr_SetNone(PyObject *exception)
162 {
163     PyErr_SetObject(exception, (PyObject *)NULL);
164 }
165 
166 void
PyErr_SetString(PyObject * exception,const char * string)167 PyErr_SetString(PyObject *exception, const char *string)
168 {
169     PyObject *value = PyUnicode_FromString(string);
170     PyErr_SetObject(exception, value);
171     Py_XDECREF(value);
172 }
173 
174 
175 PyObject* _Py_HOT_FUNCTION
PyErr_Occurred(void)176 PyErr_Occurred(void)
177 {
178     PyThreadState *tstate = PyThreadState_GET();
179     return tstate == NULL ? NULL : tstate->curexc_type;
180 }
181 
182 
183 int
PyErr_GivenExceptionMatches(PyObject * err,PyObject * exc)184 PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
185 {
186     if (err == NULL || exc == NULL) {
187         /* maybe caused by "import exceptions" that failed early on */
188         return 0;
189     }
190     if (PyTuple_Check(exc)) {
191         Py_ssize_t i, n;
192         n = PyTuple_Size(exc);
193         for (i = 0; i < n; i++) {
194             /* Test recursively */
195              if (PyErr_GivenExceptionMatches(
196                  err, PyTuple_GET_ITEM(exc, i)))
197              {
198                  return 1;
199              }
200         }
201         return 0;
202     }
203     /* err might be an instance, so check its class. */
204     if (PyExceptionInstance_Check(err))
205         err = PyExceptionInstance_Class(err);
206 
207     if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
208         return PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
209     }
210 
211     return err == exc;
212 }
213 
214 
215 int
PyErr_ExceptionMatches(PyObject * exc)216 PyErr_ExceptionMatches(PyObject *exc)
217 {
218     return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
219 }
220 
221 
222 #ifndef Py_NORMALIZE_RECURSION_LIMIT
223 #define Py_NORMALIZE_RECURSION_LIMIT 32
224 #endif
225 
226 /* Used in many places to normalize a raised exception, including in
227    eval_code2(), do_raise(), and PyErr_Print()
228 
229    XXX: should PyErr_NormalizeException() also call
230             PyException_SetTraceback() with the resulting value and tb?
231 */
232 void
PyErr_NormalizeException(PyObject ** exc,PyObject ** val,PyObject ** tb)233 PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
234 {
235     int recursion_depth = 0;
236     PyObject *type, *value, *initial_tb;
237 
238   restart:
239     type = *exc;
240     if (type == NULL) {
241         /* There was no exception, so nothing to do. */
242         return;
243     }
244 
245     value = *val;
246     /* If PyErr_SetNone() was used, the value will have been actually
247        set to NULL.
248     */
249     if (!value) {
250         value = Py_None;
251         Py_INCREF(value);
252     }
253 
254     /* Normalize the exception so that if the type is a class, the
255        value will be an instance.
256     */
257     if (PyExceptionClass_Check(type)) {
258         PyObject *inclass = NULL;
259         int is_subclass = 0;
260 
261         if (PyExceptionInstance_Check(value)) {
262             inclass = PyExceptionInstance_Class(value);
263             is_subclass = PyObject_IsSubclass(inclass, type);
264             if (is_subclass < 0) {
265                 goto error;
266             }
267         }
268 
269         /* If the value was not an instance, or is not an instance
270            whose class is (or is derived from) type, then use the
271            value as an argument to instantiation of the type
272            class.
273         */
274         if (!is_subclass) {
275             PyObject *fixed_value = _PyErr_CreateException(type, value);
276             if (fixed_value == NULL) {
277                 goto error;
278             }
279             Py_DECREF(value);
280             value = fixed_value;
281         }
282         /* If the class of the instance doesn't exactly match the
283            class of the type, believe the instance.
284         */
285         else if (inclass != type) {
286             Py_INCREF(inclass);
287             Py_DECREF(type);
288             type = inclass;
289         }
290     }
291     *exc = type;
292     *val = value;
293     return;
294 
295   error:
296     Py_DECREF(type);
297     Py_DECREF(value);
298     recursion_depth++;
299     if (recursion_depth == Py_NORMALIZE_RECURSION_LIMIT) {
300         PyErr_SetString(PyExc_RecursionError, "maximum recursion depth "
301                         "exceeded while normalizing an exception");
302     }
303     /* If the new exception doesn't set a traceback and the old
304        exception had a traceback, use the old traceback for the
305        new exception.  It's better than nothing.
306     */
307     initial_tb = *tb;
308     PyErr_Fetch(exc, val, tb);
309     assert(*exc != NULL);
310     if (initial_tb != NULL) {
311         if (*tb == NULL)
312             *tb = initial_tb;
313         else
314             Py_DECREF(initial_tb);
315     }
316     /* Abort when Py_NORMALIZE_RECURSION_LIMIT has been exceeded, and the
317        corresponding RecursionError could not be normalized, and the
318        MemoryError raised when normalize this RecursionError could not be
319        normalized. */
320     if (recursion_depth >= Py_NORMALIZE_RECURSION_LIMIT + 2) {
321         if (PyErr_GivenExceptionMatches(*exc, PyExc_MemoryError)) {
322             Py_FatalError("Cannot recover from MemoryErrors "
323                           "while normalizing exceptions.");
324         }
325         else {
326             Py_FatalError("Cannot recover from the recursive normalization "
327                           "of an exception.");
328         }
329     }
330     goto restart;
331 }
332 
333 
334 void
PyErr_Fetch(PyObject ** p_type,PyObject ** p_value,PyObject ** p_traceback)335 PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
336 {
337     PyThreadState *tstate = PyThreadState_GET();
338 
339     *p_type = tstate->curexc_type;
340     *p_value = tstate->curexc_value;
341     *p_traceback = tstate->curexc_traceback;
342 
343     tstate->curexc_type = NULL;
344     tstate->curexc_value = NULL;
345     tstate->curexc_traceback = NULL;
346 }
347 
348 void
PyErr_Clear(void)349 PyErr_Clear(void)
350 {
351     PyErr_Restore(NULL, NULL, NULL);
352 }
353 
354 void
PyErr_GetExcInfo(PyObject ** p_type,PyObject ** p_value,PyObject ** p_traceback)355 PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
356 {
357     PyThreadState *tstate = PyThreadState_GET();
358 
359     _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
360     *p_type = exc_info->exc_type;
361     *p_value = exc_info->exc_value;
362     *p_traceback = exc_info->exc_traceback;
363 
364 
365     Py_XINCREF(*p_type);
366     Py_XINCREF(*p_value);
367     Py_XINCREF(*p_traceback);
368 }
369 
370 void
PyErr_SetExcInfo(PyObject * p_type,PyObject * p_value,PyObject * p_traceback)371 PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
372 {
373     PyObject *oldtype, *oldvalue, *oldtraceback;
374     PyThreadState *tstate = PyThreadState_GET();
375 
376     oldtype = tstate->exc_info->exc_type;
377     oldvalue = tstate->exc_info->exc_value;
378     oldtraceback = tstate->exc_info->exc_traceback;
379 
380     tstate->exc_info->exc_type = p_type;
381     tstate->exc_info->exc_value = p_value;
382     tstate->exc_info->exc_traceback = p_traceback;
383 
384     Py_XDECREF(oldtype);
385     Py_XDECREF(oldvalue);
386     Py_XDECREF(oldtraceback);
387 }
388 
389 /* Like PyErr_Restore(), but if an exception is already set,
390    set the context associated with it.
391  */
392 void
_PyErr_ChainExceptions(PyObject * exc,PyObject * val,PyObject * tb)393 _PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
394 {
395     if (exc == NULL)
396         return;
397 
398     if (PyErr_Occurred()) {
399         PyObject *exc2, *val2, *tb2;
400         PyErr_Fetch(&exc2, &val2, &tb2);
401         PyErr_NormalizeException(&exc, &val, &tb);
402         if (tb != NULL) {
403             PyException_SetTraceback(val, tb);
404             Py_DECREF(tb);
405         }
406         Py_DECREF(exc);
407         PyErr_NormalizeException(&exc2, &val2, &tb2);
408         PyException_SetContext(val2, val);
409         PyErr_Restore(exc2, val2, tb2);
410     }
411     else {
412         PyErr_Restore(exc, val, tb);
413     }
414 }
415 
416 static PyObject *
_PyErr_FormatVFromCause(PyObject * exception,const char * format,va_list vargs)417 _PyErr_FormatVFromCause(PyObject *exception, const char *format, va_list vargs)
418 {
419     PyObject *exc, *val, *val2, *tb;
420 
421     assert(PyErr_Occurred());
422     PyErr_Fetch(&exc, &val, &tb);
423     PyErr_NormalizeException(&exc, &val, &tb);
424     if (tb != NULL) {
425         PyException_SetTraceback(val, tb);
426         Py_DECREF(tb);
427     }
428     Py_DECREF(exc);
429     assert(!PyErr_Occurred());
430 
431     PyErr_FormatV(exception, format, vargs);
432 
433     PyErr_Fetch(&exc, &val2, &tb);
434     PyErr_NormalizeException(&exc, &val2, &tb);
435     Py_INCREF(val);
436     PyException_SetCause(val2, val);
437     PyException_SetContext(val2, val);
438     PyErr_Restore(exc, val2, tb);
439 
440     return NULL;
441 }
442 
443 PyObject *
_PyErr_FormatFromCause(PyObject * exception,const char * format,...)444 _PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
445 {
446     va_list vargs;
447 #ifdef HAVE_STDARG_PROTOTYPES
448     va_start(vargs, format);
449 #else
450     va_start(vargs);
451 #endif
452     _PyErr_FormatVFromCause(exception, format, vargs);
453     va_end(vargs);
454     return NULL;
455 }
456 
457 /* Convenience functions to set a type error exception and return 0 */
458 
459 int
PyErr_BadArgument(void)460 PyErr_BadArgument(void)
461 {
462     PyErr_SetString(PyExc_TypeError,
463                     "bad argument type for built-in operation");
464     return 0;
465 }
466 
467 PyObject *
PyErr_NoMemory(void)468 PyErr_NoMemory(void)
469 {
470     if (Py_TYPE(PyExc_MemoryError) == NULL) {
471         /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
472            initialized by _PyExc_Init() */
473         Py_FatalError("Out of memory and PyExc_MemoryError is not "
474                       "initialized yet");
475     }
476     PyErr_SetNone(PyExc_MemoryError);
477     return NULL;
478 }
479 
480 PyObject *
PyErr_SetFromErrnoWithFilenameObject(PyObject * exc,PyObject * filenameObject)481 PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
482 {
483     return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
484 }
485 
486 PyObject *
PyErr_SetFromErrnoWithFilenameObjects(PyObject * exc,PyObject * filenameObject,PyObject * filenameObject2)487 PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
488 {
489     PyObject *message;
490     PyObject *v, *args;
491     int i = errno;
492 #ifdef MS_WINDOWS
493     WCHAR *s_buf = NULL;
494 #endif /* Unix/Windows */
495 
496 #ifdef EINTR
497     if (i == EINTR && PyErr_CheckSignals())
498         return NULL;
499 #endif
500 
501 #ifndef MS_WINDOWS
502     if (i != 0) {
503         char *s = strerror(i);
504         message = PyUnicode_DecodeLocale(s, "surrogateescape");
505     }
506     else {
507         /* Sometimes errno didn't get set */
508         message = PyUnicode_FromString("Error");
509     }
510 #else
511     if (i == 0)
512         message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
513     else
514     {
515         /* Note that the Win32 errors do not lineup with the
516            errno error.  So if the error is in the MSVC error
517            table, we use it, otherwise we assume it really _is_
518            a Win32 error code
519         */
520         if (i > 0 && i < _sys_nerr) {
521             message = PyUnicode_FromString(_sys_errlist[i]);
522         }
523         else {
524             int len = FormatMessageW(
525                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
526                 FORMAT_MESSAGE_FROM_SYSTEM |
527                 FORMAT_MESSAGE_IGNORE_INSERTS,
528                 NULL,                   /* no message source */
529                 i,
530                 MAKELANGID(LANG_NEUTRAL,
531                            SUBLANG_DEFAULT),
532                            /* Default language */
533                 (LPWSTR) &s_buf,
534                 0,                      /* size not used */
535                 NULL);                  /* no args */
536             if (len==0) {
537                 /* Only ever seen this in out-of-mem
538                    situations */
539                 s_buf = NULL;
540                 message = PyUnicode_FromFormat("Windows Error 0x%x", i);
541             } else {
542                 /* remove trailing cr/lf and dots */
543                 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
544                     s_buf[--len] = L'\0';
545                 message = PyUnicode_FromWideChar(s_buf, len);
546             }
547         }
548     }
549 #endif /* Unix/Windows */
550 
551     if (message == NULL)
552     {
553 #ifdef MS_WINDOWS
554         LocalFree(s_buf);
555 #endif
556         return NULL;
557     }
558 
559     if (filenameObject != NULL) {
560         if (filenameObject2 != NULL)
561             args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
562         else
563             args = Py_BuildValue("(iOO)", i, message, filenameObject);
564     } else {
565         assert(filenameObject2 == NULL);
566         args = Py_BuildValue("(iO)", i, message);
567     }
568     Py_DECREF(message);
569 
570     if (args != NULL) {
571         v = PyObject_Call(exc, args, NULL);
572         Py_DECREF(args);
573         if (v != NULL) {
574             PyErr_SetObject((PyObject *) Py_TYPE(v), v);
575             Py_DECREF(v);
576         }
577     }
578 #ifdef MS_WINDOWS
579     LocalFree(s_buf);
580 #endif
581     return NULL;
582 }
583 
584 PyObject *
PyErr_SetFromErrnoWithFilename(PyObject * exc,const char * filename)585 PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
586 {
587     PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
588     PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
589     Py_XDECREF(name);
590     return result;
591 }
592 
593 #ifdef MS_WINDOWS
594 PyObject *
PyErr_SetFromErrnoWithUnicodeFilename(PyObject * exc,const Py_UNICODE * filename)595 PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
596 {
597     PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
598     PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
599     Py_XDECREF(name);
600     return result;
601 }
602 #endif /* MS_WINDOWS */
603 
604 PyObject *
PyErr_SetFromErrno(PyObject * exc)605 PyErr_SetFromErrno(PyObject *exc)
606 {
607     return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
608 }
609 
610 #ifdef MS_WINDOWS
611 /* Windows specific error code handling */
PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject * exc,int ierr,PyObject * filenameObject)612 PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
613     PyObject *exc,
614     int ierr,
615     PyObject *filenameObject)
616 {
617     return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
618         filenameObject, NULL);
619 }
620 
PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject * exc,int ierr,PyObject * filenameObject,PyObject * filenameObject2)621 PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
622     PyObject *exc,
623     int ierr,
624     PyObject *filenameObject,
625     PyObject *filenameObject2)
626 {
627     int len;
628     WCHAR *s_buf = NULL; /* Free via LocalFree */
629     PyObject *message;
630     PyObject *args, *v;
631     DWORD err = (DWORD)ierr;
632     if (err==0) err = GetLastError();
633     len = FormatMessageW(
634         /* Error API error */
635         FORMAT_MESSAGE_ALLOCATE_BUFFER |
636         FORMAT_MESSAGE_FROM_SYSTEM |
637         FORMAT_MESSAGE_IGNORE_INSERTS,
638         NULL,           /* no message source */
639         err,
640         MAKELANGID(LANG_NEUTRAL,
641         SUBLANG_DEFAULT), /* Default language */
642         (LPWSTR) &s_buf,
643         0,              /* size not used */
644         NULL);          /* no args */
645     if (len==0) {
646         /* Only seen this in out of mem situations */
647         message = PyUnicode_FromFormat("Windows Error 0x%x", err);
648         s_buf = NULL;
649     } else {
650         /* remove trailing cr/lf and dots */
651         while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
652             s_buf[--len] = L'\0';
653         message = PyUnicode_FromWideChar(s_buf, len);
654     }
655 
656     if (message == NULL)
657     {
658         LocalFree(s_buf);
659         return NULL;
660     }
661 
662     if (filenameObject == NULL) {
663         assert(filenameObject2 == NULL);
664         filenameObject = filenameObject2 = Py_None;
665     }
666     else if (filenameObject2 == NULL)
667         filenameObject2 = Py_None;
668     /* This is the constructor signature for OSError.
669        The POSIX translation will be figured out by the constructor. */
670     args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
671     Py_DECREF(message);
672 
673     if (args != NULL) {
674         v = PyObject_Call(exc, args, NULL);
675         Py_DECREF(args);
676         if (v != NULL) {
677             PyErr_SetObject((PyObject *) Py_TYPE(v), v);
678             Py_DECREF(v);
679         }
680     }
681     LocalFree(s_buf);
682     return NULL;
683 }
684 
PyErr_SetExcFromWindowsErrWithFilename(PyObject * exc,int ierr,const char * filename)685 PyObject *PyErr_SetExcFromWindowsErrWithFilename(
686     PyObject *exc,
687     int ierr,
688     const char *filename)
689 {
690     PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
691     PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
692                                                                  ierr,
693                                                                  name,
694                                                                  NULL);
695     Py_XDECREF(name);
696     return ret;
697 }
698 
PyErr_SetExcFromWindowsErrWithUnicodeFilename(PyObject * exc,int ierr,const Py_UNICODE * filename)699 PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
700     PyObject *exc,
701     int ierr,
702     const Py_UNICODE *filename)
703 {
704     PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
705     PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
706                                                                  ierr,
707                                                                  name,
708                                                                  NULL);
709     Py_XDECREF(name);
710     return ret;
711 }
712 
PyErr_SetExcFromWindowsErr(PyObject * exc,int ierr)713 PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
714 {
715     return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
716 }
717 
PyErr_SetFromWindowsErr(int ierr)718 PyObject *PyErr_SetFromWindowsErr(int ierr)
719 {
720     return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
721                                                   ierr, NULL);
722 }
723 
PyErr_SetFromWindowsErrWithFilename(int ierr,const char * filename)724 PyObject *PyErr_SetFromWindowsErrWithFilename(
725     int ierr,
726     const char *filename)
727 {
728     PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
729     PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
730                                                   PyExc_OSError,
731                                                   ierr, name, NULL);
732     Py_XDECREF(name);
733     return result;
734 }
735 
PyErr_SetFromWindowsErrWithUnicodeFilename(int ierr,const Py_UNICODE * filename)736 PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
737     int ierr,
738     const Py_UNICODE *filename)
739 {
740     PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
741     PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
742                                                   PyExc_OSError,
743                                                   ierr, name, NULL);
744     Py_XDECREF(name);
745     return result;
746 }
747 #endif /* MS_WINDOWS */
748 
749 PyObject *
PyErr_SetImportErrorSubclass(PyObject * exception,PyObject * msg,PyObject * name,PyObject * path)750 PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
751     PyObject *name, PyObject *path)
752 {
753     int issubclass;
754     PyObject *kwargs, *error;
755 
756     issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
757     if (issubclass < 0) {
758         return NULL;
759     }
760     else if (!issubclass) {
761         PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError");
762         return NULL;
763     }
764 
765     if (msg == NULL) {
766         PyErr_SetString(PyExc_TypeError, "expected a message argument");
767         return NULL;
768     }
769 
770     if (name == NULL) {
771         name = Py_None;
772     }
773     if (path == NULL) {
774         path = Py_None;
775     }
776 
777     kwargs = PyDict_New();
778     if (kwargs == NULL) {
779         return NULL;
780     }
781     if (PyDict_SetItemString(kwargs, "name", name) < 0) {
782         goto done;
783     }
784     if (PyDict_SetItemString(kwargs, "path", path) < 0) {
785         goto done;
786     }
787 
788     error = _PyObject_FastCallDict(exception, &msg, 1, kwargs);
789     if (error != NULL) {
790         PyErr_SetObject((PyObject *)Py_TYPE(error), error);
791         Py_DECREF(error);
792     }
793 
794 done:
795     Py_DECREF(kwargs);
796     return NULL;
797 }
798 
799 PyObject *
PyErr_SetImportError(PyObject * msg,PyObject * name,PyObject * path)800 PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
801 {
802     return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
803 }
804 
805 void
_PyErr_BadInternalCall(const char * filename,int lineno)806 _PyErr_BadInternalCall(const char *filename, int lineno)
807 {
808     PyErr_Format(PyExc_SystemError,
809                  "%s:%d: bad argument to internal function",
810                  filename, lineno);
811 }
812 
813 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
814    export the entry point for existing object code: */
815 #undef PyErr_BadInternalCall
816 void
PyErr_BadInternalCall(void)817 PyErr_BadInternalCall(void)
818 {
819     assert(0 && "bad argument to internal function");
820     PyErr_Format(PyExc_SystemError,
821                  "bad argument to internal function");
822 }
823 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
824 
825 
826 PyObject *
PyErr_FormatV(PyObject * exception,const char * format,va_list vargs)827 PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
828 {
829     PyObject* string;
830 
831     /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
832        exception set, it calls arbitrary Python code like PyObject_Repr() */
833     PyErr_Clear();
834 
835     string = PyUnicode_FromFormatV(format, vargs);
836 
837     PyErr_SetObject(exception, string);
838     Py_XDECREF(string);
839     return NULL;
840 }
841 
842 
843 PyObject *
PyErr_Format(PyObject * exception,const char * format,...)844 PyErr_Format(PyObject *exception, const char *format, ...)
845 {
846     va_list vargs;
847 #ifdef HAVE_STDARG_PROTOTYPES
848     va_start(vargs, format);
849 #else
850     va_start(vargs);
851 #endif
852     PyErr_FormatV(exception, format, vargs);
853     va_end(vargs);
854     return NULL;
855 }
856 
857 
858 PyObject *
PyErr_NewException(const char * name,PyObject * base,PyObject * dict)859 PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
860 {
861     const char *dot;
862     PyObject *modulename = NULL;
863     PyObject *classname = NULL;
864     PyObject *mydict = NULL;
865     PyObject *bases = NULL;
866     PyObject *result = NULL;
867     dot = strrchr(name, '.');
868     if (dot == NULL) {
869         PyErr_SetString(PyExc_SystemError,
870             "PyErr_NewException: name must be module.class");
871         return NULL;
872     }
873     if (base == NULL)
874         base = PyExc_Exception;
875     if (dict == NULL) {
876         dict = mydict = PyDict_New();
877         if (dict == NULL)
878             goto failure;
879     }
880     if (PyDict_GetItemString(dict, "__module__") == NULL) {
881         modulename = PyUnicode_FromStringAndSize(name,
882                                              (Py_ssize_t)(dot-name));
883         if (modulename == NULL)
884             goto failure;
885         if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
886             goto failure;
887     }
888     if (PyTuple_Check(base)) {
889         bases = base;
890         /* INCREF as we create a new ref in the else branch */
891         Py_INCREF(bases);
892     } else {
893         bases = PyTuple_Pack(1, base);
894         if (bases == NULL)
895             goto failure;
896     }
897     /* Create a real class. */
898     result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
899                                    dot+1, bases, dict);
900   failure:
901     Py_XDECREF(bases);
902     Py_XDECREF(mydict);
903     Py_XDECREF(classname);
904     Py_XDECREF(modulename);
905     return result;
906 }
907 
908 
909 /* Create an exception with docstring */
910 PyObject *
PyErr_NewExceptionWithDoc(const char * name,const char * doc,PyObject * base,PyObject * dict)911 PyErr_NewExceptionWithDoc(const char *name, const char *doc,
912                           PyObject *base, PyObject *dict)
913 {
914     int result;
915     PyObject *ret = NULL;
916     PyObject *mydict = NULL; /* points to the dict only if we create it */
917     PyObject *docobj;
918 
919     if (dict == NULL) {
920         dict = mydict = PyDict_New();
921         if (dict == NULL) {
922             return NULL;
923         }
924     }
925 
926     if (doc != NULL) {
927         docobj = PyUnicode_FromString(doc);
928         if (docobj == NULL)
929             goto failure;
930         result = PyDict_SetItemString(dict, "__doc__", docobj);
931         Py_DECREF(docobj);
932         if (result < 0)
933             goto failure;
934     }
935 
936     ret = PyErr_NewException(name, base, dict);
937   failure:
938     Py_XDECREF(mydict);
939     return ret;
940 }
941 
942 
943 /* Call when an exception has occurred but there is no way for Python
944    to handle it.  Examples: exception in __del__ or during GC. */
945 void
PyErr_WriteUnraisable(PyObject * obj)946 PyErr_WriteUnraisable(PyObject *obj)
947 {
948     _Py_IDENTIFIER(__module__);
949     PyObject *f, *t, *v, *tb;
950     PyObject *moduleName = NULL;
951     char* className;
952 
953     PyErr_Fetch(&t, &v, &tb);
954 
955     f = _PySys_GetObjectId(&PyId_stderr);
956     if (f == NULL || f == Py_None)
957         goto done;
958 
959     if (obj) {
960         if (PyFile_WriteString("Exception ignored in: ", f) < 0)
961             goto done;
962         if (PyFile_WriteObject(obj, f, 0) < 0) {
963             PyErr_Clear();
964             if (PyFile_WriteString("<object repr() failed>", f) < 0) {
965                 goto done;
966             }
967         }
968         if (PyFile_WriteString("\n", f) < 0)
969             goto done;
970     }
971 
972     if (PyTraceBack_Print(tb, f) < 0)
973         goto done;
974 
975     if (!t)
976         goto done;
977 
978     assert(PyExceptionClass_Check(t));
979     className = PyExceptionClass_Name(t);
980     if (className != NULL) {
981         char *dot = strrchr(className, '.');
982         if (dot != NULL)
983             className = dot+1;
984     }
985 
986     moduleName = _PyObject_GetAttrId(t, &PyId___module__);
987     if (moduleName == NULL || !PyUnicode_Check(moduleName)) {
988         PyErr_Clear();
989         if (PyFile_WriteString("<unknown>", f) < 0)
990             goto done;
991     }
992     else {
993         if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
994             if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
995                 goto done;
996             if (PyFile_WriteString(".", f) < 0)
997                 goto done;
998         }
999     }
1000     if (className == NULL) {
1001         if (PyFile_WriteString("<unknown>", f) < 0)
1002             goto done;
1003     }
1004     else {
1005         if (PyFile_WriteString(className, f) < 0)
1006             goto done;
1007     }
1008 
1009     if (v && v != Py_None) {
1010         if (PyFile_WriteString(": ", f) < 0)
1011             goto done;
1012         if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
1013             PyErr_Clear();
1014             if (PyFile_WriteString("<exception str() failed>", f) < 0) {
1015                 goto done;
1016             }
1017         }
1018     }
1019     if (PyFile_WriteString("\n", f) < 0)
1020         goto done;
1021 
1022 done:
1023     Py_XDECREF(moduleName);
1024     Py_XDECREF(t);
1025     Py_XDECREF(v);
1026     Py_XDECREF(tb);
1027     PyErr_Clear(); /* Just in case */
1028 }
1029 
1030 extern PyObject *PyModule_GetWarningsModule(void);
1031 
1032 
1033 void
PyErr_SyntaxLocation(const char * filename,int lineno)1034 PyErr_SyntaxLocation(const char *filename, int lineno)
1035 {
1036     PyErr_SyntaxLocationEx(filename, lineno, -1);
1037 }
1038 
1039 
1040 /* Set file and line information for the current exception.
1041    If the exception is not a SyntaxError, also sets additional attributes
1042    to make printing of exceptions believe it is a syntax error. */
1043 
1044 void
PyErr_SyntaxLocationObject(PyObject * filename,int lineno,int col_offset)1045 PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
1046 {
1047     PyObject *exc, *v, *tb, *tmp;
1048     _Py_IDENTIFIER(filename);
1049     _Py_IDENTIFIER(lineno);
1050     _Py_IDENTIFIER(msg);
1051     _Py_IDENTIFIER(offset);
1052     _Py_IDENTIFIER(print_file_and_line);
1053     _Py_IDENTIFIER(text);
1054 
1055     /* add attributes for the line number and filename for the error */
1056     PyErr_Fetch(&exc, &v, &tb);
1057     PyErr_NormalizeException(&exc, &v, &tb);
1058     /* XXX check that it is, indeed, a syntax error. It might not
1059      * be, though. */
1060     tmp = PyLong_FromLong(lineno);
1061     if (tmp == NULL)
1062         PyErr_Clear();
1063     else {
1064         if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
1065             PyErr_Clear();
1066         Py_DECREF(tmp);
1067     }
1068     tmp = NULL;
1069     if (col_offset >= 0) {
1070         tmp = PyLong_FromLong(col_offset);
1071         if (tmp == NULL)
1072             PyErr_Clear();
1073     }
1074     if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
1075         PyErr_Clear();
1076     Py_XDECREF(tmp);
1077     if (filename != NULL) {
1078         if (_PyObject_SetAttrId(v, &PyId_filename, filename))
1079             PyErr_Clear();
1080 
1081         tmp = PyErr_ProgramTextObject(filename, lineno);
1082         if (tmp) {
1083             if (_PyObject_SetAttrId(v, &PyId_text, tmp))
1084                 PyErr_Clear();
1085             Py_DECREF(tmp);
1086         }
1087     }
1088     if (exc != PyExc_SyntaxError) {
1089         if (!_PyObject_HasAttrId(v, &PyId_msg)) {
1090             tmp = PyObject_Str(v);
1091             if (tmp) {
1092                 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
1093                     PyErr_Clear();
1094                 Py_DECREF(tmp);
1095             } else {
1096                 PyErr_Clear();
1097             }
1098         }
1099         if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1100             if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1101                                     Py_None))
1102                 PyErr_Clear();
1103         }
1104     }
1105     PyErr_Restore(exc, v, tb);
1106 }
1107 
1108 void
PyErr_SyntaxLocationEx(const char * filename,int lineno,int col_offset)1109 PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1110 {
1111     PyObject *fileobj;
1112     if (filename != NULL) {
1113         fileobj = PyUnicode_DecodeFSDefault(filename);
1114         if (fileobj == NULL)
1115             PyErr_Clear();
1116     }
1117     else
1118         fileobj = NULL;
1119     PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1120     Py_XDECREF(fileobj);
1121 }
1122 
1123 /* Attempt to load the line of text that the exception refers to.  If it
1124    fails, it will return NULL but will not set an exception.
1125 
1126    XXX The functionality of this function is quite similar to the
1127    functionality in tb_displayline() in traceback.c. */
1128 
1129 static PyObject *
err_programtext(FILE * fp,int lineno)1130 err_programtext(FILE *fp, int lineno)
1131 {
1132     int i;
1133     char linebuf[1000];
1134 
1135     if (fp == NULL)
1136         return NULL;
1137     for (i = 0; i < lineno; i++) {
1138         char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1139         do {
1140             *pLastChar = '\0';
1141             if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1142                                          fp, NULL) == NULL)
1143                 break;
1144             /* fgets read *something*; if it didn't get as
1145                far as pLastChar, it must have found a newline
1146                or hit the end of the file; if pLastChar is \n,
1147                it obviously found a newline; else we haven't
1148                yet seen a newline, so must continue */
1149         } while (*pLastChar != '\0' && *pLastChar != '\n');
1150     }
1151     fclose(fp);
1152     if (i == lineno) {
1153         PyObject *res;
1154         res = PyUnicode_FromString(linebuf);
1155         if (res == NULL)
1156             PyErr_Clear();
1157         return res;
1158     }
1159     return NULL;
1160 }
1161 
1162 PyObject *
PyErr_ProgramText(const char * filename,int lineno)1163 PyErr_ProgramText(const char *filename, int lineno)
1164 {
1165     FILE *fp;
1166     if (filename == NULL || *filename == '\0' || lineno <= 0)
1167         return NULL;
1168     fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
1169     return err_programtext(fp, lineno);
1170 }
1171 
1172 PyObject *
PyErr_ProgramTextObject(PyObject * filename,int lineno)1173 PyErr_ProgramTextObject(PyObject *filename, int lineno)
1174 {
1175     FILE *fp;
1176     if (filename == NULL || lineno <= 0)
1177         return NULL;
1178     fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
1179     if (fp == NULL) {
1180         PyErr_Clear();
1181         return NULL;
1182     }
1183     return err_programtext(fp, lineno);
1184 }
1185 
1186 #ifdef __cplusplus
1187 }
1188 #endif
1189