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