blob: 996292a04479a2cf3897b94bbea453f2e9c602bc [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
Victor Stinnerbd303c12013-11-07 23:07:29 +010023_Py_IDENTIFIER(builtins);
24_Py_IDENTIFIER(stderr);
25
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000026
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000027void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000028PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 PyThreadState *tstate = PyThreadState_GET();
31 PyObject *oldtype, *oldvalue, *oldtraceback;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 if (traceback != NULL && !PyTraceBack_Check(traceback)) {
34 /* XXX Should never happen -- fatal error instead? */
35 /* Well, it could be None. */
36 Py_DECREF(traceback);
37 traceback = NULL;
38 }
Guido van Rossuma027efa1997-05-05 20:56:21 +000039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 /* Save these in locals to safeguard against recursive
41 invocation through Py_XDECREF */
42 oldtype = tstate->curexc_type;
43 oldvalue = tstate->curexc_value;
44 oldtraceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +000045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 tstate->curexc_type = type;
47 tstate->curexc_value = value;
48 tstate->curexc_traceback = traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +000049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 Py_XDECREF(oldtype);
51 Py_XDECREF(oldvalue);
52 Py_XDECREF(oldtraceback);
Guido van Rossum1ae940a1995-01-02 19:04:15 +000053}
54
55void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000056PyErr_SetObject(PyObject *exception, PyObject *value)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 PyThreadState *tstate = PyThreadState_GET();
59 PyObject *exc_value;
60 PyObject *tb = NULL;
Guido van Rossumb4fb6e42008-06-14 20:20:24 +000061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 if (exception != NULL &&
63 !PyExceptionClass_Check(exception)) {
64 PyErr_Format(PyExc_SystemError,
65 "exception %R not a BaseException subclass",
66 exception);
67 return;
68 }
69 Py_XINCREF(value);
70 exc_value = tstate->exc_value;
71 if (exc_value != NULL && exc_value != Py_None) {
72 /* Implicit exception chaining */
73 Py_INCREF(exc_value);
74 if (value == NULL || !PyExceptionInstance_Check(value)) {
75 /* We must normalize the value right now */
76 PyObject *args, *fixed_value;
Victor Stinnerace47d72013-07-18 01:41:08 +020077#ifdef Py_DEBUG
78 /* in debug mode, PyEval_EvalFrameEx() fails with an assertion
79 error if an exception is set when it is called */
80 PyErr_Clear();
81#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 if (value == NULL || value == Py_None)
83 args = PyTuple_New(0);
84 else if (PyTuple_Check(value)) {
85 Py_INCREF(value);
86 args = value;
87 }
88 else
89 args = PyTuple_Pack(1, value);
90 fixed_value = args ?
91 PyEval_CallObject(exception, args) : NULL;
92 Py_XDECREF(args);
93 Py_XDECREF(value);
94 if (fixed_value == NULL)
95 return;
96 value = fixed_value;
97 }
98 /* Avoid reference cycles through the context chain.
99 This is O(chain length) but context chains are
100 usually very short. Sensitive readers may try
101 to inline the call to PyException_GetContext. */
102 if (exc_value != value) {
103 PyObject *o = exc_value, *context;
104 while ((context = PyException_GetContext(o))) {
105 Py_DECREF(context);
106 if (context == value) {
107 PyException_SetContext(o, NULL);
108 break;
109 }
110 o = context;
111 }
112 PyException_SetContext(value, exc_value);
113 } else {
114 Py_DECREF(exc_value);
115 }
116 }
117 if (value != NULL && PyExceptionInstance_Check(value))
118 tb = PyException_GetTraceback(value);
119 Py_XINCREF(exception);
120 PyErr_Restore(exception, value, tb);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121}
122
Raymond Hettinger69492da2013-09-02 15:59:26 -0700123/* Set a key error with the specified argument, wrapping it in a
124 * tuple automatically so that tuple keys are not unpacked as the
125 * exception arguments. */
126void
127_PyErr_SetKeyError(PyObject *arg)
128{
129 PyObject *tup;
130 tup = PyTuple_Pack(1, arg);
131 if (!tup)
132 return; /* caller will expect error to be set anyway */
133 PyErr_SetObject(PyExc_KeyError, tup);
134 Py_DECREF(tup);
135}
136
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000138PyErr_SetNone(PyObject *exception)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141}
142
143void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000144PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 PyObject *value = PyUnicode_FromString(string);
147 PyErr_SetObject(exception, value);
148 Py_XDECREF(value);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149}
150
Guido van Rossum3a241811994-08-29 12:14:12 +0000151
Guido van Rossum373c8691997-04-29 18:22:47 +0000152PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000153PyErr_Occurred(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154{
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +0000155 /* If there is no thread state, PyThreadState_GET calls
156 Py_FatalError, which calls PyErr_Occurred. To avoid the
157 resulting infinite loop, we inline PyThreadState_GET here and
158 treat no thread as no error. */
159 PyThreadState *tstate =
160 ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current));
Guido van Rossuma027efa1997-05-05 20:56:21 +0000161
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +0000162 return tstate == NULL ? NULL : tstate->curexc_type;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000165
166int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000167PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 if (err == NULL || exc == NULL) {
170 /* maybe caused by "import exceptions" that failed early on */
171 return 0;
172 }
173 if (PyTuple_Check(exc)) {
174 Py_ssize_t i, n;
175 n = PyTuple_Size(exc);
176 for (i = 0; i < n; i++) {
177 /* Test recursively */
178 if (PyErr_GivenExceptionMatches(
179 err, PyTuple_GET_ITEM(exc, i)))
180 {
181 return 1;
182 }
183 }
184 return 0;
185 }
186 /* err might be an instance, so check its class. */
187 if (PyExceptionInstance_Check(err))
188 err = PyExceptionInstance_Class(err);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
191 int res = 0;
192 PyObject *exception, *value, *tb;
193 PyErr_Fetch(&exception, &value, &tb);
194 /* PyObject_IsSubclass() can recurse and therefore is
195 not safe (see test_bad_getattr in test.pickletester). */
196 res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
197 /* This function must not fail, so print the error here */
198 if (res == -1) {
199 PyErr_WriteUnraisable(err);
200 res = 0;
201 }
202 PyErr_Restore(exception, value, tb);
203 return res;
204 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 return err == exc;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000207}
Guido van Rossum743007d1999-04-21 15:27:31 +0000208
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000209
210int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000211PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000214}
215
216
217/* Used in many places to normalize a raised exception, including in
218 eval_code2(), do_raise(), and PyErr_Print()
Benjamin Petersone6528212008-07-15 15:32:09 +0000219
220 XXX: should PyErr_NormalizeException() also call
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 PyException_SetTraceback() with the resulting value and tb?
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000222*/
223void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000224PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyObject *type = *exc;
227 PyObject *value = *val;
228 PyObject *inclass = NULL;
229 PyObject *initial_tb = NULL;
230 PyThreadState *tstate = NULL;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (type == NULL) {
233 /* There was no exception, so nothing to do. */
234 return;
235 }
Guido van Rossumed473a42000-08-07 19:18:27 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 /* If PyErr_SetNone() was used, the value will have been actually
238 set to NULL.
239 */
240 if (!value) {
241 value = Py_None;
242 Py_INCREF(value);
243 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (PyExceptionInstance_Check(value))
246 inclass = PyExceptionInstance_Class(value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 /* Normalize the exception so that if the type is a class, the
249 value will be an instance.
250 */
251 if (PyExceptionClass_Check(type)) {
Victor Stinner74a7fa62013-07-17 00:44:53 +0200252 int is_subclass;
253 if (inclass) {
254 is_subclass = PyObject_IsSubclass(inclass, type);
255 if (is_subclass < 0)
256 goto finally;
257 }
258 else
259 is_subclass = 0;
260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 /* if the value was not an instance, or is not an instance
262 whose class is (or is derived from) type, then use the
263 value as an argument to instantiation of the type
264 class.
265 */
Victor Stinner74a7fa62013-07-17 00:44:53 +0200266 if (!inclass || !is_subclass) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 PyObject *args, *res;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (value == Py_None)
270 args = PyTuple_New(0);
271 else if (PyTuple_Check(value)) {
272 Py_INCREF(value);
273 args = value;
274 }
275 else
276 args = PyTuple_Pack(1, value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 if (args == NULL)
279 goto finally;
280 res = PyEval_CallObject(type, args);
281 Py_DECREF(args);
282 if (res == NULL)
283 goto finally;
284 Py_DECREF(value);
285 value = res;
286 }
287 /* if the class of the instance doesn't exactly match the
288 class of the type, believe the instance
289 */
290 else if (inclass != type) {
291 Py_DECREF(type);
292 type = inclass;
293 Py_INCREF(type);
294 }
295 }
296 *exc = type;
297 *val = value;
298 return;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000299finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 Py_DECREF(type);
301 Py_DECREF(value);
302 /* If the new exception doesn't set a traceback and the old
303 exception had a traceback, use the old traceback for the
304 new exception. It's better than nothing.
305 */
306 initial_tb = *tb;
307 PyErr_Fetch(exc, val, tb);
308 if (initial_tb != NULL) {
309 if (*tb == NULL)
310 *tb = initial_tb;
311 else
312 Py_DECREF(initial_tb);
313 }
314 /* normalize recursively */
315 tstate = PyThreadState_GET();
316 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
317 --tstate->recursion_depth;
318 /* throw away the old exception... */
319 Py_DECREF(*exc);
320 Py_DECREF(*val);
321 /* ... and use the recursion error instead */
322 *exc = PyExc_RuntimeError;
323 *val = PyExc_RecursionErrorInst;
324 Py_INCREF(*exc);
325 Py_INCREF(*val);
326 /* just keeping the old traceback */
327 return;
328 }
329 PyErr_NormalizeException(exc, val, tb);
330 --tstate->recursion_depth;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000331}
332
333
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000334void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000335PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 *p_type = tstate->curexc_type;
340 *p_value = tstate->curexc_value;
341 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 tstate->curexc_type = NULL;
344 tstate->curexc_value = NULL;
345 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346}
347
348void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000349PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000353
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200354void
355PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
356{
357 PyThreadState *tstate = PyThreadState_GET();
358
359 *p_type = tstate->exc_type;
360 *p_value = tstate->exc_value;
361 *p_traceback = tstate->exc_traceback;
362
363 Py_XINCREF(*p_type);
364 Py_XINCREF(*p_value);
365 Py_XINCREF(*p_traceback);
366}
367
368void
369PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
370{
371 PyObject *oldtype, *oldvalue, *oldtraceback;
372 PyThreadState *tstate = PyThreadState_GET();
373
374 oldtype = tstate->exc_type;
375 oldvalue = tstate->exc_value;
376 oldtraceback = tstate->exc_traceback;
377
378 tstate->exc_type = p_type;
379 tstate->exc_value = p_value;
380 tstate->exc_traceback = p_traceback;
381
382 Py_XDECREF(oldtype);
383 Py_XDECREF(oldvalue);
384 Py_XDECREF(oldtraceback);
385}
386
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000387/* Convenience functions to set a type error exception and return 0 */
388
389int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000390PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 PyErr_SetString(PyExc_TypeError,
393 "bad argument type for built-in operation");
394 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000395}
396
Guido van Rossum373c8691997-04-29 18:22:47 +0000397PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000398PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000399{
Victor Stinnerf54a5742013-07-22 22:28:37 +0200400 if (Py_TYPE(PyExc_MemoryError) == NULL) {
401 /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
402 initialized by _PyExc_Init() */
403 Py_FatalError("Out of memory and PyExc_MemoryError is not "
404 "initialized yet");
405 }
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000406 PyErr_SetNone(PyExc_MemoryError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000408}
409
Guido van Rossum373c8691997-04-29 18:22:47 +0000410PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000411PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000412{
Larry Hastingsb0827312014-02-09 22:05:19 -0800413 return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
414}
415
416PyObject *
417PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 PyObject *message;
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200420 PyObject *v, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 int i = errno;
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100422#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 WCHAR *s_buf = NULL;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000424#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000425
Guido van Rossume9fbc091995-02-18 14:52:19 +0000426#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (i == EINTR && PyErr_CheckSignals())
428 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000429#endif
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000430
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000431#ifndef MS_WINDOWS
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100432 if (i != 0) {
433 char *s = strerror(i);
Victor Stinner1b579672011-12-17 05:47:23 +0100434 message = PyUnicode_DecodeLocale(s, "surrogateescape");
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100435 }
436 else {
437 /* Sometimes errno didn't get set */
438 message = PyUnicode_FromString("Error");
439 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000440#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 if (i == 0)
442 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
443 else
444 {
445 /* Note that the Win32 errors do not lineup with the
446 errno error. So if the error is in the MSVC error
447 table, we use it, otherwise we assume it really _is_
448 a Win32 error code
449 */
450 if (i > 0 && i < _sys_nerr) {
451 message = PyUnicode_FromString(_sys_errlist[i]);
452 }
453 else {
454 int len = FormatMessageW(
455 FORMAT_MESSAGE_ALLOCATE_BUFFER |
456 FORMAT_MESSAGE_FROM_SYSTEM |
457 FORMAT_MESSAGE_IGNORE_INSERTS,
458 NULL, /* no message source */
459 i,
460 MAKELANGID(LANG_NEUTRAL,
461 SUBLANG_DEFAULT),
462 /* Default language */
463 (LPWSTR) &s_buf,
464 0, /* size not used */
465 NULL); /* no args */
466 if (len==0) {
467 /* Only ever seen this in out-of-mem
468 situations */
469 s_buf = NULL;
470 message = PyUnicode_FromFormat("Windows Error 0x%X", i);
471 } else {
472 /* remove trailing cr/lf and dots */
473 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
474 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200475 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 }
477 }
478 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000479#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (message == NULL)
482 {
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000483#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 LocalFree(s_buf);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000485#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 return NULL;
487 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000488
Larry Hastingsb0827312014-02-09 22:05:19 -0800489 if (filenameObject != NULL) {
490 if (filenameObject2 != NULL)
491 args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
492 else
493 args = Py_BuildValue("(iOO)", i, message, filenameObject);
494 } else {
495 assert(filenameObject2 == NULL);
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200496 args = Py_BuildValue("(iO)", i, message);
Larry Hastingsb0827312014-02-09 22:05:19 -0800497 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000499
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200500 if (args != NULL) {
501 v = PyObject_Call(exc, args, NULL);
502 Py_DECREF(args);
503 if (v != NULL) {
504 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
505 Py_DECREF(v);
506 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000508#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000510#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000512}
Guido van Rossum743007d1999-04-21 15:27:31 +0000513
Barry Warsaw97d95151998-07-23 16:05:56 +0000514PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000515PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800518 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 Py_XDECREF(name);
520 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000521}
522
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000523#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000524PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000525PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 PyObject *name = filename ?
528 PyUnicode_FromUnicode(filename, wcslen(filename)) :
529 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800530 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 Py_XDECREF(name);
532 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000533}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000534#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000535
536PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000537PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000538{
Larry Hastingsb0827312014-02-09 22:05:19 -0800539 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000540}
Guido van Rossum683a0721990-10-21 22:09:12 +0000541
Brett Cannonbf364092006-03-01 04:25:17 +0000542#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000543/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000544PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 PyObject *exc,
546 int ierr,
547 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000548{
Larry Hastingsb0827312014-02-09 22:05:19 -0800549 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
550 filenameObject, NULL);
551}
552
553PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
554 PyObject *exc,
555 int ierr,
556 PyObject *filenameObject,
557 PyObject *filenameObject2)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 int len;
560 WCHAR *s_buf = NULL; /* Free via LocalFree */
561 PyObject *message;
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200562 PyObject *args, *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 DWORD err = (DWORD)ierr;
564 if (err==0) err = GetLastError();
565 len = FormatMessageW(
566 /* Error API error */
567 FORMAT_MESSAGE_ALLOCATE_BUFFER |
568 FORMAT_MESSAGE_FROM_SYSTEM |
569 FORMAT_MESSAGE_IGNORE_INSERTS,
570 NULL, /* no message source */
571 err,
572 MAKELANGID(LANG_NEUTRAL,
573 SUBLANG_DEFAULT), /* Default language */
574 (LPWSTR) &s_buf,
575 0, /* size not used */
576 NULL); /* no args */
577 if (len==0) {
578 /* Only seen this in out of mem situations */
579 message = PyUnicode_FromFormat("Windows Error 0x%X", err);
580 s_buf = NULL;
581 } else {
582 /* remove trailing cr/lf and dots */
583 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
584 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200585 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 if (message == NULL)
589 {
590 LocalFree(s_buf);
591 return NULL;
592 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000593
Larry Hastingsb0827312014-02-09 22:05:19 -0800594 if (filenameObject == NULL) {
595 assert(filenameObject2 == NULL);
596 filenameObject = filenameObject2 = Py_None;
597 }
598 else if (filenameObject2 == NULL)
599 filenameObject2 = Py_None;
600 /* This is the constructor signature for OSError.
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200601 The POSIX translation will be figured out by the constructor. */
Larry Hastingsb0827312014-02-09 22:05:19 -0800602 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000604
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200605 if (args != NULL) {
606 v = PyObject_Call(exc, args, NULL);
607 Py_DECREF(args);
608 if (v != NULL) {
609 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
610 Py_DECREF(v);
611 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 }
613 LocalFree(s_buf);
614 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000615}
616
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000617PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 PyObject *exc,
619 int ierr,
620 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000621{
Victor Stinner92be9392010-12-28 00:28:21 +0000622 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800623 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800625 name,
626 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 Py_XDECREF(name);
628 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000629}
630
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000631PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyObject *exc,
633 int ierr,
634 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyObject *name = filename ?
637 PyUnicode_FromUnicode(filename, wcslen(filename)) :
638 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800639 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800641 name,
642 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 Py_XDECREF(name);
644 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000645}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000646
Thomas Heller085358a2002-07-29 14:27:41 +0000647PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
648{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800649 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000650}
651
Guido van Rossum795e1892000-02-17 15:19:15 +0000652PyObject *PyErr_SetFromWindowsErr(int ierr)
653{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800654 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
655 ierr, NULL);
Larry Hastingsb0827312014-02-09 22:05:19 -0800656}
657
Thomas Heller085358a2002-07-29 14:27:41 +0000658PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 int ierr,
660 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000661{
Victor Stinner92be9392010-12-28 00:28:21 +0000662 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800663 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200664 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800665 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 Py_XDECREF(name);
667 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000668}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000669
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000670PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 int ierr,
672 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyObject *name = filename ?
675 PyUnicode_FromUnicode(filename, wcslen(filename)) :
676 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800677 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200678 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800679 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 Py_XDECREF(name);
681 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000682}
Guido van Rossum795e1892000-02-17 15:19:15 +0000683#endif /* MS_WINDOWS */
684
Brett Cannon79ec55e2012-04-12 20:24:54 -0400685PyObject *
Brett Cannon82da8882013-07-04 17:48:16 -0400686PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Brett Cannon79ec55e2012-04-12 20:24:54 -0400687{
Brian Curtin09b86d12012-04-17 16:57:09 -0500688 PyObject *args, *kwargs, *error;
689
Brett Cannon82da8882013-07-04 17:48:16 -0400690 if (msg == NULL)
Brian Curtin94c001b2012-04-18 08:30:51 -0500691 return NULL;
692
Antoine Pitrouec9bac42012-04-18 16:57:54 +0200693 args = PyTuple_New(1);
Brian Curtin09b86d12012-04-17 16:57:09 -0500694 if (args == NULL)
695 return NULL;
696
697 kwargs = PyDict_New();
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400698 if (kwargs == NULL) {
699 Py_DECREF(args);
Brian Curtin09b86d12012-04-17 16:57:09 -0500700 return NULL;
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400701 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500702
Brian Curtin94c001b2012-04-18 08:30:51 -0500703 if (name == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500704 name = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500705 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500706
Brian Curtin94c001b2012-04-18 08:30:51 -0500707 if (path == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500708 path = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500709 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500710
711 Py_INCREF(msg);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400712 PyTuple_SET_ITEM(args, 0, msg);
Victor Stinner479054b2013-07-17 21:54:25 +0200713
714 if (PyDict_SetItemString(kwargs, "name", name) < 0)
715 return NULL;
716 if (PyDict_SetItemString(kwargs, "path", path) < 0)
717 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400718
Brett Cannon82da8882013-07-04 17:48:16 -0400719 error = PyObject_Call(PyExc_ImportError, args, kwargs);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400720 if (error != NULL) {
721 PyErr_SetObject((PyObject *)Py_TYPE(error), error);
Brian Curtin09b86d12012-04-17 16:57:09 -0500722 Py_DECREF(error);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400723 }
724
Brett Cannon79ec55e2012-04-12 20:24:54 -0400725 Py_DECREF(args);
726 Py_DECREF(kwargs);
727
Brian Curtin09b86d12012-04-17 16:57:09 -0500728 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400729}
730
Guido van Rossum683a0721990-10-21 22:09:12 +0000731void
Neal Norwitzb382b842007-08-24 20:00:37 +0000732_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyErr_Format(PyExc_SystemError,
735 "%s:%d: bad argument to internal function",
736 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000737}
738
739/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
740 export the entry point for existing object code: */
741#undef PyErr_BadInternalCall
742void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000743PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000744{
Victor Stinnerfb3a6302013-07-12 00:37:30 +0200745 assert(0 && "bad argument to internal function");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyErr_Format(PyExc_SystemError,
747 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000748}
Fred Drake6d63adf2000-08-24 22:38:39 +0000749#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
750
Guido van Rossum1548bac1997-02-14 17:09:47 +0000751
752
Guido van Rossum1548bac1997-02-14 17:09:47 +0000753PyObject *
754PyErr_Format(PyObject *exception, const char *format, ...)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 va_list vargs;
757 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000758
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000759#ifdef HAVE_STDARG_PROTOTYPES
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 va_start(vargs, format);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000761#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 va_start(vargs);
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +0000763#endif
Guido van Rossum1548bac1997-02-14 17:09:47 +0000764
Victor Stinnerace47d72013-07-18 01:41:08 +0200765#ifdef Py_DEBUG
766 /* in debug mode, PyEval_EvalFrameEx() fails with an assertion error
767 if an exception is set when it is called */
768 PyErr_Clear();
769#endif
770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 string = PyUnicode_FromFormatV(format, vargs);
772 PyErr_SetObject(exception, string);
773 Py_XDECREF(string);
774 va_end(vargs);
775 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000776}
Guido van Rossum7617e051997-09-16 18:43:50 +0000777
778
Thomas Wouters477c8d52006-05-27 19:21:47 +0000779
Guido van Rossum7617e051997-09-16 18:43:50 +0000780PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000781PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 const char *dot;
784 PyObject *modulename = NULL;
785 PyObject *classname = NULL;
786 PyObject *mydict = NULL;
787 PyObject *bases = NULL;
788 PyObject *result = NULL;
789 dot = strrchr(name, '.');
790 if (dot == NULL) {
791 PyErr_SetString(PyExc_SystemError,
792 "PyErr_NewException: name must be module.class");
793 return NULL;
794 }
795 if (base == NULL)
796 base = PyExc_Exception;
797 if (dict == NULL) {
798 dict = mydict = PyDict_New();
799 if (dict == NULL)
800 goto failure;
801 }
802 if (PyDict_GetItemString(dict, "__module__") == NULL) {
803 modulename = PyUnicode_FromStringAndSize(name,
804 (Py_ssize_t)(dot-name));
805 if (modulename == NULL)
806 goto failure;
807 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
808 goto failure;
809 }
810 if (PyTuple_Check(base)) {
811 bases = base;
812 /* INCREF as we create a new ref in the else branch */
813 Py_INCREF(bases);
814 } else {
815 bases = PyTuple_Pack(1, base);
816 if (bases == NULL)
817 goto failure;
818 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100819 /* Create a real class. */
Victor Stinner7eeb5b52010-06-07 19:57:46 +0000820 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000822 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 Py_XDECREF(bases);
824 Py_XDECREF(mydict);
825 Py_XDECREF(classname);
826 Py_XDECREF(modulename);
827 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000828}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000829
Georg Brandl1e28a272009-12-28 08:41:01 +0000830
831/* Create an exception with docstring */
832PyObject *
833PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 int result;
837 PyObject *ret = NULL;
838 PyObject *mydict = NULL; /* points to the dict only if we create it */
839 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (dict == NULL) {
842 dict = mydict = PyDict_New();
843 if (dict == NULL) {
844 return NULL;
845 }
846 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (doc != NULL) {
849 docobj = PyUnicode_FromString(doc);
850 if (docobj == NULL)
851 goto failure;
852 result = PyDict_SetItemString(dict, "__doc__", docobj);
853 Py_DECREF(docobj);
854 if (result < 0)
855 goto failure;
856 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000859 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 Py_XDECREF(mydict);
861 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000862}
863
864
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000865/* Call when an exception has occurred but there is no way for Python
866 to handle it. Examples: exception in __del__ or during GC. */
867void
868PyErr_WriteUnraisable(PyObject *obj)
869{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200870 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 PyObject *f, *t, *v, *tb;
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200872 PyObject *moduleName = NULL;
873 char* className;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000874
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200875 PyErr_Fetch(&t, &v, &tb);
876
Victor Stinnerbd303c12013-11-07 23:07:29 +0100877 f = _PySys_GetObjectId(&PyId_stderr);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200878 if (f == NULL || f == Py_None)
879 goto done;
880
881 if (obj) {
882 if (PyFile_WriteString("Exception ignored in: ", f) < 0)
883 goto done;
884 if (PyFile_WriteObject(obj, f, 0) < 0)
885 goto done;
886 if (PyFile_WriteString("\n", f) < 0)
887 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200889
890 if (PyTraceBack_Print(tb, f) < 0)
891 goto done;
892
893 if (!t)
894 goto done;
895
896 assert(PyExceptionClass_Check(t));
897 className = PyExceptionClass_Name(t);
898 if (className != NULL) {
899 char *dot = strrchr(className, '.');
900 if (dot != NULL)
901 className = dot+1;
902 }
903
904 moduleName = _PyObject_GetAttrId(t, &PyId___module__);
905 if (moduleName == NULL) {
906 PyErr_Clear();
907 if (PyFile_WriteString("<unknown>", f) < 0)
908 goto done;
909 }
910 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100911 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200912 if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
913 goto done;
914 if (PyFile_WriteString(".", f) < 0)
915 goto done;
916 }
917 }
918 if (className == NULL) {
919 if (PyFile_WriteString("<unknown>", f) < 0)
920 goto done;
921 }
922 else {
923 if (PyFile_WriteString(className, f) < 0)
924 goto done;
925 }
926
927 if (v && v != Py_None) {
928 if (PyFile_WriteString(": ", f) < 0)
929 goto done;
930 if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0)
931 goto done;
932 }
933 if (PyFile_WriteString("\n", f) < 0)
934 goto done;
935
936done:
937 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 Py_XDECREF(t);
939 Py_XDECREF(v);
940 Py_XDECREF(tb);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200941 PyErr_Clear(); /* Just in case */
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000942}
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000943
Armin Rigo092381a2003-10-25 14:29:27 +0000944extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000945
Guido van Rossum2fd45652001-02-28 21:46:24 +0000946
Benjamin Peterson2c539712010-09-20 22:42:10 +0000947void
Victor Stinner14e461d2013-08-26 22:28:21 +0200948PyErr_SyntaxLocation(const char *filename, int lineno)
949{
Benjamin Peterson2c539712010-09-20 22:42:10 +0000950 PyErr_SyntaxLocationEx(filename, lineno, -1);
951}
952
953
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000954/* Set file and line information for the current exception.
955 If the exception is not a SyntaxError, also sets additional attributes
956 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +0000957
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000958void
Victor Stinner14e461d2013-08-26 22:28:21 +0200959PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 PyObject *exc, *v, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200962 _Py_IDENTIFIER(filename);
963 _Py_IDENTIFIER(lineno);
964 _Py_IDENTIFIER(msg);
965 _Py_IDENTIFIER(offset);
966 _Py_IDENTIFIER(print_file_and_line);
967 _Py_IDENTIFIER(text);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 /* add attributes for the line number and filename for the error */
970 PyErr_Fetch(&exc, &v, &tb);
971 PyErr_NormalizeException(&exc, &v, &tb);
972 /* XXX check that it is, indeed, a syntax error. It might not
973 * be, though. */
974 tmp = PyLong_FromLong(lineno);
975 if (tmp == NULL)
976 PyErr_Clear();
977 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200978 if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyErr_Clear();
980 Py_DECREF(tmp);
981 }
Benjamin Peterson2c539712010-09-20 22:42:10 +0000982 if (col_offset >= 0) {
983 tmp = PyLong_FromLong(col_offset);
984 if (tmp == NULL)
985 PyErr_Clear();
986 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200987 if (_PyObject_SetAttrId(v, &PyId_offset, tmp))
Benjamin Peterson2c539712010-09-20 22:42:10 +0000988 PyErr_Clear();
989 Py_DECREF(tmp);
990 }
991 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (filename != NULL) {
Victor Stinner14e461d2013-08-26 22:28:21 +0200993 if (_PyObject_SetAttrId(v, &PyId_filename, filename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyErr_Clear();
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000995
Victor Stinner14e461d2013-08-26 22:28:21 +0200996 tmp = PyErr_ProgramTextObject(filename, lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200998 if (_PyObject_SetAttrId(v, &PyId_text, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyErr_Clear();
1000 Py_DECREF(tmp);
1001 }
1002 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001003 if (_PyObject_SetAttrId(v, &PyId_offset, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyErr_Clear();
1005 }
1006 if (exc != PyExc_SyntaxError) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001007 if (!_PyObject_HasAttrId(v, &PyId_msg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 tmp = PyObject_Str(v);
1009 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001010 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 PyErr_Clear();
1012 Py_DECREF(tmp);
1013 } else {
1014 PyErr_Clear();
1015 }
1016 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001017 if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1018 if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1019 Py_None))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyErr_Clear();
1021 }
1022 }
1023 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001024}
1025
Victor Stinner14e461d2013-08-26 22:28:21 +02001026void
1027PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1028{
1029 PyObject *fileobj;
1030 if (filename != NULL) {
1031 fileobj = PyUnicode_DecodeFSDefault(filename);
1032 if (fileobj == NULL)
1033 PyErr_Clear();
1034 }
1035 else
1036 fileobj = NULL;
1037 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1038 Py_XDECREF(fileobj);
1039}
1040
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001041/* Attempt to load the line of text that the exception refers to. If it
1042 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001043
1044 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001045 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001046
Antoine Pitrou409b5382013-10-12 22:41:17 +02001047static PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001048err_programtext(FILE *fp, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 int i;
1051 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 if (fp == NULL)
1054 return NULL;
1055 for (i = 0; i < lineno; i++) {
1056 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1057 do {
1058 *pLastChar = '\0';
1059 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1060 fp, NULL) == NULL)
1061 break;
1062 /* fgets read *something*; if it didn't get as
1063 far as pLastChar, it must have found a newline
1064 or hit the end of the file; if pLastChar is \n,
1065 it obviously found a newline; else we haven't
1066 yet seen a newline, so must continue */
1067 } while (*pLastChar != '\0' && *pLastChar != '\n');
1068 }
1069 fclose(fp);
1070 if (i == lineno) {
1071 char *p = linebuf;
1072 PyObject *res;
1073 while (*p == ' ' || *p == '\t' || *p == '\014')
1074 p++;
1075 res = PyUnicode_FromString(p);
1076 if (res == NULL)
1077 PyErr_Clear();
1078 return res;
1079 }
1080 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001081}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001082
Victor Stinner14e461d2013-08-26 22:28:21 +02001083PyObject *
1084PyErr_ProgramText(const char *filename, int lineno)
1085{
1086 FILE *fp;
1087 if (filename == NULL || *filename == '\0' || lineno <= 0)
1088 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001089 fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001090 return err_programtext(fp, lineno);
1091}
1092
1093PyObject *
1094PyErr_ProgramTextObject(PyObject *filename, int lineno)
1095{
1096 FILE *fp;
1097 if (filename == NULL || lineno <= 0)
1098 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001099 fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001100 return err_programtext(fp, lineno);
1101}
1102
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001103#ifdef __cplusplus
1104}
1105#endif