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