blob: e98d7a946cad3cda3297bc1612e0f688179d7d06 [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
Martin v. Löwis5d12abe2007-09-03 07:40:24 +000013#include <windows.h>
14#include <winbase.h>
Guido van Rossum743007d1999-04-21 15:27:31 +000015#endif
16
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +000017#include <ctype.h>
18
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 Pitrouf95a1b32010-05-09 15:52:27 +000027 PyThreadState *tstate = PyThreadState_GET();
28 PyObject *oldtype, *oldvalue, *oldtraceback;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +000055 PyThreadState *tstate = PyThreadState_GET();
56 PyObject *exc_value;
57 PyObject *tb = NULL;
Guido van Rossumb4fb6e42008-06-14 20:20:24 +000058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 if (exception != NULL &&
60 !PyExceptionClass_Check(exception)) {
61 PyErr_Format(PyExc_SystemError,
62 "exception %R not a BaseException subclass",
63 exception);
64 return;
65 }
66 Py_XINCREF(value);
67 exc_value = tstate->exc_value;
68 if (exc_value != NULL && exc_value != Py_None) {
69 /* Implicit exception chaining */
70 Py_INCREF(exc_value);
71 if (value == NULL || !PyExceptionInstance_Check(value)) {
72 /* We must normalize the value right now */
73 PyObject *args, *fixed_value;
74 if (value == NULL || value == Py_None)
75 args = PyTuple_New(0);
76 else if (PyTuple_Check(value)) {
77 Py_INCREF(value);
78 args = value;
79 }
80 else
81 args = PyTuple_Pack(1, value);
82 fixed_value = args ?
83 PyEval_CallObject(exception, args) : NULL;
84 Py_XDECREF(args);
85 Py_XDECREF(value);
86 if (fixed_value == NULL)
87 return;
88 value = fixed_value;
89 }
90 /* Avoid reference cycles through the context chain.
91 This is O(chain length) but context chains are
92 usually very short. Sensitive readers may try
93 to inline the call to PyException_GetContext. */
94 if (exc_value != value) {
95 PyObject *o = exc_value, *context;
96 while ((context = PyException_GetContext(o))) {
97 Py_DECREF(context);
98 if (context == value) {
99 PyException_SetContext(o, NULL);
100 break;
101 }
102 o = context;
103 }
104 PyException_SetContext(value, exc_value);
105 } else {
106 Py_DECREF(exc_value);
107 }
108 }
109 if (value != NULL && PyExceptionInstance_Check(value))
110 tb = PyException_GetTraceback(value);
111 Py_XINCREF(exception);
112 PyErr_Restore(exception, value, tb);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000113}
114
115void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000116PyErr_SetNone(PyObject *exception)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119}
120
121void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000122PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 PyObject *value = PyUnicode_FromString(string);
125 PyErr_SetObject(exception, value);
126 Py_XDECREF(value);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000127}
128
Guido van Rossum3a241811994-08-29 12:14:12 +0000129
Guido van Rossum373c8691997-04-29 18:22:47 +0000130PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000131PyErr_Occurred(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 return tstate->curexc_type;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136}
137
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000138
139int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000140PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (err == NULL || exc == NULL) {
143 /* maybe caused by "import exceptions" that failed early on */
144 return 0;
145 }
146 if (PyTuple_Check(exc)) {
147 Py_ssize_t i, n;
148 n = PyTuple_Size(exc);
149 for (i = 0; i < n; i++) {
150 /* Test recursively */
151 if (PyErr_GivenExceptionMatches(
152 err, PyTuple_GET_ITEM(exc, i)))
153 {
154 return 1;
155 }
156 }
157 return 0;
158 }
159 /* err might be an instance, so check its class. */
160 if (PyExceptionInstance_Check(err))
161 err = PyExceptionInstance_Class(err);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
164 int res = 0;
165 PyObject *exception, *value, *tb;
166 PyErr_Fetch(&exception, &value, &tb);
167 /* PyObject_IsSubclass() can recurse and therefore is
168 not safe (see test_bad_getattr in test.pickletester). */
169 res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
170 /* This function must not fail, so print the error here */
171 if (res == -1) {
172 PyErr_WriteUnraisable(err);
173 res = 0;
174 }
175 PyErr_Restore(exception, value, tb);
176 return res;
177 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 return err == exc;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000180}
Guido van Rossum743007d1999-04-21 15:27:31 +0000181
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000182
183int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000184PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000187}
188
189
190/* Used in many places to normalize a raised exception, including in
191 eval_code2(), do_raise(), and PyErr_Print()
Benjamin Petersone6528212008-07-15 15:32:09 +0000192
193 XXX: should PyErr_NormalizeException() also call
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyException_SetTraceback() with the resulting value and tb?
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000195*/
196void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000197PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 PyObject *type = *exc;
200 PyObject *value = *val;
201 PyObject *inclass = NULL;
202 PyObject *initial_tb = NULL;
203 PyThreadState *tstate = NULL;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 if (type == NULL) {
206 /* There was no exception, so nothing to do. */
207 return;
208 }
Guido van Rossumed473a42000-08-07 19:18:27 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 /* If PyErr_SetNone() was used, the value will have been actually
211 set to NULL.
212 */
213 if (!value) {
214 value = Py_None;
215 Py_INCREF(value);
216 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (PyExceptionInstance_Check(value))
219 inclass = PyExceptionInstance_Class(value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 /* Normalize the exception so that if the type is a class, the
222 value will be an instance.
223 */
224 if (PyExceptionClass_Check(type)) {
225 /* if the value was not an instance, or is not an instance
226 whose class is (or is derived from) type, then use the
227 value as an argument to instantiation of the type
228 class.
229 */
230 if (!inclass || !PyObject_IsSubclass(inclass, type)) {
231 PyObject *args, *res;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (value == Py_None)
234 args = PyTuple_New(0);
235 else if (PyTuple_Check(value)) {
236 Py_INCREF(value);
237 args = value;
238 }
239 else
240 args = PyTuple_Pack(1, value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 if (args == NULL)
243 goto finally;
244 res = PyEval_CallObject(type, args);
245 Py_DECREF(args);
246 if (res == NULL)
247 goto finally;
248 Py_DECREF(value);
249 value = res;
250 }
251 /* if the class of the instance doesn't exactly match the
252 class of the type, believe the instance
253 */
254 else if (inclass != type) {
255 Py_DECREF(type);
256 type = inclass;
257 Py_INCREF(type);
258 }
259 }
260 *exc = type;
261 *val = value;
262 return;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000263finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 Py_DECREF(type);
265 Py_DECREF(value);
266 /* If the new exception doesn't set a traceback and the old
267 exception had a traceback, use the old traceback for the
268 new exception. It's better than nothing.
269 */
270 initial_tb = *tb;
271 PyErr_Fetch(exc, val, tb);
272 if (initial_tb != NULL) {
273 if (*tb == NULL)
274 *tb = initial_tb;
275 else
276 Py_DECREF(initial_tb);
277 }
278 /* normalize recursively */
279 tstate = PyThreadState_GET();
280 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
281 --tstate->recursion_depth;
282 /* throw away the old exception... */
283 Py_DECREF(*exc);
284 Py_DECREF(*val);
285 /* ... and use the recursion error instead */
286 *exc = PyExc_RuntimeError;
287 *val = PyExc_RecursionErrorInst;
288 Py_INCREF(*exc);
289 Py_INCREF(*val);
290 /* just keeping the old traceback */
291 return;
292 }
293 PyErr_NormalizeException(exc, val, tb);
294 --tstate->recursion_depth;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000295}
296
297
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000299PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 *p_type = tstate->curexc_type;
304 *p_value = tstate->curexc_value;
305 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 tstate->curexc_type = NULL;
308 tstate->curexc_value = NULL;
309 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000310}
311
312void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000313PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000316}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000317
318/* Convenience functions to set a type error exception and return 0 */
319
320int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000321PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 PyErr_SetString(PyExc_TypeError,
324 "bad argument type for built-in operation");
325 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000326}
327
Guido van Rossum373c8691997-04-29 18:22:47 +0000328PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000329PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 if (PyErr_ExceptionMatches(PyExc_MemoryError))
332 /* already current */
333 return NULL;
Vladimir Marangozov0888ff12000-08-18 18:01:06 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* raise the pre-allocated instance if it still exists */
336 if (PyExc_MemoryErrorInst)
337 {
338 /* Clear the previous traceback, otherwise it will be appended
339 * to the current one.
340 *
341 * The following statement is not likely to raise any error;
342 * if it does, we simply discard it.
343 */
344 PyException_SetTraceback(PyExc_MemoryErrorInst, Py_None);
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
347 }
348 else
349 /* this will probably fail since there's no memory and hee,
350 hee, we have to instantiate this class
351 */
352 PyErr_SetNone(PyExc_MemoryError);
Barry Warsaw2d8adff1997-08-29 21:54:35 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000355}
356
Guido van Rossum373c8691997-04-29 18:22:47 +0000357PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000358PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyObject *message;
361 PyObject *v;
362 int i = errno;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000363#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 char *s;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000365#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 WCHAR *s_buf = NULL;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000367#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000368
Guido van Rossume9fbc091995-02-18 14:52:19 +0000369#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 if (i == EINTR && PyErr_CheckSignals())
371 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000372#endif
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000373
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000374#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (i == 0)
376 s = "Error"; /* Sometimes errno didn't get set */
377 else
378 s = strerror(i);
379 message = PyUnicode_DecodeUTF8(s, strlen(s), "ignore");
Guido van Rossum743007d1999-04-21 15:27:31 +0000380#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (i == 0)
382 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
383 else
384 {
385 /* Note that the Win32 errors do not lineup with the
386 errno error. So if the error is in the MSVC error
387 table, we use it, otherwise we assume it really _is_
388 a Win32 error code
389 */
390 if (i > 0 && i < _sys_nerr) {
391 message = PyUnicode_FromString(_sys_errlist[i]);
392 }
393 else {
394 int len = FormatMessageW(
395 FORMAT_MESSAGE_ALLOCATE_BUFFER |
396 FORMAT_MESSAGE_FROM_SYSTEM |
397 FORMAT_MESSAGE_IGNORE_INSERTS,
398 NULL, /* no message source */
399 i,
400 MAKELANGID(LANG_NEUTRAL,
401 SUBLANG_DEFAULT),
402 /* Default language */
403 (LPWSTR) &s_buf,
404 0, /* size not used */
405 NULL); /* no args */
406 if (len==0) {
407 /* Only ever seen this in out-of-mem
408 situations */
409 s_buf = NULL;
410 message = PyUnicode_FromFormat("Windows Error 0x%X", i);
411 } else {
412 /* remove trailing cr/lf and dots */
413 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
414 s_buf[--len] = L'\0';
415 message = PyUnicode_FromUnicode(s_buf, len);
416 }
417 }
418 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000419#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (message == NULL)
422 {
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000423#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 LocalFree(s_buf);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000425#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 return NULL;
427 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (filenameObject != NULL)
430 v = Py_BuildValue("(iOO)", i, message, filenameObject);
431 else
432 v = Py_BuildValue("(iO)", i, message);
433 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (v != NULL) {
436 PyErr_SetObject(exc, v);
437 Py_DECREF(v);
438 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000439#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000441#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000443}
Guido van Rossum743007d1999-04-21 15:27:31 +0000444
Barry Warsaw97d95151998-07-23 16:05:56 +0000445
446PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000447PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
450 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
451 Py_XDECREF(name);
452 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000453}
454
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000455#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000456PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000457PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 PyObject *name = filename ?
460 PyUnicode_FromUnicode(filename, wcslen(filename)) :
461 NULL;
462 PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
463 Py_XDECREF(name);
464 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000465}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000466#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000467
468PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000469PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000472}
Guido van Rossum683a0721990-10-21 22:09:12 +0000473
Brett Cannonbf364092006-03-01 04:25:17 +0000474#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000475/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000476PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 PyObject *exc,
478 int ierr,
479 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 int len;
482 WCHAR *s_buf = NULL; /* Free via LocalFree */
483 PyObject *message;
484 PyObject *v;
485 DWORD err = (DWORD)ierr;
486 if (err==0) err = GetLastError();
487 len = FormatMessageW(
488 /* Error API error */
489 FORMAT_MESSAGE_ALLOCATE_BUFFER |
490 FORMAT_MESSAGE_FROM_SYSTEM |
491 FORMAT_MESSAGE_IGNORE_INSERTS,
492 NULL, /* no message source */
493 err,
494 MAKELANGID(LANG_NEUTRAL,
495 SUBLANG_DEFAULT), /* Default language */
496 (LPWSTR) &s_buf,
497 0, /* size not used */
498 NULL); /* no args */
499 if (len==0) {
500 /* Only seen this in out of mem situations */
501 message = PyUnicode_FromFormat("Windows Error 0x%X", err);
502 s_buf = NULL;
503 } else {
504 /* remove trailing cr/lf and dots */
505 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
506 s_buf[--len] = L'\0';
507 message = PyUnicode_FromUnicode(s_buf, len);
508 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (message == NULL)
511 {
512 LocalFree(s_buf);
513 return NULL;
514 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (filenameObject != NULL)
517 v = Py_BuildValue("(iOO)", err, message, filenameObject);
518 else
519 v = Py_BuildValue("(iO)", err, message);
520 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (v != NULL) {
523 PyErr_SetObject(exc, v);
524 Py_DECREF(v);
525 }
526 LocalFree(s_buf);
527 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000528}
529
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000530PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 PyObject *exc,
532 int ierr,
533 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
536 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
537 ierr,
538 name);
539 Py_XDECREF(name);
540 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000541}
542
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000543PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 PyObject *exc,
545 int ierr,
546 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 PyObject *name = filename ?
549 PyUnicode_FromUnicode(filename, wcslen(filename)) :
550 NULL;
551 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
552 ierr,
553 name);
554 Py_XDECREF(name);
555 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000556}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000557
Thomas Heller085358a2002-07-29 14:27:41 +0000558PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000561}
562
Guido van Rossum795e1892000-02-17 15:19:15 +0000563PyObject *PyErr_SetFromWindowsErr(int ierr)
564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
566 ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000567}
568PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 int ierr,
570 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
573 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
574 PyExc_WindowsError,
575 ierr, name);
576 Py_XDECREF(name);
577 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000578}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000579
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000580PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 int ierr,
582 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 PyObject *name = filename ?
585 PyUnicode_FromUnicode(filename, wcslen(filename)) :
586 NULL;
587 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
588 PyExc_WindowsError,
589 ierr, name);
590 Py_XDECREF(name);
591 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000592}
Guido van Rossum795e1892000-02-17 15:19:15 +0000593#endif /* MS_WINDOWS */
594
Guido van Rossum683a0721990-10-21 22:09:12 +0000595void
Neal Norwitzb382b842007-08-24 20:00:37 +0000596_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 PyErr_Format(PyExc_SystemError,
599 "%s:%d: bad argument to internal function",
600 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000601}
602
603/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
604 export the entry point for existing object code: */
605#undef PyErr_BadInternalCall
606void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000607PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyErr_Format(PyExc_SystemError,
610 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000611}
Fred Drake6d63adf2000-08-24 22:38:39 +0000612#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
613
Guido van Rossum1548bac1997-02-14 17:09:47 +0000614
615
Guido van Rossum1548bac1997-02-14 17:09:47 +0000616PyObject *
617PyErr_Format(PyObject *exception, const char *format, ...)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 va_list vargs;
620 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000621
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000622#ifdef HAVE_STDARG_PROTOTYPES
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 va_start(vargs, format);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000624#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 va_start(vargs);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000626#endif
Guido van Rossum1548bac1997-02-14 17:09:47 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 string = PyUnicode_FromFormatV(format, vargs);
629 PyErr_SetObject(exception, string);
630 Py_XDECREF(string);
631 va_end(vargs);
632 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000633}
Guido van Rossum7617e051997-09-16 18:43:50 +0000634
635
Thomas Wouters477c8d52006-05-27 19:21:47 +0000636
Guido van Rossum7617e051997-09-16 18:43:50 +0000637PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000638PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 const char *dot;
641 PyObject *modulename = NULL;
642 PyObject *classname = NULL;
643 PyObject *mydict = NULL;
644 PyObject *bases = NULL;
645 PyObject *result = NULL;
646 dot = strrchr(name, '.');
647 if (dot == NULL) {
648 PyErr_SetString(PyExc_SystemError,
649 "PyErr_NewException: name must be module.class");
650 return NULL;
651 }
652 if (base == NULL)
653 base = PyExc_Exception;
654 if (dict == NULL) {
655 dict = mydict = PyDict_New();
656 if (dict == NULL)
657 goto failure;
658 }
659 if (PyDict_GetItemString(dict, "__module__") == NULL) {
660 modulename = PyUnicode_FromStringAndSize(name,
661 (Py_ssize_t)(dot-name));
662 if (modulename == NULL)
663 goto failure;
664 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
665 goto failure;
666 }
667 if (PyTuple_Check(base)) {
668 bases = base;
669 /* INCREF as we create a new ref in the else branch */
670 Py_INCREF(bases);
671 } else {
672 bases = PyTuple_Pack(1, base);
673 if (bases == NULL)
674 goto failure;
675 }
676 /* Create a real new-style class. */
677 result = PyObject_CallFunction((PyObject *)&PyType_Type, "UOO",
678 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000679 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 Py_XDECREF(bases);
681 Py_XDECREF(mydict);
682 Py_XDECREF(classname);
683 Py_XDECREF(modulename);
684 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000685}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000686
Georg Brandl1e28a272009-12-28 08:41:01 +0000687
688/* Create an exception with docstring */
689PyObject *
690PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 int result;
694 PyObject *ret = NULL;
695 PyObject *mydict = NULL; /* points to the dict only if we create it */
696 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (dict == NULL) {
699 dict = mydict = PyDict_New();
700 if (dict == NULL) {
701 return NULL;
702 }
703 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (doc != NULL) {
706 docobj = PyUnicode_FromString(doc);
707 if (docobj == NULL)
708 goto failure;
709 result = PyDict_SetItemString(dict, "__doc__", docobj);
710 Py_DECREF(docobj);
711 if (result < 0)
712 goto failure;
713 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000716 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 Py_XDECREF(mydict);
718 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000719}
720
721
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000722/* Call when an exception has occurred but there is no way for Python
723 to handle it. Examples: exception in __del__ or during GC. */
724void
725PyErr_WriteUnraisable(PyObject *obj)
726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 PyObject *f, *t, *v, *tb;
728 PyErr_Fetch(&t, &v, &tb);
729 f = PySys_GetObject("stderr");
730 if (f != NULL && f != Py_None) {
731 PyFile_WriteString("Exception ", f);
732 if (t) {
733 PyObject* moduleName;
734 char* className;
735 assert(PyExceptionClass_Check(t));
736 className = PyExceptionClass_Name(t);
737 if (className != NULL) {
738 char *dot = strrchr(className, '.');
739 if (dot != NULL)
740 className = dot+1;
741 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 moduleName = PyObject_GetAttrString(t, "__module__");
744 if (moduleName == NULL)
745 PyFile_WriteString("<unknown>", f);
746 else {
747 char* modstr = _PyUnicode_AsString(moduleName);
748 if (modstr &&
749 strcmp(modstr, "builtins") != 0)
750 {
751 PyFile_WriteString(modstr, f);
752 PyFile_WriteString(".", f);
753 }
754 }
755 if (className == NULL)
756 PyFile_WriteString("<unknown>", f);
757 else
758 PyFile_WriteString(className, f);
759 if (v && v != Py_None) {
760 PyFile_WriteString(": ", f);
761 PyFile_WriteObject(v, f, 0);
762 }
763 Py_XDECREF(moduleName);
764 }
765 PyFile_WriteString(" in ", f);
766 PyFile_WriteObject(obj, f, 0);
767 PyFile_WriteString(" ignored\n", f);
768 PyErr_Clear(); /* Just in case */
769 }
770 Py_XDECREF(t);
771 Py_XDECREF(v);
772 Py_XDECREF(tb);
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000773}
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000774
Armin Rigo092381a2003-10-25 14:29:27 +0000775extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000776
Guido van Rossum2fd45652001-02-28 21:46:24 +0000777
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000778/* Set file and line information for the current exception.
779 If the exception is not a SyntaxError, also sets additional attributes
780 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +0000781
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000782void
Martin v. Löwis95292d62002-12-11 14:04:59 +0000783PyErr_SyntaxLocation(const char *filename, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 PyObject *exc, *v, *tb, *tmp;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /* add attributes for the line number and filename for the error */
788 PyErr_Fetch(&exc, &v, &tb);
789 PyErr_NormalizeException(&exc, &v, &tb);
790 /* XXX check that it is, indeed, a syntax error. It might not
791 * be, though. */
792 tmp = PyLong_FromLong(lineno);
793 if (tmp == NULL)
794 PyErr_Clear();
795 else {
796 if (PyObject_SetAttrString(v, "lineno", tmp))
797 PyErr_Clear();
798 Py_DECREF(tmp);
799 }
800 if (filename != NULL) {
801 tmp = PyUnicode_FromString(filename);
802 if (tmp == NULL)
803 PyErr_Clear();
804 else {
805 if (PyObject_SetAttrString(v, "filename", tmp))
806 PyErr_Clear();
807 Py_DECREF(tmp);
808 }
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 tmp = PyErr_ProgramText(filename, lineno);
811 if (tmp) {
812 if (PyObject_SetAttrString(v, "text", tmp))
813 PyErr_Clear();
814 Py_DECREF(tmp);
815 }
816 }
817 if (PyObject_SetAttrString(v, "offset", Py_None)) {
818 PyErr_Clear();
819 }
820 if (exc != PyExc_SyntaxError) {
821 if (!PyObject_HasAttrString(v, "msg")) {
822 tmp = PyObject_Str(v);
823 if (tmp) {
824 if (PyObject_SetAttrString(v, "msg", tmp))
825 PyErr_Clear();
826 Py_DECREF(tmp);
827 } else {
828 PyErr_Clear();
829 }
830 }
831 if (!PyObject_HasAttrString(v, "print_file_and_line")) {
832 if (PyObject_SetAttrString(v, "print_file_and_line",
833 Py_None))
834 PyErr_Clear();
835 }
836 }
837 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000838}
839
Guido van Rossumebe8f8a2007-10-10 18:53:36 +0000840/* Attempt to load the line of text that the exception refers to. If it
841 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000842
843 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +0000844 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000845
846PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +0000847PyErr_ProgramText(const char *filename, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 FILE *fp;
850 int i;
851 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (filename == NULL || *filename == '\0' || lineno <= 0)
854 return NULL;
855 fp = fopen(filename, "r" PY_STDIOTEXTMODE);
856 if (fp == NULL)
857 return NULL;
858 for (i = 0; i < lineno; i++) {
859 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
860 do {
861 *pLastChar = '\0';
862 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
863 fp, NULL) == NULL)
864 break;
865 /* fgets read *something*; if it didn't get as
866 far as pLastChar, it must have found a newline
867 or hit the end of the file; if pLastChar is \n,
868 it obviously found a newline; else we haven't
869 yet seen a newline, so must continue */
870 } while (*pLastChar != '\0' && *pLastChar != '\n');
871 }
872 fclose(fp);
873 if (i == lineno) {
874 char *p = linebuf;
875 PyObject *res;
876 while (*p == ' ' || *p == '\t' || *p == '\014')
877 p++;
878 res = PyUnicode_FromString(p);
879 if (res == NULL)
880 PyErr_Clear();
881 return res;
882 }
883 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000884}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000885
886#ifdef __cplusplus
887}
888#endif