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