Silence SyntaxWarning and DeprecationWarning in pydoc triggered by tuple
[python.git] / Python / errors.c
blob5d9cab5a4c13884227269117927b98665822d76a
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 /* issubclass did not succeed */
117 res = 0;
119 PyErr_Restore(exception, value, tb);
120 return res;
123 return err == exc;
128 PyErr_ExceptionMatches(PyObject *exc)
130 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
134 /* Used in many places to normalize a raised exception, including in
135 eval_code2(), do_raise(), and PyErr_Print()
137 void
138 PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
140 PyObject *type = *exc;
141 PyObject *value = *val;
142 PyObject *inclass = NULL;
143 PyObject *initial_tb = NULL;
144 PyThreadState *tstate = NULL;
146 if (type == NULL) {
147 /* There was no exception, so nothing to do. */
148 return;
151 /* If PyErr_SetNone() was used, the value will have been actually
152 set to NULL.
154 if (!value) {
155 value = Py_None;
156 Py_INCREF(value);
159 if (PyExceptionInstance_Check(value))
160 inclass = PyExceptionInstance_Class(value);
162 /* Normalize the exception so that if the type is a class, the
163 value will be an instance.
165 if (PyExceptionClass_Check(type)) {
166 /* if the value was not an instance, or is not an instance
167 whose class is (or is derived from) type, then use the
168 value as an argument to instantiation of the type
169 class.
171 if (!inclass || !PyObject_IsSubclass(inclass, type)) {
172 PyObject *args, *res;
174 if (value == Py_None)
175 args = PyTuple_New(0);
176 else if (PyTuple_Check(value)) {
177 Py_INCREF(value);
178 args = value;
180 else
181 args = PyTuple_Pack(1, value);
183 if (args == NULL)
184 goto finally;
185 res = PyEval_CallObject(type, args);
186 Py_DECREF(args);
187 if (res == NULL)
188 goto finally;
189 Py_DECREF(value);
190 value = res;
192 /* if the class of the instance doesn't exactly match the
193 class of the type, believe the instance
195 else if (inclass != type) {
196 Py_DECREF(type);
197 type = inclass;
198 Py_INCREF(type);
201 *exc = type;
202 *val = value;
203 return;
204 finally:
205 Py_DECREF(type);
206 Py_DECREF(value);
207 /* If the new exception doesn't set a traceback and the old
208 exception had a traceback, use the old traceback for the
209 new exception. It's better than nothing.
211 initial_tb = *tb;
212 PyErr_Fetch(exc, val, tb);
213 if (initial_tb != NULL) {
214 if (*tb == NULL)
215 *tb = initial_tb;
216 else
217 Py_DECREF(initial_tb);
219 /* normalize recursively */
220 tstate = PyThreadState_GET();
221 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
222 --tstate->recursion_depth;
223 PyErr_SetObject(PyExc_RuntimeError, PyExc_RecursionErrorInst);
224 return;
226 PyErr_NormalizeException(exc, val, tb);
227 --tstate->recursion_depth;
231 void
232 PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
234 PyThreadState *tstate = PyThreadState_GET();
236 *p_type = tstate->curexc_type;
237 *p_value = tstate->curexc_value;
238 *p_traceback = tstate->curexc_traceback;
240 tstate->curexc_type = NULL;
241 tstate->curexc_value = NULL;
242 tstate->curexc_traceback = NULL;
245 void
246 PyErr_Clear(void)
248 PyErr_Restore(NULL, NULL, NULL);
251 /* Convenience functions to set a type error exception and return 0 */
254 PyErr_BadArgument(void)
256 PyErr_SetString(PyExc_TypeError,
257 "bad argument type for built-in operation");
258 return 0;
261 PyObject *
262 PyErr_NoMemory(void)
264 if (PyErr_ExceptionMatches(PyExc_MemoryError))
265 /* already current */
266 return NULL;
268 /* raise the pre-allocated instance if it still exists */
269 if (PyExc_MemoryErrorInst)
270 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
271 else
272 /* this will probably fail since there's no memory and hee,
273 hee, we have to instantiate this class
275 PyErr_SetNone(PyExc_MemoryError);
277 return NULL;
280 PyObject *
281 PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
283 PyObject *v;
284 char *s;
285 int i = errno;
286 #ifdef PLAN9
287 char errbuf[ERRMAX];
288 #endif
289 #ifdef MS_WINDOWS
290 char *s_buf = NULL;
291 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
292 #endif
293 #ifdef EINTR
294 if (i == EINTR && PyErr_CheckSignals())
295 return NULL;
296 #endif
297 #ifdef PLAN9
298 rerrstr(errbuf, sizeof errbuf);
299 s = errbuf;
300 #else
301 if (i == 0)
302 s = "Error"; /* Sometimes errno didn't get set */
303 else
304 #ifndef MS_WINDOWS
305 s = strerror(i);
306 #else
308 /* Note that the Win32 errors do not lineup with the
309 errno error. So if the error is in the MSVC error
310 table, we use it, otherwise we assume it really _is_
311 a Win32 error code
313 if (i > 0 && i < _sys_nerr) {
314 s = _sys_errlist[i];
316 else {
317 int len = FormatMessage(
318 FORMAT_MESSAGE_ALLOCATE_BUFFER |
319 FORMAT_MESSAGE_FROM_SYSTEM |
320 FORMAT_MESSAGE_IGNORE_INSERTS,
321 NULL, /* no message source */
323 MAKELANGID(LANG_NEUTRAL,
324 SUBLANG_DEFAULT),
325 /* Default language */
326 (LPTSTR) &s_buf,
327 0, /* size not used */
328 NULL); /* no args */
329 if (len==0) {
330 /* Only ever seen this in out-of-mem
331 situations */
332 sprintf(s_small_buf, "Windows Error 0x%X", i);
333 s = s_small_buf;
334 s_buf = NULL;
335 } else {
336 s = s_buf;
337 /* remove trailing cr/lf and dots */
338 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
339 s[--len] = '\0';
343 #endif /* Unix/Windows */
344 #endif /* PLAN 9*/
345 if (filenameObject != NULL)
346 v = Py_BuildValue("(isO)", i, s, filenameObject);
347 else
348 v = Py_BuildValue("(is)", i, s);
349 if (v != NULL) {
350 PyErr_SetObject(exc, v);
351 Py_DECREF(v);
353 #ifdef MS_WINDOWS
354 LocalFree(s_buf);
355 #endif
356 return NULL;
360 PyObject *
361 PyErr_SetFromErrnoWithFilename(PyObject *exc, char *filename)
363 PyObject *name = filename ? PyString_FromString(filename) : NULL;
364 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
365 Py_XDECREF(name);
366 return result;
369 #ifdef Py_WIN_WIDE_FILENAMES
370 PyObject *
371 PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, Py_UNICODE *filename)
373 PyObject *name = filename ?
374 PyUnicode_FromUnicode(filename, wcslen(filename)) :
375 NULL;
376 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
377 Py_XDECREF(name);
378 return result;
380 #endif /* Py_WIN_WIDE_FILENAMES */
382 PyObject *
383 PyErr_SetFromErrno(PyObject *exc)
385 return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
388 #ifdef MS_WINDOWS
389 /* Windows specific error code handling */
390 PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
391 PyObject *exc,
392 int ierr,
393 PyObject *filenameObject)
395 int len;
396 char *s;
397 char *s_buf = NULL; /* Free via LocalFree */
398 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
399 PyObject *v;
400 DWORD err = (DWORD)ierr;
401 if (err==0) err = GetLastError();
402 len = FormatMessage(
403 /* Error API error */
404 FORMAT_MESSAGE_ALLOCATE_BUFFER |
405 FORMAT_MESSAGE_FROM_SYSTEM |
406 FORMAT_MESSAGE_IGNORE_INSERTS,
407 NULL, /* no message source */
408 err,
409 MAKELANGID(LANG_NEUTRAL,
410 SUBLANG_DEFAULT), /* Default language */
411 (LPTSTR) &s_buf,
412 0, /* size not used */
413 NULL); /* no args */
414 if (len==0) {
415 /* Only seen this in out of mem situations */
416 sprintf(s_small_buf, "Windows Error 0x%X", err);
417 s = s_small_buf;
418 s_buf = NULL;
419 } else {
420 s = s_buf;
421 /* remove trailing cr/lf and dots */
422 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
423 s[--len] = '\0';
425 if (filenameObject != NULL)
426 v = Py_BuildValue("(isO)", err, s, filenameObject);
427 else
428 v = Py_BuildValue("(is)", err, s);
429 if (v != NULL) {
430 PyErr_SetObject(exc, v);
431 Py_DECREF(v);
433 LocalFree(s_buf);
434 return NULL;
437 PyObject *PyErr_SetExcFromWindowsErrWithFilename(
438 PyObject *exc,
439 int ierr,
440 const char *filename)
442 PyObject *name = filename ? PyString_FromString(filename) : NULL;
443 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
444 ierr,
445 name);
446 Py_XDECREF(name);
447 return ret;
450 #ifdef Py_WIN_WIDE_FILENAMES
451 PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
452 PyObject *exc,
453 int ierr,
454 const Py_UNICODE *filename)
456 PyObject *name = filename ?
457 PyUnicode_FromUnicode(filename, wcslen(filename)) :
458 NULL;
459 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
460 ierr,
461 name);
462 Py_XDECREF(name);
463 return ret;
465 #endif /* Py_WIN_WIDE_FILENAMES */
467 PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
469 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
472 PyObject *PyErr_SetFromWindowsErr(int ierr)
474 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
475 ierr, NULL);
477 PyObject *PyErr_SetFromWindowsErrWithFilename(
478 int ierr,
479 const char *filename)
481 PyObject *name = filename ? PyString_FromString(filename) : NULL;
482 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
483 PyExc_WindowsError,
484 ierr, name);
485 Py_XDECREF(name);
486 return result;
489 #ifdef Py_WIN_WIDE_FILENAMES
490 PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
491 int ierr,
492 const Py_UNICODE *filename)
494 PyObject *name = filename ?
495 PyUnicode_FromUnicode(filename, wcslen(filename)) :
496 NULL;
497 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
498 PyExc_WindowsError,
499 ierr, name);
500 Py_XDECREF(name);
501 return result;
503 #endif /* Py_WIN_WIDE_FILENAMES */
504 #endif /* MS_WINDOWS */
506 void
507 _PyErr_BadInternalCall(char *filename, int lineno)
509 PyErr_Format(PyExc_SystemError,
510 "%s:%d: bad argument to internal function",
511 filename, lineno);
514 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
515 export the entry point for existing object code: */
516 #undef PyErr_BadInternalCall
517 void
518 PyErr_BadInternalCall(void)
520 PyErr_Format(PyExc_SystemError,
521 "bad argument to internal function");
523 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
527 PyObject *
528 PyErr_Format(PyObject *exception, const char *format, ...)
530 va_list vargs;
531 PyObject* string;
533 #ifdef HAVE_STDARG_PROTOTYPES
534 va_start(vargs, format);
535 #else
536 va_start(vargs);
537 #endif
539 string = PyString_FromFormatV(format, vargs);
540 PyErr_SetObject(exception, string);
541 Py_XDECREF(string);
542 va_end(vargs);
543 return NULL;
548 PyObject *
549 PyErr_NewException(char *name, PyObject *base, PyObject *dict)
551 char *dot;
552 PyObject *modulename = NULL;
553 PyObject *classname = NULL;
554 PyObject *mydict = NULL;
555 PyObject *bases = NULL;
556 PyObject *result = NULL;
557 dot = strrchr(name, '.');
558 if (dot == NULL) {
559 PyErr_SetString(PyExc_SystemError,
560 "PyErr_NewException: name must be module.class");
561 return NULL;
563 if (base == NULL)
564 base = PyExc_Exception;
565 if (dict == NULL) {
566 dict = mydict = PyDict_New();
567 if (dict == NULL)
568 goto failure;
570 if (PyDict_GetItemString(dict, "__module__") == NULL) {
571 modulename = PyString_FromStringAndSize(name,
572 (Py_ssize_t)(dot-name));
573 if (modulename == NULL)
574 goto failure;
575 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
576 goto failure;
578 if (PyTuple_Check(base)) {
579 bases = base;
580 /* INCREF as we create a new ref in the else branch */
581 Py_INCREF(bases);
582 } else {
583 bases = PyTuple_Pack(1, base);
584 if (bases == NULL)
585 goto failure;
587 /* Create a real new-style class. */
588 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
589 dot+1, bases, dict);
590 failure:
591 Py_XDECREF(bases);
592 Py_XDECREF(mydict);
593 Py_XDECREF(classname);
594 Py_XDECREF(modulename);
595 return result;
598 /* Call when an exception has occurred but there is no way for Python
599 to handle it. Examples: exception in __del__ or during GC. */
600 void
601 PyErr_WriteUnraisable(PyObject *obj)
603 PyObject *f, *t, *v, *tb;
604 PyErr_Fetch(&t, &v, &tb);
605 f = PySys_GetObject("stderr");
606 if (f != NULL) {
607 PyFile_WriteString("Exception ", f);
608 if (t) {
609 PyObject* moduleName;
610 char* className;
611 assert(PyExceptionClass_Check(t));
612 className = PyExceptionClass_Name(t);
613 if (className != NULL) {
614 char *dot = strrchr(className, '.');
615 if (dot != NULL)
616 className = dot+1;
619 moduleName = PyObject_GetAttrString(t, "__module__");
620 if (moduleName == NULL)
621 PyFile_WriteString("<unknown>", f);
622 else {
623 char* modstr = PyString_AsString(moduleName);
624 if (modstr &&
625 strcmp(modstr, "exceptions") != 0)
627 PyFile_WriteString(modstr, f);
628 PyFile_WriteString(".", f);
631 if (className == NULL)
632 PyFile_WriteString("<unknown>", f);
633 else
634 PyFile_WriteString(className, f);
635 if (v && v != Py_None) {
636 PyFile_WriteString(": ", f);
637 PyFile_WriteObject(v, f, 0);
639 Py_XDECREF(moduleName);
641 PyFile_WriteString(" in ", f);
642 PyFile_WriteObject(obj, f, 0);
643 PyFile_WriteString(" ignored\n", f);
644 PyErr_Clear(); /* Just in case */
646 Py_XDECREF(t);
647 Py_XDECREF(v);
648 Py_XDECREF(tb);
651 extern PyObject *PyModule_GetWarningsModule(void);
654 /* Set file and line information for the current exception.
655 If the exception is not a SyntaxError, also sets additional attributes
656 to make printing of exceptions believe it is a syntax error. */
658 void
659 PyErr_SyntaxLocation(const char *filename, int lineno)
661 PyObject *exc, *v, *tb, *tmp;
663 /* add attributes for the line number and filename for the error */
664 PyErr_Fetch(&exc, &v, &tb);
665 PyErr_NormalizeException(&exc, &v, &tb);
666 /* XXX check that it is, indeed, a syntax error. It might not
667 * be, though. */
668 tmp = PyInt_FromLong(lineno);
669 if (tmp == NULL)
670 PyErr_Clear();
671 else {
672 if (PyObject_SetAttrString(v, "lineno", tmp))
673 PyErr_Clear();
674 Py_DECREF(tmp);
676 if (filename != NULL) {
677 tmp = PyString_FromString(filename);
678 if (tmp == NULL)
679 PyErr_Clear();
680 else {
681 if (PyObject_SetAttrString(v, "filename", tmp))
682 PyErr_Clear();
683 Py_DECREF(tmp);
686 tmp = PyErr_ProgramText(filename, lineno);
687 if (tmp) {
688 if (PyObject_SetAttrString(v, "text", tmp))
689 PyErr_Clear();
690 Py_DECREF(tmp);
693 if (PyObject_SetAttrString(v, "offset", Py_None)) {
694 PyErr_Clear();
696 if (exc != PyExc_SyntaxError) {
697 if (!PyObject_HasAttrString(v, "msg")) {
698 tmp = PyObject_Str(v);
699 if (tmp) {
700 if (PyObject_SetAttrString(v, "msg", tmp))
701 PyErr_Clear();
702 Py_DECREF(tmp);
703 } else {
704 PyErr_Clear();
707 if (!PyObject_HasAttrString(v, "print_file_and_line")) {
708 if (PyObject_SetAttrString(v, "print_file_and_line",
709 Py_None))
710 PyErr_Clear();
713 PyErr_Restore(exc, v, tb);
716 /* com_fetch_program_text will attempt to load the line of text that
717 the exception refers to. If it fails, it will return NULL but will
718 not set an exception.
720 XXX The functionality of this function is quite similar to the
721 functionality in tb_displayline() in traceback.c.
724 PyObject *
725 PyErr_ProgramText(const char *filename, int lineno)
727 FILE *fp;
728 int i;
729 char linebuf[1000];
731 if (filename == NULL || *filename == '\0' || lineno <= 0)
732 return NULL;
733 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
734 if (fp == NULL)
735 return NULL;
736 for (i = 0; i < lineno; i++) {
737 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
738 do {
739 *pLastChar = '\0';
740 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
741 break;
742 /* fgets read *something*; if it didn't get as
743 far as pLastChar, it must have found a newline
744 or hit the end of the file; if pLastChar is \n,
745 it obviously found a newline; else we haven't
746 yet seen a newline, so must continue */
747 } while (*pLastChar != '\0' && *pLastChar != '\n');
749 fclose(fp);
750 if (i == lineno) {
751 char *p = linebuf;
752 while (*p == ' ' || *p == '\t' || *p == '\014')
753 p++;
754 return PyString_FromString(p);
756 return NULL;
759 #ifdef __cplusplus
761 #endif