errors.c 18.2 KB
Newer Older
1

2
/* Error handling */
Guido van Rossum's avatar
Guido van Rossum committed
3

4
#include "Python.h"
5

Guido van Rossum's avatar
Guido van Rossum committed
6
#ifndef __STDC__
7
#ifndef MS_WINDOWS
8
extern char *strerror(int);
Guido van Rossum's avatar
Guido van Rossum committed
9
#endif
10
#endif
11

12
#ifdef MS_WINDOWS
13 14
#include <windows.h>
#include <winbase.h>
15 16
#endif

17 18
#include <ctype.h>

19 20 21 22 23
#ifdef __cplusplus
extern "C" {
#endif


Guido van Rossum's avatar
Guido van Rossum committed
24
void
25
PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
Guido van Rossum's avatar
Guido van Rossum committed
26
{
27
	PyThreadState *tstate = PyThreadState_GET();
28 29 30 31
	PyObject *oldtype, *oldvalue, *oldtraceback;

	if (traceback != NULL && !PyTraceBack_Check(traceback)) {
		/* XXX Should never happen -- fatal error instead? */
32
		/* Well, it could be None. */
33 34 35
		Py_DECREF(traceback);
		traceback = NULL;
	}
36

37 38 39 40 41 42 43 44 45 46 47 48 49
	/* Save these in locals to safeguard against recursive
	   invocation through Py_XDECREF */
	oldtype = tstate->curexc_type;
	oldvalue = tstate->curexc_value;
	oldtraceback = tstate->curexc_traceback;

	tstate->curexc_type = type;
	tstate->curexc_value = value;
	tstate->curexc_traceback = traceback;

	Py_XDECREF(oldtype);
	Py_XDECREF(oldvalue);
	Py_XDECREF(oldtraceback);
50 51 52
}

void
53
PyErr_SetObject(PyObject *exception, PyObject *value)
54
{
55 56 57
	if (exception != NULL &&
	    !PyExceptionClass_Check(exception)) {
		PyErr_Format(PyExc_SystemError,
58 59
			     "exception %R not a BaseException subclass",
			     exception);
60 61
		return;
	}
62 63 64
	Py_XINCREF(exception);
	Py_XINCREF(value);
	PyErr_Restore(exception, value, (PyObject *)NULL);
Guido van Rossum's avatar
Guido van Rossum committed
65 66 67
}

void
68
PyErr_SetNone(PyObject *exception)
Guido van Rossum's avatar
Guido van Rossum committed
69
{
70
	PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum's avatar
Guido van Rossum committed
71 72 73
}

void
74
PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum's avatar
Guido van Rossum committed
75
{
76
	PyObject *value = PyUnicode_FromString(string);
77 78
	PyErr_SetObject(exception, value);
	Py_XDECREF(value);
Guido van Rossum's avatar
Guido van Rossum committed
79 80
}

81

82
PyObject *
83
PyErr_Occurred(void)
Guido van Rossum's avatar
Guido van Rossum committed
84
{
85
	PyThreadState *tstate = PyThreadState_GET();
86 87

	return tstate->curexc_type;
Guido van Rossum's avatar
Guido van Rossum committed
88 89
}

90 91

int
92
PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
93
{
94 95 96 97
	if (err == NULL || exc == NULL) {
		/* maybe caused by "import exceptions" that failed early on */
		return 0;
	}
98
	if (PyTuple_Check(exc)) {
99
		Py_ssize_t i, n;
100 101 102 103 104 105 106 107 108 109 110 111
		n = PyTuple_Size(exc);
		for (i = 0; i < n; i++) {
			/* Test recursively */
		     if (PyErr_GivenExceptionMatches(
			     err, PyTuple_GET_ITEM(exc, i)))
		     {
			     return 1;
		     }
		}
		return 0;
	}
	/* err might be an instance, so check its class. */
112 113
	if (PyExceptionInstance_Check(err))
		err = PyExceptionInstance_Class(err);
114

115 116 117 118 119
	if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
		/* problems here!?  not sure PyObject_IsSubclass expects to
		   be called with an exception pending... */
		return PyObject_IsSubclass(err, exc);
	}
120 121 122

	return err == exc;
}
123

124 125

int
126
PyErr_ExceptionMatches(PyObject *exc)
127 128 129 130 131 132 133 134 135
{
	return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
}


