errors.c 18.9 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 15 16
#include "windows.h"
#include "winbase.h"
#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

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

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

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

	/* Normalize the exception so that if the type is a class, the
	   value will be an instance.
	*/
162
	if (PyExceptionClass_Check(type)) {
163 164 165 166 167
		/* 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.
		*/
168
		if (!inclass || !PyObject_IsSubclass(inclass, type)) {
169 170 171
			PyObject *args, *res;

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

			if (args == NULL)
				goto finally;
			res = PyEval_CallObject(type, args);
			Py_DECREF(args);
			if (res == NULL)
				goto finally;
			Py_DECREF(value);
			value = res;
		}
189 190 191 192 193 194 195 196
		/* 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);
		}
197 198 199 200 201
	}
	*exc = type;
	*val = value;
	return;
finally:
202 203
	Py_DECREF(type);
	Py_DECREF(value);
204 205 206 207 208
	/* 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;
209
	PyErr_Fetch(exc, val, tb);
210 211 212 213 214 215
	if (initial_tb != NULL) {
		if (*tb == NULL)
			*tb = initial_tb;
		else
			Py_DECREF(initial_tb);
	}
216 217 218 219 220
	/* normalize recursively */
	PyErr_NormalizeException(exc, val, tb);
}


Guido van Rossum's avatar
Guido van Rossum committed
221
void
222
PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum's avatar
Guido van Rossum committed
223
{
224
	PyThreadState *tstate = PyThreadState_GET();
225 226 227 228 229 230 231 232

	*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
233 234 235
}

void
236
PyErr_Clear(void)
Guido van Rossum's avatar
Guido van Rossum committed
237
{
238
	PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum's avatar
Guido van Rossum committed
239
}
240 241 242 243

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

int
244
PyErr_BadArgument(void)
245
{
246
	PyErr_SetString(PyExc_TypeError,
Fred Drake's avatar
Fred Drake committed
247
			"bad argument type for built-in operation");
248 249 250
	return 0;
}

251
PyObject *
252
PyErr_NoMemory(void)
253
{
254 255 256 257
	if (PyErr_ExceptionMatches(PyExc_MemoryError))
		/* already current */
		return NULL;

258 259 260 261 262 263 264 265 266
	/* 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);

267 268 269
	return NULL;
}

270
PyObject *
271
PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
272
{
273
	PyObject *v;
274
	char *s;
275
	int i = errno;
276 277 278
#ifdef PLAN9
	char errbuf[ERRMAX];
#endif
279
#ifdef MS_WINDOWS
280
	char *s_buf = NULL;
281
	char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
282
#endif
283
#ifdef EINTR
284
	if (i == EINTR && PyErr_CheckSignals())
285
		return NULL;
286
#endif
287 288 289 290
#ifdef PLAN9
	rerrstr(errbuf, sizeof errbuf);
	s = errbuf;
#else
291 292 293
	if (i == 0)
		s = "Error"; /* Sometimes errno didn't get set */
	else
294
#ifndef MS_WINDOWS
295
		s = strerror(i);
296 297
#else
	{
298 299
		/* Note that the Win32 errors do not lineup with the
		   errno error.  So if the error is in the MSVC error
300
		   table, we use it, otherwise we assume it really _is_
301 302
		   a Win32 error code
		*/
303
		if (i > 0 && i < _sys_nerr) {
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
			s = _sys_errlist[i];
		}
		else {
			int len = FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER |
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,	/* no message source */
				i,
				MAKELANGID(LANG_NEUTRAL,
					   SUBLANG_DEFAULT),
				           /* Default language */
				(LPTSTR) &s_buf,
				0,	/* size not used */
				NULL);	/* no args */
319
			if (len==0) {
320
				/* Only ever seen this in out-of-mem
321 322 323 324 325 326 327 328 329 330
				   situations */
				sprintf(s_small_buf, "Windows Error 0x%X", i);
				s = s_small_buf;
				s_buf = NULL;
			} else {
				s = s_buf;
				/* remove trailing cr/lf and dots */
				while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
					s[--len] = '\0';
			}
331
		}
332
	}
333 334
#endif /* Unix/Windows */
#endif /* PLAN 9*/
335
	if (filenameObject != NULL)
336
		v = Py_BuildValue("(iUO)", i, s, filenameObject);
337
	else
