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