/* Used in many places to normalize a raised exception, including in
   eval_code2(), do_raise(), and PyErr_Print()
*/
void
136
PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
137 138 139 140
{
	PyObject *type = *exc;
	PyObject *value = *val;
	PyObject *inclass = NULL;
141
	PyObject *initial_tb = NULL;
142
	PyThreadState *tstate = NULL;
143

144
	if (type == NULL) {
145 146
		/* There was no exception, so nothing to do. */
		return;
147 148
	}

149 150 151 152 153 154 155 156
	/* If PyErr_SetNone() was used, the value will have been actually
	   set to NULL.
	*/
	if (!value) {
		value = Py_None;
		Py_INCREF(value);
	}

157 158
	if (PyExceptionInstance_Check(value))
		inclass = PyExceptionInstance_Class(value);
159 160 161 162

	/* Normalize the exception so that if the type is a class, the
	   value will be an instance.
	*/
163
	if (PyExceptionClass_Check(type)) {
164 165 166 167 168
		/* if the value was not an instance, or is not an instance
		   whose class is (or is derived from) type, then use the
		   value as an argument to instantiation of the type
		   class.
		*/
169
		if (!inclass || !PyObject_IsSubclass(inclass, type)) {
170 171 172
			PyObject *args, *res;

			if (value == Py_None)
173
				args = PyTuple_New(0);
174 175 176 177 178
			else if (PyTuple_Check(value)) {
				Py_INCREF(value);
				args = value;
			}
			else
179
				args = PyTuple_Pack(1, value);
180 181 182 183 184 185 186 187 188 189

			if (args == NULL)
				goto finally;
			res = PyEval_CallObject(type, args);
			Py_DECREF(args);
			if (res == NULL)
				goto finally;
			Py_DECREF(value);
			value = res;
		}
190 191 192 193 194 195 196 197
		/* if the class of the instance doesn't exactly match the
		   class of the type, believe the instance
		*/
		else if (inclass != type) {
 			Py_DECREF(type);
			type = inclass;
			Py_INCREF(type);
		}
198 199 200 201 202
	}
	*exc = type;
	*val = value;
	return;
finally:
203 204
	Py_DECREF(type);
	Py_DECREF(value);
205 206 207 208 209
	/* If the new exception doesn't set a traceback and the old
	   exception had a traceback, use the old traceback for the
	   new exception.  It's better than nothing.
	*/
	initial_tb = *tb;
210
	PyErr_Fetch(exc, val, tb);
211 212 213 214 215 216
	if (initial_tb != NULL) {
		if (*tb == NULL)
			*tb = initial_tb;
		else
			Py_DECREF(initial_tb);
	}
217
	/* normalize recursively */
218 219 220 221 222 223
	tstate = PyThreadState_GET();
	if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
	    --tstate->recursion_depth;
	    PyErr_SetObject(PyExc_RuntimeError, PyExc_RecursionErrorInst);
	    return;
	}
224
	PyErr_NormalizeException(exc, val, tb);
225
	--tstate->recursion_depth;
226 227 228
}


Guido van Rossum's avatar
Guido van Rossum committed
229
void
230
PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum's avatar
Guido van Rossum committed
231
{
232
	PyThreadState *tstate = PyThreadState_GET();
233 234 235 236 237 238 239 240

	*p_type = tstate->curexc_type;
	*p_value = tstate->curexc_value;
	*p_traceback = tstate->curexc_traceback;

	tstate->curexc_type = NULL;
	tstate->curexc_value = NULL;
	tstate->curexc_traceback = NULL;
Guido van Rossum's avatar
Guido van Rossum committed
241 242 243
}

void
244
PyErr_Clear(void)
Guido van Rossum's avatar
Guido van Rossum committed
245
{
246
	PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum's avatar
Guido van Rossum committed
247
}
248 249 250 251

/* Convenience functions to set a type error exception and return 0 */

int
252
PyErr_BadArgument(void)
253
{
254
	PyErr_SetString(PyExc_TypeError,
Fred Drake's avatar
Fred Drake committed
255
			"bad argument type for built-in operation");
256 257 258
	return 0;
}

