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