blob: 89d956f9777006ec3952ed7cf969a587ca4349b1 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum373c8691997-04-29 18:22:47 +00002/* Error handling */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossum373c8691997-04-29 18:22:47 +00004#include "Python.h"
Guido van Rossumf22120a1990-12-20 23:05:40 +00005
Jack Jansen8fd2d941994-12-14 12:54:54 +00006#ifdef macintosh
Tim Petersdbd9ba62000-07-09 03:09:57 +00007extern char *PyMac_StrError(int);
Jack Jansen5ef86d51995-01-19 12:16:44 +00008#undef strerror
Guido van Rossume9fbc091995-02-18 14:52:19 +00009#define strerror PyMac_StrError
10#endif /* macintosh */
11
Guido van Rossum53e8d441995-03-09 12:11:31 +000012#ifndef __STDC__
Guido van Rossum7844e381997-04-11 20:44:04 +000013#ifndef MS_WINDOWS
Tim Petersdbd9ba62000-07-09 03:09:57 +000014extern char *strerror(int);
Guido van Rossum53e8d441995-03-09 12:11:31 +000015#endif
Guido van Rossum7844e381997-04-11 20:44:04 +000016#endif
Guido van Rossumf5401bd1990-11-02 17:50:28 +000017
Guido van Rossum743007d1999-04-21 15:27:31 +000018#ifdef MS_WIN32
19#include "windows.h"
20#include "winbase.h"
21#endif
22
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +000023#include <ctype.h>
24
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000025void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000026PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000027{
Guido van Rossum885553e1998-12-21 18:33:30 +000028 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +000029 PyObject *oldtype, *oldvalue, *oldtraceback;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000030
Guido van Rossuma027efa1997-05-05 20:56:21 +000031 if (traceback != NULL && !PyTraceBack_Check(traceback)) {
32 /* XXX Should never happen -- fatal error instead? */
33 Py_DECREF(traceback);
34 traceback = NULL;
35 }
36
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;
42
43 tstate->curexc_type = type;
44 tstate->curexc_value = value;
45 tstate->curexc_traceback = traceback;
46
47 Py_XDECREF(oldtype);
48 Py_XDECREF(oldvalue);
49 Py_XDECREF(oldtraceback);
Guido van Rossum1ae940a1995-01-02 19:04:15 +000050}
51
52void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000053PyErr_SetObject(PyObject *exception, PyObject *value)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Guido van Rossum373c8691997-04-29 18:22:47 +000055 Py_XINCREF(exception);
56 Py_XINCREF(value);
57 PyErr_Restore(exception, value, (PyObject *)NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058}
59
60void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000061PyErr_SetNone(PyObject *exception)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062{
Guido van Rossum373c8691997-04-29 18:22:47 +000063 PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000064}
65
66void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000067PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068{
Guido van Rossum373c8691997-04-29 18:22:47 +000069 PyObject *value = PyString_FromString(string);
70 PyErr_SetObject(exception, value);
71 Py_XDECREF(value);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072}
73
Guido van Rossum3a241811994-08-29 12:14:12 +000074
Guido van Rossum373c8691997-04-29 18:22:47 +000075PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000076PyErr_Occurred(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077{
Tim Peters024da352001-05-30 06:09:50 +000078 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +000079
80 return tstate->curexc_type;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000081}
82
Barry Warsawc0dc92a1997-08-22 21:22:58 +000083
84int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000085PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +000086{
Barry Warsawfa5c3152000-05-02 19:27:51 +000087 if (err == NULL || exc == NULL) {
88 /* maybe caused by "import exceptions" that failed early on */
89 return 0;
90 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +000091 if (PyTuple_Check(exc)) {
92 int 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)))
98 {
99 return 1;
100 }
101 }
102 return 0;
103 }
104 /* err might be an instance, so check its class. */
105 if (PyInstance_Check(err))
106 err = (PyObject*)((PyInstanceObject*)err)->in_class;
107
108 if (PyClass_Check(err) && PyClass_Check(exc))
109 return PyClass_IsSubclass(err, exc);
110
111 return err == exc;
112}
Guido van Rossum743007d1999-04-21 15:27:31 +0000113
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000114
115int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000116PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000117{
118 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
119}
120
121
122/* Used in many places to normalize a raised exception, including in
123 eval_code2(), do_raise(), and PyErr_Print()
124*/
125void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000126PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000127{
128 PyObject *type = *exc;
129 PyObject *value = *val;
130 PyObject *inclass = NULL;
131
Guido van Rossumed473a42000-08-07 19:18:27 +0000132 if (type == NULL) {
133 /* This is a bug. Should never happen. Don't dump core. */
134 PyErr_SetString(PyExc_SystemError,
135 "PyErr_NormalizeException() called without exception");
136 }
137
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000138 /* If PyErr_SetNone() was used, the value will have been actually
139 set to NULL.
140 */
141 if (!value) {
142 value = Py_None;
143 Py_INCREF(value);
144 }
145
146 if (PyInstance_Check(value))
147 inclass = (PyObject*)((PyInstanceObject*)value)->in_class;
148
149 /* Normalize the exception so that if the type is a class, the
150 value will be an instance.
151 */
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
156 class.
157 */
158 if (!inclass || !PyClass_IsSubclass(inclass, type)) {
159 PyObject *args, *res;
160
161 if (value == Py_None)
162 args = Py_BuildValue("()");
163 else if (PyTuple_Check(value)) {
164 Py_INCREF(value);
165 args = value;
166 }
167 else
168 args = Py_BuildValue("(O)", value);
169
170 if (args == NULL)
171 goto finally;
172 res = PyEval_CallObject(type, args);
173 Py_DECREF(args);
174 if (res == NULL)
175 goto finally;
176 Py_DECREF(value);
177 value = res;
178 }
Barry Warsaw3a749931997-09-30 15:00:18 +0000179 /* if the class of the instance doesn't exactly match the
180 class of the type, believe the instance
181 */
182 else if (inclass != type) {
183 Py_DECREF(type);
184 type = inclass;
185 Py_INCREF(type);
186 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000187 }
188 *exc = type;
189 *val = value;
190 return;
191finally:
Guido van Rossum19b55f21997-12-09 14:11:39 +0000192 Py_DECREF(type);
193 Py_DECREF(value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000194 Py_XDECREF(*tb);
195 PyErr_Fetch(exc, val, tb);
196 /* normalize recursively */
197 PyErr_NormalizeException(exc, val, tb);
198}
199
200
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000202PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204 PyThreadState *tstate = PyThreadState_Get();
205
206 *p_type = tstate->curexc_type;
207 *p_value = tstate->curexc_value;
208 *p_traceback = tstate->curexc_traceback;
209
210 tstate->curexc_type = NULL;
211 tstate->curexc_value = NULL;
212 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213}
214
215void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000216PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000217{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000218 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000220
221/* Convenience functions to set a type error exception and return 0 */
222
223int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000224PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000225{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000226 PyErr_SetString(PyExc_TypeError,
Fred Drake661ea262000-10-24 19:57:45 +0000227 "bad argument type for built-in operation");
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000228 return 0;
229}
230
Guido van Rossum373c8691997-04-29 18:22:47 +0000231PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000232PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000233{
Vladimir Marangozov0888ff12000-08-18 18:01:06 +0000234 if (PyErr_ExceptionMatches(PyExc_MemoryError))
235 /* already current */
236 return NULL;
237
Barry Warsaw2d8adff1997-08-29 21:54:35 +0000238 /* raise the pre-allocated instance if it still exists */
239 if (PyExc_MemoryErrorInst)
240 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
241 else
242 /* this will probably fail since there's no memory and hee,
243 hee, we have to instantiate this class
244 */
245 PyErr_SetNone(PyExc_MemoryError);
246
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000247 return NULL;
248}
249
Guido van Rossum373c8691997-04-29 18:22:47 +0000250PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000251PyErr_SetFromErrnoWithFilename(PyObject *exc, char *filename)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000252{
Guido van Rossum373c8691997-04-29 18:22:47 +0000253 PyObject *v;
Guido van Rossume0e59821998-10-14 20:38:13 +0000254 char *s;
Guido van Rossum3a241811994-08-29 12:14:12 +0000255 int i = errno;
Guido van Rossum795e1892000-02-17 15:19:15 +0000256#ifdef MS_WIN32
257 char *s_buf = NULL;
258#endif
Guido van Rossume9fbc091995-02-18 14:52:19 +0000259#ifdef EINTR
Guido van Rossum373c8691997-04-29 18:22:47 +0000260 if (i == EINTR && PyErr_CheckSignals())
Guido van Rossum5063bab1991-10-20 20:14:56 +0000261 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000262#endif
Guido van Rossume0e59821998-10-14 20:38:13 +0000263 if (i == 0)
264 s = "Error"; /* Sometimes errno didn't get set */
Barry Warsaw97d95151998-07-23 16:05:56 +0000265 else
Guido van Rossum743007d1999-04-21 15:27:31 +0000266#ifndef MS_WIN32
Guido van Rossume0e59821998-10-14 20:38:13 +0000267 s = strerror(i);
Guido van Rossum743007d1999-04-21 15:27:31 +0000268#else
269 {
Guido van Rossum795e1892000-02-17 15:19:15 +0000270 /* 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_
273 a Win32 error code
274 */
Guido van Rossum584b16a2000-02-21 16:50:31 +0000275 if (i > 0 && i < _sys_nerr) {
Guido van Rossum795e1892000-02-17 15:19:15 +0000276 s = _sys_errlist[i];
277 }
278 else {
279 int len = FormatMessage(
280 FORMAT_MESSAGE_ALLOCATE_BUFFER |
281 FORMAT_MESSAGE_FROM_SYSTEM |
282 FORMAT_MESSAGE_IGNORE_INSERTS,
283 NULL, /* no message source */
284 i,
285 MAKELANGID(LANG_NEUTRAL,
286 SUBLANG_DEFAULT),
287 /* Default language */
288 (LPTSTR) &s_buf,
289 0, /* size not used */
290 NULL); /* no args */
291 s = s_buf;
292 /* remove trailing cr/lf and dots */
293 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
294 s[--len] = '\0';
295 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000296 }
297#endif
Barry Warsawfa5c3152000-05-02 19:27:51 +0000298 if (filename != NULL)
Guido van Rossume0e59821998-10-14 20:38:13 +0000299 v = Py_BuildValue("(iss)", i, s, filename);
300 else
301 v = Py_BuildValue("(is)", i, s);
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000302 if (v != NULL) {
Guido van Rossum373c8691997-04-29 18:22:47 +0000303 PyErr_SetObject(exc, v);
304 Py_DECREF(v);
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000305 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000306#ifdef MS_WIN32
Guido van Rossum795e1892000-02-17 15:19:15 +0000307 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000308#endif
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000309 return NULL;
310}
Guido van Rossum743007d1999-04-21 15:27:31 +0000311
Barry Warsaw97d95151998-07-23 16:05:56 +0000312
313PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000314PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000315{
316 return PyErr_SetFromErrnoWithFilename(exc, NULL);
317}
Guido van Rossum683a0721990-10-21 22:09:12 +0000318
Guido van Rossum795e1892000-02-17 15:19:15 +0000319#ifdef MS_WINDOWS
320/* Windows specific error code handling */
321PyObject *PyErr_SetFromWindowsErrWithFilename(
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000322 int ierr,
Guido van Rossum795e1892000-02-17 15:19:15 +0000323 const char *filename)
324{
325 int len;
326 char *s;
327 PyObject *v;
328 DWORD err = (DWORD)ierr;
329 if (err==0) err = GetLastError();
330 len = FormatMessage(
331 /* Error API error */
332 FORMAT_MESSAGE_ALLOCATE_BUFFER |
333 FORMAT_MESSAGE_FROM_SYSTEM |
334 FORMAT_MESSAGE_IGNORE_INSERTS,
335 NULL, /* no message source */
336 err,
337 MAKELANGID(LANG_NEUTRAL,
338 SUBLANG_DEFAULT), /* Default language */
339 (LPTSTR) &s,
340 0, /* size not used */
341 NULL); /* no args */
342 /* remove trailing cr/lf and dots */
343 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
344 s[--len] = '\0';
Barry Warsawfa5c3152000-05-02 19:27:51 +0000345 if (filename != NULL)
Guido van Rossum795e1892000-02-17 15:19:15 +0000346 v = Py_BuildValue("(iss)", err, s, filename);
347 else
348 v = Py_BuildValue("(is)", err, s);
349 if (v != NULL) {
Guido van Rossum0b556702000-03-02 13:55:01 +0000350 PyErr_SetObject(PyExc_WindowsError, v);
Guido van Rossum795e1892000-02-17 15:19:15 +0000351 Py_DECREF(v);
352 }
353 LocalFree(s);
354 return NULL;
355}
356
357PyObject *PyErr_SetFromWindowsErr(int ierr)
358{
359 return PyErr_SetFromWindowsErrWithFilename(ierr, NULL);
Guido van Rossum795e1892000-02-17 15:19:15 +0000360}
361#endif /* MS_WINDOWS */
362
Guido van Rossum683a0721990-10-21 22:09:12 +0000363void
Fred Drake6d63adf2000-08-24 22:38:39 +0000364_PyErr_BadInternalCall(char *filename, int lineno)
365{
366 PyErr_Format(PyExc_SystemError,
367 "%s:%d: bad argument to internal function",
368 filename, lineno);
369}
370
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
374void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000375PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000376{
Fred Drake6d63adf2000-08-24 22:38:39 +0000377 PyErr_Format(PyExc_SystemError,
378 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000379}
Fred Drake6d63adf2000-08-24 22:38:39 +0000380#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
381
Guido van Rossum1548bac1997-02-14 17:09:47 +0000382
383
Guido van Rossum1548bac1997-02-14 17:09:47 +0000384PyObject *
385PyErr_Format(PyObject *exception, const char *format, ...)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000386{
387 va_list vargs;
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000388 int n, i;
389 const char* f;
390 char* s;
391 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000392
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000393 /* step 1: figure out how large a buffer we need */
394
395#ifdef HAVE_STDARG_PROTOTYPES
Guido van Rossum1548bac1997-02-14 17:09:47 +0000396 va_start(vargs, format);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000397#else
398 va_start(vargs);
399#endif
Guido van Rossum1548bac1997-02-14 17:09:47 +0000400
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000401 n = 0;
402 for (f = format; *f; f++) {
403 if (*f == '%') {
404 const char* p = f;
Martin v. Löwis2b6727b2001-03-06 12:12:02 +0000405 while (*++f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000406 ;
407 switch (*f) {
408 case 'c':
Fred Drakee693df92000-10-10 21:10:35 +0000409 (void) va_arg(vargs, int);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000410 /* fall through... */
411 case '%':
412 n++;
413 break;
414 case 'd': case 'i': case 'x':
Fred Drakee693df92000-10-10 21:10:35 +0000415 (void) va_arg(vargs, int);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000416 /* 20 bytes should be enough to hold a 64-bit
417 integer */
418 n = n + 20;
419 break;
420 case 's':
421 s = va_arg(vargs, char*);
422 n = n + strlen(s);
423 break;
424 default:
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) */
431 n = n + strlen(p);
432 goto expand;
433 }
434 } else
435 n = n + 1;
436 }
437
438 expand:
439
440 string = PyString_FromStringAndSize(NULL, n);
441 if (!string)
442 return NULL;
443
444#ifdef HAVE_STDARG_PROTOTYPES
445 va_start(vargs, format);
446#else
447 va_start(vargs);
448#endif
449
450 /* step 2: fill the buffer */
451
452 s = PyString_AsString(string);
453
454 for (f = format; *f; f++) {
455 if (*f == '%') {
456 const char* p = f++;
457 /* parse the width.precision part (we're only
458 interested in the precision value, if any) */
459 n = 0;
Martin v. Löwis2b6727b2001-03-06 12:12:02 +0000460 while (isdigit(Py_CHARMASK(*f)))
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000461 n = (n*10) + *f++ - '0';
462 if (*f == '.') {
463 f++;
464 n = 0;
Martin v. Löwis2b6727b2001-03-06 12:12:02 +0000465 while (isdigit(Py_CHARMASK(*f)))
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000466 n = (n*10) + *f++ - '0';
467 }
Martin v. Löwis2b6727b2001-03-06 12:12:02 +0000468 while (*f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000469 f++;
470 switch (*f) {
471 case 'c':
472 *s++ = va_arg(vargs, int);
473 break;
474 case 'd':
475 sprintf(s, "%d", va_arg(vargs, int));
476 s = s + strlen(s);
477 break;
478 case 'i':
479 sprintf(s, "%i", va_arg(vargs, int));
480 s = s + strlen(s);
481 break;
482 case 'x':
483 sprintf(s, "%x", va_arg(vargs, int));
484 s = s + strlen(s);
485 break;
486 case 's':
487 p = va_arg(vargs, char*);
488 i = strlen(p);
489 if (n > 0 && i > n)
490 i = n;
491 memcpy(s, p, i);
492 s = s + i;
493 break;
494 case '%':
495 *s++ = '%';
496 break;
497 default:
498 strcpy(s, p);
499 s = s + strlen(s);
500 goto end;
501 }
502 } else
503 *s++ = *f;
504 }
505
506 end:
507
508 _PyString_Resize(&string, s - PyString_AsString(string));
509
510 PyErr_SetObject(exception, string);
511 Py_XDECREF(string);
512
Guido van Rossum1548bac1997-02-14 17:09:47 +0000513 return NULL;
514}
Guido van Rossum7617e051997-09-16 18:43:50 +0000515
516
517PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000518PyErr_NewException(char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000519{
Guido van Rossum2ac650f1997-10-03 19:50:55 +0000520 char *dot;
521 PyObject *modulename = NULL;
522 PyObject *classname = NULL;
523 PyObject *mydict = NULL;
524 PyObject *bases = NULL;
Guido van Rossum7617e051997-09-16 18:43:50 +0000525 PyObject *result = NULL;
Guido van Rossum2ac650f1997-10-03 19:50:55 +0000526 dot = strrchr(name, '.');
527 if (dot == NULL) {
528 PyErr_SetString(PyExc_SystemError,
529 "PyErr_NewException: name must be module.class");
Guido van Rossum7617e051997-09-16 18:43:50 +0000530 return NULL;
Guido van Rossum7617e051997-09-16 18:43:50 +0000531 }
532 if (base == NULL)
533 base = PyExc_Exception;
Guido van Rossum2ac650f1997-10-03 19:50:55 +0000534 if (!PyClass_Check(base)) {
535 /* Must be using string-based standard exceptions (-X) */
536 return PyString_FromString(name);
537 }
538 if (dict == NULL) {
539 dict = mydict = PyDict_New();
540 if (dict == NULL)
541 goto failure;
542 }
543 if (PyDict_GetItemString(dict, "__module__") == NULL) {
544 modulename = PyString_FromStringAndSize(name, (int)(dot-name));
545 if (modulename == NULL)
546 goto failure;
547 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
548 goto failure;
549 }
550 classname = PyString_FromString(dot+1);
551 if (classname == NULL)
Guido van Rossum7617e051997-09-16 18:43:50 +0000552 goto failure;
Guido van Rossum2ac650f1997-10-03 19:50:55 +0000553 bases = Py_BuildValue("(O)", base);
554 if (bases == NULL)
555 goto failure;
556 result = PyClass_New(bases, dict, classname);
Guido van Rossum7617e051997-09-16 18:43:50 +0000557 failure:
Guido van Rossum2ac650f1997-10-03 19:50:55 +0000558 Py_XDECREF(bases);
559 Py_XDECREF(mydict);
560 Py_XDECREF(classname);
561 Py_XDECREF(modulename);
Guido van Rossum7617e051997-09-16 18:43:50 +0000562 return result;
563}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000564
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. */
567void
568PyErr_WriteUnraisable(PyObject *obj)
569{
570 PyObject *f, *t, *v, *tb;
571 PyErr_Fetch(&t, &v, &tb);
572 f = PySys_GetObject("stderr");
573 if (f != NULL) {
574 PyFile_WriteString("Exception ", f);
575 if (t) {
576 PyFile_WriteObject(t, f, Py_PRINT_RAW);
577 if (v && v != Py_None) {
578 PyFile_WriteString(": ", f);
579 PyFile_WriteObject(v, f, 0);
580 }
581 }
582 PyFile_WriteString(" in ", f);
583 PyFile_WriteObject(obj, f, 0);
584 PyFile_WriteString(" ignored\n", f);
585 PyErr_Clear(); /* Just in case */
586 }
587 Py_XDECREF(t);
588 Py_XDECREF(v);
589 Py_XDECREF(tb);
590}
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000591
592
593/* Function to issue a warning message; may raise an exception. */
594int
595PyErr_Warn(PyObject *category, char *message)
596{
597 PyObject *mod, *dict, *func = NULL;
598
599 mod = PyImport_ImportModule("warnings");
600 if (mod != NULL) {
601 dict = PyModule_GetDict(mod);
602 func = PyDict_GetItemString(dict, "warn");
603 Py_DECREF(mod);
604 }
605 if (func == NULL) {
606 PySys_WriteStderr("warning: %s\n", message);
607 return 0;
608 }
609 else {
610 PyObject *args, *res;
611
612 if (category == NULL)
613 category = PyExc_RuntimeWarning;
614 args = Py_BuildValue("(sO)", message, category);
615 if (args == NULL)
616 return -1;
617 res = PyEval_CallObject(func, args);
618 Py_DECREF(args);
619 if (res == NULL)
620 return -1;
621 Py_DECREF(res);
622 return 0;
623 }
624}
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000625
Guido van Rossum2fd45652001-02-28 21:46:24 +0000626
627/* Warning with explicit origin */
628int
629PyErr_WarnExplicit(PyObject *category, char *message,
630 char *filename, int lineno,
631 char *module, PyObject *registry)
632{
633 PyObject *mod, *dict, *func = NULL;
634
635 mod = PyImport_ImportModule("warnings");
636 if (mod != NULL) {
637 dict = PyModule_GetDict(mod);
638 func = PyDict_GetItemString(dict, "warn_explicit");
639 Py_DECREF(mod);
640 }
641 if (func == NULL) {
642 PySys_WriteStderr("warning: %s\n", message);
643 return 0;
644 }
645 else {
646 PyObject *args, *res;
647
648 if (category == NULL)
649 category = PyExc_RuntimeWarning;
650 if (registry == NULL)
651 registry = Py_None;
652 args = Py_BuildValue("(sOsizO)", message, category,
653 filename, lineno, module, registry);
654 if (args == NULL)
655 return -1;
656 res = PyEval_CallObject(func, args);
657 Py_DECREF(args);
658 if (res == NULL)
659 return -1;
660 Py_DECREF(res);
661 return 0;
662 }
663}
664
665
666/* XXX There's a comment missing here */
667
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000668void
669PyErr_SyntaxLocation(char *filename, int lineno)
670{
671 PyObject *exc, *v, *tb, *tmp;
672
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);
678 if (tmp == NULL)
679 PyErr_Clear();
680 else {
681 if (PyObject_SetAttrString(v, "lineno", tmp))
682 PyErr_Clear();
683 Py_DECREF(tmp);
684 }
685 if (filename != NULL) {
686 tmp = PyString_FromString(filename);
687 if (tmp == NULL)
688 PyErr_Clear();
689 else {
690 if (PyObject_SetAttrString(v, "filename", tmp))
691 PyErr_Clear();
692 Py_DECREF(tmp);
693 }
694
695 tmp = PyErr_ProgramText(filename, lineno);
696 if (tmp) {
697 PyObject_SetAttrString(v, "text", tmp);
698 Py_DECREF(tmp);
699 }
700 }
701 PyErr_Restore(exc, v, tb);
702}
703
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.
707
708 XXX The functionality of this function is quite similar to the
709 functionality in tb_displayline() in traceback.c.
710*/
711
712PyObject *
713PyErr_ProgramText(char *filename, int lineno)
714{
715 FILE *fp;
716 int i;
717 char linebuf[1000];
718
719 if (filename == NULL || lineno <= 0)
720 return NULL;
721 fp = fopen(filename, "r");
722 if (fp == NULL)
723 return NULL;
724 for (i = 0; i < lineno; i++) {
725 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
726 do {
727 *pLastChar = '\0';
728 if (fgets(linebuf, sizeof linebuf, fp) == NULL)
729 break;
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');
736 }
737 fclose(fp);
738 if (i == lineno) {
739 char *p = linebuf;
740 while (*p == ' ' || *p == '\t' || *p == '\014')
741 p++;
742 return PyString_FromString(p);
743 }
744 return NULL;
745}