259
PyObject *
260
PyErr_NoMemory(void)
261
{
262 263 264 265
	if (PyErr_ExceptionMatches(PyExc_MemoryError))
		/* already current */
		return NULL;

266 267 268 269 270 271 272 273 274
	/* raise the pre-allocated instance if it still exists */
	if (PyExc_MemoryErrorInst)
		PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
	else
		/* this will probably fail since there's no memory and hee,
		   hee, we have to instantiate this class
		*/
		PyErr_SetNone(PyExc_MemoryError);

275 276 277
	return NULL;
}

278
PyObject *
279
PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
280
{
281
	PyObject *message;
282
	PyObject *v;
283
	int i = errno;
284 285
#ifdef PLAN9
	char errbuf[ERRMAX];
286 287 288 289 290 291 292 293
#else
#ifndef MS_WINDOWS
	char *s;
#else
	WCHAR *s_buf = NULL;
#endif /* Unix/Windows */
#endif /* PLAN 9*/

294
#ifdef EINTR
295
	if (i == EINTR && PyErr_CheckSignals())
296
		return NULL;
297
#endif
298

299 300
#ifdef PLAN9
	rerrstr(errbuf, sizeof errbuf);
301
	message = PyUnicode_DecodeUTF8(errbuf, strlen(errbuf), "ignore");
302
#else
303
#ifndef MS_WINDOWS
304 305 306 307
	if (i == 0)
		s = "Error"; /* Sometimes errno didn't get set */
	else
		s = strerror(i);
308
	message = PyUnicode_DecodeUTF8(s, strlen(s), "ignore");
309
#else
310 311 312
	if (i == 0)
		message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
	else
313
	{
314 315
		/* Note that the Win32 errors do not lineup with the
		   errno error.  So if the error is in the MSVC error
316
		   table, we use it, otherwise we assume it really _is_
317 318
		   a Win32 error code
		*/
319
		if (i > 0 && i < _sys_nerr) {
320
			message = PyUnicode_FromString(_sys_errlist[i]);
321 322
		}
		else {
323
			int len = FormatMessageW(
324 325 326 327 328 329 330 331
				FORMAT_MESSAGE_ALLOCATE_BUFFER |
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,	/* no message source */
				i,
				MAKELANGID(LANG_NEUTRAL,
					   SUBLANG_DEFAULT),
				           /* Default language */
332
				(LPWSTR) &s_buf,
333 334
				0,	/* size not used */
				NULL);	/* no args */
335
			if (len==0) {
336
				/* Only ever seen this in out-of-mem
337 338
				   situations */
				s_buf = NULL;
339
				message = PyUnicode_FromFormat("Windows Error 0x%X", i);
340 341
			} else {
				/* remove trailing cr/lf and dots */
342 343 344
				while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
					s_buf[--len] = L'\0';
				message = PyUnicode_FromUnicode(s_buf, len);
345
			}
346
		}
347
	}
348 349
#endif /* Unix/Windows */
#endif /* PLAN 9*/
350 351 352 353 354 355 356 357 358

	if (message == NULL)
	{
#ifdef MS_WINDOWS
		LocalFree(s_buf);
#endif
		return NULL;
	}

359
	if (filenameObject != NULL)
360
		v = Py_BuildValue("(iOO)", i, message, filenameObject);
361
	else
362 363 364
		v = Py_BuildValue("(iO)", i, message);
	Py_DECREF(message);

365
	if (v != NULL) {
366 367
		PyErr_SetObject(exc, v);
		Py_DECREF(v);
368
	}
369
#ifdef MS_WINDOWS
370
	LocalFree(s_buf);
371
#endif
372 373
	return NULL;
}
374

375

376
PyObject *
377
PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
378
{
379
	PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
380
	PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
381
	Py_XDECREF(name);
382 383 384 385 386
	return result;
}

#ifdef Py_WIN_WIDE_FILENAMES
PyObject *
387
PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
388
{
389 390
	PyObject *name = filename ?
	                 PyUnicode_FromUnicode(filename, wcslen(filename)) :
391 392 393 394 395 396 397
	                 NULL;
	PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
	Py_XDECREF(name);
	return result;
}
#endif /* Py_WIN_WIDE_FILENAMES */

398
PyObject *
399
PyErr_SetFromErrno(PyObject *exc)
400
{
401
	return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
402
}
Guido van Rossum's avatar
Guido van Rossum committed
403

