7 extern char *PyMac_StrError(int);
9 #define strerror PyMac_StrError
10 #endif /* macintosh */
14 extern char *strerror(int);
26 PyErr_Restore(PyObject
*type
, PyObject
*value
, PyObject
*traceback
)
28 PyThreadState
*tstate
= PyThreadState_GET();
29 PyObject
*oldtype
, *oldvalue
, *oldtraceback
;
31 if (traceback
!= NULL
&& !PyTraceBack_Check(traceback
)) {
32 /* XXX Should never happen -- fatal error instead? */
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
;
49 Py_XDECREF(oldtraceback
);
53 PyErr_SetObject(PyObject
*exception
, PyObject
*value
)
55 Py_XINCREF(exception
);
57 PyErr_Restore(exception
, value
, (PyObject
*)NULL
);
61 PyErr_SetNone(PyObject
*exception
)
63 PyErr_SetObject(exception
, (PyObject
*)NULL
);
67 PyErr_SetString(PyObject
*exception
, const char *string
)
69 PyObject
*value
= PyString_FromString(string
);
70 PyErr_SetObject(exception
, value
);
78 PyThreadState
*tstate
= PyThreadState_Get();
80 return tstate
->curexc_type
;
85 PyErr_GivenExceptionMatches(PyObject
*err
, PyObject
*exc
)
87 if (err
== NULL
|| exc
== NULL
) {
88 /* maybe caused by "import exceptions" that failed early on */
91 if (PyTuple_Check(exc
)) {
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
)))
104 /* err might be an instance, so check its class. */
105 if (PyInstance_Check(err
))
106 err
= (PyObject
*)((PyInstanceObject
*)err
)->in_class
;
108 if (PyClass_Check(err
) && PyClass_Check(exc
))
109 return PyClass_IsSubclass(err
, exc
);
116 PyErr_ExceptionMatches(PyObject
*exc
)
118 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc
);
122 /* Used in many places to normalize a raised exception, including in
123 eval_code2(), do_raise(), and PyErr_Print()
126 PyErr_NormalizeException(PyObject
**exc
, PyObject
**val
, PyObject
**tb
)
128 PyObject
*type
= *exc
;
129 PyObject
*value
= *val
;
130 PyObject
*inclass
= NULL
;
133 /* This is a bug. Should never happen. Don't dump core. */
134 PyErr_SetString(PyExc_SystemError
,
135 "PyErr_NormalizeException() called without exception");
138 /* If PyErr_SetNone() was used, the value will have been actually
146 if (PyInstance_Check(value
))
147 inclass
= (PyObject
*)((PyInstanceObject
*)value
)->in_class
;
149 /* Normalize the exception so that if the type is a class, the
150 value will be an instance.
152 if (PyClass_Check(type
)) {
153 /* if the value was not an instance, or is not an instance
154 whose class is (or is derived from) type, then use the
155 value as an argument to instantiation of the type
158 if (!inclass
|| !PyClass_IsSubclass(inclass
, type
)) {
159 PyObject
*args
, *res
;
161 if (value
== Py_None
)
162 args
= Py_BuildValue("()");
163 else if (PyTuple_Check(value
)) {
168 args
= Py_BuildValue("(O)", value
);
172 res
= PyEval_CallObject(type
, args
);
179 /* if the class of the instance doesn't exactly match the
180 class of the type, believe the instance
182 else if (inclass
!= type
) {
195 PyErr_Fetch(exc
, val
, tb
);
196 /* normalize recursively */
197 PyErr_NormalizeException(exc
, val
, tb
);
202 PyErr_Fetch(PyObject
**p_type
, PyObject
**p_value
, PyObject
**p_traceback
)
204 PyThreadState
*tstate
= PyThreadState_Get();
206 *p_type
= tstate
->curexc_type
;
207 *p_value
= tstate
->curexc_value
;
208 *p_traceback
= tstate
->curexc_traceback
;
210 tstate
->curexc_type
= NULL
;
211 tstate
->curexc_value
= NULL
;
212 tstate
->curexc_traceback
= NULL
;
218 PyErr_Restore(NULL
, NULL
, NULL
);
221 /* Convenience functions to set a type error exception and return 0 */
224 PyErr_BadArgument(void)
226 PyErr_SetString(PyExc_TypeError
,
227 "bad argument type for built-in operation");
234 if (PyErr_ExceptionMatches(PyExc_MemoryError
))
235 /* already current */
238 /* raise the pre-allocated instance if it still exists */
239 if (PyExc_MemoryErrorInst
)
240 PyErr_SetObject(PyExc_MemoryError
, PyExc_MemoryErrorInst
);
242 /* this will probably fail since there's no memory and hee,
243 hee, we have to instantiate this class
245 PyErr_SetNone(PyExc_MemoryError
);
251 PyErr_SetFromErrnoWithFilename(PyObject
*exc
, char *filename
)
260 if (i
== EINTR
&& PyErr_CheckSignals())
264 s
= "Error"; /* Sometimes errno didn't get set */
270 /* Note that the Win32 errors do not lineup with the
271 errno error. So if the error is in the MSVC error
272 table, we use it, otherwise we assume it really _is_
275 if (i
> 0 && i
< _sys_nerr
) {
279 int len
= FormatMessage(
280 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
281 FORMAT_MESSAGE_FROM_SYSTEM
|
282 FORMAT_MESSAGE_IGNORE_INSERTS
,
283 NULL
, /* no message source */
285 MAKELANGID(LANG_NEUTRAL
,
287 /* Default language */
289 0, /* size not used */
292 /* remove trailing cr/lf and dots */
293 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
298 if (filename
!= NULL
)
299 v
= Py_BuildValue("(iss)", i
, s
, filename
);
301 v
= Py_BuildValue("(is)", i
, s
);
303 PyErr_SetObject(exc
, v
);
314 PyErr_SetFromErrno(PyObject
*exc
)
316 return PyErr_SetFromErrnoWithFilename(exc
, NULL
);
320 /* Windows specific error code handling */
321 PyObject
*PyErr_SetFromWindowsErrWithFilename(
323 const char *filename
)
328 DWORD err
= (DWORD
)ierr
;
329 if (err
==0) err
= GetLastError();
331 /* Error API error */
332 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
333 FORMAT_MESSAGE_FROM_SYSTEM
|
334 FORMAT_MESSAGE_IGNORE_INSERTS
,
335 NULL
, /* no message source */
337 MAKELANGID(LANG_NEUTRAL
,
338 SUBLANG_DEFAULT
), /* Default language */
340 0, /* size not used */
342 /* remove trailing cr/lf and dots */
343 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
345 if (filename
!= NULL
)
346 v
= Py_BuildValue("(iss)", err
, s
, filename
);
348 v
= Py_BuildValue("(is)", err
, s
);
350 PyErr_SetObject(PyExc_WindowsError
, v
);
357 PyObject
*PyErr_SetFromWindowsErr(int ierr
)
359 return PyErr_SetFromWindowsErrWithFilename(ierr
, NULL
);
361 #endif /* MS_WINDOWS */
364 _PyErr_BadInternalCall(char *filename
, int lineno
)
366 PyErr_Format(PyExc_SystemError
,
367 "%s:%d: bad argument to internal function",
371 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
372 export the entry point for existing object code: */
373 #undef PyErr_BadInternalCall
375 PyErr_BadInternalCall(void)
377 PyErr_Format(PyExc_SystemError
,
378 "bad argument to internal function");
380 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
385 PyErr_Format(PyObject
*exception
, const char *format
, ...)
393 /* step 1: figure out how large a buffer we need */
395 #ifdef HAVE_STDARG_PROTOTYPES
396 va_start(vargs
, format
);
402 for (f
= format
; *f
; f
++) {
405 while (*++f
&& *f
!= '%' && !isalpha(Py_CHARMASK(*f
)))
409 (void) va_arg(vargs
, int);
410 /* fall through... */
414 case 'd': case 'i': case 'x':
415 (void) va_arg(vargs
, int);
416 /* 20 bytes should be enough to hold a 64-bit
421 s
= va_arg(vargs
, char*);
425 /* if we stumble upon an unknown
426 formatting code, copy the rest of
427 the format string to the output
428 string. (we cannot just skip the
429 code, since there's no way to know
430 what's in the argument list) */
440 string
= PyString_FromStringAndSize(NULL
, n
);
444 #ifdef HAVE_STDARG_PROTOTYPES
445 va_start(vargs
, format
);
450 /* step 2: fill the buffer */
452 s
= PyString_AsString(string
);
454 for (f
= format
; *f
; f
++) {
457 /* parse the width.precision part (we're only
458 interested in the precision value, if any) */
460 while (isdigit(Py_CHARMASK(*f
)))
461 n
= (n
*10) + *f
++ - '0';
465 while (isdigit(Py_CHARMASK(*f
)))
466 n
= (n
*10) + *f
++ - '0';
468 while (*f
&& *f
!= '%' && !isalpha(Py_CHARMASK(*f
)))
472 *s
++ = va_arg(vargs
, int);
475 sprintf(s
, "%d", va_arg(vargs
, int));
479 sprintf(s
, "%i", va_arg(vargs
, int));
483 sprintf(s
, "%x", va_arg(vargs
, int));
487 p
= va_arg(vargs
, char*);
508 _PyString_Resize(&string
, s
- PyString_AsString(string
));
510 PyErr_SetObject(exception
, string
);
518 PyErr_NewException(char *name
, PyObject
*base
, PyObject
*dict
)
521 PyObject
*modulename
= NULL
;
522 PyObject
*classname
= NULL
;
523 PyObject
*mydict
= NULL
;
524 PyObject
*bases
= NULL
;
525 PyObject
*result
= NULL
;
526 dot
= strrchr(name
, '.');
528 PyErr_SetString(PyExc_SystemError
,
529 "PyErr_NewException: name must be module.class");
533 base
= PyExc_Exception
;
534 if (!PyClass_Check(base
)) {
535 /* Must be using string-based standard exceptions (-X) */
536 return PyString_FromString(name
);
539 dict
= mydict
= PyDict_New();
543 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
544 modulename
= PyString_FromStringAndSize(name
, (int)(dot
-name
));
545 if (modulename
== NULL
)
547 if (PyDict_SetItemString(dict
, "__module__", modulename
) != 0)
550 classname
= PyString_FromString(dot
+1);
551 if (classname
== NULL
)
553 bases
= Py_BuildValue("(O)", base
);
556 result
= PyClass_New(bases
, dict
, classname
);
560 Py_XDECREF(classname
);
561 Py_XDECREF(modulename
);
565 /* Call when an exception has occurred but there is no way for Python
566 to handle it. Examples: exception in __del__ or during GC. */
568 PyErr_WriteUnraisable(PyObject
*obj
)
570 PyObject
*f
, *t
, *v
, *tb
;
571 PyErr_Fetch(&t
, &v
, &tb
);
572 f
= PySys_GetObject("stderr");
574 PyFile_WriteString("Exception ", f
);
576 PyFile_WriteObject(t
, f
, Py_PRINT_RAW
);
577 if (v
&& v
!= Py_None
) {
578 PyFile_WriteString(": ", f
);
579 PyFile_WriteObject(v
, f
, 0);
582 PyFile_WriteString(" in ", f
);
583 PyFile_WriteObject(obj
, f
, 0);
584 PyFile_WriteString(" ignored\n", f
);
585 PyErr_Clear(); /* Just in case */
593 /* Function to issue a warning message; may raise an exception. */
595 PyErr_Warn(PyObject
*category
, char *message
)
597 PyObject
*mod
, *dict
, *func
= NULL
;
599 mod
= PyImport_ImportModule("warnings");
601 dict
= PyModule_GetDict(mod
);
602 func
= PyDict_GetItemString(dict
, "warn");
606 PySys_WriteStderr("warning: %s\n", message
);
610 PyObject
*args
, *res
;
612 if (category
== NULL
)
613 category
= PyExc_RuntimeWarning
;
614 args
= Py_BuildValue("(sO)", message
, category
);
617 res
= PyEval_CallObject(func
, args
);
627 /* Warning with explicit origin */
629 PyErr_WarnExplicit(PyObject
*category
, char *message
,
630 char *filename
, int lineno
,
631 char *module
, PyObject
*registry
)
633 PyObject
*mod
, *dict
, *func
= NULL
;
635 mod
= PyImport_ImportModule("warnings");
637 dict
= PyModule_GetDict(mod
);
638 func
= PyDict_GetItemString(dict
, "warn_explicit");
642 PySys_WriteStderr("warning: %s\n", message
);
646 PyObject
*args
, *res
;
648 if (category
== NULL
)
649 category
= PyExc_RuntimeWarning
;
650 if (registry
== NULL
)
652 args
= Py_BuildValue("(sOsizO)", message
, category
,
653 filename
, lineno
, module
, registry
);
656 res
= PyEval_CallObject(func
, args
);
666 /* XXX There's a comment missing here */
669 PyErr_SyntaxLocation(char *filename
, int lineno
)
671 PyObject
*exc
, *v
, *tb
, *tmp
;
673 /* add attributes for the line number and filename for the error */
674 PyErr_Fetch(&exc
, &v
, &tb
);
675 PyErr_NormalizeException(&exc
, &v
, &tb
);
676 /* XXX check that it is, indeed, a syntax error */
677 tmp
= PyInt_FromLong(lineno
);
681 if (PyObject_SetAttrString(v
, "lineno", tmp
))
685 if (filename
!= NULL
) {
686 tmp
= PyString_FromString(filename
);
690 if (PyObject_SetAttrString(v
, "filename", tmp
))
695 tmp
= PyErr_ProgramText(filename
, lineno
);
697 PyObject_SetAttrString(v
, "text", tmp
);
701 PyErr_Restore(exc
, v
, tb
);
704 /* com_fetch_program_text will attempt to load the line of text that
705 the exception refers to. If it fails, it will return NULL but will
706 not set an exception.
708 XXX The functionality of this function is quite similar to the
709 functionality in tb_displayline() in traceback.c.
713 PyErr_ProgramText(char *filename
, int lineno
)
719 if (filename
== NULL
|| lineno
<= 0)
721 fp
= fopen(filename
, "r");
724 for (i
= 0; i
< lineno
; i
++) {
725 char *pLastChar
= &linebuf
[sizeof(linebuf
) - 2];
728 if (fgets(linebuf
, sizeof linebuf
, fp
) == NULL
)
730 /* fgets read *something*; if it didn't get as
731 far as pLastChar, it must have found a newline
732 or hit the end of the file; if pLastChar is \n,
733 it obviously found a newline; else we haven't
734 yet seen a newline, so must continue */
735 } while (*pLastChar
!= '\0' && *pLastChar
!= '\n');
740 while (*p
== ' ' || *p
== '\t' || *p
== '\014')
742 return PyString_FromString(p
);