blob: 00dfd3ec540ebabe7c3ecde41a558bdc4fce6130 [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
Guido van Rossum53e8d441995-03-09 12:11:31 +00006#ifndef __STDC__
Guido van Rossum7844e381997-04-11 20:44:04 +00007#ifndef MS_WINDOWS
Tim Petersdbd9ba62000-07-09 03:09:57 +00008extern char *strerror(int);
Guido van Rossum53e8d441995-03-09 12:11:31 +00009#endif
Guido van Rossum7844e381997-04-11 20:44:04 +000010#endif
Guido van Rossumf5401bd1990-11-02 17:50:28 +000011
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000012#ifdef MS_WINDOWS
Guido van Rossum743007d1999-04-21 15:27:31 +000013#include "windows.h"
14#include "winbase.h"
15#endif
16
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +000017#include <ctype.h>
18
Anthony Baxterac6bd462006-04-13 02:06:09 +000019#ifdef __cplusplus
20extern "C" {
21#endif
22
23
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000024void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000025PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000026{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000027 PyThreadState *tstate = PyThreadState_GET();
28 PyObject *oldtype, *oldvalue, *oldtraceback;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000029
Antoine Pitrouc83ea132010-05-09 14:46:46 +000030 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;
35 }
Guido van Rossuma027efa1997-05-05 20:56:21 +000036
Antoine Pitrouc83ea132010-05-09 14:46:46 +000037 /* 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;
Guido van Rossuma027efa1997-05-05 20:56:21 +000042
Antoine Pitrouc83ea132010-05-09 14:46:46 +000043 tstate->curexc_type = type;
44 tstate->curexc_value = value;
45 tstate->curexc_traceback = traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +000046
Antoine Pitrouc83ea132010-05-09 14:46:46 +000047 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000078 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +000079
Antoine Pitrouc83ea132010-05-09 14:46:46 +000080 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000087 if (err == NULL || exc == NULL) {
88 /* maybe caused by "import exceptions" that failed early on */
89 return 0;
90 }
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)))
98 {
99 return 1;
100 }
101 }
102 return 0;
103 }
104 /* err might be an instance, so check its class. */
105 if (PyExceptionInstance_Check(err))
106 err = PyExceptionInstance_Class(err);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000107
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000108 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
109 int res = 0, reclimit;
110 PyObject *exception, *value, *tb;
111 PyErr_Fetch(&exception, &value, &tb);
112 /* Temporarily bump the recursion limit, so that in the most
113 common case PyObject_IsSubclass will not raise a recursion
Amaury Forgeot d'Arc4bf21e22011-12-07 21:46:48 +0100114 error we have to ignore anyway. Don't do it when the limit
115 is already insanely high, to avoid overflow */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000116 reclimit = Py_GetRecursionLimit();
Amaury Forgeot d'Arc4bf21e22011-12-07 21:46:48 +0100117 if (reclimit < (1 << 30))
118 Py_SetRecursionLimit(reclimit + 5);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000119 res = PyObject_IsSubclass(err, exc);
120 Py_SetRecursionLimit(reclimit);
121 /* This function must not fail, so print the error here */
122 if (res == -1) {
123 PyErr_WriteUnraisable(err);
124 res = 0;
125 }
126 PyErr_Restore(exception, value, tb);
127 return res;
128 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000129
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000130 return err == exc;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000131}
Guido van Rossum743007d1999-04-21 15:27:31 +0000132
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000133
134int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000135PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000136{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000137 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000138}
139
140
141/* Used in many places to normalize a raised exception, including in
142 eval_code2(), do_raise(), and PyErr_Print()
143*/
144void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000145PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000146{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000147 PyObject *type = *exc;
148 PyObject *value = *val;
149 PyObject *inclass = NULL;
150 PyObject *initial_tb = NULL;
151 PyThreadState *tstate = NULL;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000152
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000153 if (type == NULL) {
154 /* There was no exception, so nothing to do. */
155 return;
156 }
Guido van Rossumed473a42000-08-07 19:18:27 +0000157
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000158 /* If PyErr_SetNone() was used, the value will have been actually
159 set to NULL.
160 */
161 if (!value) {
162 value = Py_None;
163 Py_INCREF(value);
164 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000165
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000166 if (PyExceptionInstance_Check(value))
167 inclass = PyExceptionInstance_Class(value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000168
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000169 /* Normalize the exception so that if the type is a class, the
170 value will be an instance.
171 */
172 if (PyExceptionClass_Check(type)) {
173 /* if the value was not an instance, or is not an instance
174 whose class is (or is derived from) type, then use the
175 value as an argument to instantiation of the type
176 class.
177 */
178 if (!inclass || !PyObject_IsSubclass(inclass, type)) {
179 PyObject *args, *res;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000180
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000181 if (value == Py_None)
182 args = PyTuple_New(0);
183 else if (PyTuple_Check(value)) {
184 Py_INCREF(value);
185 args = value;
186 }
187 else
188 args = PyTuple_Pack(1, value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000189
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000190 if (args == NULL)
191 goto finally;
192 res = PyEval_CallObject(type, args);
193 Py_DECREF(args);
194 if (res == NULL)
195 goto finally;
196 Py_DECREF(value);
197 value = res;
198 }
199 /* if the class of the instance doesn't exactly match the
200 class of the type, believe the instance
201 */
202 else if (inclass != type) {
203 Py_DECREF(type);
204 type = inclass;
205 Py_INCREF(type);
206 }
207 }
208 *exc = type;
209 *val = value;
210 return;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000211finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000212 Py_DECREF(type);
213 Py_DECREF(value);
214 /* If the new exception doesn't set a traceback and the old
215 exception had a traceback, use the old traceback for the
216 new exception. It's better than nothing.
217 */
218 initial_tb = *tb;
219 PyErr_Fetch(exc, val, tb);
220 if (initial_tb != NULL) {
221 if (*tb == NULL)
222 *tb = initial_tb;
223 else
224 Py_DECREF(initial_tb);
225 }
226 /* normalize recursively */
227 tstate = PyThreadState_GET();
228 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
229 --tstate->recursion_depth;
230 /* throw away the old exception... */
231 Py_DECREF(*exc);
232 Py_DECREF(*val);
233 /* ... and use the recursion error instead */
234 *exc = PyExc_RuntimeError;
235 *val = PyExc_RecursionErrorInst;
236 Py_INCREF(*exc);
237 Py_INCREF(*val);
238 /* just keeping the old traceback */
239 return;
240 }
241 PyErr_NormalizeException(exc, val, tb);
242 --tstate->recursion_depth;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000243}
244
245
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000247PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000249 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000250
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000251 *p_type = tstate->curexc_type;
252 *p_value = tstate->curexc_value;
253 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000254
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000255 tstate->curexc_type = NULL;
256 tstate->curexc_value = NULL;
257 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000258}
259
260void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000261PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000263 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000264}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000265
Serhiy Storchakaaa64c462015-03-30 09:48:42 +0300266/* Restore previously fetched exception if an exception is not set,
267 otherwise drop previously fetched exception.
268 Like _PyErr_ChainExceptions() in Python 3, but doesn't set the context.
269 */
270void
271_PyErr_ReplaceException(PyObject *exc, PyObject *val, PyObject *tb)
272{
273 if (exc == NULL)
274 return;
275
276 if (PyErr_Occurred()) {
277 Py_DECREF(exc);
278 Py_XDECREF(val);
279 Py_XDECREF(tb);
280 }
281 else {
282 PyErr_Restore(exc, val, tb);
283 }
284}
285
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000286/* Convenience functions to set a type error exception and return 0 */
287
288int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000289PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000290{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000291 PyErr_SetString(PyExc_TypeError,
292 "bad argument type for built-in operation");
293 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000294}
295
Guido van Rossum373c8691997-04-29 18:22:47 +0000296PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000297PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000298{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000299 if (PyErr_ExceptionMatches(PyExc_MemoryError))
300 /* already current */
301 return NULL;
Vladimir Marangozov0888ff12000-08-18 18:01:06 +0000302
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303 /* raise the pre-allocated instance if it still exists */
304 if (PyExc_MemoryErrorInst)
305 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
306 else
307 /* this will probably fail since there's no memory and hee,
308 hee, we have to instantiate this class
309 */
310 PyErr_SetNone(PyExc_MemoryError);
Barry Warsaw2d8adff1997-08-29 21:54:35 +0000311
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000312 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000313}
314
Guido van Rossum373c8691997-04-29 18:22:47 +0000315PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000316PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000317{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000318 PyObject *v;
319 char *s;
320 int i = errno;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000321#ifdef PLAN9
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000322 char errbuf[ERRMAX];
Martin v. Löwis3484a182002-03-09 12:07:51 +0000323#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000324#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000325 char *s_buf = NULL;
326 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
Guido van Rossum795e1892000-02-17 15:19:15 +0000327#endif
Guido van Rossume9fbc091995-02-18 14:52:19 +0000328#ifdef EINTR
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000329 if (i == EINTR && PyErr_CheckSignals())
330 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000331#endif
Martin v. Löwis3484a182002-03-09 12:07:51 +0000332#ifdef PLAN9
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000333 rerrstr(errbuf, sizeof errbuf);
334 s = errbuf;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000335#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000336 if (i == 0)
337 s = "Error"; /* Sometimes errno didn't get set */
338 else
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000339#ifndef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000340 s = strerror(i);
Guido van Rossum743007d1999-04-21 15:27:31 +0000341#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000342 {
343 /* Note that the Win32 errors do not lineup with the
344 errno error. So if the error is in the MSVC error
345 table, we use it, otherwise we assume it really _is_
346 a Win32 error code
347 */
348 if (i > 0 && i < _sys_nerr) {
349 s = _sys_errlist[i];
350 }
351 else {
352 int len = FormatMessage(
353 FORMAT_MESSAGE_ALLOCATE_BUFFER |
354 FORMAT_MESSAGE_FROM_SYSTEM |
355 FORMAT_MESSAGE_IGNORE_INSERTS,
356 NULL, /* no message source */
357 i,
358 MAKELANGID(LANG_NEUTRAL,
359 SUBLANG_DEFAULT),
360 /* Default language */
361 (LPTSTR) &s_buf,
362 0, /* size not used */
363 NULL); /* no args */
364 if (len==0) {
365 /* Only ever seen this in out-of-mem
366 situations */
367 sprintf(s_small_buf, "Windows Error 0x%X", i);
368 s = s_small_buf;
369 s_buf = NULL;
370 } else {
371 s = s_buf;
372 /* remove trailing cr/lf and dots */
373 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
374 s[--len] = '\0';
375 }
376 }
377 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000378#endif /* Unix/Windows */
379#endif /* PLAN 9*/
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000380 if (filenameObject != NULL)
381 v = Py_BuildValue("(isO)", i, s, filenameObject);
382 else
383 v = Py_BuildValue("(is)", i, s);
384 if (v != NULL) {
385 PyErr_SetObject(exc, v);
386 Py_DECREF(v);
387 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000388#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000389 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000390#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000391 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000392}
Guido van Rossum743007d1999-04-21 15:27:31 +0000393
Barry Warsaw97d95151998-07-23 16:05:56 +0000394
395PyObject *
Alexandre Vassalottia6e34742009-06-12 20:57:12 +0000396PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000397{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000398 PyObject *name = filename ? PyString_FromString(filename) : NULL;
399 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
400 Py_XDECREF(name);
401 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000402}
403
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000404#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000405PyObject *
Alexandre Vassalottia6e34742009-06-12 20:57:12 +0000406PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000407{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000408 PyObject *name = filename ?
409 PyUnicode_FromUnicode(filename, wcslen(filename)) :
410 NULL;
411 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
412 Py_XDECREF(name);
413 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000414}
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000415#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000416
417PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000418PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000419{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000420 return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000421}
Guido van Rossum683a0721990-10-21 22:09:12 +0000422
Brett Cannonbf364092006-03-01 04:25:17 +0000423#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000424/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000425PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000426 PyObject *exc,
427 int ierr,
428 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000429{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000430 int len;
431 char *s;
432 char *s_buf = NULL; /* Free via LocalFree */
433 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
434 PyObject *v;
435 DWORD err = (DWORD)ierr;
436 if (err==0) err = GetLastError();
437 len = FormatMessage(
438 /* Error API error */
439 FORMAT_MESSAGE_ALLOCATE_BUFFER |
440 FORMAT_MESSAGE_FROM_SYSTEM |
441 FORMAT_MESSAGE_IGNORE_INSERTS,
442 NULL, /* no message source */
443 err,
444 MAKELANGID(LANG_NEUTRAL,
445 SUBLANG_DEFAULT), /* Default language */
446 (LPTSTR) &s_buf,
447 0, /* size not used */
448 NULL); /* no args */
449 if (len==0) {
450 /* Only seen this in out of mem situations */
451 sprintf(s_small_buf, "Windows Error 0x%X", err);
452 s = s_small_buf;
453 s_buf = NULL;
454 } else {
455 s = s_buf;
456 /* remove trailing cr/lf and dots */
457 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
458 s[--len] = '\0';
459 }
460 if (filenameObject != NULL)
461 v = Py_BuildValue("(isO)", err, s, filenameObject);
462 else
463 v = Py_BuildValue("(is)", err, s);
464 if (v != NULL) {
465 PyErr_SetObject(exc, v);
466 Py_DECREF(v);
467 }
468 LocalFree(s_buf);
469 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000470}
471
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000472PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000473 PyObject *exc,
474 int ierr,
475 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000476{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000477 PyObject *name = filename ? PyString_FromString(filename) : NULL;
478 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
479 ierr,
480 name);
481 Py_XDECREF(name);
482 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000483}
484
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000485PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 PyObject *exc,
487 int ierr,
488 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000489{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000490 PyObject *name = filename ?
491 PyUnicode_FromUnicode(filename, wcslen(filename)) :
492 NULL;
493 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
494 ierr,
495 name);
496 Py_XDECREF(name);
497 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000498}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000499
Thomas Heller085358a2002-07-29 14:27:41 +0000500PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
501{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000502 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000503}
504
Guido van Rossum795e1892000-02-17 15:19:15 +0000505PyObject *PyErr_SetFromWindowsErr(int ierr)
506{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000507 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
508 ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000509}
510PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000511 int ierr,
512 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000513{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000514 PyObject *name = filename ? PyString_FromString(filename) : NULL;
515 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
516 PyExc_WindowsError,
517 ierr, name);
518 Py_XDECREF(name);
519 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000520}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000521
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000522PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000523 int ierr,
524 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000525{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000526 PyObject *name = filename ?
527 PyUnicode_FromUnicode(filename, wcslen(filename)) :
528 NULL;
529 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
530 PyExc_WindowsError,
531 ierr, name);
532 Py_XDECREF(name);
533 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000534}
Guido van Rossum795e1892000-02-17 15:19:15 +0000535#endif /* MS_WINDOWS */
536
Guido van Rossum683a0721990-10-21 22:09:12 +0000537void
Fred Drake6d63adf2000-08-24 22:38:39 +0000538_PyErr_BadInternalCall(char *filename, int lineno)
539{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000540 PyErr_Format(PyExc_SystemError,
541 "%s:%d: bad argument to internal function",
542 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000543}
544
545/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
546 export the entry point for existing object code: */
547#undef PyErr_BadInternalCall
548void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000549PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000550{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000551 PyErr_Format(PyExc_SystemError,
552 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000553}
Fred Drake6d63adf2000-08-24 22:38:39 +0000554#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
555
Guido van Rossum1548bac1997-02-14 17:09:47 +0000556
557
Guido van Rossum1548bac1997-02-14 17:09:47 +0000558PyObject *
559PyErr_Format(PyObject *exception, const char *format, ...)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000560{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000561 va_list vargs;
562 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000563
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000564#ifdef HAVE_STDARG_PROTOTYPES
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000565 va_start(vargs, format);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000566#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000567 va_start(vargs);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000568#endif
Guido van Rossum1548bac1997-02-14 17:09:47 +0000569
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000570 string = PyString_FromFormatV(format, vargs);
571 PyErr_SetObject(exception, string);
572 Py_XDECREF(string);
573 va_end(vargs);
574 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000575}
Guido van Rossum7617e051997-09-16 18:43:50 +0000576
577
Georg Brandl658d5132006-05-23 11:17:21 +0000578
Guido van Rossum7617e051997-09-16 18:43:50 +0000579PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000580PyErr_NewException(char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000581{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000582 char *dot;
583 PyObject *modulename = NULL;
584 PyObject *classname = NULL;
585 PyObject *mydict = NULL;
586 PyObject *bases = NULL;
587 PyObject *result = NULL;
588 dot = strrchr(name, '.');
589 if (dot == NULL) {
590 PyErr_SetString(PyExc_SystemError,
591 "PyErr_NewException: name must be module.class");
592 return NULL;
593 }
594 if (base == NULL)
595 base = PyExc_Exception;
596 if (dict == NULL) {
597 dict = mydict = PyDict_New();
598 if (dict == NULL)
599 goto failure;
600 }
601 if (PyDict_GetItemString(dict, "__module__") == NULL) {
602 modulename = PyString_FromStringAndSize(name,
603 (Py_ssize_t)(dot-name));
604 if (modulename == NULL)
605 goto failure;
606 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
607 goto failure;
608 }
609 if (PyTuple_Check(base)) {
610 bases = base;
611 /* INCREF as we create a new ref in the else branch */
612 Py_INCREF(bases);
613 } else {
614 bases = PyTuple_Pack(1, base);
615 if (bases == NULL)
616 goto failure;
617 }
618 /* Create a real new-style class. */
619 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
620 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000621 failure:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000622 Py_XDECREF(bases);
623 Py_XDECREF(mydict);
624 Py_XDECREF(classname);
625 Py_XDECREF(modulename);
626 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000627}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000628
Georg Brandl740cdc32009-12-28 08:34:58 +0000629
630/* Create an exception with docstring */
631PyObject *
632PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict)
633{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000634 int result;
635 PyObject *ret = NULL;
636 PyObject *mydict = NULL; /* points to the dict only if we create it */
637 PyObject *docobj;
Georg Brandl740cdc32009-12-28 08:34:58 +0000638
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000639 if (dict == NULL) {
640 dict = mydict = PyDict_New();
641 if (dict == NULL) {
642 return NULL;
643 }
644 }
Georg Brandl740cdc32009-12-28 08:34:58 +0000645
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000646 if (doc != NULL) {
647 docobj = PyString_FromString(doc);
648 if (docobj == NULL)
649 goto failure;
650 result = PyDict_SetItemString(dict, "__doc__", docobj);
651 Py_DECREF(docobj);
652 if (result < 0)
653 goto failure;
654 }
Georg Brandl740cdc32009-12-28 08:34:58 +0000655
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000656 ret = PyErr_NewException(name, base, dict);
Georg Brandl740cdc32009-12-28 08:34:58 +0000657 failure:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000658 Py_XDECREF(mydict);
659 return ret;
Georg Brandl740cdc32009-12-28 08:34:58 +0000660}
661
662
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000663/* Call when an exception has occurred but there is no way for Python
664 to handle it. Examples: exception in __del__ or during GC. */
665void
666PyErr_WriteUnraisable(PyObject *obj)
667{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000668 PyObject *f, *t, *v, *tb;
669 PyErr_Fetch(&t, &v, &tb);
670 f = PySys_GetObject("stderr");
671 if (f != NULL) {
672 PyFile_WriteString("Exception ", f);
673 if (t) {
674 PyObject* moduleName;
675 char* className;
676 assert(PyExceptionClass_Check(t));
677 className = PyExceptionClass_Name(t);
678 if (className != NULL) {
679 char *dot = strrchr(className, '.');
680 if (dot != NULL)
681 className = dot+1;
682 }
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000683
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000684 moduleName = PyObject_GetAttrString(t, "__module__");
685 if (moduleName == NULL)
686 PyFile_WriteString("<unknown>", f);
687 else {
688 char* modstr = PyString_AsString(moduleName);
689 if (modstr &&
690 strcmp(modstr, "exceptions") != 0)
691 {
692 PyFile_WriteString(modstr, f);
693 PyFile_WriteString(".", f);
694 }
695 }
696 if (className == NULL)
697 PyFile_WriteString("<unknown>", f);
698 else
699 PyFile_WriteString(className, f);
700 if (v && v != Py_None) {
701 PyFile_WriteString(": ", f);
702 PyFile_WriteObject(v, f, 0);
703 }
704 Py_XDECREF(moduleName);
705 }
706 PyFile_WriteString(" in ", f);
707 PyFile_WriteObject(obj, f, 0);
708 PyFile_WriteString(" ignored\n", f);
709 PyErr_Clear(); /* Just in case */
710 }
711 Py_XDECREF(t);
712 Py_XDECREF(v);
713 Py_XDECREF(tb);
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000714}
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000715
Armin Rigo092381a2003-10-25 14:29:27 +0000716extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000717
Guido van Rossum2fd45652001-02-28 21:46:24 +0000718
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000719/* Set file and line information for the current exception.
720 If the exception is not a SyntaxError, also sets additional attributes
721 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +0000722
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000723void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000724PyErr_SyntaxLocation(const char *filename, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000725{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000726 PyObject *exc, *v, *tb, *tmp;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000727
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000728 /* add attributes for the line number and filename for the error */
729 PyErr_Fetch(&exc, &v, &tb);
730 PyErr_NormalizeException(&exc, &v, &tb);
731 /* XXX check that it is, indeed, a syntax error. It might not
732 * be, though. */
733 tmp = PyInt_FromLong(lineno);
734 if (tmp == NULL)
735 PyErr_Clear();
736 else {
737 if (PyObject_SetAttrString(v, "lineno", tmp))
738 PyErr_Clear();
739 Py_DECREF(tmp);
740 }
741 if (filename != NULL) {
742 tmp = PyString_FromString(filename);
743 if (tmp == NULL)
744 PyErr_Clear();
745 else {
746 if (PyObject_SetAttrString(v, "filename", tmp))
747 PyErr_Clear();
748 Py_DECREF(tmp);
749 }
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000750
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751 tmp = PyErr_ProgramText(filename, lineno);
752 if (tmp) {
753 if (PyObject_SetAttrString(v, "text", tmp))
754 PyErr_Clear();
755 Py_DECREF(tmp);
756 }
757 }
758 if (PyObject_SetAttrString(v, "offset", Py_None)) {
759 PyErr_Clear();
760 }
761 if (exc != PyExc_SyntaxError) {
762 if (!PyObject_HasAttrString(v, "msg")) {
763 tmp = PyObject_Str(v);
764 if (tmp) {
765 if (PyObject_SetAttrString(v, "msg", tmp))
766 PyErr_Clear();
767 Py_DECREF(tmp);
768 } else {
769 PyErr_Clear();
770 }
771 }
772 if (!PyObject_HasAttrString(v, "print_file_and_line")) {
773 if (PyObject_SetAttrString(v, "print_file_and_line",
774 Py_None))
775 PyErr_Clear();
776 }
777 }
778 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000779}
780
781/* com_fetch_program_text will attempt to load the line of text that
782 the exception refers to. If it fails, it will return NULL but will
Brett Cannonbf364092006-03-01 04:25:17 +0000783 not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000784
785 XXX The functionality of this function is quite similar to the
786 functionality in tb_displayline() in traceback.c.
787*/
788
789PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +0000790PyErr_ProgramText(const char *filename, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000791{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000792 FILE *fp;
793 int i;
794 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000795
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000796 if (filename == NULL || *filename == '\0' || lineno <= 0)
797 return NULL;
798 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
799 if (fp == NULL)
800 return NULL;
801 for (i = 0; i < lineno; i++) {
802 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
803 do {
804 *pLastChar = '\0';
805 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
806 break;
807 /* fgets read *something*; if it didn't get as
808 far as pLastChar, it must have found a newline
809 or hit the end of the file; if pLastChar is \n,
810 it obviously found a newline; else we haven't
811 yet seen a newline, so must continue */
812 } while (*pLastChar != '\0' && *pLastChar != '\n');
813 }
814 fclose(fp);
815 if (i == lineno) {
816 char *p = linebuf;
817 while (*p == ' ' || *p == '\t' || *p == '\014')
818 p++;
819 return PyString_FromString(p);
820 }
821 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000822}
Anthony Baxterac6bd462006-04-13 02:06:09 +0000823
824#ifdef __cplusplus
825}
826#endif
827