404
#ifdef MS_WINDOWS
405
/* Windows specific error code handling */
406
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
407
	PyObject *exc,
408
	int ierr,
409
	PyObject *filenameObject)
410 411
{
	int len;
412 413
	WCHAR *s_buf = NULL; /* Free via LocalFree */
	PyObject *message;
414 415 416
	PyObject *v;
	DWORD err = (DWORD)ierr;
	if (err==0) err = GetLastError();
417
	len = FormatMessageW(
418 419 420 421 422 423 424 425
		/* Error API error */
		FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,	/* no message source */
		err,
		MAKELANGID(LANG_NEUTRAL,
		SUBLANG_DEFAULT), /* Default language */
426
		(LPWSTR) &s_buf,
427 428
		0,	/* size not used */
		NULL);	/* no args */
429 430
	if (len==0) {
		/* Only seen this in out of mem situations */
431
		message = PyUnicode_FromFormat("Windows Error 0x%X", err);
432 433 434
		s_buf = NULL;
	} else {
		/* remove trailing cr/lf and dots */
435 436 437
		while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
			s_buf[--len] = L'\0';
		message = PyUnicode_FromUnicode(s_buf, len);
438
	}
439 440 441 442 443 444 445

	if (message == NULL)
	{
		LocalFree(s_buf);
		return NULL;
	}

446
	if (filenameObject != NULL)
447
		v = Py_BuildValue("(iOO)", err, message, filenameObject);
448
	else
449 450 451
		v = Py_BuildValue("(iO)", err, message);
	Py_DECREF(message);

452
	if (v != NULL) {
453
		PyErr_SetObject(exc, v);
454 455
		Py_DECREF(v);
	}
456
	LocalFree(s_buf);
457 458 459
	return NULL;
}

460 461 462 463 464
PyObject *PyErr_SetExcFromWindowsErrWithFilename(
	PyObject *exc,
	int ierr,
	const char *filename)
{
465
	PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
466 467
	PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
	                                                             ierr,
468 469 470 471 472 473 474 475 476 477 478
	                                                             name);
	Py_XDECREF(name);
	return ret;
}

#ifdef Py_WIN_WIDE_FILENAMES
PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
	PyObject *exc,
	int ierr,
	const Py_UNICODE *filename)
{
479 480
	PyObject *name = filename ?
	                 PyUnicode_FromUnicode(filename, wcslen(filename)) :
481
	                 NULL;
482 483
	PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
	                                                             ierr,
484 485 486 487 488 489
	                                                             name);
	Py_XDECREF(name);
	return ret;
}
#endif /* Py_WIN_WIDE_FILENAMES */

490 491 492 493 494
PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
{
	return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
}

495 496
PyObject *PyErr_SetFromWindowsErr(int ierr)
{
497 498 499 500 501 502 503
	return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
						      ierr, NULL);
}
PyObject *PyErr_SetFromWindowsErrWithFilename(
	int ierr,
	const char *filename)
{
504
	PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
505 506 507
	PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
						      PyExc_WindowsError,
						      ierr, name);
508
	Py_XDECREF(name);
509 510 511 512 513 514 515 516
	return result;
}

#ifdef Py_WIN_WIDE_FILENAMES
PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
	int ierr,
	const Py_UNICODE *filename)
{
517 518
	PyObject *name = filename ?
	                 PyUnicode_FromUnicode(filename, wcslen(filename)) :
519 520 521 522
	                 NULL;
	PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
						      PyExc_WindowsError,
						      ierr, name);
523
	Py_XDECREF(name);
524
	return result;
525
}
526
#endif /* Py_WIN_WIDE_FILENAMES */
527 528
#endif /* MS_WINDOWS */

529
void
530
_PyErr_BadInternalCall(const char *filename, int lineno)
531 532 533 534 535 536 537 538 539
{
	PyErr_Format(PyExc_SystemError,
		     "%s:%d: bad argument to internal function",
		     filename, lineno);
}

/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
   export the entry point for existing object code: */
#undef PyErr_BadInternalCall
Guido van Rossum's avatar
Guido van Rossum committed
540
void
541
PyErr_BadInternalCall(void)
Guido van Rossum's avatar
Guido van Rossum committed
542
{
543 544
	PyErr_Format(PyExc_SystemError,
		     "bad argument to internal function");
Guido van Rossum's avatar
Guido van Rossum committed
545
}
546 547
#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)

