Added more cross-reference targets and tidied up list of useful handlers.
[python.git] / Python / errors.c
blobc88a1909c7fb86b710fe18f2327d7b6a95e99818
2 /* Error handling */
4 #include "Python.h"
6 #ifndef __STDC__
7 #ifndef MS_WINDOWS
8 extern char *strerror(int);
9 #endif
10 #endif
12 #ifdef MS_WINDOWS
13 #include "windows.h"
14 #include "winbase.h"
15 #endif
17 #include <ctype.h>
19 #ifdef __cplusplus
20 extern "C" {
21 #endif
24 void
25 PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
27 PyThreadState *tstate = PyThreadState_GET();
28 PyObject *oldtype, *oldvalue, *oldtraceback;
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;
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;
43 tstate->curexc_type = type;
44 tstate->curexc_value = value;
45 tstate->curexc_traceback = traceback;
47 Py_XDECREF(oldtype);
48 Py_XDECREF(oldvalue);
49 Py_XDECREF(oldtraceback);
52 void
53 PyErr_SetObject(PyObject *exception, PyObject *value)
55 Py_XINCREF(exception);
56 Py_XINCREF(value);
57 PyErr_Restore(exception, value, (PyObject *)NULL);
60 void
61 PyErr_SetNone(PyObject *exception)
63 PyErr_SetObject(exception, (PyObject *)NULL);
66 void
67 PyErr_SetString(PyObject *exception, const char *string)
69 PyObject *value = PyString_FromString(string);
70 PyErr_SetObject(exception, value);
71 Py_XDECREF(value);
75 PyObject *
76 PyErr_Occurred(void)
78 PyThreadState *tstate = PyThreadState_GET();
80 return tstate->curexc_type;
84 int
85 PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
87 if (err == NULL || exc == NULL) {
88 /* maybe caused by "import exceptions" that failed early on */
89 return 0;
91 if (PyTuple_Check(exc)) {
92 Py_ssize_t i, n;
93 n = PyTuple_Size(exc);
94 for (i = 0; i < n; i++) {
95 /* Test recursively */
96 if (PyErr_GivenExceptionMatches(
97 err, PyTuple_GET_ITEM(exc, i)))
99 return 1;
102 return 0;
104 /* err might be an instance, so check its class. */
105 if (PyExceptionInstance_Check(err))
106 err = PyExceptionInstance_Class(err);
108 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
109 int res = 0;
110 PyObject *exception, *value, *tb;
111 PyErr_Fetch(&exception, &value, &tb);
112 res = PyObject_IsSubclass(err, exc);
113 /* This function must not fail, so print the error here */
114 if (res == -1) {
115 PyErr_WriteUnraisable(err);
116 res = 0;
118 PyErr_Restore(exception, value, tb);
119 return res;
122 return err == exc;
127 PyErr_ExceptionMatches(PyObject *exc)
129 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
133 /* Used in many places to normalize a raised exception, including in
134 eval_code2(), do_raise(), and PyErr_Print()
136 void
137 PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
139 PyObject *type = *exc;
140 PyObject *value = *val;
141 PyObject *inclass = NULL;
142 PyObject *initial_tb = NULL;
143 PyThreadState *tstate = NULL;
145 if (type == NULL) {
146 /* There was no exception, so nothing to do. */
147 return;
150 /* If PyErr_SetNone() was used, the value will have been actually
151 set to NULL.
153 if (!value) {
154 value = Py_None;
155 Py_INCREF(value);
158 if (PyExceptionInstance_Check(value))
159 inclass = PyExceptionInstance_Class(value);
161 /* Normalize the exception so that if the type is a class, the
162 value will be an instance.
164 if (PyExceptionClass_Check(type)) {
165 /* if the value was not an instance, or is not an instance
166 whose class is (or is derived from) type, then use the
167 value as an argument to instantiation of the type
168 class.
170 if (!inclass || !PyObject_IsSubclass(inclass, type)) {
171 PyObject *args, *res;
173 if (value == Py_None)
174 args = PyTuple_New(0);
175 else if (PyTuple_Check(value)) {
176 Py_INCREF(value);
177 args = value;
179 else
180 args = PyTuple_Pack(1, value);
182 if (args == NULL)
183 goto finally;
184 res = PyEval_CallObject(type, args);
185 Py_DECREF(args);
186 if (res == NULL)
187 goto finally;
188 Py_DECREF(value);
189 value = res;
191 /* if the class of the instance doesn't exactly match the
192 class of the type, believe the instance
194 else if (inclass != type) {
195 Py_DECREF(type);
196 type = inclass;
197 Py_INCREF(type);
200 *exc = type;
201 *val = value;
202 return;
203 finally:
204 Py_DECREF(type);
205 Py_DECREF(value);
206 /* If the new exception doesn't set a traceback and the old
207 exception had a traceback, use the old traceback for the
208 new exception. It's better than nothing.
210 initial_tb = *tb;
211 PyErr_Fetch(exc, val, tb);
212 if (initial_tb != NULL) {
213 if (*tb == NULL)
214 *tb = initial_tb;
215 else
216 Py_DECREF(initial_tb);
218 /* normalize recursively */
219 tstate = PyThreadState_GET();
220 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
221 --tstate->recursion_depth;
222 PyErr_SetObject(PyExc_RuntimeError, PyExc_RecursionErrorInst);
223 return;
225 PyErr_NormalizeException(exc, val, tb);
226 --tstate->recursion_depth;
230 void
231 PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
233 PyThreadState *tstate = PyThreadState_GET();
235 *p_type = tstate->curexc_type;
236 *p_value = tstate->curexc_value;
237 *p_traceback = tstate->curexc_traceback;
239 tstate->curexc_type = NULL;
240 tstate->curexc_value = NULL;
241 tstate->curexc_traceback = NULL;
244 void
245 PyErr_Clear(void)
247 PyErr_Restore(NULL, NULL, NULL);
250 /* Convenience functions to set a type error exception and return 0 */
253 PyErr_BadArgument(void)
255 PyErr_SetString(PyExc_TypeError,
256 "bad argument type for built-in operation");
257 return 0;
260 PyObject *
261 PyErr_NoMemory(void)
263 if (PyErr_ExceptionMatches(PyExc_MemoryError))
264 /* already current */
265 return NULL;
267 /* raise the pre-allocated instance if it still exists */
268 if (PyExc_MemoryErrorInst)
269 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
270 else
271 /* this will probably fail since there's no memory and hee,
272 hee, we have to instantiate this class
274 PyErr_SetNone(PyExc_MemoryError);
276 return NULL;
279 PyObject *
280 PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
282 PyObject *v;
283 char *s;
284 int i = errno;
285 #ifdef PLAN9
286 char errbuf[ERRMAX];
287 #endif
288 #ifdef MS_WINDOWS
289 char *s_buf = NULL;
290 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
291 #endif
292 #ifdef EINTR
293 if (i == EINTR && PyErr_CheckSignals())
294 return NULL;
295 #endif
296 #ifdef PLAN9
297 rerrstr(errbuf, sizeof errbuf);
298 s = errbuf;
299 #else
300 if (i == 0)
301 s = "Error"; /* Sometimes errno didn't get set */
302 else
303 #ifndef MS_WINDOWS
304 s = strerror(i);
305 #else
307 /* Note that the Win32 errors do not lineup with the
308 errno error. So if the error is in the MSVC error
309 table, we use it, otherwise we assume it really _is_
310 a Win32 error code
312 if (i > 0 && i < _sys_nerr) {
313 s = _sys_errlist[i];
315 else {
316 int len = FormatMessage(
317 FORMAT_MESSAGE_ALLOCATE_BUFFER |
318 FORMAT_MESSAGE_FROM_SYSTEM |
319 FORMAT_MESSAGE_IGNORE_INSERTS,
320 NULL, /* no message source */
322 MAKELANGID(LANG_NEUTRAL,
323 SUBLANG_DEFAULT),
324 /* Default language */
325 (LPTSTR) &s_buf,
326 0, /* size not used */
327 NULL); /* no args */
328 if (len==0) {
329 /* Only ever seen this in out-of-mem
330 situations */
331 sprintf(s_small_buf, "Windows Error 0x%X", i);
332 s = s_small_buf;
333 s_buf = NULL;
334 } else {
335 s = s_buf;
336 /* remove trailing cr/lf and dots */
337 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
338 s[--len] = '\0';
342 #endif /* Unix/Windows */
343 #endif /* PLAN 9*/
344 if (filenameObject != NULL)
345 v = Py_BuildValue("(isO)", i, s, filenameObject);
346 else
347 v = Py_BuildValue("(is)", i, s);
348 if (v != NULL) {
349 PyErr_SetObject(exc, v);
350 Py_DECREF(v);
352 #ifdef MS_WINDOWS
353 LocalFree(s_buf);
354 #endif
355 return NULL;
359 PyObject *
360 PyErr_SetFromErrnoWithFilename(PyObject *exc, char *filename)
362 PyObject *name = filename ? PyString_FromString(filename) : NULL;
363 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
364 Py_XDECREF(name);
365 return result;
368 #ifdef Py_WIN_WIDE_FILENAMES
369 PyObject *
370 PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, Py_UNICODE *filename)
372 PyObject *name = filename ?
373 PyUnicode_FromUnicode(filename, wcslen(filename)) :
374 NULL;
375 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
376 Py_XDECREF(name);
377 return result;
379 #endif /* Py_WIN_WIDE_FILENAMES */
381 PyObject *
382 PyErr_SetFromErrno(PyObject *exc)
384 return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
387 #ifdef MS_WINDOWS
388 /* Windows specific error code handling */
389 PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
390 PyObject *exc,
391 int ierr,
392 PyObject *filenameObject)
394 int len;
395 char *s;
396 char *s_buf = NULL; /* Free via LocalFree */
397 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
398 PyObject *v;
399 DWORD err = (DWORD)ierr;
400 if (err==0) err = GetLastError();
401 len = FormatMessage(
402 /* Error API error */
403 FORMAT_MESSAGE_ALLOCATE_BUFFER |
404 FORMAT_MESSAGE_FROM_SYSTEM |
405 FORMAT_MESSAGE_IGNORE_INSERTS,
406 NULL, /* no message source */
407 err,
408 MAKELANGID(LANG_NEUTRAL,
409 SUBLANG_DEFAULT), /* Default language */
410 (LPTSTR) &s_buf,
411 0, /* size not used */
412 NULL); /* no args */
413 if (len==0) {
414 /* Only seen this in out of mem situations */
415 sprintf(s_small_buf, "Windows Error 0x%X", err);
416 s = s_small_buf;
417 s_buf = NULL;
418 } else {
419 s = s_buf;
420 /* remove trailing cr/lf and dots */
421 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
422 s[--len] = '\0';
424 if (filenameObject != NULL)
425 v = Py_BuildValue("(isO)", err, s, filenameObject);
426 else
427 v = Py_BuildValue("(is)", err, s);
428 if (v != NULL) {
429 PyErr_SetObject(exc, v);
430 Py_DECREF(v);
432 LocalFree(s_buf);
433 return NULL;
436 PyObject *PyErr_SetExcFromWindowsErrWithFilename(
437 PyObject *exc,
438 int ierr,
439 const char *filename)
441 PyObject *name = filename ? PyString_FromString(filename) : NULL;
442 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
443 ierr,
444 name);
445 Py_XDECREF(name);
446 return ret;
449 #ifdef Py_WIN_WIDE_FILENAMES
450 PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
451 PyObject *exc,
452 int ierr,
453 const Py_UNICODE *filename)
455 PyObject *name = filename ?
456 PyUnicode_FromUnicode(filename, wcslen(filename)) :
457 NULL;
458 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
459 ierr,
460 name);
461 Py_XDECREF(name);
462 return ret;
464 #endif /* Py_WIN_WIDE_FILENAMES */
466 PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
468 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
471 PyObject *PyErr_SetFromWindowsErr(int ierr)
473 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
474 ierr, NULL);
476 PyObject *PyErr_SetFromWindowsErrWithFilename(
477 int ierr,
478 const char *filename)
480 PyObject *name = filename ? PyString_FromString(filename) : NULL;
481 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
482 PyExc_WindowsError,
483 ierr, name);
484 Py_XDECREF(name);
485 return result;
488 #ifdef Py_WIN_WIDE_FILENAMES
489 PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
490 int ierr,
491 const Py_UNICODE *filename)
493 PyObject *name = filename ?
494 PyUnicode_FromUnicode(filename, wcslen(filename)) :
495 NULL;
496 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
497 PyExc_WindowsError,
498 ierr, name);
499 Py_XDECREF(name);
500 return result;
502 #endif /* Py_WIN_WIDE_FILENAMES */
503 #endif /* MS_WINDOWS */
505 void
506 _PyErr_BadInternalCall(char *filename, int lineno)
508 PyErr_Format(PyExc_SystemError,
509 "%s:%d: bad argument to internal function",
510 filename, lineno);
513 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
514 export the entry point for existing object code: */
515 #undef PyErr_BadInternalCall
516 void
517 PyErr_BadInternalCall(void)
519 PyErr_Format(PyExc_SystemError,
520 "bad argument to internal function");
522 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
526 PyObject *
527 PyErr_Format(PyObject *exception, const char *format, ...)
529 va_list vargs;
530 PyObject* string;
532 #ifdef HAVE_STDARG_PROTOTYPES
533 va_start(vargs, format);
534 #else
535 va_start(vargs);
536 #endif
538 string = PyString_FromFormatV(format, vargs);
539 PyErr_SetObject(exception, string);
540 Py_XDECREF(string);
541 va_end(vargs);
542 return NULL;
547 PyObject *
548 PyErr_NewException(char *name, PyObject *base, PyObject *dict)
550 char *dot;
551 PyObject *modulename = NULL;
552 PyObject *classname = NULL;
553 PyObject *mydict = NULL;
554 PyObject *bases = NULL;
555 PyObject *result = NULL;
556 dot = strrchr(name, '.');
557 if (dot == NULL) {
558 PyErr_SetString(PyExc_SystemError,
559 "PyErr_NewException: name must be module.class");
560 return NULL;
562 if (base == NULL)
563 base = PyExc_Exception;
564 if (dict == NULL) {
565 dict = mydict = PyDict_New();
566 if (dict == NULL)
567 goto failure;
569 if (PyDict_GetItemString(dict, "__module__") == NULL) {
570 modulename = PyString_FromStringAndSize(name,
571 (Py_ssize_t)(dot-name));
572 if (modulename == NULL)
573 goto failure;
574 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
575 goto failure;
577 if (PyTuple_Check(base)) {
578 bases = base;
579 /* INCREF as we create a new ref in the else branch */
580 Py_INCREF(bases);
581 } else {
582 bases = PyTuple_Pack(1, base);
583 if (bases == NULL)
584 goto failure;
586 /* Create a real new-style class. */
587 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
588 dot+1, bases, dict);
589 failure:
590 Py_XDECREF(bases);
591 Py_XDECREF(mydict);
592 Py_XDECREF(classname);
593 Py_XDECREF(modulename);
594 return result;
597 /* Call when an exception has occurred but there is no way for Python
598 to handle it. Examples: exception in __del__ or during GC. */
599 void
600 PyErr_WriteUnraisable(PyObject *obj)
602 PyObject *f, *t, *v, *tb;
603 PyErr_Fetch(&t, &v, &tb);
604 f = PySys_GetObject("stderr");
605 if (f != NULL) {
606 PyFile_WriteString("Exception ", f);
607 if (t) {
608 PyObject* moduleName;
609 char* className;
610 assert(PyExceptionClass_Check(t));
611 className = PyExceptionClass_Name(t);
612 if (className != NULL) {
613 char *dot = strrchr(className, '.');
614 if (dot != NULL)
615 className = dot+1;
618 moduleName = PyObject_GetAttrString(t, "__module__");
619 if (moduleName == NULL)
620 PyFile_WriteString("<unknown>", f);
621 else {
622 char* modstr = PyString_AsString(moduleName);
623 if (modstr &&
624 strcmp(modstr, "exceptions") != 0)
626 PyFile_WriteString(modstr, f);
627 PyFile_WriteString(".", f);
630 if (className == NULL)
631 PyFile_WriteString("<unknown>", f);
632 else
633 PyFile_WriteString(className, f);
634 if (v && v != Py_None) {
635 PyFile_WriteString(": ", f);
636 PyFile_WriteObject(v, f, 0);
638 Py_XDECREF(moduleName);
640 PyFile_WriteString(" in ", f);
641 PyFile_WriteObject(obj, f, 0);
642 PyFile_WriteString(" ignored\n", f);
643 PyErr_Clear(); /* Just in case */
645 Py_XDECREF(t);
646 Py_XDECREF(v);
647 Py_XDECREF(tb);
650 extern PyObject *PyModule_GetWarningsModule(void);
653 /* Set file and line information for the current exception.
654 If the exception is not a SyntaxError, also sets additional attributes
655 to make printing of exceptions believe it is a syntax error. */
657 void
658 PyErr_SyntaxLocation(const char *filename, int lineno)
660 PyObject *exc, *v, *tb, *tmp;
662 /* add attributes for the line number and filename for the error */
663 PyErr_Fetch(&exc, &v, &tb);
664 PyErr_NormalizeException(&exc, &v, &tb);
665 /* XXX check that it is, indeed, a syntax error. It might not
666 * be, though. */
667 tmp = PyInt_FromLong(lineno);
668 if (tmp == NULL)
669 PyErr_Clear();
670 else {
671 if (PyObject_SetAttrString(v, "lineno", tmp))
672 PyErr_Clear();
673 Py_DECREF(tmp);
675 if (filename != NULL) {
676 tmp = PyString_FromString(filename);
677 if (tmp == NULL)
678 PyErr_Clear();
679 else {
680 if (PyObject_SetAttrString(v, "filename", tmp))
681 PyErr_Clear();
682 Py_DECREF(tmp);
685 tmp = PyErr_ProgramText(filename, lineno);
686 if (tmp) {
687 if (PyObject_SetAttrString(v, "text", tmp))
688 PyErr_Clear();
689 Py_DECREF(tmp);
692 if (PyObject_SetAttrString(v, "offset", Py_None)) {
693 PyErr_Clear();
695 if (exc != PyExc_SyntaxError) {
696 if (!PyObject_HasAttrString(v, "msg")) {
697 tmp = PyObject_Str(v);
698 if (tmp) {
699 if (PyObject_SetAttrString(v, "msg", tmp))
700 PyErr_Clear();
701 Py_DECREF(tmp);
702 } else {
703 PyErr_Clear();
706 if (!PyObject_HasAttrString(v, "print_file_and_line")) {
707 if (PyObject_SetAttrString(v, "print_file_and_line",
708 Py_None))
709 PyErr_Clear();
712 PyErr_Restore(exc, v, tb);
715 /* com_fetch_program_text will attempt to load the line of text that
716 the exception refers to. If it fails, it will return NULL but will
717 not set an exception.
719 XXX The functionality of this function is quite similar to the
720 functionality in tb_displayline() in traceback.c.
723 PyObject *
724 PyErr_ProgramText(const char *filename, int lineno)
726 FILE *fp;
727 int i;
728 char linebuf[1000];
730 if (filename == NULL || *filename == '\0' || lineno <= 0)
731 return NULL;
732 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
733 if (fp == NULL)
734 return NULL;
735 for (i = 0; i < lineno; i++) {
736 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
737 do {
738 *pLastChar = '\0';
739 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
740 break;
741 /* fgets read *something*; if it didn't get as
742 far as pLastChar, it must have found a newline
743 or hit the end of the file; if pLastChar is \n,
744 it obviously found a newline; else we haven't
745 yet seen a newline, so must continue */
746 } while (*pLastChar != '\0' && *pLastChar != '\n');
748 fclose(fp);
749 if (i == lineno) {
750 char *p = linebuf;
751 while (*p == ' ' || *p == '\t' || *p == '\014')
752 p++;
753 return PyString_FromString(p);
755 return NULL;
758 #ifdef __cplusplus
760 #endif