Updated with fix for #3136.
[python.git] / Python / errors.c
blob8951d5793548573a2ed7a9c7fc2ee407a8a2b83c
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 /* problems here!? not sure PyObject_IsSubclass expects to
110 be called with an exception pending... */
111 return PyObject_IsSubclass(err, exc);
114 return err == exc;
119 PyErr_ExceptionMatches(PyObject *exc)
121 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
125 /* Used in many places to normalize a raised exception, including in
126 eval_code2(), do_raise(), and PyErr_Print()
128 void
129 PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
131 PyObject *type = *exc;
132 PyObject *value = *val;
133 PyObject *inclass = NULL;
134 PyObject *initial_tb = NULL;
135 PyThreadState *tstate = NULL;
137 if (type == NULL) {
138 /* There was no exception, so nothing to do. */
139 return;
142 /* If PyErr_SetNone() was used, the value will have been actually
143 set to NULL.
145 if (!value) {
146 value = Py_None;
147 Py_INCREF(value);
150 if (PyExceptionInstance_Check(value))
151 inclass = PyExceptionInstance_Class(value);
153 /* Normalize the exception so that if the type is a class, the
154 value will be an instance.
156 if (PyExceptionClass_Check(type)) {
157 /* if the value was not an instance, or is not an instance
158 whose class is (or is derived from) type, then use the
159 value as an argument to instantiation of the type
160 class.
162 if (!inclass || !PyObject_IsSubclass(inclass, type)) {
163 PyObject *args, *res;
165 if (value == Py_None)
166 args = PyTuple_New(0);
167 else if (PyTuple_Check(value)) {
168 Py_INCREF(value);
169 args = value;
171 else
172 args = PyTuple_Pack(1, value);
174 if (args == NULL)
175 goto finally;
176 res = PyEval_CallObject(type, args);
177 Py_DECREF(args);
178 if (res == NULL)
179 goto finally;
180 Py_DECREF(value);
181 value = res;
183 /* if the class of the instance doesn't exactly match the
184 class of the type, believe the instance
186 else if (inclass != type) {
187 Py_DECREF(type);
188 type = inclass;
189 Py_INCREF(type);
192 *exc = type;
193 *val = value;
194 return;
195 finally:
196 Py_DECREF(type);
197 Py_DECREF(value);
198 /* If the new exception doesn't set a traceback and the old
199 exception had a traceback, use the old traceback for the
200 new exception. It's better than nothing.
202 initial_tb = *tb;
203 PyErr_Fetch(exc, val, tb);
204 if (initial_tb != NULL) {
205 if (*tb == NULL)
206 *tb = initial_tb;
207 else
208 Py_DECREF(initial_tb);
210 /* normalize recursively */
211 tstate = PyThreadState_GET();
212 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
213 --tstate->recursion_depth;
214 PyErr_SetObject(PyExc_RuntimeError, PyExc_RecursionErrorInst);
215 return;
217 PyErr_NormalizeException(exc, val, tb);
218 --tstate->recursion_depth;
222 void
223 PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
225 PyThreadState *tstate = PyThreadState_GET();
227 *p_type = tstate->curexc_type;
228 *p_value = tstate->curexc_value;
229 *p_traceback = tstate->curexc_traceback;
231 tstate->curexc_type = NULL;
232 tstate->curexc_value = NULL;
233 tstate->curexc_traceback = NULL;
236 void
237 PyErr_Clear(void)
239 PyErr_Restore(NULL, NULL, NULL);
242 /* Convenience functions to set a type error exception and return 0 */
245 PyErr_BadArgument(void)
247 PyErr_SetString(PyExc_TypeError,
248 "bad argument type for built-in operation");
249 return 0;
252 PyObject *
253 PyErr_NoMemory(void)
255 if (PyErr_ExceptionMatches(PyExc_MemoryError))
256 /* already current */
257 return NULL;
259 /* raise the pre-allocated instance if it still exists */
260 if (PyExc_MemoryErrorInst)
261 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
262 else
263 /* this will probably fail since there's no memory and hee,
264 hee, we have to instantiate this class
266 PyErr_SetNone(PyExc_MemoryError);
268 return NULL;
271 PyObject *
272 PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
274 PyObject *v;
275 char *s;
276 int i = errno;
277 #ifdef PLAN9
278 char errbuf[ERRMAX];
279 #endif
280 #ifdef MS_WINDOWS
281 char *s_buf = NULL;
282 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
283 #endif
284 #ifdef EINTR
285 if (i == EINTR && PyErr_CheckSignals())
286 return NULL;
287 #endif
288 #ifdef PLAN9
289 rerrstr(errbuf, sizeof errbuf);
290 s = errbuf;
291 #else
292 if (i == 0)
293 s = "Error"; /* Sometimes errno didn't get set */
294 else
295 #ifndef MS_WINDOWS
296 s = strerror(i);
297 #else
299 /* Note that the Win32 errors do not lineup with the
300 errno error. So if the error is in the MSVC error
301 table, we use it, otherwise we assume it really _is_
302 a Win32 error code
304 if (i > 0 && i < _sys_nerr) {
305 s = _sys_errlist[i];
307 else {
308 int len = FormatMessage(
309 FORMAT_MESSAGE_ALLOCATE_BUFFER |
310 FORMAT_MESSAGE_FROM_SYSTEM |
311 FORMAT_MESSAGE_IGNORE_INSERTS,
312 NULL, /* no message source */
314 MAKELANGID(LANG_NEUTRAL,
315 SUBLANG_DEFAULT),
316 /* Default language */
317 (LPTSTR) &s_buf,
318 0, /* size not used */
319 NULL); /* no args */
320 if (len==0) {
321 /* Only ever seen this in out-of-mem
322 situations */
323 sprintf(s_small_buf, "Windows Error 0x%X", i);
324 s = s_small_buf;
325 s_buf = NULL;
326 } else {
327 s = s_buf;
328 /* remove trailing cr/lf and dots */
329 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
330 s[--len] = '\0';
334 #endif /* Unix/Windows */
335 #endif /* PLAN 9*/
336 if (filenameObject != NULL)
337 v = Py_BuildValue("(isO)", i, s, filenameObject);
338 else
339 v = Py_BuildValue("(is)", i, s);
340 if (v != NULL) {
341 PyErr_SetObject(exc, v);
342 Py_DECREF(v);
344 #ifdef MS_WINDOWS
345 LocalFree(s_buf);
346 #endif
347 return NULL;
351 PyObject *
352 PyErr_SetFromErrnoWithFilename(PyObject *exc, char *filename)
354 PyObject *name = filename ? PyString_FromString(filename) : NULL;
355 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
356 Py_XDECREF(name);
357 return result;
360 #ifdef Py_WIN_WIDE_FILENAMES
361 PyObject *
362 PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, Py_UNICODE *filename)
364 PyObject *name = filename ?
365 PyUnicode_FromUnicode(filename, wcslen(filename)) :
366 NULL;
367 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
368 Py_XDECREF(name);
369 return result;
371 #endif /* Py_WIN_WIDE_FILENAMES */
373 PyObject *
374 PyErr_SetFromErrno(PyObject *exc)
376 return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
379 #ifdef MS_WINDOWS
380 /* Windows specific error code handling */
381 PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
382 PyObject *exc,
383 int ierr,
384 PyObject *filenameObject)
386 int len;
387 char *s;
388 char *s_buf = NULL; /* Free via LocalFree */
389 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
390 PyObject *v;
391 DWORD err = (DWORD)ierr;
392 if (err==0) err = GetLastError();
393 len = FormatMessage(
394 /* Error API error */
395 FORMAT_MESSAGE_ALLOCATE_BUFFER |
396 FORMAT_MESSAGE_FROM_SYSTEM |
397 FORMAT_MESSAGE_IGNORE_INSERTS,
398 NULL, /* no message source */
399 err,
400 MAKELANGID(LANG_NEUTRAL,
401 SUBLANG_DEFAULT), /* Default language */
402 (LPTSTR) &s_buf,
403 0, /* size not used */
404 NULL); /* no args */
405 if (len==0) {
406 /* Only seen this in out of mem situations */
407 sprintf(s_small_buf, "Windows Error 0x%X", err);
408 s = s_small_buf;
409 s_buf = NULL;
410 } else {
411 s = s_buf;
412 /* remove trailing cr/lf and dots */
413 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
414 s[--len] = '\0';
416 if (filenameObject != NULL)
417 v = Py_BuildValue("(isO)", err, s, filenameObject);
418 else
419 v = Py_BuildValue("(is)", err, s);
420 if (v != NULL) {
421 PyErr_SetObject(exc, v);
422 Py_DECREF(v);
424 LocalFree(s_buf);
425 return NULL;
428 PyObject *PyErr_SetExcFromWindowsErrWithFilename(
429 PyObject *exc,
430 int ierr,
431 const char *filename)
433 PyObject *name = filename ? PyString_FromString(filename) : NULL;
434 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
435 ierr,
436 name);
437 Py_XDECREF(name);
438 return ret;
441 #ifdef Py_WIN_WIDE_FILENAMES
442 PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
443 PyObject *exc,
444 int ierr,
445 const Py_UNICODE *filename)
447 PyObject *name = filename ?
448 PyUnicode_FromUnicode(filename, wcslen(filename)) :
449 NULL;
450 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
451 ierr,
452 name);
453 Py_XDECREF(name);
454 return ret;
456 #endif /* Py_WIN_WIDE_FILENAMES */
458 PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
460 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
463 PyObject *PyErr_SetFromWindowsErr(int ierr)
465 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
466 ierr, NULL);
468 PyObject *PyErr_SetFromWindowsErrWithFilename(
469 int ierr,
470 const char *filename)
472 PyObject *name = filename ? PyString_FromString(filename) : NULL;
473 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
474 PyExc_WindowsError,
475 ierr, name);
476 Py_XDECREF(name);
477 return result;
480 #ifdef Py_WIN_WIDE_FILENAMES
481 PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
482 int ierr,
483 const Py_UNICODE *filename)
485 PyObject *name = filename ?
486 PyUnicode_FromUnicode(filename, wcslen(filename)) :
487 NULL;
488 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
489 PyExc_WindowsError,
490 ierr, name);
491 Py_XDECREF(name);
492 return result;
494 #endif /* Py_WIN_WIDE_FILENAMES */
495 #endif /* MS_WINDOWS */
497 void
498 _PyErr_BadInternalCall(char *filename, int lineno)
500 PyErr_Format(PyExc_SystemError,
501 "%s:%d: bad argument to internal function",
502 filename, lineno);
505 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
506 export the entry point for existing object code: */
507 #undef PyErr_BadInternalCall
508 void
509 PyErr_BadInternalCall(void)
511 PyErr_Format(PyExc_SystemError,
512 "bad argument to internal function");
514 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
518 PyObject *
519 PyErr_Format(PyObject *exception, const char *format, ...)
521 va_list vargs;
522 PyObject* string;
524 #ifdef HAVE_STDARG_PROTOTYPES
525 va_start(vargs, format);
526 #else
527 va_start(vargs);
528 #endif
530 string = PyString_FromFormatV(format, vargs);
531 PyErr_SetObject(exception, string);
532 Py_XDECREF(string);
533 va_end(vargs);
534 return NULL;
539 PyObject *
540 PyErr_NewException(char *name, PyObject *base, PyObject *dict)
542 char *dot;
543 PyObject *modulename = NULL;
544 PyObject *classname = NULL;
545 PyObject *mydict = NULL;
546 PyObject *bases = NULL;
547 PyObject *result = NULL;
548 dot = strrchr(name, '.');
549 if (dot == NULL) {
550 PyErr_SetString(PyExc_SystemError,
551 "PyErr_NewException: name must be module.class");
552 return NULL;
554 if (base == NULL)
555 base = PyExc_Exception;
556 if (dict == NULL) {
557 dict = mydict = PyDict_New();
558 if (dict == NULL)
559 goto failure;
561 if (PyDict_GetItemString(dict, "__module__") == NULL) {
562 modulename = PyString_FromStringAndSize(name,
563 (Py_ssize_t)(dot-name));
564 if (modulename == NULL)
565 goto failure;
566 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
567 goto failure;
569 if (PyTuple_Check(base)) {
570 bases = base;
571 /* INCREF as we create a new ref in the else branch */
572 Py_INCREF(bases);
573 } else {
574 bases = PyTuple_Pack(1, base);
575 if (bases == NULL)
576 goto failure;
578 /* Create a real new-style class. */
579 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
580 dot+1, bases, dict);
581 failure:
582 Py_XDECREF(bases);
583 Py_XDECREF(mydict);
584 Py_XDECREF(classname);
585 Py_XDECREF(modulename);
586 return result;
589 /* Call when an exception has occurred but there is no way for Python
590 to handle it. Examples: exception in __del__ or during GC. */
591 void
592 PyErr_WriteUnraisable(PyObject *obj)
594 PyObject *f, *t, *v, *tb;
595 PyErr_Fetch(&t, &v, &tb);
596 f = PySys_GetObject("stderr");
597 if (f != NULL) {
598 PyFile_WriteString("Exception ", f);
599 if (t) {
600 PyObject* moduleName;
601 char* className;
602 assert(PyExceptionClass_Check(t));
603 className = PyExceptionClass_Name(t);
604 if (className != NULL) {
605 char *dot = strrchr(className, '.');
606 if (dot != NULL)
607 className = dot+1;
610 moduleName = PyObject_GetAttrString(t, "__module__");
611 if (moduleName == NULL)
612 PyFile_WriteString("<unknown>", f);
613 else {
614 char* modstr = PyString_AsString(moduleName);
615 if (modstr &&
616 strcmp(modstr, "exceptions") != 0)
618 PyFile_WriteString(modstr, f);
619 PyFile_WriteString(".", f);
622 if (className == NULL)
623 PyFile_WriteString("<unknown>", f);
624 else
625 PyFile_WriteString(className, f);
626 if (v && v != Py_None) {
627 PyFile_WriteString(": ", f);
628 PyFile_WriteObject(v, f, 0);
630 Py_XDECREF(moduleName);
632 PyFile_WriteString(" in ", f);
633 PyFile_WriteObject(obj, f, 0);
634 PyFile_WriteString(" ignored\n", f);
635 PyErr_Clear(); /* Just in case */
637 Py_XDECREF(t);
638 Py_XDECREF(v);
639 Py_XDECREF(tb);
642 extern PyObject *PyModule_GetWarningsModule(void);
645 /* Set file and line information for the current exception.
646 If the exception is not a SyntaxError, also sets additional attributes
647 to make printing of exceptions believe it is a syntax error. */
649 void
650 PyErr_SyntaxLocation(const char *filename, int lineno)
652 PyObject *exc, *v, *tb, *tmp;
654 /* add attributes for the line number and filename for the error */
655 PyErr_Fetch(&exc, &v, &tb);
656 PyErr_NormalizeException(&exc, &v, &tb);
657 /* XXX check that it is, indeed, a syntax error. It might not
658 * be, though. */
659 tmp = PyInt_FromLong(lineno);
660 if (tmp == NULL)
661 PyErr_Clear();
662 else {
663 if (PyObject_SetAttrString(v, "lineno", tmp))
664 PyErr_Clear();
665 Py_DECREF(tmp);
667 if (filename != NULL) {
668 tmp = PyString_FromString(filename);
669 if (tmp == NULL)
670 PyErr_Clear();
671 else {
672 if (PyObject_SetAttrString(v, "filename", tmp))
673 PyErr_Clear();
674 Py_DECREF(tmp);
677 tmp = PyErr_ProgramText(filename, lineno);
678 if (tmp) {
679 if (PyObject_SetAttrString(v, "text", tmp))
680 PyErr_Clear();
681 Py_DECREF(tmp);
684 if (PyObject_SetAttrString(v, "offset", Py_None)) {
685 PyErr_Clear();
687 if (exc != PyExc_SyntaxError) {
688 if (!PyObject_HasAttrString(v, "msg")) {
689 tmp = PyObject_Str(v);
690 if (tmp) {
691 if (PyObject_SetAttrString(v, "msg", tmp))
692 PyErr_Clear();
693 Py_DECREF(tmp);
694 } else {
695 PyErr_Clear();
698 if (!PyObject_HasAttrString(v, "print_file_and_line")) {
699 if (PyObject_SetAttrString(v, "print_file_and_line",
700 Py_None))
701 PyErr_Clear();
704 PyErr_Restore(exc, v, tb);
707 /* com_fetch_program_text will attempt to load the line of text that
708 the exception refers to. If it fails, it will return NULL but will
709 not set an exception.
711 XXX The functionality of this function is quite similar to the
712 functionality in tb_displayline() in traceback.c.
715 PyObject *
716 PyErr_ProgramText(const char *filename, int lineno)
718 FILE *fp;
719 int i;
720 char linebuf[1000];
722 if (filename == NULL || *filename == '\0' || lineno <= 0)
723 return NULL;
724 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
725 if (fp == NULL)
726 return NULL;
727 for (i = 0; i < lineno; i++) {
728 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
729 do {
730 *pLastChar = '\0';
731 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
732 break;
733 /* fgets read *something*; if it didn't get as
734 far as pLastChar, it must have found a newline
735 or hit the end of the file; if pLastChar is \n,
736 it obviously found a newline; else we haven't
737 yet seen a newline, so must continue */
738 } while (*pLastChar != '\0' && *pLastChar != '\n');
740 fclose(fp);
741 if (i == lineno) {
742 char *p = linebuf;
743 while (*p == ' ' || *p == '\t' || *p == '\014')
744 p++;
745 return PyString_FromString(p);
747 return NULL;
750 #ifdef __cplusplus
752 #endif