548 549 550 551 552 553


PyObject *
PyErr_Format(PyObject *exception, const char *format, ...)
{
	va_list vargs;
554
	PyObject* string;
555

556
#ifdef HAVE_STDARG_PROTOTYPES
557
	va_start(vargs, format);
558 559 560
#else
	va_start(vargs);
#endif
561

562
	string = PyUnicode_FromFormatV(format, vargs);
563 564
	PyErr_SetObject(exception, string);
	Py_XDECREF(string);
565
	va_end(vargs);
566 567
	return NULL;
}
568 569


570

571
PyObject *
572
PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
573
{
574
	const char *dot;
575 576 577 578
	PyObject *modulename = NULL;
	PyObject *classname = NULL;
	PyObject *mydict = NULL;
	PyObject *bases = NULL;
579
	PyObject *result = NULL;
580 581 582 583
	dot = strrchr(name, '.');
	if (dot == NULL) {
		PyErr_SetString(PyExc_SystemError,
			"PyErr_NewException: name must be module.class");
584
		return NULL;
585 586 587
	}
	if (base == NULL)
		base = PyExc_Exception;
588
	if (dict == NULL) {
589
		dict = mydict = PyDict_New();
590 591 592
		if (dict == NULL)
			goto failure;
	}
593
	if (PyDict_GetItemString(dict, "__module__") == NULL) {
594
		modulename = PyUnicode_FromStringAndSize(name,
595
						     (Py_ssize_t)(dot-name));
596 597 598 599 600
		if (modulename == NULL)
			goto failure;
		if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
			goto failure;
	}
601 602 603 604 605 606 607 608 609 610
	if (PyTuple_Check(base)) {
		bases = base;
		/* INCREF as we create a new ref in the else branch */
		Py_INCREF(bases);
	} else {
		bases = PyTuple_Pack(1, base);
		if (bases == NULL)
			goto failure;
	}
	/* Create a real new-style class. */
611
	result = PyObject_CallFunction((PyObject *)&PyType_Type, "UOO",
612
				       dot+1, bases, dict);
613
  failure:
614 615 616 617
	Py_XDECREF(bases);
	Py_XDECREF(mydict);
	Py_XDECREF(classname);
	Py_XDECREF(modulename);
618 619
	return result;
}
620 621 622 623 624 625 626 627 628

/* Call when an exception has occurred but there is no way for Python
   to handle it.  Examples: exception in __del__ or during GC. */
void
PyErr_WriteUnraisable(PyObject *obj)
{
	PyObject *f, *t, *v, *tb;
	PyErr_Fetch(&t, &v, &tb);
	f = PySys_GetObject("stderr");
629
	if (f != NULL && f != Py_None) {
630 631
		PyFile_WriteString("Exception ", f);
		if (t) {
632
			PyObject* moduleName;
633 634 635
			char* className;
			assert(PyExceptionClass_Check(t));
			className = PyExceptionClass_Name(t);
636 637 638 639 640 641 642
			if (className != NULL) {
				char *dot = strrchr(className, '.');
				if (dot != NULL)
					className = dot+1;
			}

			moduleName = PyObject_GetAttrString(t, "__module__");
643 644 645
			if (moduleName == NULL)
				PyFile_WriteString("<unknown>", f);
			else {
646
				char* modstr = PyUnicode_AsString(moduleName);
647
				if (modstr &&
648
				    strcmp(modstr, "builtins") != 0)
649 650 651 652 653 654 655 656 657
				{
					PyFile_WriteString(modstr, f);
					PyFile_WriteString(".", f);
				}
			}
			if (className == NULL)
				PyFile_WriteString("<unknown>", f);
			else
				PyFile_WriteString(className, f);
658 659 660 661
			if (v && v != Py_None) {
				PyFile_WriteString(": ", f);
				PyFile_WriteObject(v, f, 0);
			}
662
			Py_XDECREF(moduleName);
663 664 665 666 667 668 669 670 671 672
		}
		PyFile_WriteString(" in ", f);
		PyFile_WriteObject(obj, f, 0);
		PyFile_WriteString(" ignored\n", f);
		PyErr_Clear(); /* Just in case */
	}
	Py_XDECREF(t);
	Py_XDECREF(v);
	Py_XDECREF(tb);
}
Guido van Rossum's avatar
Guido van Rossum committed
673