338
		v = Py_BuildValue("(iU)", i, s);
339
	if (v != NULL) {
340 341
		PyErr_SetObject(exc, v);
		Py_DECREF(v);
342
	}
343
#ifdef MS_WINDOWS
344
	LocalFree(s_buf);
345
#endif
346 347
	return NULL;
}
348

349

350
PyObject *
351
PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
352
{
353
	PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
354
	PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
355
	Py_XDECREF(name);
356 357 358 359 360
	return result;
}

#ifdef Py_WIN_WIDE_FILENAMES
PyObject *
361
PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
362
{
363 364
	PyObject *name = filename ?
	                 PyUnicode_FromUnicode(filename, wcslen(filename)) :
365 366 367 368 369 370 371
	                 NULL;
	PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
	Py_XDECREF(name);
	return result;
}
#endif /* Py_WIN_WIDE_FILENAMES */

372
PyObject *
373
PyErr_SetFromErrno(PyObject *exc)
374
{
375
	return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
376
}
Guido van Rossum's avatar
Guido van Rossum committed
377

378
#ifdef MS_WINDOWS
379
/* Windows specific error code handling */
380
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
381
	PyObject *exc,
382
	int ierr,
383
	PyObject *filenameObject)
384 385 386
{
	int len;
	char *s;
387 388
	char *s_buf = NULL; /* Free via LocalFree */
	char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
389 390 391 392 393 394 395 396 397 398 399 400
	PyObject *v;
	DWORD err = (DWORD)ierr;
	if (err==0) err = GetLastError();
	len = FormatMessage(
		/* 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 */
401
		(LPTSTR) &s_buf,
402 403
		0,	/* size not used */
		NULL);	/* no args */
404 405 406 407 408 409 410 411 412 413 414
	if (len==0) {
		/* Only seen this in out of mem situations */
		sprintf(s_small_buf, "Windows Error 0x%X", err);
		s = s_small_buf;
		s_buf = NULL;
	} else {
		s = s_buf;
		/* remove trailing cr/lf and dots */
		while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
			s[--len] = '\0';
	}
415
	if (filenameObject != NULL)
416
		v = Py_BuildValue("(iUO)", err, s, filenameObject);
417
	else
418
		v = Py_BuildValue("(iU)", err, s);
419
	if (v != NULL) {
420
		PyErr_SetObject(exc, v);
421 422
		Py_DECREF(v);
	}
423
	LocalFree(s_buf);
424 425 426
	return NULL;
}

427 428 429 430 431
PyObject *PyErr_SetExcFromWindowsErrWithFilename(
	PyObject *exc,
	int ierr,
	const char *filename)
{
432
	PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
433 434
	PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
	                                                             ierr,
435 436 437 438 439 440 441 442 443 444 445
	                                                             name);
	Py_XDECREF(name);
	return ret;
}

#ifdef Py_WIN_WIDE_FILENAMES
PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
	PyObject *exc,
	int ierr,
	const Py_UNICODE *filename)
{
446 447
	PyObject *name = filename ?
	                 PyUnicode_FromUnicode(filename, wcslen(filename)) :
448
	                 NULL;
449 450
	PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
	                                                             ierr,
451 452 453 454 455 456
	                                                             name);
	Py_XDECREF(name);
	return ret;
}
#endif /* Py_WIN_WIDE_FILENAMES */

457 458 459 460 461
PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
{
	return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
}

462 463
PyObject *PyErr_SetFromWindowsErr(int ierr)
{
464 465 466 467 468 469 470
	return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
						      ierr, NULL);
}
PyObject *PyErr_SetFromWindowsErrWithFilename(
	int ierr,
	const char *filename)
{
471
	PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
472 473 474
	PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
						      PyExc_WindowsError,
						      ierr, name);
475
	Py_XDECREF(name);
476 477 478 479 480 481 482 483
	return result;
}

#ifdef Py_WIN_WIDE_FILENAMES
PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
	int ierr,
	const Py_UNICODE *filename)
{
484 485
	PyObject *name = filename ?
	                 PyUnicode_FromUnicode(filename, wcslen(filename)) :
486 487 488 489
	                 NULL;
	PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
						      PyExc_WindowsError,
						      ierr, name);
490
	Py_XDECREF(name);
491
	return result;
