Catch situations where currentframe() returns None. See SF patch #1447410, this is...
[python.git] / Python / errors.c
blob7fc4c97c825d106c2865a3e025f0dac61bbccfd3
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 void
20 PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
22 PyThreadState *tstate = PyThreadState_GET();
23 PyObject *oldtype, *oldvalue, *oldtraceback;
25 if (traceback != NULL && !PyTraceBack_Check(traceback)) {
26 /* XXX Should never happen -- fatal error instead? */
27 /* Well, it could be None. */
28 Py_DECREF(traceback);
29 traceback = NULL;
32 /* Save these in locals to safeguard against recursive
33 invocation through Py_XDECREF */
34 oldtype = tstate->curexc_type;
35 oldvalue = tstate->curexc_value;
36 oldtraceback = tstate->curexc_traceback;
38 tstate->curexc_type = type;
39 tstate->curexc_value = value;
40 tstate->curexc_traceback = traceback;
42 Py_XDECREF(oldtype);
43 Py_XDECREF(oldvalue);
44 Py_XDECREF(oldtraceback);
47 void
48 PyErr_SetObject(PyObject *exception, PyObject *value)
50 Py_XINCREF(exception);
51 Py_XINCREF(value);
52 PyErr_Restore(exception, value, (PyObject *)NULL);
55 void
56 PyErr_SetNone(PyObject *exception)
58 PyErr_SetObject(exception, (PyObject *)NULL);
61 void
62 PyErr_SetString(PyObject *exception, const char *string)
64 PyObject *value = PyString_FromString(string);
65 PyErr_SetObject(exception, value);
66 Py_XDECREF(value);
70 PyObject *
71 PyErr_Occurred(void)
73 PyThreadState *tstate = PyThreadState_GET();
75 return tstate->curexc_type;
79 int
80 PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
82 if (err == NULL || exc == NULL) {
83 /* maybe caused by "import exceptions" that failed early on */
84 return 0;
86 if (PyTuple_Check(exc)) {
87 Py_ssize_t i, n;
88 n = PyTuple_Size(exc);
89 for (i = 0; i < n; i++) {
90 /* Test recursively */
91 if (PyErr_GivenExceptionMatches(
92 err, PyTuple_GET_ITEM(exc, i)))
94 return 1;
97 return 0;
99 /* err might be an instance, so check its class. */
100 if (PyExceptionInstance_Check(err))
101 err = PyExceptionInstance_Class(err);
103 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
104 /* problems here!? not sure PyObject_IsSubclass expects to
105 be called with an exception pending... */
106 return PyObject_IsSubclass(err, exc);
109 return err == exc;
114 PyErr_ExceptionMatches(PyObject *exc)
116 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
120 /* Used in many places to normalize a raised exception, including in
121 eval_code2(), do_raise(), and PyErr_Print()
123 void
124 PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
126 PyObject *type = *exc;
127 PyObject *value = *val;
128 PyObject *inclass = NULL;
129 PyObject *initial_tb = NULL;
131 if (type == NULL) {
132 /* There was no exception, so nothing to do. */
133 return;
136 /* If PyErr_SetNone() was used, the value will have been actually
137 set to NULL.
139 if (!value) {
140 value = Py_None;
141 Py_INCREF(value);
144 if (PyExceptionInstance_Check(value))
145 inclass = PyExceptionInstance_Class(value);
147 /* Normalize the exception so that if the type is a class, the
148 value will be an instance.
150 if (PyExceptionClass_Check(type)) {
151 /* if the value was not an instance, or is not an instance
152 whose class is (or is derived from) type, then use the
153 value as an argument to instantiation of the type
154 class.
156 if (!inclass || !PyObject_IsSubclass(inclass, type)) {
157 PyObject *args, *res;
159 if (value == Py_None)
160 args = PyTuple_New(0);
161 else if (PyTuple_Check(value)) {
162 Py_INCREF(value);
163 args = value;
165 else
166 args = PyTuple_Pack(1, value);
168 if (args == NULL)
169 goto finally;
170 res = PyEval_CallObject(type, args);
171 Py_DECREF(args);
172 if (res == NULL)
173 goto finally;
174 Py_DECREF(value);
175 value = res;
177 /* if the class of the instance doesn't exactly match the
178 class of the type, believe the instance
180 else if (inclass != type) {
181 Py_DECREF(type);
182 type = inclass;
183 Py_INCREF(type);
186 *exc = type;
187 *val = value;
188 return;
189 finally:
190 Py_DECREF(type);
191 Py_DECREF(value);
192 /* If the new exception doesn't set a traceback and the old
193 exception had a traceback, use the old traceback for the
194 new exception. It's better than nothing.
196 initial_tb = *tb;
197 PyErr_Fetch(exc, val, tb);
198 if (initial_tb != NULL) {
199 if (*tb == NULL)
200 *tb = initial_tb;
201 else
202 Py_DECREF(initial_tb);
204 /* normalize recursively */
205 PyErr_NormalizeException(exc, val, tb);
209 void
210 PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
212 PyThreadState *tstate = PyThreadState_GET();
214 *p_type = tstate->curexc_type;
215 *p_value = tstate->curexc_value;
216 *p_traceback = tstate->curexc_traceback;
218 tstate->curexc_type = NULL;
219 tstate->curexc_value = NULL;
220 tstate->curexc_traceback = NULL;
223 void
224 PyErr_Clear(void)
226 PyErr_Restore(NULL, NULL, NULL);
229 /* Convenience functions to set a type error exception and return 0 */
232 PyErr_BadArgument(void)
234 PyErr_SetString(PyExc_TypeError,
235 "bad argument type for built-in operation");
236 return 0;
239 PyObject *
240 PyErr_NoMemory(void)
242 if (PyErr_ExceptionMatches(PyExc_MemoryError))
243 /* already current */
244 return NULL;
246 /* raise the pre-allocated instance if it still exists */
247 if (PyExc_MemoryErrorInst)
248 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
249 else
250 /* this will probably fail since there's no memory and hee,
251 hee, we have to instantiate this class
253 PyErr_SetNone(PyExc_MemoryError);
255 return NULL;
258 PyObject *
259 PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
261 PyObject *v;
262 char *s;
263 int i = errno;
264 #ifdef PLAN9
265 char errbuf[ERRMAX];
266 #endif
267 #ifdef MS_WINDOWS
268 char *s_buf = NULL;
269 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
270 #endif
271 #ifdef EINTR
272 if (i == EINTR && PyErr_CheckSignals())
273 return NULL;
274 #endif
275 #ifdef PLAN9
276 rerrstr(errbuf, sizeof errbuf);
277 s = errbuf;
278 #else
279 if (i == 0)
280 s = "Error"; /* Sometimes errno didn't get set */
281 else
282 #ifndef MS_WINDOWS
283 s = strerror(i);
284 #else
286 /* Note that the Win32 errors do not lineup with the
287 errno error. So if the error is in the MSVC error
288 table, we use it, otherwise we assume it really _is_
289 a Win32 error code
291 if (i > 0 && i < _sys_nerr) {
292 s = _sys_errlist[i];
294 else {
295 int len = FormatMessage(
296 FORMAT_MESSAGE_ALLOCATE_BUFFER |
297 FORMAT_MESSAGE_FROM_SYSTEM |
298 FORMAT_MESSAGE_IGNORE_INSERTS,
299 NULL, /* no message source */
301 MAKELANGID(LANG_NEUTRAL,
302 SUBLANG_DEFAULT),
303 /* Default language */
304 (LPTSTR) &s_buf,
305 0, /* size not used */
306 NULL); /* no args */
307 if (len==0) {
308 /* Only ever seen this in out-of-mem
309 situations */
310 sprintf(s_small_buf, "Windows Error 0x%X", i);
311 s = s_small_buf;
312 s_buf = NULL;
313 } else {
314 s = s_buf;
315 /* remove trailing cr/lf and dots */
316 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
317 s[--len] = '\0';
321 #endif /* Unix/Windows */
322 #endif /* PLAN 9*/
323 if (filenameObject != NULL)
324 v = Py_BuildValue("(isO)", i, s, filenameObject);
325 else
326 v = Py_BuildValue("(is)", i, s);
327 if (v != NULL) {
328 PyErr_SetObject(exc, v);
329 Py_DECREF(v);
331 #ifdef MS_WINDOWS
332 LocalFree(s_buf);
333 #endif
334 return NULL;
338 PyObject *
339 PyErr_SetFromErrnoWithFilename(PyObject *exc, char *filename)
341 PyObject *name = filename ? PyString_FromString(filename) : NULL;
342 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
343 Py_XDECREF(name);
344 return result;
347 #ifdef Py_WIN_WIDE_FILENAMES
348 PyObject *
349 PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, Py_UNICODE *filename)
351 PyObject *name = filename ?
352 PyUnicode_FromUnicode(filename, wcslen(filename)) :
353 NULL;
354 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
355 Py_XDECREF(name);
356 return result;
358 #endif /* Py_WIN_WIDE_FILENAMES */
360 PyObject *
361 PyErr_SetFromErrno(PyObject *exc)
363 return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
366 #ifdef MS_WINDOWS
367 /* Windows specific error code handling */
368 PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
369 PyObject *exc,
370 int ierr,
371 PyObject *filenameObject)
373 int len;
374 char *s;
375 char *s_buf = NULL; /* Free via LocalFree */
376 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
377 PyObject *v;
378 DWORD err = (DWORD)ierr;
379 if (err==0) err = GetLastError();
380 len = FormatMessage(
381 /* Error API error */
382 FORMAT_MESSAGE_ALLOCATE_BUFFER |
383 FORMAT_MESSAGE_FROM_SYSTEM |
384 FORMAT_MESSAGE_IGNORE_INSERTS,
385 NULL, /* no message source */
386 err,
387 MAKELANGID(LANG_NEUTRAL,
388 SUBLANG_DEFAULT), /* Default language */
389 (LPTSTR) &s_buf,
390 0, /* size not used */
391 NULL); /* no args */
392 if (len==0) {
393 /* Only seen this in out of mem situations */
394 sprintf(s_small_buf, "Windows Error 0x%X", err);
395 s = s_small_buf;
396 s_buf = NULL;
397 } else {
398 s = s_buf;
399 /* remove trailing cr/lf and dots */
400 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
401 s[--len] = '\0';
403 if (filenameObject != NULL)
404 v = Py_BuildValue("(isO)", err, s, filenameObject);
405 else
406 v = Py_BuildValue("(is)", err, s);
407 if (v != NULL) {
408 PyErr_SetObject(exc, v);
409 Py_DECREF(v);
411 LocalFree(s_buf);
412 return NULL;
415 PyObject *PyErr_SetExcFromWindowsErrWithFilename(
416 PyObject *exc,
417 int ierr,
418 const char *filename)
420 PyObject *name = filename ? PyString_FromString(filename) : NULL;
421 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
422 ierr,
423 name);
424 Py_XDECREF(name);
425 return ret;
428 #ifdef Py_WIN_WIDE_FILENAMES
429 PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
430 PyObject *exc,
431 int ierr,
432 const Py_UNICODE *filename)
434 PyObject *name = filename ?
435 PyUnicode_FromUnicode(filename, wcslen(filename)) :
436 NULL;
437 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
438 ierr,
439 name);
440 Py_XDECREF(name);
441 return ret;
443 #endif /* Py_WIN_WIDE_FILENAMES */
445 PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
447 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
450 PyObject *PyErr_SetFromWindowsErr(int ierr)
452 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
453 ierr, NULL);
455 PyObject *PyErr_SetFromWindowsErrWithFilename(
456 int ierr,
457 const char *filename)
459 PyObject *name = filename ? PyString_FromString(filename) : NULL;
460 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
461 PyExc_WindowsError,
462 ierr, name);
463 Py_XDECREF(name);
464 return result;
467 #ifdef Py_WIN_WIDE_FILENAMES
468 PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
469 int ierr,
470 const Py_UNICODE *filename)
472 PyObject *name = filename ?
473 PyUnicode_FromUnicode(filename, wcslen(filename)) :
474 NULL;
475 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
476 PyExc_WindowsError,
477 ierr, name);
478 Py_XDECREF(name);
479 return result;
481 #endif /* Py_WIN_WIDE_FILENAMES */
482 #endif /* MS_WINDOWS */
484 void
485 _PyErr_BadInternalCall(char *filename, int lineno)
487 PyErr_Format(PyExc_SystemError,
488 "%s:%d: bad argument to internal function",
489 filename, lineno);
492 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
493 export the entry point for existing object code: */
494 #undef PyErr_BadInternalCall
495 void
496 PyErr_BadInternalCall(void)
498 PyErr_Format(PyExc_SystemError,
499 "bad argument to internal function");
501 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
505 PyObject *
506 PyErr_Format(PyObject *exception, const char *format, ...)
508 va_list vargs;
509 PyObject* string;
511 #ifdef HAVE_STDARG_PROTOTYPES
512 va_start(vargs, format);
513 #else
514 va_start(vargs);
515 #endif
517 string = PyString_FromFormatV(format, vargs);
518 PyErr_SetObject(exception, string);
519 Py_XDECREF(string);
520 va_end(vargs);
521 return NULL;
525 PyObject *
526 PyErr_NewException(char *name, PyObject *base, PyObject *dict)
528 char *dot;
529 PyObject *modulename = NULL;
530 PyObject *classname = NULL;
531 PyObject *mydict = NULL;
532 PyObject *bases = NULL;
533 PyObject *result = NULL;
534 dot = strrchr(name, '.');
535 if (dot == NULL) {
536 PyErr_SetString(PyExc_SystemError,
537 "PyErr_NewException: name must be module.class");
538 return NULL;
540 if (base == NULL)
541 base = PyExc_Exception;
542 if (dict == NULL) {
543 dict = mydict = PyDict_New();
544 if (dict == NULL)
545 goto failure;
547 if (PyDict_GetItemString(dict, "__module__") == NULL) {
548 modulename = PyString_FromStringAndSize(name, (int)(dot-name));
549 if (modulename == NULL)
550 goto failure;
551 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
552 goto failure;
554 classname = PyString_FromString(dot+1);
555 if (classname == NULL)
556 goto failure;
557 bases = PyTuple_Pack(1, base);
558 if (bases == NULL)
559 goto failure;
560 result = PyClass_New(bases, dict, classname);
561 failure:
562 Py_XDECREF(bases);
563 Py_XDECREF(mydict);
564 Py_XDECREF(classname);
565 Py_XDECREF(modulename);
566 return result;
569 /* Call when an exception has occurred but there is no way for Python
570 to handle it. Examples: exception in __del__ or during GC. */
571 void
572 PyErr_WriteUnraisable(PyObject *obj)
574 PyObject *f, *t, *v, *tb;
575 PyErr_Fetch(&t, &v, &tb);
576 f = PySys_GetObject("stderr");
577 if (f != NULL) {
578 PyFile_WriteString("Exception ", f);
579 if (t) {
580 char* className = PyExceptionClass_Name(t);
581 PyObject* moduleName =
582 PyObject_GetAttrString(t, "__module__");
584 if (moduleName == NULL)
585 PyFile_WriteString("<unknown>", f);
586 else {
587 char* modstr = PyString_AsString(moduleName);
588 if (modstr)
590 PyFile_WriteString(modstr, f);
591 PyFile_WriteString(".", f);
594 if (className == NULL)
595 PyFile_WriteString("<unknown>", f);
596 else
597 PyFile_WriteString(className, f);
598 if (v && v != Py_None) {
599 PyFile_WriteString(": ", f);
600 PyFile_WriteObject(v, f, 0);
603 PyFile_WriteString(" in ", f);
604 PyFile_WriteObject(obj, f, 0);
605 PyFile_WriteString(" ignored\n", f);
606 PyErr_Clear(); /* Just in case */
608 Py_XDECREF(t);
609 Py_XDECREF(v);
610 Py_XDECREF(tb);
613 extern PyObject *PyModule_GetWarningsModule(void);
615 /* Function to issue a warning message; may raise an exception. */
617 PyErr_Warn(PyObject *category, char *message)
619 PyObject *dict, *func = NULL;
620 PyObject *warnings_module = PyModule_GetWarningsModule();
622 if (warnings_module != NULL) {
623 dict = PyModule_GetDict(warnings_module);
624 func = PyDict_GetItemString(dict, "warn");
626 if (func == NULL) {
627 PySys_WriteStderr("warning: %s\n", message);
628 return 0;
630 else {
631 PyObject *args, *res;
633 if (category == NULL)
634 category = PyExc_RuntimeWarning;
635 args = Py_BuildValue("(sO)", message, category);
636 if (args == NULL)
637 return -1;
638 res = PyEval_CallObject(func, args);
639 Py_DECREF(args);
640 if (res == NULL)
641 return -1;
642 Py_DECREF(res);
643 return 0;
648 /* Warning with explicit origin */
650 PyErr_WarnExplicit(PyObject *category, const char *message,
651 const char *filename, int lineno,
652 const char *module, PyObject *registry)
654 PyObject *mod, *dict, *func = NULL;
656 mod = PyImport_ImportModule("warnings");
657 if (mod != NULL) {
658 dict = PyModule_GetDict(mod);
659 func = PyDict_GetItemString(dict, "warn_explicit");
660 Py_DECREF(mod);
662 if (func == NULL) {
663 PySys_WriteStderr("warning: %s\n", message);
664 return 0;
666 else {
667 PyObject *args, *res;
669 if (category == NULL)
670 category = PyExc_RuntimeWarning;
671 if (registry == NULL)
672 registry = Py_None;
673 args = Py_BuildValue("(sOsizO)", message, category,
674 filename, lineno, module, registry);
675 if (args == NULL)
676 return -1;
677 res = PyEval_CallObject(func, args);
678 Py_DECREF(args);
679 if (res == NULL)
680 return -1;
681 Py_DECREF(res);
682 return 0;
687 /* Set file and line information for the current exception.
688 If the exception is not a SyntaxError, also sets additional attributes
689 to make printing of exceptions believe it is a syntax error. */
691 void
692 PyErr_SyntaxLocation(const char *filename, int lineno)
694 PyObject *exc, *v, *tb, *tmp;
696 /* add attributes for the line number and filename for the error */
697 PyErr_Fetch(&exc, &v, &tb);
698 PyErr_NormalizeException(&exc, &v, &tb);
699 /* XXX check that it is, indeed, a syntax error */
700 tmp = PyInt_FromLong(lineno);
701 if (tmp == NULL)
702 PyErr_Clear();
703 else {
704 if (PyObject_SetAttrString(v, "lineno", tmp))
705 PyErr_Clear();
706 Py_DECREF(tmp);
708 if (filename != NULL) {
709 tmp = PyString_FromString(filename);
710 if (tmp == NULL)
711 PyErr_Clear();
712 else {
713 if (PyObject_SetAttrString(v, "filename", tmp))
714 PyErr_Clear();
715 Py_DECREF(tmp);
718 tmp = PyErr_ProgramText(filename, lineno);
719 if (tmp) {
720 PyObject_SetAttrString(v, "text", tmp);
721 Py_DECREF(tmp);
724 if (PyObject_SetAttrString(v, "offset", Py_None)) {
725 PyErr_Clear();
727 if (exc != PyExc_SyntaxError) {
728 if (!PyObject_HasAttrString(v, "msg")) {
729 tmp = PyObject_Str(v);
730 if (tmp) {
731 if (PyObject_SetAttrString(v, "msg", tmp))
732 PyErr_Clear();
733 Py_DECREF(tmp);
734 } else {
735 PyErr_Clear();
738 if (!PyObject_HasAttrString(v, "print_file_and_line")) {
739 if (PyObject_SetAttrString(v, "print_file_and_line",
740 Py_None))
741 PyErr_Clear();
744 PyErr_Restore(exc, v, tb);
747 /* com_fetch_program_text will attempt to load the line of text that
748 the exception refers to. If it fails, it will return NULL but will
749 not set an exception.
751 XXX The functionality of this function is quite similar to the
752 functionality in tb_displayline() in traceback.c.
755 PyObject *
756 PyErr_ProgramText(const char *filename, int lineno)
758 FILE *fp;
759 int i;
760 char linebuf[1000];
762 if (filename == NULL || *filename == '\0' || lineno <= 0)
763 return NULL;
764 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
765 if (fp == NULL)
766 return NULL;
767 for (i = 0; i < lineno; i++) {
768 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
769 do {
770 *pLastChar = '\0';
771 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
772 break;
773 /* fgets read *something*; if it didn't get as
774 far as pLastChar, it must have found a newline
775 or hit the end of the file; if pLastChar is \n,
776 it obviously found a newline; else we haven't
777 yet seen a newline, so must continue */
778 } while (*pLastChar != '\0' && *pLastChar != '\n');
780 fclose(fp);
781 if (i == lineno) {
782 char *p = linebuf;
783 while (*p == ' ' || *p == '\t' || *p == '\014')
784 p++;
785 return PyString_FromString(p);
787 return NULL;