674
extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossum's avatar
Guido van Rossum committed
675

676

677 678 679
/* Set file and line information for the current exception.
   If the exception is not a SyntaxError, also sets additional attributes
   to make printing of exceptions believe it is a syntax error. */
680

681
void
682
PyErr_SyntaxLocation(const char *filename, int lineno)
683 684 685 686 687 688
{
	PyObject *exc, *v, *tb, *tmp;

	/* add attributes for the line number and filename for the error */
	PyErr_Fetch(&exc, &v, &tb);
	PyErr_NormalizeException(&exc, &v, &tb);
689 690
	/* XXX check that it is, indeed, a syntax error. It might not
	 * be, though. */
691
	tmp = PyLong_FromLong(lineno);
692 693 694 695 696 697 698 699
	if (tmp == NULL)
		PyErr_Clear();
	else {
		if (PyObject_SetAttrString(v, "lineno", tmp))
			PyErr_Clear();
		Py_DECREF(tmp);
	}
	if (filename != NULL) {
700
		tmp = PyUnicode_FromString(filename);
701 702 703 704 705 706 707 708 709 710
		if (tmp == NULL)
			PyErr_Clear();
		else {
			if (PyObject_SetAttrString(v, "filename", tmp))
				PyErr_Clear();
			Py_DECREF(tmp);
		}

		tmp = PyErr_ProgramText(filename, lineno);
		if (tmp) {
711 712
			if (PyObject_SetAttrString(v, "text", tmp))
				PyErr_Clear();
713 714 715
			Py_DECREF(tmp);
		}
	}
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
	if (PyObject_SetAttrString(v, "offset", Py_None)) {
		PyErr_Clear();
	}
	if (exc != PyExc_SyntaxError) {
		if (!PyObject_HasAttrString(v, "msg")) {
			tmp = PyObject_Str(v);
			if (tmp) {
				if (PyObject_SetAttrString(v, "msg", tmp))
					PyErr_Clear();
				Py_DECREF(tmp);
			} else {
				PyErr_Clear();
			}
		}
		if (!PyObject_HasAttrString(v, "print_file_and_line")) {
			if (PyObject_SetAttrString(v, "print_file_and_line",
						   Py_None))
				PyErr_Clear();
		}
	}
736 737 738
	PyErr_Restore(exc, v, tb);
}

739 740
/* Attempt to load the line of text that the exception refers to.  If it
   fails, it will return NULL but will not set an exception.
741 742

   XXX The functionality of this function is quite similar to the
743
   functionality in tb_displayline() in traceback.c. */
744 745

PyObject *
746
PyErr_ProgramText(const char *filename, int lineno)
747 748 749 750 751
{
	FILE *fp;
	int i;
	char linebuf[1000];

752
	if (filename == NULL || *filename == '\0' || lineno <= 0)
753
		return NULL;
754
	fp = fopen(filename, "r" PY_STDIOTEXTMODE);
755 756 757 758 759 760
	if (fp == NULL)
		return NULL;
	for (i = 0; i < lineno; i++) {
		char *pLastChar = &linebuf[sizeof(linebuf) - 2];
		do {
			*pLastChar = '\0';
761 762
			if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
						     fp, NULL) == NULL)
763 764 765
				break;
			/* fgets read *something*; if it didn't get as
			   far as pLastChar, it must have found a newline
766
			   or hit the end of the file; if pLastChar is \n,
767 768 769 770 771 772 773
			   it obviously found a newline; else we haven't
			   yet seen a newline, so must continue */
		} while (*pLastChar != '\0' && *pLastChar != '\n');
	}
	fclose(fp);
	if (i == lineno) {
		char *p = linebuf;
774
                PyObject *res;
775 776
		while (*p == ' ' || *p == '\t' || *p == '\014')
			p++;
777 778 779 780
		res = PyUnicode_FromString(p);
                if (res == NULL)
			PyErr_Clear();
		return res;
781 782 783
	}
	return NULL;
}
784 785 786 787

#ifdef __cplusplus
}
#endif