errors.c revision ed473a46fc06d3e707821e5b83fa7210239a492d
1/***********************************************************
2Copyright (c) 2000, BeOpen.com.
3Copyright (c) 1995-2000, Corporation for National Research Initiatives.
4Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
5All rights reserved.
6
7See the file "Misc/COPYRIGHT" for information on usage and
8redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
9******************************************************************/
10
11/* Error handling */
12
13#include "Python.h"
14
15#ifdef macintosh
16extern char *PyMac_StrError(int);
17#undef strerror
18#define strerror PyMac_StrError
19#endif /* macintosh */
20
21#ifndef __STDC__
22#ifndef MS_WINDOWS
23extern char *strerror(int);
24#endif
25#endif
26
27#ifdef MS_WIN32
28#include "windows.h"
29#include "winbase.h"
30#endif
31
32void
33PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
34{
35	PyThreadState *tstate = PyThreadState_GET();
36	PyObject *oldtype, *oldvalue, *oldtraceback;
37
38	if (traceback != NULL && !PyTraceBack_Check(traceback)) {
39		/* XXX Should never happen -- fatal error instead? */
40		Py_DECREF(traceback);
41		traceback = NULL;
42	}
43
44	/* Save these in locals to safeguard against recursive
45	   invocation through Py_XDECREF */
46	oldtype = tstate->curexc_type;
47	oldvalue = tstate->curexc_value;
48	oldtraceback = tstate->curexc_traceback;
49
50	tstate->curexc_type = type;
51	tstate->curexc_value = value;
52	tstate->curexc_traceback = traceback;
53
54	Py_XDECREF(oldtype);
55	Py_XDECREF(oldvalue);
56	Py_XDECREF(oldtraceback);
57}
58
59void
60PyErr_SetObject(PyObject *exception, PyObject *value)
61{
62	Py_XINCREF(exception);
63	Py_XINCREF(value);
64	PyErr_Restore(exception, value, (PyObject *)NULL);
65}
66
67void
68PyErr_SetNone(PyObject *exception)
69{
70	PyErr_SetObject(exception, (PyObject *)NULL);
71}
72
73void
74PyErr_SetString(PyObject *exception, const char *string)
75{
76	PyObject *value = PyString_FromString(string);
77	PyErr_SetObject(exception, value);
78	Py_XDECREF(value);
79}
80
81
82PyObject *
83PyErr_Occurred(void)
84{
85	PyThreadState *tstate = PyThreadState_Get();
86
87	return tstate->curexc_type;
88}
89
90
91int
92PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
93{
94	if (err == NULL || exc == NULL) {
95		/* maybe caused by "import exceptions" that failed early on */
96		return 0;
97	}
98	if (PyTuple_Check(exc)) {
99		int i, n;
100		n = PyTuple_Size(exc);
101		for (i = 0; i < n; i++) {
102			/* Test recursively */
103		     if (PyErr_GivenExceptionMatches(
104			     err, PyTuple_GET_ITEM(exc, i)))
105		     {
106			     return 1;
107		     }
108		}
109		return 0;
110	}
111	/* err might be an instance, so check its class. */
112	if (PyInstance_Check(err))
113		err = (PyObject*)((PyInstanceObject*)err)->in_class;
114
115	if (PyClass_Check(err) && PyClass_Check(exc))
116		return PyClass_IsSubclass(err, exc);
117
118	return err == exc;
119}
120
121
122int
123PyErr_ExceptionMatches(PyObject *exc)
124{
125	return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
126}
127
128
129/* Used in many places to normalize a raised exception, including in
130   eval_code2(), do_raise(), and PyErr_Print()
131*/
132void
133PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
134{
135	PyObject *type = *exc;
136	PyObject *value = *val;
137	PyObject *inclass = NULL;
138
139	if (type == NULL) {
140		/* This is a bug.  Should never happen.  Don't dump core. */
141		PyErr_SetString(PyExc_SystemError,
142			"PyErr_NormalizeException() called without exception");
143	}
144
145	/* If PyErr_SetNone() was used, the value will have been actually
146	   set to NULL.
147	*/
148	if (!value) {
149		value = Py_None;
150		Py_INCREF(value);
151	}
152
153	if (PyInstance_Check(value))
154		inclass = (PyObject*)((PyInstanceObject*)value)->in_class;
155
156	/* Normalize the exception so that if the type is a class, the
157	   value will be an instance.
158	*/
159	if (PyClass_Check(type)) {
160		/* if the value was not an instance, or is not an instance
161		   whose class is (or is derived from) type, then use the
162		   value as an argument to instantiation of the type
163		   class.
164		*/
165		if (!inclass || !PyClass_IsSubclass(inclass, type)) {
166			PyObject *args, *res;
167
168			if (value == Py_None)
169				args = Py_BuildValue("()");
170			else if (PyTuple_Check(value)) {
171				Py_INCREF(value);
172				args = value;
173			}
174			else
175				args = Py_BuildValue("(O)", value);
176
177			if (args == NULL)
178				goto finally;
179			res = PyEval_CallObject(type, args);
180			Py_DECREF(args);
181			if (res == NULL)
182				goto finally;
183			Py_DECREF(value);
184			value = res;
185		}
186		/* if the class of the instance doesn't exactly match the
187		   class of the type, believe the instance
188		*/
189		else if (inclass != type) {
190 			Py_DECREF(type);
191			type = inclass;
192			Py_INCREF(type);
193		}
194	}
195	*exc = type;
196	*val = value;
197	return;
198finally:
199	Py_DECREF(type);
200	Py_DECREF(value);
201	Py_XDECREF(*tb);
202	PyErr_Fetch(exc, val, tb);
203	/* normalize recursively */
204	PyErr_NormalizeException(exc, val, tb);
205}
206
207
208void
209PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
210{
211	PyThreadState *tstate = PyThreadState_Get();
212
213	*p_type = tstate->curexc_type;
214	*p_value = tstate->curexc_value;
215	*p_traceback = tstate->curexc_traceback;
216
217	tstate->curexc_type = NULL;
218	tstate->curexc_value = NULL;
219	tstate->curexc_traceback = NULL;
220}
221
222void
223PyErr_Clear(void)
224{
225	PyErr_Restore(NULL, NULL, NULL);
226}
227
228/* Convenience functions to set a type error exception and return 0 */
229
230int
231PyErr_BadArgument(void)
232{
233	PyErr_SetString(PyExc_TypeError,
234			"illegal argument type for built-in operation");
235	return 0;
236}
237
238PyObject *
239PyErr_NoMemory(void)
240{
241	/* raise the pre-allocated instance if it still exists */
242	if (PyExc_MemoryErrorInst)
243		PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
244	else
245		/* this will probably fail since there's no memory and hee,
246		   hee, we have to instantiate this class
247		*/
248		PyErr_SetNone(PyExc_MemoryError);
249
250	return NULL;
251}
252
253PyObject *
254PyErr_SetFromErrnoWithFilename(PyObject *exc, char *filename)
255{
256	PyObject *v;
257	char *s;
258	int i = errno;
259#ifdef MS_WIN32
260	char *s_buf = NULL;
261#endif
262#ifdef EINTR
263	if (i == EINTR && PyErr_CheckSignals())
264		return NULL;
265#endif
266	if (i == 0)
267		s = "Error"; /* Sometimes errno didn't get set */
268	else
269#ifndef MS_WIN32
270		s = strerror(i);
271#else
272	{
273		/* Note that the Win32 errors do not lineup with the
274		   errno error.  So if the error is in the MSVC error
275		   table, we use it, otherwise we assume it really _is_
276		   a Win32 error code
277		*/
278		if (i > 0 && i < _sys_nerr) {
279			s = _sys_errlist[i];
280		}
281		else {
282			int len = FormatMessage(
283				FORMAT_MESSAGE_ALLOCATE_BUFFER |
284				FORMAT_MESSAGE_FROM_SYSTEM |
285				FORMAT_MESSAGE_IGNORE_INSERTS,
286				NULL,	/* no message source */
287				i,
288				MAKELANGID(LANG_NEUTRAL,
289					   SUBLANG_DEFAULT),
290				           /* Default language */
291				(LPTSTR) &s_buf,
292				0,	/* size not used */
293				NULL);	/* no args */
294			s = s_buf;
295			/* remove trailing cr/lf and dots */
296			while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
297				s[--len] = '\0';
298		}
299	}
300#endif
301	if (filename != NULL)
302		v = Py_BuildValue("(iss)", i, s, filename);
303	else
304		v = Py_BuildValue("(is)", i, s);
305	if (v != NULL) {
306		PyErr_SetObject(exc, v);
307		Py_DECREF(v);
308	}
309#ifdef MS_WIN32
310	LocalFree(s_buf);
311#endif
312	return NULL;
313}
314
315
316PyObject *
317PyErr_SetFromErrno(PyObject *exc)
318{
319	return PyErr_SetFromErrnoWithFilename(exc, NULL);
320}
321
322#ifdef MS_WINDOWS
323/* Windows specific error code handling */
324PyObject *PyErr_SetFromWindowsErrWithFilename(
325	int ierr,
326	const char *filename)
327{
328	int len;
329	char *s;
330	PyObject *v;
331	DWORD err = (DWORD)ierr;
332	if (err==0) err = GetLastError();
333	len = FormatMessage(
334		/* Error API error */
335		FORMAT_MESSAGE_ALLOCATE_BUFFER |
336		FORMAT_MESSAGE_FROM_SYSTEM |
337		FORMAT_MESSAGE_IGNORE_INSERTS,
338		NULL,	/* no message source */
339		err,
340		MAKELANGID(LANG_NEUTRAL,
341		SUBLANG_DEFAULT), /* Default language */
342		(LPTSTR) &s,
343		0,	/* size not used */
344		NULL);	/* no args */
345	/* remove trailing cr/lf and dots */
346	while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
347		s[--len] = '\0';
348	if (filename != NULL)
349		v = Py_BuildValue("(iss)", err, s, filename);
350	else
351		v = Py_BuildValue("(is)", err, s);
352	if (v != NULL) {
353		PyErr_SetObject(PyExc_WindowsError, v);
354		Py_DECREF(v);
355	}
356	LocalFree(s);
357	return NULL;
358}
359
360PyObject *PyErr_SetFromWindowsErr(int ierr)
361{
362	return PyErr_SetFromWindowsErrWithFilename(ierr, NULL);
363
364}
365#endif /* MS_WINDOWS */
366
367void
368PyErr_BadInternalCall(void)
369{
370	PyErr_SetString(PyExc_SystemError,
371			"bad argument to internal function");
372}
373
374
375PyObject *
376PyErr_Format(PyObject *exception, const char *format, ...)
377{
378	va_list vargs;
379	char buffer[500]; /* Caller is responsible for limiting the format */
380
381	va_start(vargs, format);
382
383	vsprintf(buffer, format, vargs);
384	PyErr_SetString(exception, buffer);
385	return NULL;
386}
387
388
389PyObject *
390PyErr_NewException(char *name, PyObject *base, PyObject *dict)
391{
392	char *dot;
393	PyObject *modulename = NULL;
394	PyObject *classname = NULL;
395	PyObject *mydict = NULL;
396	PyObject *bases = NULL;
397	PyObject *result = NULL;
398	dot = strrchr(name, '.');
399	if (dot == NULL) {
400		PyErr_SetString(PyExc_SystemError,
401			"PyErr_NewException: name must be module.class");
402		return NULL;
403	}
404	if (base == NULL)
405		base = PyExc_Exception;
406	if (!PyClass_Check(base)) {
407		/* Must be using string-based standard exceptions (-X) */
408		return PyString_FromString(name);
409	}
410	if (dict == NULL) {
411		dict = mydict = PyDict_New();
412		if (dict == NULL)
413			goto failure;
414	}
415	if (PyDict_GetItemString(dict, "__module__") == NULL) {
416		modulename = PyString_FromStringAndSize(name, (int)(dot-name));
417		if (modulename == NULL)
418			goto failure;
419		if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
420			goto failure;
421	}
422	classname = PyString_FromString(dot+1);
423	if (classname == NULL)
424		goto failure;
425	bases = Py_BuildValue("(O)", base);
426	if (bases == NULL)
427		goto failure;
428	result = PyClass_New(bases, dict, classname);
429  failure:
430	Py_XDECREF(bases);
431	Py_XDECREF(mydict);
432	Py_XDECREF(classname);
433	Py_XDECREF(modulename);
434	return result;
435}
436