Location | Tool | Test ID | Function | Issue |
---|---|---|---|---|
/builddir/build/BUILD/Python-2.7.3/Python/errors.c:183:22 | clang-analyzer | Access to field 'tp_flags' results in a dereference of a null pointer (loaded from field 'ob_type') | ||
/builddir/build/BUILD/Python-2.7.3/Python/errors.c:196:13 | clang-analyzer | Access to field 'tp_dealloc' results in a dereference of a null pointer (loaded from field 'ob_type') | ||
/builddir/build/BUILD/Python-2.7.3/Python/errors.c:213:5 | clang-analyzer | Access to field 'tp_dealloc' results in a dereference of a null pointer (loaded from field 'ob_type') |
1 /* Error handling */
2
3 #include "Python.h"
4
5 #ifndef __STDC__
6 #ifndef MS_WINDOWS
7 extern char *strerror(int);
8 #endif
9 #endif
10
11 #ifdef MS_WINDOWS
12 #include "windows.h"
13 #include "winbase.h"
14 #endif
15
16 #include <ctype.h>
17
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
21
22
23 void
24 PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
25 {
26 PyThreadState *tstate = PyThreadState_GET();
27 PyObject *oldtype, *oldvalue, *oldtraceback;
28
29 if (traceback != NULL && !PyTraceBack_Check(traceback)) {
30 /* XXX Should never happen -- fatal error instead? */
31 /* Well, it could be None. */
32 Py_DECREF(traceback);
33 traceback = NULL;
34 }
35
36 /* Save these in locals to safeguard against recursive
37 invocation through Py_XDECREF */
38 oldtype = tstate->curexc_type;
39 oldvalue = tstate->curexc_value;
40 oldtraceback = tstate->curexc_traceback;
41
42 tstate->curexc_type = type;
43 tstate->curexc_value = value;
44 tstate->curexc_traceback = traceback;
45
46 Py_XDECREF(oldtype);
47 Py_XDECREF(oldvalue);
48 Py_XDECREF(oldtraceback);
49 }
50
51 void
52 PyErr_SetObject(PyObject *exception, PyObject *value)
53 {
54 Py_XINCREF(exception);
55 Py_XINCREF(value);
56 PyErr_Restore(exception, value, (PyObject *)NULL);
57 }
58
59 void
60 PyErr_SetNone(PyObject *exception)
61 {
62 PyErr_SetObject(exception, (PyObject *)NULL);
63 }
64
65 void
66 PyErr_SetString(PyObject *exception, const char *string)
67 {
68 PyObject *value = PyString_FromString(string);
69 PyErr_SetObject(exception, value);
70 Py_XDECREF(value);
71 }
72
73
74 PyObject *
75 PyErr_Occurred(void)
76 {
77 PyThreadState *tstate = PyThreadState_GET();
78
79 return tstate->curexc_type;
80 }
81
82
83 int
84 PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
85 {
86 if (err == NULL || exc == NULL) {
87 /* maybe caused by "import exceptions" that failed early on */
88 return 0;
89 }
90 if (PyTuple_Check(exc)) {
91 Py_ssize_t i, n;
92 n = PyTuple_Size(exc);
93 for (i = 0; i < n; i++) {
94 /* Test recursively */
95 if (PyErr_GivenExceptionMatches(
96 err, PyTuple_GET_ITEM(exc, i)))
97 {
98 return 1;
99 }
100 }
101 return 0;
102 }
103 /* err might be an instance, so check its class. */
104 if (PyExceptionInstance_Check(err))
105 err = PyExceptionInstance_Class(err);
106
107 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
108 int res = 0, reclimit;
109 PyObject *exception, *value, *tb;
110 PyErr_Fetch(&exception, &value, &tb);
111 /* Temporarily bump the recursion limit, so that in the most
112 common case PyObject_IsSubclass will not raise a recursion
113 error we have to ignore anyway. Don't do it when the limit
114 is already insanely high, to avoid overflow */
115 reclimit = Py_GetRecursionLimit();
116 if (reclimit < (1 << 30))
117 Py_SetRecursionLimit(reclimit + 5);
118 res = PyObject_IsSubclass(err, exc);
119 Py_SetRecursionLimit(reclimit);
120 /* This function must not fail, so print the error here */
121 if (res == -1) {
122 PyErr_WriteUnraisable(err);
123 res = 0;
124 }
125 PyErr_Restore(exception, value, tb);
126 return res;
127 }
128
129 return err == exc;
130 }
131
132
133 int
134 PyErr_ExceptionMatches(PyObject *exc)
135 {
136 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
137 }
138
139
140 /* Used in many places to normalize a raised exception, including in
141 eval_code2(), do_raise(), and PyErr_Print()
142 */
143 void
144 PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
145 {
146 PyObject *type = *exc;
147 PyObject *value = *val;
148 PyObject *inclass = NULL;
149 PyObject *initial_tb = NULL;
150 PyThreadState *tstate = NULL;
151
152 if (type == NULL) {
153 /* There was no exception, so nothing to do. */
154 return;
155 }
156
157 /* If PyErr_SetNone() was used, the value will have been actually
158 set to NULL.
159 */
160 if (!value) {
161 value = Py_None;
162 Py_INCREF(value);
163 }
164
165 if (PyExceptionInstance_Check(value))
166 inclass = PyExceptionInstance_Class(value);
167
168 /* Normalize the exception so that if the type is a class, the
169 value will be an instance.
170 */
171 if (PyExceptionClass_Check(type)) {
172 /* if the value was not an instance, or is not an instance
173 whose class is (or is derived from) type, then use the
174 value as an argument to instantiation of the type
175 class.
176 */
177 if (!inclass || !PyObject_IsSubclass(inclass, type)) {
178 PyObject *args, *res;
179
180 if (value == Py_None)
181 args = PyTuple_New(0);
182 else if (PyTuple_Check(value)) {
183 Py_INCREF(value);
(emitted by clang-analyzer)TODO: a detailed trace is available in the data model (not yet rendered in this report)
184 args = value;
185 }
186 else
187 args = PyTuple_Pack(1, value);
188
189 if (args == NULL)
190 goto finally;
191 res = PyEval_CallObject(type, args);
192 Py_DECREF(args);
193 if (res == NULL)
194 goto finally;
195 Py_DECREF(value);
196 value = res;
(emitted by clang-analyzer)TODO: a detailed trace is available in the data model (not yet rendered in this report)
197 }
198 /* if the class of the instance doesn't exactly match the
199 class of the type, believe the instance
200 */
201 else if (inclass != type) {
202 Py_DECREF(type);
203 type = inclass;
204 Py_INCREF(type);
205 }
206 }
207 *exc = type;
208 *val = value;
209 return;
210 finally:
211 Py_DECREF(type);
212 Py_DECREF(value);
213 /* If the new exception doesn't set a traceback and the old
(emitted by clang-analyzer)TODO: a detailed trace is available in the data model (not yet rendered in this report)
214 exception had a traceback, use the old traceback for the
215 new exception. It's better than nothing.
216 */
217 initial_tb = *tb;
218 PyErr_Fetch(exc, val, tb);
219 if (initial_tb != NULL) {
220 if (*tb == NULL)
221 *tb = initial_tb;
222 else
223 Py_DECREF(initial_tb);
224 }
225 /* normalize recursively */
226 tstate = PyThreadState_GET();
227 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
228 --tstate->recursion_depth;
229 /* throw away the old exception... */
230 Py_DECREF(*exc);
231 Py_DECREF(*val);
232 /* ... and use the recursion error instead */
233 *exc = PyExc_RuntimeError;
234 *val = PyExc_RecursionErrorInst;
235 Py_INCREF(*exc);
236 Py_INCREF(*val);
237 /* just keeping the old traceback */
238 return;
239 }
240 PyErr_NormalizeException(exc, val, tb);
241 --tstate->recursion_depth;
242 }
243
244
245 void
246 PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
247 {
248 PyThreadState *tstate = PyThreadState_GET();
249
250 *p_type = tstate->curexc_type;
251 *p_value = tstate->curexc_value;
252 *p_traceback = tstate->curexc_traceback;
253
254 tstate->curexc_type = NULL;
255 tstate->curexc_value = NULL;
256 tstate->curexc_traceback = NULL;
257 }
258
259 void
260 PyErr_Clear(void)
261 {
262 PyErr_Restore(NULL, NULL, NULL);
263 }
264
265 /* Convenience functions to set a type error exception and return 0 */
266
267 int
268 PyErr_BadArgument(void)
269 {
270 PyErr_SetString(PyExc_TypeError,
271 "bad argument type for built-in operation");
272 return 0;
273 }
274
275 PyObject *
276 PyErr_NoMemory(void)
277 {
278 if (PyErr_ExceptionMatches(PyExc_MemoryError))
279 /* already current */
280 return NULL;
281
282 /* raise the pre-allocated instance if it still exists */
283 if (PyExc_MemoryErrorInst)
284 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
285 else
286 /* this will probably fail since there's no memory and hee,
287 hee, we have to instantiate this class
288 */
289 PyErr_SetNone(PyExc_MemoryError);
290
291 return NULL;
292 }
293
294 PyObject *
295 PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
296 {
297 PyObject *v;
298 char *s;
299 int i = errno;
300 #ifdef PLAN9
301 char errbuf[ERRMAX];
302 #endif
303 #ifdef MS_WINDOWS
304 char *s_buf = NULL;
305 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
306 #endif
307 #ifdef EINTR
308 if (i == EINTR && PyErr_CheckSignals())
309 return NULL;
310 #endif
311 #ifdef PLAN9
312 rerrstr(errbuf, sizeof errbuf);
313 s = errbuf;
314 #else
315 if (i == 0)
316 s = "Error"; /* Sometimes errno didn't get set */
317 else
318 #ifndef MS_WINDOWS
319 s = strerror(i);
320 #else
321 {
322 /* Note that the Win32 errors do not lineup with the
323 errno error. So if the error is in the MSVC error
324 table, we use it, otherwise we assume it really _is_
325 a Win32 error code
326 */
327 if (i > 0 && i < _sys_nerr) {
328 s = _sys_errlist[i];
329 }
330 else {
331 int len = FormatMessage(
332 FORMAT_MESSAGE_ALLOCATE_BUFFER |
333 FORMAT_MESSAGE_FROM_SYSTEM |
334 FORMAT_MESSAGE_IGNORE_INSERTS,
335 NULL, /* no message source */
336 i,
337 MAKELANGID(LANG_NEUTRAL,
338 SUBLANG_DEFAULT),
339 /* Default language */
340 (LPTSTR) &s_buf,
341 0, /* size not used */
342 NULL); /* no args */
343 if (len==0) {
344 /* Only ever seen this in out-of-mem
345 situations */
346 sprintf(s_small_buf, "Windows Error 0x%X", i);
347 s = s_small_buf;
348 s_buf = NULL;
349 } else {
350 s = s_buf;
351 /* remove trailing cr/lf and dots */
352 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
353 s[--len] = '\0';
354 }
355 }
356 }
357 #endif /* Unix/Windows */
358 #endif /* PLAN 9*/
359 if (filenameObject != NULL)
360 v = Py_BuildValue("(isO)", i, s, filenameObject);
361 else
362 v = Py_BuildValue("(is)", i, s);
363 if (v != NULL) {
364 PyErr_SetObject(exc, v);
365 Py_DECREF(v);
366 }
367 #ifdef MS_WINDOWS
368 LocalFree(s_buf);
369 #endif
370 return NULL;
371 }
372
373
374 PyObject *
375 PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
376 {
377 PyObject *name = filename ? PyString_FromString(filename) : NULL;
378 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
379 Py_XDECREF(name);
380 return result;
381 }
382
383 #ifdef MS_WINDOWS
384 PyObject *
385 PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
386 {
387 PyObject *name = filename ?
388 PyUnicode_FromUnicode(filename, wcslen(filename)) :
389 NULL;
390 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
391 Py_XDECREF(name);
392 return result;
393 }
394 #endif /* MS_WINDOWS */
395
396 PyObject *
397 PyErr_SetFromErrno(PyObject *exc)
398 {
399 return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
400 }
401
402 #ifdef MS_WINDOWS
403 /* Windows specific error code handling */
404 PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
405 PyObject *exc,
406 int ierr,
407 PyObject *filenameObject)
408 {
409 int len;
410 char *s;
411 char *s_buf = NULL; /* Free via LocalFree */
412 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
413 PyObject *v;
414 DWORD err = (DWORD)ierr;
415 if (err==0) err = GetLastError();
416 len = FormatMessage(
417 /* Error API error */
418 FORMAT_MESSAGE_ALLOCATE_BUFFER |
419 FORMAT_MESSAGE_FROM_SYSTEM |
420 FORMAT_MESSAGE_IGNORE_INSERTS,
421 NULL, /* no message source */
422 err,
423 MAKELANGID(LANG_NEUTRAL,
424 SUBLANG_DEFAULT), /* Default language */
425 (LPTSTR) &s_buf,
426 0, /* size not used */
427 NULL); /* no args */
428 if (len==0) {
429 /* Only seen this in out of mem situations */
430 sprintf(s_small_buf, "Windows Error 0x%X", err);
431 s = s_small_buf;
432 s_buf = NULL;
433 } else {
434 s = s_buf;
435 /* remove trailing cr/lf and dots */
436 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
437 s[--len] = '\0';
438 }
439 if (filenameObject != NULL)
440 v = Py_BuildValue("(isO)", err, s, filenameObject);
441 else
442 v = Py_BuildValue("(is)", err, s);
443 if (v != NULL) {
444 PyErr_SetObject(exc, v);
445 Py_DECREF(v);
446 }
447 LocalFree(s_buf);
448 return NULL;
449 }
450
451 PyObject *PyErr_SetExcFromWindowsErrWithFilename(
452 PyObject *exc,
453 int ierr,
454 const char *filename)
455 {
456 PyObject *name = filename ? PyString_FromString(filename) : NULL;
457 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
458 ierr,
459 name);
460 Py_XDECREF(name);
461 return ret;
462 }
463
464 PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
465 PyObject *exc,
466 int ierr,
467 const Py_UNICODE *filename)
468 {
469 PyObject *name = filename ?
470 PyUnicode_FromUnicode(filename, wcslen(filename)) :
471 NULL;
472 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
473 ierr,
474 name);
475 Py_XDECREF(name);
476 return ret;
477 }
478
479 PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
480 {
481 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
482 }
483
484 PyObject *PyErr_SetFromWindowsErr(int ierr)
485 {
486 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
487 ierr, NULL);
488 }
489 PyObject *PyErr_SetFromWindowsErrWithFilename(
490 int ierr,
491 const char *filename)
492 {
493 PyObject *name = filename ? PyString_FromString(filename) : NULL;
494 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
495 PyExc_WindowsError,
496 ierr, name);
497 Py_XDECREF(name);
498 return result;
499 }
500
501 PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
502 int ierr,
503 const Py_UNICODE *filename)
504 {
505 PyObject *name = filename ?
506 PyUnicode_FromUnicode(filename, wcslen(filename)) :
507 NULL;
508 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
509 PyExc_WindowsError,
510 ierr, name);
511 Py_XDECREF(name);
512 return result;
513 }
514 #endif /* MS_WINDOWS */
515
516 void
517 _PyErr_BadInternalCall(char *filename, int lineno)
518 {
519 PyErr_Format(PyExc_SystemError,
520 "%s:%d: bad argument to internal function",
521 filename, lineno);
522 }
523
524 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
525 export the entry point for existing object code: */
526 #undef PyErr_BadInternalCall
527 void
528 PyErr_BadInternalCall(void)
529 {
530 PyErr_Format(PyExc_SystemError,
531 "bad argument to internal function");
532 }
533 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
534
535
536
537 PyObject *
538 PyErr_Format(PyObject *exception, const char *format, ...)
539 {
540 va_list vargs;
541 PyObject* string;
542
543 #ifdef HAVE_STDARG_PROTOTYPES
544 va_start(vargs, format);
545 #else
546 va_start(vargs);
547 #endif
548
549 string = PyString_FromFormatV(format, vargs);
550 PyErr_SetObject(exception, string);
551 Py_XDECREF(string);
552 va_end(vargs);
553 return NULL;
554 }
555
556
557
558 PyObject *
559 PyErr_NewException(char *name, PyObject *base, PyObject *dict)
560 {
561 char *dot;
562 PyObject *modulename = NULL;
563 PyObject *classname = NULL;
564 PyObject *mydict = NULL;
565 PyObject *bases = NULL;
566 PyObject *result = NULL;
567 dot = strrchr(name, '.');
568 if (dot == NULL) {
569 PyErr_SetString(PyExc_SystemError,
570 "PyErr_NewException: name must be module.class");
571 return NULL;
572 }
573 if (base == NULL)
574 base = PyExc_Exception;
575 if (dict == NULL) {
576 dict = mydict = PyDict_New();
577 if (dict == NULL)
578 goto failure;
579 }
580 if (PyDict_GetItemString(dict, "__module__") == NULL) {
581 modulename = PyString_FromStringAndSize(name,
582 (Py_ssize_t)(dot-name));
583 if (modulename == NULL)
584 goto failure;
585 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
586 goto failure;
587 }
588 if (PyTuple_Check(base)) {
589 bases = base;
590 /* INCREF as we create a new ref in the else branch */
591 Py_INCREF(bases);
592 } else {
593 bases = PyTuple_Pack(1, base);
594 if (bases == NULL)
595 goto failure;
596 }
597 /* Create a real new-style class. */
598 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
599 dot+1, bases, dict);
600 failure:
601 Py_XDECREF(bases);
602 Py_XDECREF(mydict);
603 Py_XDECREF(classname);
604 Py_XDECREF(modulename);
605 return result;
606 }
607
608
609 /* Create an exception with docstring */
610 PyObject *
611 PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict)
612 {
613 int result;
614 PyObject *ret = NULL;
615 PyObject *mydict = NULL; /* points to the dict only if we create it */
616 PyObject *docobj;
617
618 if (dict == NULL) {
619 dict = mydict = PyDict_New();
620 if (dict == NULL) {
621 return NULL;
622 }
623 }
624
625 if (doc != NULL) {
626 docobj = PyString_FromString(doc);
627 if (docobj == NULL)
628 goto failure;
629 result = PyDict_SetItemString(dict, "__doc__", docobj);
630 Py_DECREF(docobj);
631 if (result < 0)
632 goto failure;
633 }
634
635 ret = PyErr_NewException(name, base, dict);
636 failure:
637 Py_XDECREF(mydict);
638 return ret;
639 }
640
641
642 /* Call when an exception has occurred but there is no way for Python
643 to handle it. Examples: exception in __del__ or during GC. */
644 void
645 PyErr_WriteUnraisable(PyObject *obj)
646 {
647 PyObject *f, *t, *v, *tb;
648 PyErr_Fetch(&t, &v, &tb);
649 f = PySys_GetObject("stderr");
650 if (f != NULL) {
651 PyFile_WriteString("Exception ", f);
652 if (t) {
653 PyObject* moduleName;
654 char* className;
655 assert(PyExceptionClass_Check(t));
656 className = PyExceptionClass_Name(t);
657 if (className != NULL) {
658 char *dot = strrchr(className, '.');
659 if (dot != NULL)
660 className = dot+1;
661 }
662
663 moduleName = PyObject_GetAttrString(t, "__module__");
664 if (moduleName == NULL)
665 PyFile_WriteString("<unknown>", f);
666 else {
667 char* modstr = PyString_AsString(moduleName);
668 if (modstr &&
669 strcmp(modstr, "exceptions") != 0)
670 {
671 PyFile_WriteString(modstr, f);
672 PyFile_WriteString(".", f);
673 }
674 }
675 if (className == NULL)
676 PyFile_WriteString("<unknown>", f);
677 else
678 PyFile_WriteString(className, f);
679 if (v && v != Py_None) {
680 PyFile_WriteString(": ", f);
681 PyFile_WriteObject(v, f, 0);
682 }
683 Py_XDECREF(moduleName);
684 }
685 PyFile_WriteString(" in ", f);
686 PyFile_WriteObject(obj, f, 0);
687 PyFile_WriteString(" ignored\n", f);
688 PyErr_Clear(); /* Just in case */
689 }
690 Py_XDECREF(t);
691 Py_XDECREF(v);
692 Py_XDECREF(tb);
693 }
694
695 extern PyObject *PyModule_GetWarningsModule(void);
696
697
698 /* Set file and line information for the current exception.
699 If the exception is not a SyntaxError, also sets additional attributes
700 to make printing of exceptions believe it is a syntax error. */
701
702 void
703 PyErr_SyntaxLocation(const char *filename, int lineno)
704 {
705 PyObject *exc, *v, *tb, *tmp;
706
707 /* add attributes for the line number and filename for the error */
708 PyErr_Fetch(&exc, &v, &tb);
709 PyErr_NormalizeException(&exc, &v, &tb);
710 /* XXX check that it is, indeed, a syntax error. It might not
711 * be, though. */
712 tmp = PyInt_FromLong(lineno);
713 if (tmp == NULL)
714 PyErr_Clear();
715 else {
716 if (PyObject_SetAttrString(v, "lineno", tmp))
717 PyErr_Clear();
718 Py_DECREF(tmp);
719 }
720 if (filename != NULL) {
721 tmp = PyString_FromString(filename);
722 if (tmp == NULL)
723 PyErr_Clear();
724 else {
725 if (PyObject_SetAttrString(v, "filename", tmp))
726 PyErr_Clear();
727 Py_DECREF(tmp);
728 }
729
730 tmp = PyErr_ProgramText(filename, lineno);
731 if (tmp) {
732 if (PyObject_SetAttrString(v, "text", tmp))
733 PyErr_Clear();
734 Py_DECREF(tmp);
735 }
736 }
737 if (PyObject_SetAttrString(v, "offset", Py_None)) {
738 PyErr_Clear();
739 }
740 if (exc != PyExc_SyntaxError) {
741 if (!PyObject_HasAttrString(v, "msg")) {
742 tmp = PyObject_Str(v);
743 if (tmp) {
744 if (PyObject_SetAttrString(v, "msg", tmp))
745 PyErr_Clear();
746 Py_DECREF(tmp);
747 } else {
748 PyErr_Clear();
749 }
750 }
751 if (!PyObject_HasAttrString(v, "print_file_and_line")) {
752 if (PyObject_SetAttrString(v, "print_file_and_line",
753 Py_None))
754 PyErr_Clear();
755 }
756 }
757 PyErr_Restore(exc, v, tb);
758 }
759
760 /* com_fetch_program_text will attempt to load the line of text that
761 the exception refers to. If it fails, it will return NULL but will
762 not set an exception.
763
764 XXX The functionality of this function is quite similar to the
765 functionality in tb_displayline() in traceback.c.
766 */
767
768 PyObject *
769 PyErr_ProgramText(const char *filename, int lineno)
770 {
771 FILE *fp;
772 int i;
773 char linebuf[1000];
774
775 if (filename == NULL || *filename == '\0' || lineno <= 0)
776 return NULL;
777 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
778 if (fp == NULL)
779 return NULL;
780 for (i = 0; i < lineno; i++) {
781 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
782 do {
783 *pLastChar = '\0';
784 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
785 break;
786 /* fgets read *something*; if it didn't get as
787 far as pLastChar, it must have found a newline
788 or hit the end of the file; if pLastChar is \n,
789 it obviously found a newline; else we haven't
790 yet seen a newline, so must continue */
791 } while (*pLastChar != '\0' && *pLastChar != '\n');
792 }
793 fclose(fp);
794 if (i == lineno) {
795 char *p = linebuf;
796 while (*p == ' ' || *p == '\t' || *p == '\014')
797 p++;
798 return PyString_FromString(p);
799 }
800 return NULL;
801 }
802
803 #ifdef __cplusplus
804 }
805 #endif