blob: 5cbf5c969809cd14a696dc13bfa7ba1a78aae70a [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;
Serhiy Storchaka2e6c8292015-12-27 15:41:58 +0200230 /* throw away the old exception and use the recursion error instead */
231 Py_INCREF(PyExc_RuntimeError);
232 Py_SETREF(*exc, PyExc_RuntimeError);
233 Py_INCREF(PyExc_RecursionErrorInst);
234 Py_SETREF(*val, PyExc_RecursionErrorInst);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000235 /* just keeping the old traceback */
236 return;
237 }
238 PyErr_NormalizeException(exc, val, tb);
239 --tstate->recursion_depth;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000240}
241
242
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000244PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000246 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000247
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 *p_type = tstate->curexc_type;
249 *p_value = tstate->curexc_value;
250 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000251
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000252 tstate->curexc_type = NULL;
253 tstate->curexc_value = NULL;
254 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255}
256
257void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000258PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000259{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000260 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000261}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000262
Serhiy Storchakaaa64c462015-03-30 09:48:42 +0300263/* Restore previously fetched exception if an exception is not set,
264 otherwise drop previously fetched exception.
265 Like _PyErr_ChainExceptions() in Python 3, but doesn't set the context.
266 */
267void
268_PyErr_ReplaceException(PyObject *exc, PyObject *val, PyObject *tb)
269{
270 if (exc == NULL)
271 return;
272
273 if (PyErr_Occurred()) {
274 Py_DECREF(exc);
275 Py_XDECREF(val);
276 Py_XDECREF(tb);
277 }
278 else {
279 PyErr_Restore(exc, val, tb);
280 }
281}
282
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000283/* Convenience functions to set a type error exception and return 0 */
284
285int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000286PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000287{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000288 PyErr_SetString(PyExc_TypeError,
289 "bad argument type for built-in operation");
290 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000291}
292
Guido van Rossum373c8691997-04-29 18:22:47 +0000293PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000294PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000295{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000296 if (PyErr_ExceptionMatches(PyExc_MemoryError))
297 /* already current */
298 return NULL;
Vladimir Marangozov0888ff12000-08-18 18:01:06 +0000299
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000300 /* raise the pre-allocated instance if it still exists */
301 if (PyExc_MemoryErrorInst)
302 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
303 else
304 /* this will probably fail since there's no memory and hee,
305 hee, we have to instantiate this class
306 */
307 PyErr_SetNone(PyExc_MemoryError);
Barry Warsaw2d8adff1997-08-29 21:54:35 +0000308
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000309 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000310}
311
Guido van Rossum373c8691997-04-29 18:22:47 +0000312PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000313PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000314{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000315 PyObject *v;
316 char *s;
317 int i = errno;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000318#ifdef PLAN9
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000319 char errbuf[ERRMAX];
Martin v. Löwis3484a182002-03-09 12:07:51 +0000320#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000321#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000322 char *s_buf = NULL;
323 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
Guido van Rossum795e1892000-02-17 15:19:15 +0000324#endif
Guido van Rossume9fbc091995-02-18 14:52:19 +0000325#ifdef EINTR
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000326 if (i == EINTR && PyErr_CheckSignals())
327 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000328#endif
Martin v. Löwis3484a182002-03-09 12:07:51 +0000329#ifdef PLAN9
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 rerrstr(errbuf, sizeof errbuf);
331 s = errbuf;
Martin v. Löwis3484a182002-03-09 12:07:51 +0000332#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000333 if (i == 0)
334 s = "Error"; /* Sometimes errno didn't get set */
335 else
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000336#ifndef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000337 s = strerror(i);
Guido van Rossum743007d1999-04-21 15:27:31 +0000338#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000339 {
340 /* Note that the Win32 errors do not lineup with the
341 errno error. So if the error is in the MSVC error
342 table, we use it, otherwise we assume it really _is_
343 a Win32 error code
344 */
345 if (i > 0 && i < _sys_nerr) {
346 s = _sys_errlist[i];
347 }
348 else {
349 int len = FormatMessage(
350 FORMAT_MESSAGE_ALLOCATE_BUFFER |
351 FORMAT_MESSAGE_FROM_SYSTEM |
352 FORMAT_MESSAGE_IGNORE_INSERTS,
353 NULL, /* no message source */
354 i,
355 MAKELANGID(LANG_NEUTRAL,
356 SUBLANG_DEFAULT),
357 /* Default language */
358 (LPTSTR) &s_buf,
359 0, /* size not used */
360 NULL); /* no args */
361 if (len==0) {
362 /* Only ever seen this in out-of-mem
363 situations */
364 sprintf(s_small_buf, "Windows Error 0x%X", i);
365 s = s_small_buf;
366 s_buf = NULL;
367 } else {
368 s = s_buf;
369 /* remove trailing cr/lf and dots */
370 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
371 s[--len] = '\0';
372 }
373 }
374 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000375#endif /* Unix/Windows */
376#endif /* PLAN 9*/
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000377 if (filenameObject != NULL)
378 v = Py_BuildValue("(isO)", i, s, filenameObject);
379 else
380 v = Py_BuildValue("(is)", i, s);
381 if (v != NULL) {
382 PyErr_SetObject(exc, v);
383 Py_DECREF(v);
384 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000385#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000386 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000387#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000388 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000389}
Guido van Rossum743007d1999-04-21 15:27:31 +0000390
Barry Warsaw97d95151998-07-23 16:05:56 +0000391
392PyObject *
Alexandre Vassalottia6e34742009-06-12 20:57:12 +0000393PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000394{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000395 PyObject *name = filename ? PyString_FromString(filename) : NULL;
396 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
397 Py_XDECREF(name);
398 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000399}
400
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000401#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000402PyObject *
Alexandre Vassalottia6e34742009-06-12 20:57:12 +0000403PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000404{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000405 PyObject *name = filename ?
406 PyUnicode_FromUnicode(filename, wcslen(filename)) :
407 NULL;
408 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
409 Py_XDECREF(name);
410 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000411}
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000412#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000413
414PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000415PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000416{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000417 return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000418}
Guido van Rossum683a0721990-10-21 22:09:12 +0000419
Brett Cannonbf364092006-03-01 04:25:17 +0000420#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000421/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000422PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000423 PyObject *exc,
424 int ierr,
425 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000426{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000427 int len;
428 char *s;
429 char *s_buf = NULL; /* Free via LocalFree */
430 char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
431 PyObject *v;
432 DWORD err = (DWORD)ierr;
433 if (err==0) err = GetLastError();
434 len = FormatMessage(
435 /* Error API error */
436 FORMAT_MESSAGE_ALLOCATE_BUFFER |
437 FORMAT_MESSAGE_FROM_SYSTEM |
438 FORMAT_MESSAGE_IGNORE_INSERTS,
439 NULL, /* no message source */
440 err,
441 MAKELANGID(LANG_NEUTRAL,
442 SUBLANG_DEFAULT), /* Default language */
443 (LPTSTR) &s_buf,
444 0, /* size not used */
445 NULL); /* no args */
446 if (len==0) {
447 /* Only seen this in out of mem situations */
448 sprintf(s_small_buf, "Windows Error 0x%X", err);
449 s = s_small_buf;
450 s_buf = NULL;
451 } else {
452 s = s_buf;
453 /* remove trailing cr/lf and dots */
454 while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
455 s[--len] = '\0';
456 }
457 if (filenameObject != NULL)
458 v = Py_BuildValue("(isO)", err, s, filenameObject);
459 else
460 v = Py_BuildValue("(is)", err, s);
461 if (v != NULL) {
462 PyErr_SetObject(exc, v);
463 Py_DECREF(v);
464 }
465 LocalFree(s_buf);
466 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000467}
468
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000469PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000470 PyObject *exc,
471 int ierr,
472 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000473{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000474 PyObject *name = filename ? PyString_FromString(filename) : NULL;
475 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
476 ierr,
477 name);
478 Py_XDECREF(name);
479 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000480}
481
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000482PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 PyObject *exc,
484 int ierr,
485 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000486{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000487 PyObject *name = filename ?
488 PyUnicode_FromUnicode(filename, wcslen(filename)) :
489 NULL;
490 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
491 ierr,
492 name);
493 Py_XDECREF(name);
494 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000495}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000496
Thomas Heller085358a2002-07-29 14:27:41 +0000497PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
498{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000499 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000500}
501
Guido van Rossum795e1892000-02-17 15:19:15 +0000502PyObject *PyErr_SetFromWindowsErr(int ierr)
503{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000504 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
505 ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000506}
507PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 int ierr,
509 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000510{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000511 PyObject *name = filename ? PyString_FromString(filename) : NULL;
512 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
513 PyExc_WindowsError,
514 ierr, name);
515 Py_XDECREF(name);
516 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000517}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000518
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000519PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000520 int ierr,
521 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000522{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000523 PyObject *name = filename ?
524 PyUnicode_FromUnicode(filename, wcslen(filename)) :
525 NULL;
526 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
527 PyExc_WindowsError,
528 ierr, name);
529 Py_XDECREF(name);
530 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000531}
Guido van Rossum795e1892000-02-17 15:19:15 +0000532#endif /* MS_WINDOWS */
533
Guido van Rossum683a0721990-10-21 22:09:12 +0000534void
Fred Drake6d63adf2000-08-24 22:38:39 +0000535_PyErr_BadInternalCall(char *filename, int lineno)
536{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000537 PyErr_Format(PyExc_SystemError,
538 "%s:%d: bad argument to internal function",
539 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000540}
541
542/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
543 export the entry point for existing object code: */
544#undef PyErr_BadInternalCall
545void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000546PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000547{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000548 PyErr_Format(PyExc_SystemError,
549 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000550}
Fred Drake6d63adf2000-08-24 22:38:39 +0000551#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
552
Guido van Rossum1548bac1997-02-14 17:09:47 +0000553
554
Guido van Rossum1548bac1997-02-14 17:09:47 +0000555PyObject *
556PyErr_Format(PyObject *exception, const char *format, ...)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000557{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000558 va_list vargs;
559 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000560
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000561#ifdef HAVE_STDARG_PROTOTYPES
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000562 va_start(vargs, format);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000563#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000564 va_start(vargs);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000565#endif
Guido van Rossum1548bac1997-02-14 17:09:47 +0000566
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000567 string = PyString_FromFormatV(format, vargs);
568 PyErr_SetObject(exception, string);
569 Py_XDECREF(string);
570 va_end(vargs);
571 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000572}
Guido van Rossum7617e051997-09-16 18:43:50 +0000573
574
Georg Brandl658d5132006-05-23 11:17:21 +0000575
Guido van Rossum7617e051997-09-16 18:43:50 +0000576PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000577PyErr_NewException(char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000579 char *dot;
580 PyObject *modulename = NULL;
581 PyObject *classname = NULL;
582 PyObject *mydict = NULL;
583 PyObject *bases = NULL;
584 PyObject *result = NULL;
585 dot = strrchr(name, '.');
586 if (dot == NULL) {
587 PyErr_SetString(PyExc_SystemError,
588 "PyErr_NewException: name must be module.class");
589 return NULL;
590 }
591 if (base == NULL)
592 base = PyExc_Exception;
593 if (dict == NULL) {
594 dict = mydict = PyDict_New();
595 if (dict == NULL)
596 goto failure;
597 }
598 if (PyDict_GetItemString(dict, "__module__") == NULL) {
599 modulename = PyString_FromStringAndSize(name,
600 (Py_ssize_t)(dot-name));
601 if (modulename == NULL)
602 goto failure;
603 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
604 goto failure;
605 }
606 if (PyTuple_Check(base)) {
607 bases = base;
608 /* INCREF as we create a new ref in the else branch */
609 Py_INCREF(bases);
610 } else {
611 bases = PyTuple_Pack(1, base);
612 if (bases == NULL)
613 goto failure;
614 }
615 /* Create a real new-style class. */
616 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
617 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000618 failure:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000619 Py_XDECREF(bases);
620 Py_XDECREF(mydict);
621 Py_XDECREF(classname);
622 Py_XDECREF(modulename);
623 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000624}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000625
Georg Brandl740cdc32009-12-28 08:34:58 +0000626
627/* Create an exception with docstring */
628PyObject *
629PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict)
630{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000631 int result;
632 PyObject *ret = NULL;
633 PyObject *mydict = NULL; /* points to the dict only if we create it */
634 PyObject *docobj;
Georg Brandl740cdc32009-12-28 08:34:58 +0000635
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 if (dict == NULL) {
637 dict = mydict = PyDict_New();
638 if (dict == NULL) {
639 return NULL;
640 }
641 }
Georg Brandl740cdc32009-12-28 08:34:58 +0000642
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000643 if (doc != NULL) {
644 docobj = PyString_FromString(doc);
645 if (docobj == NULL)
646 goto failure;
647 result = PyDict_SetItemString(dict, "__doc__", docobj);
648 Py_DECREF(docobj);
649 if (result < 0)
650 goto failure;
651 }
Georg Brandl740cdc32009-12-28 08:34:58 +0000652
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000653 ret = PyErr_NewException(name, base, dict);
Georg Brandl740cdc32009-12-28 08:34:58 +0000654 failure:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000655 Py_XDECREF(mydict);
656 return ret;
Georg Brandl740cdc32009-12-28 08:34:58 +0000657}
658
659
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000660/* Call when an exception has occurred but there is no way for Python
661 to handle it. Examples: exception in __del__ or during GC. */
662void
663PyErr_WriteUnraisable(PyObject *obj)
664{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000665 PyObject *f, *t, *v, *tb;
666 PyErr_Fetch(&t, &v, &tb);
667 f = PySys_GetObject("stderr");
668 if (f != NULL) {
669 PyFile_WriteString("Exception ", f);
670 if (t) {
671 PyObject* moduleName;
672 char* className;
673 assert(PyExceptionClass_Check(t));
674 className = PyExceptionClass_Name(t);
675 if (className != NULL) {
676 char *dot = strrchr(className, '.');
677 if (dot != NULL)
678 className = dot+1;
679 }
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000680
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000681 moduleName = PyObject_GetAttrString(t, "__module__");
682 if (moduleName == NULL)
683 PyFile_WriteString("<unknown>", f);
684 else {
685 char* modstr = PyString_AsString(moduleName);
686 if (modstr &&
687 strcmp(modstr, "exceptions") != 0)
688 {
689 PyFile_WriteString(modstr, f);
690 PyFile_WriteString(".", f);
691 }
692 }
693 if (className == NULL)
694 PyFile_WriteString("<unknown>", f);
695 else
696 PyFile_WriteString(className, f);
697 if (v && v != Py_None) {
698 PyFile_WriteString(": ", f);
699 PyFile_WriteObject(v, f, 0);
700 }
701 Py_XDECREF(moduleName);
702 }
703 PyFile_WriteString(" in ", f);
704 PyFile_WriteObject(obj, f, 0);
705 PyFile_WriteString(" ignored\n", f);
706 PyErr_Clear(); /* Just in case */
707 }
708 Py_XDECREF(t);
709 Py_XDECREF(v);
710 Py_XDECREF(tb);
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000711}
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000712
Armin Rigo092381a2003-10-25 14:29:27 +0000713extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000714
Guido van Rossum2fd45652001-02-28 21:46:24 +0000715
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000716/* Set file and line information for the current exception.
717 If the exception is not a SyntaxError, also sets additional attributes
718 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +0000719
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000720void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000721PyErr_SyntaxLocation(const char *filename, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000722{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000723 PyObject *exc, *v, *tb, *tmp;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000724
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000725 /* add attributes for the line number and filename for the error */
726 PyErr_Fetch(&exc, &v, &tb);
727 PyErr_NormalizeException(&exc, &v, &tb);
728 /* XXX check that it is, indeed, a syntax error. It might not
729 * be, though. */
730 tmp = PyInt_FromLong(lineno);
731 if (tmp == NULL)
732 PyErr_Clear();
733 else {
734 if (PyObject_SetAttrString(v, "lineno", tmp))
735 PyErr_Clear();
736 Py_DECREF(tmp);
737 }
738 if (filename != NULL) {
739 tmp = PyString_FromString(filename);
740 if (tmp == NULL)
741 PyErr_Clear();
742 else {
743 if (PyObject_SetAttrString(v, "filename", tmp))
744 PyErr_Clear();
745 Py_DECREF(tmp);
746 }
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000747
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000748 tmp = PyErr_ProgramText(filename, lineno);
749 if (tmp) {
750 if (PyObject_SetAttrString(v, "text", tmp))
751 PyErr_Clear();
752 Py_DECREF(tmp);
753 }
754 }
755 if (PyObject_SetAttrString(v, "offset", Py_None)) {
756 PyErr_Clear();
757 }
758 if (exc != PyExc_SyntaxError) {
759 if (!PyObject_HasAttrString(v, "msg")) {
760 tmp = PyObject_Str(v);
761 if (tmp) {
762 if (PyObject_SetAttrString(v, "msg", tmp))
763 PyErr_Clear();
764 Py_DECREF(tmp);
765 } else {
766 PyErr_Clear();
767 }
768 }
769 if (!PyObject_HasAttrString(v, "print_file_and_line")) {
770 if (PyObject_SetAttrString(v, "print_file_and_line",
771 Py_None))
772 PyErr_Clear();
773 }
774 }
775 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000776}
777
778/* com_fetch_program_text will attempt to load the line of text that
779 the exception refers to. If it fails, it will return NULL but will
Brett Cannonbf364092006-03-01 04:25:17 +0000780 not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000781
782 XXX The functionality of this function is quite similar to the
783 functionality in tb_displayline() in traceback.c.
784*/
785
786PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +0000787PyErr_ProgramText(const char *filename, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000788{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000789 FILE *fp;
790 int i;
791 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000792
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000793 if (filename == NULL || *filename == '\0' || lineno <= 0)
794 return NULL;
795 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
796 if (fp == NULL)
797 return NULL;
798 for (i = 0; i < lineno; i++) {
799 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
800 do {
801 *pLastChar = '\0';
802 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
803 break;
804 /* fgets read *something*; if it didn't get as
805 far as pLastChar, it must have found a newline
806 or hit the end of the file; if pLastChar is \n,
807 it obviously found a newline; else we haven't
808 yet seen a newline, so must continue */
809 } while (*pLastChar != '\0' && *pLastChar != '\n');
810 }
811 fclose(fp);
812 if (i == lineno) {
813 char *p = linebuf;
814 while (*p == ' ' || *p == '\t' || *p == '\014')
815 p++;
816 return PyString_FromString(p);
817 }
818 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000819}
Anthony Baxterac6bd462006-04-13 02:06:09 +0000820
821#ifdef __cplusplus
822}
823#endif
824