492
}
493
#endif /* Py_WIN_WIDE_FILENAMES */
494 495
#endif /* MS_WINDOWS */

496
void
497
_PyErr_BadInternalCall(const char *filename, int lineno)
498 499 500 501 502 503 504 505 506
{
	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
507
void
508
PyErr_BadInternalCall(void)
Guido van Rossum's avatar
Guido van Rossum committed
509
{
510 511
	PyErr_Format(PyExc_SystemError,
		     "bad argument to internal function");
Guido van Rossum's avatar
Guido van Rossum committed
512
}
513 514
#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)

515 516 517 518 519 520


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

523
#ifdef HAVE_STDARG_PROTOTYPES
524
	va_start(vargs, format);
525 526 527
#else
	va_start(vargs);
#endif
528

529
	string = PyUnicode_FromFormatV(format, vargs);
530 531
	PyErr_SetObject(exception, string);
	Py_XDECREF(string);
532
	va_end(vargs);
533 534
	return NULL;
}
535 536


537

538
PyObject *
539
PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
540
{
541
	const char *dot;
542 543 544 545
	PyObject *modulename = NULL;
	PyObject *classname = NULL;
	PyObject *mydict = NULL;
	PyObject *bases = NULL;
546
	PyObject *result = NULL;
547 548 549 550
	dot = strrchr(name, '.');
	if (dot == NULL) {
		PyErr_SetString(PyExc_SystemError,
			"PyErr_NewException: name must be module.class");
551
		return NULL;
552 553 554
	}
	if (base == NULL)
		base = PyExc_Exception;
555
	if (dict == NULL) {
556
		dict = mydict = PyDict_New();
557 558 559
		if (dict == NULL)
			goto failure;
	}
560
	if (PyDict_GetItemString(dict, "__module__") == NULL) {
561
		modulename = PyUnicode_FromStringAndSize(name,
562
						     (Py_ssize_t)(dot-name));
563 564 565 566 567
		if (modulename == NULL)
			goto failure;
		if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
			goto failure;
	}
568 569 570 571 572 573 574 575 576 577
	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. */
Thomas Heller's avatar
Thomas Heller committed
578
	result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
579
				       dot+1, bases, dict);
580
  failure:
581 582 583 584
	Py_XDECREF(bases);
	Py_XDECREF(mydict);
	Py_XDECREF(classname);
	Py_XDECREF(modulename);
585 586
	return result;
}
587 588 589 590 591 592 593 594 595 596 597 598

/* 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");
	if (f != NULL) {
		PyFile_WriteString("Exception ", f);
		if (t) {
599
			PyObject* moduleName;
600 601 602
			char* className;
			assert(PyExceptionClass_Check(t));
			className = PyExceptionClass_Name(t);
603 604 605 606 607 608 609
			if (className != NULL) {
				char *dot = strrchr(className, '.');
				if (dot != NULL)
					className = dot+1;
			}

			moduleName = PyObject_GetAttrString(t, "__module__");
610 611 612
			if (moduleName == NULL)
				PyFile_WriteString("<unknown>", f);
			else {
613
				char* modstr = PyUnicode_AsString(moduleName);
614 615
				if (modstr &&
				    strcmp(modstr, "__builtin__") != 0)
616 617 618 619 620 621 622 623 624
				{
					PyFile_WriteString(modstr, f);
					PyFile_WriteString(".", f);
				}
			}
			if (className == NULL)
				PyFile_WriteString("<unknown>", f);
			else
				PyFile_WriteString(className, f);
625 626 627 628
			if (v && v != Py_None) {
				PyFile_WriteString(": ", f);
				PyFile_WriteObject(v, f, 0);
			}
629
			Py_XDECREF(moduleName);
630 631 632 633 634 635 636 637 638 639
		}
		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
640

641
extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossum's avatar
Guido van Rossum committed
642 643 644

/* Function to issue a warning message; may raise an exception. */
int
645
PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Guido van Rossum's avatar
Guido van Rossum committed
646
{
647
	PyObject *dict, *func = NULL;
648
	PyObject *warnings_module = PyModule_GetWarningsModule();
Guido van Rossum's avatar
Guido van Rossum committed
649

650 651
	if (warnings_module != NULL) {
		dict = PyModule_GetDict(warnings_module);
652 653
		if (dict != NULL)
			func = PyDict_GetItemString(dict, "warn");
Guido van Rossum's avatar
Guido van Rossum committed
654 655 656 657 658 659
	}
	if (func == NULL) {
		PySys_WriteStderr("warning: %s\n", message);
		return 0;
	}
	else {
660
		PyObject *res;
Guido van Rossum's avatar
Guido van Rossum committed
661 662 663

		if (category == NULL)
			category = PyExc_RuntimeWarning;
664 665
		res = PyObject_CallFunction(func, "sOn",
					    message, category, stack_level);
Guido van Rossum's avatar
Guido van Rossum committed
666 667 668 669 670 671
		if (res == NULL)
			return -1;
		Py_DECREF(res);
		return 0;
	}
}
672

673 674
/* Warning with explicit origin */
int
675 676 677
PyErr_WarnExplicit(PyObject *category, const char *message,
		   const char *filename, int lineno,
		   const char *module, PyObject *registry)
678 679 680 681 682 683 684 685 686 687 688 689 690 691
{
	PyObject *mod, *dict, *func = NULL;

	mod = PyImport_ImportModule("warnings");
	if (mod != NULL) {
		dict = PyModule_GetDict(mod);
		func = PyDict_GetItemString(dict, "warn_explicit");
		Py_DECREF(mod);
	}
	if (func == NULL) {
		PySys_WriteStderr("warning: %s\n", message);
		return 0;
	}
	else {
692
		PyObject *res;
693 694 695 696 697

		if (category == NULL)
			category = PyExc_RuntimeWarning;
		if (registry == NULL)
			registry = Py_None;
698 699
		res = PyObject_CallFunction(func, "sOsizO", message, category,
					    filename, lineno, module, registry);
700 701 702 703 704 705 706 707
		if (res == NULL)
			return -1;
		Py_DECREF(res);
		return 0;
	}
}


708 709 710
/* 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. */
711

712
void
713
PyErr_SyntaxLocation(const char *filename, int lineno)
714 715 716 717 718 719
{
	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);
720 721
	/* XXX check that it is, indeed, a syntax error. It might not
	 * be, though. */
722 723 724 725 726 727 728 729 730
	tmp = PyInt_FromLong(lineno);
	if (tmp == NULL)
		PyErr_Clear();
	else {
		if (PyObject_SetAttrString(v, "lineno", tmp))
			PyErr_Clear();
		Py_DECREF(tmp);
	}
	if (filename != NULL) {
731
		tmp = PyUnicode_FromString(filename);
732 733 734 735 736 737 738 739 740 741
		if (tmp == NULL)
			PyErr_Clear();
		else {
			if (PyObject_SetAttrString(v, "filename", tmp))
				PyErr_Clear();
			Py_DECREF(tmp);
		}

		tmp = PyErr_ProgramText(filename, lineno);
		if (tmp) {
742 743
			if (PyObject_SetAttrString(v, "text", tmp))
				PyErr_Clear();
744 745 746
			Py_DECREF(tmp);
		}
	}
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
	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();
		}
	}
767 768 769 770 771
	PyErr_Restore(exc, v, tb);
}

/* com_fetch_program_text will attempt to load the line of text that
   the exception refers to.  If it fails, it will return NULL but will
772
   not set an exception.
773 774 775 776 777 778

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

PyObject *
779
PyErr_ProgramText(const char *filename, int lineno)
780 781 782 783 784
{
	FILE *fp;
	int i;
	char linebuf[1000];

785
	if (filename == NULL || *filename == '\0' || lineno <= 0)
786
		return NULL;
787
	fp = fopen(filename, "r" PY_STDIOTEXTMODE);
788 789 790 791 792 793
	if (fp == NULL)
		return NULL;
	for (i = 0; i < lineno; i++) {
		char *pLastChar = &linebuf[sizeof(linebuf) - 2];
		do {
			*pLastChar = '\0';
794
			if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
795 796 797
				break;
			/* fgets read *something*; if it didn't get as
			   far as pLastChar, it must have found a newline
798
			   or hit the end of the file; if pLastChar is \n,
799 800 801 802 803 804 805 806 807
			   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;
		while (*p == ' ' || *p == '\t' || *p == '\014')
			p++;
808
		return PyUnicode_FromString(p);
809 810 811
	}
	return NULL;
}
812 813 814 815

#ifdef __cplusplus
}
#endif