blob: 8c8ea1cd5772b562ebe3f4fd2ca9f45d00620082 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06005#include "internal/pystate.h"
Guido van Rossumf22120a1990-12-20 23:05:40 +00006
Guido van Rossum53e8d441995-03-09 12:11:31 +00007#ifndef __STDC__
Guido van Rossum7844e381997-04-11 20:44:04 +00008#ifndef MS_WINDOWS
Tim Petersdbd9ba62000-07-09 03:09:57 +00009extern char *strerror(int);
Guido van Rossum53e8d441995-03-09 12:11:31 +000010#endif
Guido van Rossum7844e381997-04-11 20:44:04 +000011#endif
Guido van Rossumf5401bd1990-11-02 17:50:28 +000012
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000013#ifdef MS_WINDOWS
Martin v. Löwis5d12abe2007-09-03 07:40:24 +000014#include <windows.h>
15#include <winbase.h>
Guido van Rossum743007d1999-04-21 15:27:31 +000016#endif
17
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +000018#include <ctype.h>
19
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#ifdef __cplusplus
21extern "C" {
22#endif
23
Victor Stinnerbd303c12013-11-07 23:07:29 +010024_Py_IDENTIFIER(builtins);
25_Py_IDENTIFIER(stderr);
26
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000028void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000029PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 PyThreadState *tstate = PyThreadState_GET();
32 PyObject *oldtype, *oldvalue, *oldtraceback;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 if (traceback != NULL && !PyTraceBack_Check(traceback)) {
35 /* XXX Should never happen -- fatal error instead? */
36 /* Well, it could be None. */
37 Py_DECREF(traceback);
38 traceback = NULL;
39 }
Guido van Rossuma027efa1997-05-05 20:56:21 +000040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041 /* Save these in locals to safeguard against recursive
42 invocation through Py_XDECREF */
43 oldtype = tstate->curexc_type;
44 oldvalue = tstate->curexc_value;
45 oldtraceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 tstate->curexc_type = type;
48 tstate->curexc_value = value;
49 tstate->curexc_traceback = traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +000050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 Py_XDECREF(oldtype);
52 Py_XDECREF(oldvalue);
53 Py_XDECREF(oldtraceback);
Guido van Rossum1ae940a1995-01-02 19:04:15 +000054}
55
Mark Shannonae3087c2017-10-22 22:41:51 +010056_PyErr_StackItem *
57_PyErr_GetTopmostException(PyThreadState *tstate)
58{
59 _PyErr_StackItem *exc_info = tstate->exc_info;
60 while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) &&
61 exc_info->previous_item != NULL)
62 {
63 exc_info = exc_info->previous_item;
64 }
65 return exc_info;
66}
67
Victor Stinner3a840972016-08-22 23:59:08 +020068static PyObject*
69_PyErr_CreateException(PyObject *exception, PyObject *value)
70{
71 if (value == NULL || value == Py_None) {
72 return _PyObject_CallNoArg(exception);
73 }
74 else if (PyTuple_Check(value)) {
75 return PyObject_Call(exception, value, NULL);
76 }
77 else {
Victor Stinner7bfb42d2016-12-05 17:04:32 +010078 return PyObject_CallFunctionObjArgs(exception, value, NULL);
Victor Stinner3a840972016-08-22 23:59:08 +020079 }
80}
81
Guido van Rossum1ae940a1995-01-02 19:04:15 +000082void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000083PyErr_SetObject(PyObject *exception, PyObject *value)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 PyThreadState *tstate = PyThreadState_GET();
86 PyObject *exc_value;
87 PyObject *tb = NULL;
Guido van Rossumb4fb6e42008-06-14 20:20:24 +000088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 if (exception != NULL &&
90 !PyExceptionClass_Check(exception)) {
91 PyErr_Format(PyExc_SystemError,
92 "exception %R not a BaseException subclass",
93 exception);
94 return;
95 }
Victor Stinner3a840972016-08-22 23:59:08 +020096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 Py_XINCREF(value);
Mark Shannonae3087c2017-10-22 22:41:51 +010098 exc_value = _PyErr_GetTopmostException(tstate)->exc_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 if (exc_value != NULL && exc_value != Py_None) {
100 /* Implicit exception chaining */
101 Py_INCREF(exc_value);
102 if (value == NULL || !PyExceptionInstance_Check(value)) {
103 /* We must normalize the value right now */
Victor Stinner3a840972016-08-22 23:59:08 +0200104 PyObject *fixed_value;
Victor Stinnerde821be2015-03-24 12:41:23 +0100105
Victor Stinner3a840972016-08-22 23:59:08 +0200106 /* Issue #23571: functions must not be called with an
Victor Stinnerde821be2015-03-24 12:41:23 +0100107 exception set */
Victor Stinnerace47d72013-07-18 01:41:08 +0200108 PyErr_Clear();
Victor Stinnerde821be2015-03-24 12:41:23 +0100109
Victor Stinner3a840972016-08-22 23:59:08 +0200110 fixed_value = _PyErr_CreateException(exception, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 Py_XDECREF(value);
Victor Stinner3a840972016-08-22 23:59:08 +0200112 if (fixed_value == NULL) {
Miss Islington (bot)2caf86f2018-08-26 13:13:47 -0400113 Py_DECREF(exc_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 return;
Victor Stinner3a840972016-08-22 23:59:08 +0200115 }
116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 value = fixed_value;
118 }
Victor Stinner3a840972016-08-22 23:59:08 +0200119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 /* Avoid reference cycles through the context chain.
121 This is O(chain length) but context chains are
122 usually very short. Sensitive readers may try
123 to inline the call to PyException_GetContext. */
124 if (exc_value != value) {
125 PyObject *o = exc_value, *context;
126 while ((context = PyException_GetContext(o))) {
127 Py_DECREF(context);
128 if (context == value) {
129 PyException_SetContext(o, NULL);
130 break;
131 }
132 o = context;
133 }
134 PyException_SetContext(value, exc_value);
Victor Stinner3a840972016-08-22 23:59:08 +0200135 }
136 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 Py_DECREF(exc_value);
138 }
139 }
140 if (value != NULL && PyExceptionInstance_Check(value))
141 tb = PyException_GetTraceback(value);
142 Py_XINCREF(exception);
143 PyErr_Restore(exception, value, tb);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144}
145
Raymond Hettinger69492da2013-09-02 15:59:26 -0700146/* Set a key error with the specified argument, wrapping it in a
147 * tuple automatically so that tuple keys are not unpacked as the
148 * exception arguments. */
149void
150_PyErr_SetKeyError(PyObject *arg)
151{
152 PyObject *tup;
153 tup = PyTuple_Pack(1, arg);
154 if (!tup)
155 return; /* caller will expect error to be set anyway */
156 PyErr_SetObject(PyExc_KeyError, tup);
157 Py_DECREF(tup);
158}
159
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000161PyErr_SetNone(PyObject *exception)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
166void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000167PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 PyObject *value = PyUnicode_FromString(string);
170 PyErr_SetObject(exception, value);
171 Py_XDECREF(value);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000172}
173
Guido van Rossum3a241811994-08-29 12:14:12 +0000174
Victor Stinnerc6944e72016-11-11 02:13:35 +0100175PyObject* _Py_HOT_FUNCTION
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000176PyErr_Occurred(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000177{
Victor Stinner0cae6092016-11-11 01:43:56 +0100178 PyThreadState *tstate = PyThreadState_GET();
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +0000179 return tstate == NULL ? NULL : tstate->curexc_type;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180}
181
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000182
183int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000184PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (err == NULL || exc == NULL) {
187 /* maybe caused by "import exceptions" that failed early on */
188 return 0;
189 }
190 if (PyTuple_Check(exc)) {
191 Py_ssize_t i, n;
192 n = PyTuple_Size(exc);
193 for (i = 0; i < n; i++) {
194 /* Test recursively */
195 if (PyErr_GivenExceptionMatches(
196 err, PyTuple_GET_ITEM(exc, i)))
197 {
198 return 1;
199 }
200 }
201 return 0;
202 }
203 /* err might be an instance, so check its class. */
204 if (PyExceptionInstance_Check(err))
205 err = PyExceptionInstance_Class(err);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
scodere4c06bc2017-07-31 22:27:46 +0200208 return PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 return err == exc;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000212}
Guido van Rossum743007d1999-04-21 15:27:31 +0000213
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000214
215int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000216PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000219}
220
221
xdegaye56d1f5c2017-10-26 15:09:06 +0200222#ifndef Py_NORMALIZE_RECURSION_LIMIT
223#define Py_NORMALIZE_RECURSION_LIMIT 32
224#endif
225
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000226/* Used in many places to normalize a raised exception, including in
227 eval_code2(), do_raise(), and PyErr_Print()
Benjamin Petersone6528212008-07-15 15:32:09 +0000228
229 XXX: should PyErr_NormalizeException() also call
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 PyException_SetTraceback() with the resulting value and tb?
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000231*/
Serhiy Storchakacf296532017-11-05 11:27:48 +0200232void
233PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000234{
Serhiy Storchakacf296532017-11-05 11:27:48 +0200235 int recursion_depth = 0;
236 PyObject *type, *value, *initial_tb;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000237
Serhiy Storchakacf296532017-11-05 11:27:48 +0200238 restart:
239 type = *exc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (type == NULL) {
241 /* There was no exception, so nothing to do. */
242 return;
243 }
Guido van Rossumed473a42000-08-07 19:18:27 +0000244
Serhiy Storchakacf296532017-11-05 11:27:48 +0200245 value = *val;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 /* If PyErr_SetNone() was used, the value will have been actually
247 set to NULL.
248 */
249 if (!value) {
250 value = Py_None;
251 Py_INCREF(value);
252 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 /* Normalize the exception so that if the type is a class, the
255 value will be an instance.
256 */
257 if (PyExceptionClass_Check(type)) {
Serhiy Storchakacf296532017-11-05 11:27:48 +0200258 PyObject *inclass = NULL;
259 int is_subclass = 0;
Victor Stinner74a7fa62013-07-17 00:44:53 +0200260
Serhiy Storchakacf296532017-11-05 11:27:48 +0200261 if (PyExceptionInstance_Check(value)) {
262 inclass = PyExceptionInstance_Class(value);
263 is_subclass = PyObject_IsSubclass(inclass, type);
264 if (is_subclass < 0) {
265 goto error;
266 }
267 }
268
269 /* If the value was not an instance, or is not an instance
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 whose class is (or is derived from) type, then use the
271 value as an argument to instantiation of the type
272 class.
273 */
Serhiy Storchakacf296532017-11-05 11:27:48 +0200274 if (!is_subclass) {
275 PyObject *fixed_value = _PyErr_CreateException(type, value);
Victor Stinner3a840972016-08-22 23:59:08 +0200276 if (fixed_value == NULL) {
Serhiy Storchakacf296532017-11-05 11:27:48 +0200277 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 Py_DECREF(value);
Victor Stinner3a840972016-08-22 23:59:08 +0200280 value = fixed_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 }
Serhiy Storchakacf296532017-11-05 11:27:48 +0200282 /* If the class of the instance doesn't exactly match the
283 class of the type, believe the instance.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 */
285 else if (inclass != type) {
Serhiy Storchakacf296532017-11-05 11:27:48 +0200286 Py_INCREF(inclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 Py_DECREF(type);
288 type = inclass;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 }
290 }
291 *exc = type;
292 *val = value;
293 return;
Serhiy Storchakacf296532017-11-05 11:27:48 +0200294
295 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 Py_DECREF(type);
297 Py_DECREF(value);
Serhiy Storchakacf296532017-11-05 11:27:48 +0200298 recursion_depth++;
299 if (recursion_depth == Py_NORMALIZE_RECURSION_LIMIT) {
xdegaye56d1f5c2017-10-26 15:09:06 +0200300 PyErr_SetString(PyExc_RecursionError, "maximum recursion depth "
301 "exceeded while normalizing an exception");
302 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 /* If the new exception doesn't set a traceback and the old
304 exception had a traceback, use the old traceback for the
305 new exception. It's better than nothing.
306 */
307 initial_tb = *tb;
308 PyErr_Fetch(exc, val, tb);
Serhiy Storchakacf296532017-11-05 11:27:48 +0200309 assert(*exc != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (initial_tb != NULL) {
311 if (*tb == NULL)
312 *tb = initial_tb;
313 else
314 Py_DECREF(initial_tb);
315 }
Serhiy Storchakacf296532017-11-05 11:27:48 +0200316 /* Abort when Py_NORMALIZE_RECURSION_LIMIT has been exceeded, and the
317 corresponding RecursionError could not be normalized, and the
318 MemoryError raised when normalize this RecursionError could not be
319 normalized. */
320 if (recursion_depth >= Py_NORMALIZE_RECURSION_LIMIT + 2) {
xdegaye56d1f5c2017-10-26 15:09:06 +0200321 if (PyErr_GivenExceptionMatches(*exc, PyExc_MemoryError)) {
322 Py_FatalError("Cannot recover from MemoryErrors "
323 "while normalizing exceptions.");
324 }
325 else {
326 Py_FatalError("Cannot recover from the recursive normalization "
327 "of an exception.");
328 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 }
Serhiy Storchakacf296532017-11-05 11:27:48 +0200330 goto restart;
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
Mark Shannonae3087c2017-10-22 22:41:51 +0100359 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
360 *p_type = exc_info->exc_type;
361 *p_value = exc_info->exc_value;
362 *p_traceback = exc_info->exc_traceback;
363
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200364
365 Py_XINCREF(*p_type);
366 Py_XINCREF(*p_value);
367 Py_XINCREF(*p_traceback);
368}
369
370void
371PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
372{
373 PyObject *oldtype, *oldvalue, *oldtraceback;
374 PyThreadState *tstate = PyThreadState_GET();
375
Mark Shannonae3087c2017-10-22 22:41:51 +0100376 oldtype = tstate->exc_info->exc_type;
377 oldvalue = tstate->exc_info->exc_value;
378 oldtraceback = tstate->exc_info->exc_traceback;
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200379
Mark Shannonae3087c2017-10-22 22:41:51 +0100380 tstate->exc_info->exc_type = p_type;
381 tstate->exc_info->exc_value = p_value;
382 tstate->exc_info->exc_traceback = p_traceback;
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200383
384 Py_XDECREF(oldtype);
385 Py_XDECREF(oldvalue);
386 Py_XDECREF(oldtraceback);
387}
388
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300389/* Like PyErr_Restore(), but if an exception is already set,
390 set the context associated with it.
391 */
392void
393_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
394{
395 if (exc == NULL)
396 return;
397
398 if (PyErr_Occurred()) {
399 PyObject *exc2, *val2, *tb2;
400 PyErr_Fetch(&exc2, &val2, &tb2);
401 PyErr_NormalizeException(&exc, &val, &tb);
Serhiy Storchaka9e373be2016-10-21 16:19:59 +0300402 if (tb != NULL) {
403 PyException_SetTraceback(val, tb);
404 Py_DECREF(tb);
405 }
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300406 Py_DECREF(exc);
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300407 PyErr_NormalizeException(&exc2, &val2, &tb2);
408 PyException_SetContext(val2, val);
409 PyErr_Restore(exc2, val2, tb2);
410 }
411 else {
412 PyErr_Restore(exc, val, tb);
413 }
414}
415
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300416static PyObject *
417_PyErr_FormatVFromCause(PyObject *exception, const char *format, va_list vargs)
418{
419 PyObject *exc, *val, *val2, *tb;
420
421 assert(PyErr_Occurred());
422 PyErr_Fetch(&exc, &val, &tb);
423 PyErr_NormalizeException(&exc, &val, &tb);
424 if (tb != NULL) {
425 PyException_SetTraceback(val, tb);
426 Py_DECREF(tb);
427 }
428 Py_DECREF(exc);
429 assert(!PyErr_Occurred());
430
431 PyErr_FormatV(exception, format, vargs);
432
433 PyErr_Fetch(&exc, &val2, &tb);
434 PyErr_NormalizeException(&exc, &val2, &tb);
435 Py_INCREF(val);
436 PyException_SetCause(val2, val);
437 PyException_SetContext(val2, val);
438 PyErr_Restore(exc, val2, tb);
439
440 return NULL;
441}
442
443PyObject *
444_PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
445{
446 va_list vargs;
447#ifdef HAVE_STDARG_PROTOTYPES
448 va_start(vargs, format);
449#else
450 va_start(vargs);
451#endif
452 _PyErr_FormatVFromCause(exception, format, vargs);
453 va_end(vargs);
454 return NULL;
455}
456
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000457/* Convenience functions to set a type error exception and return 0 */
458
459int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000460PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PyErr_SetString(PyExc_TypeError,
463 "bad argument type for built-in operation");
464 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000465}
466
Guido van Rossum373c8691997-04-29 18:22:47 +0000467PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000468PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000469{
Victor Stinnerf54a5742013-07-22 22:28:37 +0200470 if (Py_TYPE(PyExc_MemoryError) == NULL) {
471 /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
472 initialized by _PyExc_Init() */
473 Py_FatalError("Out of memory and PyExc_MemoryError is not "
474 "initialized yet");
475 }
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000476 PyErr_SetNone(PyExc_MemoryError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000478}
479
Guido van Rossum373c8691997-04-29 18:22:47 +0000480PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000481PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000482{
Larry Hastingsb0827312014-02-09 22:05:19 -0800483 return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
484}
485
486PyObject *
487PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 PyObject *message;
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200490 PyObject *v, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 int i = errno;
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100492#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 WCHAR *s_buf = NULL;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000494#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000495
Guido van Rossume9fbc091995-02-18 14:52:19 +0000496#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (i == EINTR && PyErr_CheckSignals())
498 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000499#endif
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000500
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000501#ifndef MS_WINDOWS
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100502 if (i != 0) {
503 char *s = strerror(i);
Victor Stinner1b579672011-12-17 05:47:23 +0100504 message = PyUnicode_DecodeLocale(s, "surrogateescape");
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100505 }
506 else {
507 /* Sometimes errno didn't get set */
508 message = PyUnicode_FromString("Error");
509 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000510#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (i == 0)
512 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
513 else
514 {
515 /* Note that the Win32 errors do not lineup with the
516 errno error. So if the error is in the MSVC error
517 table, we use it, otherwise we assume it really _is_
518 a Win32 error code
519 */
520 if (i > 0 && i < _sys_nerr) {
521 message = PyUnicode_FromString(_sys_errlist[i]);
522 }
523 else {
524 int len = FormatMessageW(
525 FORMAT_MESSAGE_ALLOCATE_BUFFER |
526 FORMAT_MESSAGE_FROM_SYSTEM |
527 FORMAT_MESSAGE_IGNORE_INSERTS,
528 NULL, /* no message source */
529 i,
530 MAKELANGID(LANG_NEUTRAL,
531 SUBLANG_DEFAULT),
532 /* Default language */
533 (LPWSTR) &s_buf,
534 0, /* size not used */
535 NULL); /* no args */
536 if (len==0) {
537 /* Only ever seen this in out-of-mem
538 situations */
539 s_buf = NULL;
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300540 message = PyUnicode_FromFormat("Windows Error 0x%x", i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 } else {
542 /* remove trailing cr/lf and dots */
543 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
544 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200545 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 }
547 }
548 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000549#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (message == NULL)
552 {
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000553#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 LocalFree(s_buf);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000555#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return NULL;
557 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000558
Larry Hastingsb0827312014-02-09 22:05:19 -0800559 if (filenameObject != NULL) {
560 if (filenameObject2 != NULL)
561 args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
562 else
563 args = Py_BuildValue("(iOO)", i, message, filenameObject);
564 } else {
565 assert(filenameObject2 == NULL);
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200566 args = Py_BuildValue("(iO)", i, message);
Larry Hastingsb0827312014-02-09 22:05:19 -0800567 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000569
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200570 if (args != NULL) {
571 v = PyObject_Call(exc, args, NULL);
572 Py_DECREF(args);
573 if (v != NULL) {
574 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
575 Py_DECREF(v);
576 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000578#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000580#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000582}
Guido van Rossum743007d1999-04-21 15:27:31 +0000583
Barry Warsaw97d95151998-07-23 16:05:56 +0000584PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000585PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800588 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 Py_XDECREF(name);
590 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000591}
592
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000593#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000594PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000595PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000596{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200597 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800598 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 Py_XDECREF(name);
600 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000601}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000602#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000603
604PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000605PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000606{
Larry Hastingsb0827312014-02-09 22:05:19 -0800607 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000608}
Guido van Rossum683a0721990-10-21 22:09:12 +0000609
Brett Cannonbf364092006-03-01 04:25:17 +0000610#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000611/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000612PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 PyObject *exc,
614 int ierr,
615 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000616{
Larry Hastingsb0827312014-02-09 22:05:19 -0800617 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
618 filenameObject, NULL);
619}
620
621PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
622 PyObject *exc,
623 int ierr,
624 PyObject *filenameObject,
625 PyObject *filenameObject2)
626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 int len;
628 WCHAR *s_buf = NULL; /* Free via LocalFree */
629 PyObject *message;
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200630 PyObject *args, *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 DWORD err = (DWORD)ierr;
632 if (err==0) err = GetLastError();
633 len = FormatMessageW(
634 /* Error API error */
635 FORMAT_MESSAGE_ALLOCATE_BUFFER |
636 FORMAT_MESSAGE_FROM_SYSTEM |
637 FORMAT_MESSAGE_IGNORE_INSERTS,
638 NULL, /* no message source */
639 err,
640 MAKELANGID(LANG_NEUTRAL,
641 SUBLANG_DEFAULT), /* Default language */
642 (LPWSTR) &s_buf,
643 0, /* size not used */
644 NULL); /* no args */
645 if (len==0) {
646 /* Only seen this in out of mem situations */
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300647 message = PyUnicode_FromFormat("Windows Error 0x%x", err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 s_buf = NULL;
649 } else {
650 /* remove trailing cr/lf and dots */
651 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
652 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200653 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (message == NULL)
657 {
658 LocalFree(s_buf);
659 return NULL;
660 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000661
Larry Hastingsb0827312014-02-09 22:05:19 -0800662 if (filenameObject == NULL) {
663 assert(filenameObject2 == NULL);
664 filenameObject = filenameObject2 = Py_None;
665 }
666 else if (filenameObject2 == NULL)
667 filenameObject2 = Py_None;
668 /* This is the constructor signature for OSError.
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200669 The POSIX translation will be figured out by the constructor. */
Larry Hastingsb0827312014-02-09 22:05:19 -0800670 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000672
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200673 if (args != NULL) {
674 v = PyObject_Call(exc, args, NULL);
675 Py_DECREF(args);
676 if (v != NULL) {
677 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
678 Py_DECREF(v);
679 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 }
681 LocalFree(s_buf);
682 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000683}
684
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000685PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyObject *exc,
687 int ierr,
688 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000689{
Victor Stinner92be9392010-12-28 00:28:21 +0000690 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800691 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800693 name,
694 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 Py_XDECREF(name);
696 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000697}
698
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000699PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyObject *exc,
701 int ierr,
702 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000703{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200704 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800705 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800707 name,
708 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 Py_XDECREF(name);
710 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000711}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000712
Thomas Heller085358a2002-07-29 14:27:41 +0000713PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
714{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800715 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000716}
717
Guido van Rossum795e1892000-02-17 15:19:15 +0000718PyObject *PyErr_SetFromWindowsErr(int ierr)
719{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800720 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
721 ierr, NULL);
Larry Hastingsb0827312014-02-09 22:05:19 -0800722}
723
Thomas Heller085358a2002-07-29 14:27:41 +0000724PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 int ierr,
726 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000727{
Victor Stinner92be9392010-12-28 00:28:21 +0000728 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800729 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200730 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800731 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 Py_XDECREF(name);
733 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000734}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000735
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000736PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 int ierr,
738 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000739{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200740 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800741 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200742 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800743 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 Py_XDECREF(name);
745 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000746}
Guido van Rossum795e1892000-02-17 15:19:15 +0000747#endif /* MS_WINDOWS */
748
Brett Cannon79ec55e2012-04-12 20:24:54 -0400749PyObject *
Eric Snow46f97b82016-09-07 16:56:15 -0700750PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
751 PyObject *name, PyObject *path)
Brett Cannon79ec55e2012-04-12 20:24:54 -0400752{
Eric Snow46f97b82016-09-07 16:56:15 -0700753 int issubclass;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200754 PyObject *kwargs, *error;
Brian Curtin09b86d12012-04-17 16:57:09 -0500755
Eric Snow46f97b82016-09-07 16:56:15 -0700756 issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
757 if (issubclass < 0) {
758 return NULL;
759 }
760 else if (!issubclass) {
761 PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError");
Brian Curtin94c001b2012-04-18 08:30:51 -0500762 return NULL;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200763 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500764
Eric Snow46f97b82016-09-07 16:56:15 -0700765 if (msg == NULL) {
766 PyErr_SetString(PyExc_TypeError, "expected a message argument");
Brian Curtin09b86d12012-04-17 16:57:09 -0500767 return NULL;
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400768 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500769
Brian Curtin94c001b2012-04-18 08:30:51 -0500770 if (name == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500771 name = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500772 }
Brian Curtin94c001b2012-04-18 08:30:51 -0500773 if (path == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500774 path = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500775 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500776
Eric Snow46f97b82016-09-07 16:56:15 -0700777 kwargs = PyDict_New();
778 if (kwargs == NULL) {
779 return NULL;
780 }
Victor Stinnerf45a5612016-08-23 00:04:41 +0200781 if (PyDict_SetItemString(kwargs, "name", name) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300782 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200783 }
784 if (PyDict_SetItemString(kwargs, "path", path) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300785 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200786 }
Brett Cannon79ec55e2012-04-12 20:24:54 -0400787
Eric Snow46f97b82016-09-07 16:56:15 -0700788 error = _PyObject_FastCallDict(exception, &msg, 1, kwargs);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400789 if (error != NULL) {
790 PyErr_SetObject((PyObject *)Py_TYPE(error), error);
Brian Curtin09b86d12012-04-17 16:57:09 -0500791 Py_DECREF(error);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400792 }
793
Berker Peksagec766d32016-05-01 09:06:36 +0300794done:
Brett Cannon79ec55e2012-04-12 20:24:54 -0400795 Py_DECREF(kwargs);
Brian Curtin09b86d12012-04-17 16:57:09 -0500796 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400797}
798
Eric Snow46f97b82016-09-07 16:56:15 -0700799PyObject *
800PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
801{
802 return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
803}
804
Guido van Rossum683a0721990-10-21 22:09:12 +0000805void
Neal Norwitzb382b842007-08-24 20:00:37 +0000806_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyErr_Format(PyExc_SystemError,
809 "%s:%d: bad argument to internal function",
810 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000811}
812
813/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
814 export the entry point for existing object code: */
815#undef PyErr_BadInternalCall
816void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000817PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000818{
Victor Stinnerfb3a6302013-07-12 00:37:30 +0200819 assert(0 && "bad argument to internal function");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyErr_Format(PyExc_SystemError,
821 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000822}
Fred Drake6d63adf2000-08-24 22:38:39 +0000823#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
824
Guido van Rossum1548bac1997-02-14 17:09:47 +0000825
Guido van Rossum1548bac1997-02-14 17:09:47 +0000826PyObject *
Antoine Pitrou0676a402014-09-30 21:16:27 +0200827PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000830
Victor Stinnerde821be2015-03-24 12:41:23 +0100831 /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
832 exception set, it calls arbitrary Python code like PyObject_Repr() */
Victor Stinnerace47d72013-07-18 01:41:08 +0200833 PyErr_Clear();
Victor Stinnerace47d72013-07-18 01:41:08 +0200834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 string = PyUnicode_FromFormatV(format, vargs);
Victor Stinnerde821be2015-03-24 12:41:23 +0100836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 PyErr_SetObject(exception, string);
838 Py_XDECREF(string);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000840}
Guido van Rossum7617e051997-09-16 18:43:50 +0000841
842
Antoine Pitrou0676a402014-09-30 21:16:27 +0200843PyObject *
844PyErr_Format(PyObject *exception, const char *format, ...)
845{
846 va_list vargs;
847#ifdef HAVE_STDARG_PROTOTYPES
848 va_start(vargs, format);
849#else
850 va_start(vargs);
851#endif
852 PyErr_FormatV(exception, format, vargs);
853 va_end(vargs);
854 return NULL;
855}
856
Thomas Wouters477c8d52006-05-27 19:21:47 +0000857
Guido van Rossum7617e051997-09-16 18:43:50 +0000858PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000859PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 const char *dot;
862 PyObject *modulename = NULL;
863 PyObject *classname = NULL;
864 PyObject *mydict = NULL;
865 PyObject *bases = NULL;
866 PyObject *result = NULL;
867 dot = strrchr(name, '.');
868 if (dot == NULL) {
869 PyErr_SetString(PyExc_SystemError,
870 "PyErr_NewException: name must be module.class");
871 return NULL;
872 }
873 if (base == NULL)
874 base = PyExc_Exception;
875 if (dict == NULL) {
876 dict = mydict = PyDict_New();
877 if (dict == NULL)
878 goto failure;
879 }
880 if (PyDict_GetItemString(dict, "__module__") == NULL) {
881 modulename = PyUnicode_FromStringAndSize(name,
882 (Py_ssize_t)(dot-name));
883 if (modulename == NULL)
884 goto failure;
885 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
886 goto failure;
887 }
888 if (PyTuple_Check(base)) {
889 bases = base;
890 /* INCREF as we create a new ref in the else branch */
891 Py_INCREF(bases);
892 } else {
893 bases = PyTuple_Pack(1, base);
894 if (bases == NULL)
895 goto failure;
896 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100897 /* Create a real class. */
Victor Stinner7eeb5b52010-06-07 19:57:46 +0000898 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000900 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 Py_XDECREF(bases);
902 Py_XDECREF(mydict);
903 Py_XDECREF(classname);
904 Py_XDECREF(modulename);
905 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000906}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000907
Georg Brandl1e28a272009-12-28 08:41:01 +0000908
909/* Create an exception with docstring */
910PyObject *
911PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 int result;
915 PyObject *ret = NULL;
916 PyObject *mydict = NULL; /* points to the dict only if we create it */
917 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (dict == NULL) {
920 dict = mydict = PyDict_New();
921 if (dict == NULL) {
922 return NULL;
923 }
924 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (doc != NULL) {
927 docobj = PyUnicode_FromString(doc);
928 if (docobj == NULL)
929 goto failure;
930 result = PyDict_SetItemString(dict, "__doc__", docobj);
931 Py_DECREF(docobj);
932 if (result < 0)
933 goto failure;
934 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000937 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 Py_XDECREF(mydict);
939 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000940}
941
942
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000943/* Call when an exception has occurred but there is no way for Python
944 to handle it. Examples: exception in __del__ or during GC. */
945void
946PyErr_WriteUnraisable(PyObject *obj)
947{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200948 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyObject *f, *t, *v, *tb;
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200950 PyObject *moduleName = NULL;
951 char* className;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000952
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200953 PyErr_Fetch(&t, &v, &tb);
954
Victor Stinnerbd303c12013-11-07 23:07:29 +0100955 f = _PySys_GetObjectId(&PyId_stderr);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200956 if (f == NULL || f == Py_None)
957 goto done;
958
959 if (obj) {
960 if (PyFile_WriteString("Exception ignored in: ", f) < 0)
961 goto done;
Martin Panter3263f682016-02-28 03:16:11 +0000962 if (PyFile_WriteObject(obj, f, 0) < 0) {
963 PyErr_Clear();
964 if (PyFile_WriteString("<object repr() failed>", f) < 0) {
965 goto done;
966 }
967 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200968 if (PyFile_WriteString("\n", f) < 0)
969 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200971
972 if (PyTraceBack_Print(tb, f) < 0)
973 goto done;
974
975 if (!t)
976 goto done;
977
978 assert(PyExceptionClass_Check(t));
979 className = PyExceptionClass_Name(t);
980 if (className != NULL) {
981 char *dot = strrchr(className, '.');
982 if (dot != NULL)
983 className = dot+1;
984 }
985
986 moduleName = _PyObject_GetAttrId(t, &PyId___module__);
Oren Milmanf6e61df2017-09-14 01:30:05 +0300987 if (moduleName == NULL || !PyUnicode_Check(moduleName)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200988 PyErr_Clear();
989 if (PyFile_WriteString("<unknown>", f) < 0)
990 goto done;
991 }
992 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200993 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200994 if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
995 goto done;
996 if (PyFile_WriteString(".", f) < 0)
997 goto done;
998 }
999 }
1000 if (className == NULL) {
1001 if (PyFile_WriteString("<unknown>", f) < 0)
1002 goto done;
1003 }
1004 else {
1005 if (PyFile_WriteString(className, f) < 0)
1006 goto done;
1007 }
1008
1009 if (v && v != Py_None) {
1010 if (PyFile_WriteString(": ", f) < 0)
1011 goto done;
Martin Panter3263f682016-02-28 03:16:11 +00001012 if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
1013 PyErr_Clear();
1014 if (PyFile_WriteString("<exception str() failed>", f) < 0) {
1015 goto done;
1016 }
1017 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001018 }
1019 if (PyFile_WriteString("\n", f) < 0)
1020 goto done;
1021
1022done:
1023 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 Py_XDECREF(t);
1025 Py_XDECREF(v);
1026 Py_XDECREF(tb);
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001027 PyErr_Clear(); /* Just in case */
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001028}
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001029
Armin Rigo092381a2003-10-25 14:29:27 +00001030extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001031
Guido van Rossum2fd45652001-02-28 21:46:24 +00001032
Benjamin Peterson2c539712010-09-20 22:42:10 +00001033void
Victor Stinner14e461d2013-08-26 22:28:21 +02001034PyErr_SyntaxLocation(const char *filename, int lineno)
1035{
Benjamin Peterson2c539712010-09-20 22:42:10 +00001036 PyErr_SyntaxLocationEx(filename, lineno, -1);
1037}
1038
1039
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001040/* Set file and line information for the current exception.
1041 If the exception is not a SyntaxError, also sets additional attributes
1042 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +00001043
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001044void
Victor Stinner14e461d2013-08-26 22:28:21 +02001045PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyObject *exc, *v, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001048 _Py_IDENTIFIER(filename);
1049 _Py_IDENTIFIER(lineno);
1050 _Py_IDENTIFIER(msg);
1051 _Py_IDENTIFIER(offset);
1052 _Py_IDENTIFIER(print_file_and_line);
1053 _Py_IDENTIFIER(text);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 /* add attributes for the line number and filename for the error */
1056 PyErr_Fetch(&exc, &v, &tb);
1057 PyErr_NormalizeException(&exc, &v, &tb);
1058 /* XXX check that it is, indeed, a syntax error. It might not
1059 * be, though. */
1060 tmp = PyLong_FromLong(lineno);
1061 if (tmp == NULL)
1062 PyErr_Clear();
1063 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001064 if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyErr_Clear();
1066 Py_DECREF(tmp);
1067 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001068 tmp = NULL;
Benjamin Peterson2c539712010-09-20 22:42:10 +00001069 if (col_offset >= 0) {
1070 tmp = PyLong_FromLong(col_offset);
1071 if (tmp == NULL)
1072 PyErr_Clear();
Benjamin Peterson2c539712010-09-20 22:42:10 +00001073 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001074 if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
1075 PyErr_Clear();
1076 Py_XDECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 if (filename != NULL) {
Victor Stinner14e461d2013-08-26 22:28:21 +02001078 if (_PyObject_SetAttrId(v, &PyId_filename, filename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 PyErr_Clear();
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001080
Victor Stinner14e461d2013-08-26 22:28:21 +02001081 tmp = PyErr_ProgramTextObject(filename, lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001083 if (_PyObject_SetAttrId(v, &PyId_text, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyErr_Clear();
1085 Py_DECREF(tmp);
1086 }
1087 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (exc != PyExc_SyntaxError) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001089 if (!_PyObject_HasAttrId(v, &PyId_msg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 tmp = PyObject_Str(v);
1091 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001092 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyErr_Clear();
1094 Py_DECREF(tmp);
1095 } else {
1096 PyErr_Clear();
1097 }
1098 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001099 if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1100 if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1101 Py_None))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 PyErr_Clear();
1103 }
1104 }
1105 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001106}
1107
Victor Stinner14e461d2013-08-26 22:28:21 +02001108void
1109PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1110{
1111 PyObject *fileobj;
1112 if (filename != NULL) {
1113 fileobj = PyUnicode_DecodeFSDefault(filename);
1114 if (fileobj == NULL)
1115 PyErr_Clear();
1116 }
1117 else
1118 fileobj = NULL;
1119 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1120 Py_XDECREF(fileobj);
1121}
1122
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001123/* Attempt to load the line of text that the exception refers to. If it
1124 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001125
1126 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001127 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001128
Antoine Pitrou409b5382013-10-12 22:41:17 +02001129static PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001130err_programtext(FILE *fp, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 int i;
1133 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (fp == NULL)
1136 return NULL;
1137 for (i = 0; i < lineno; i++) {
1138 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1139 do {
1140 *pLastChar = '\0';
1141 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1142 fp, NULL) == NULL)
1143 break;
1144 /* fgets read *something*; if it didn't get as
1145 far as pLastChar, it must have found a newline
1146 or hit the end of the file; if pLastChar is \n,
1147 it obviously found a newline; else we haven't
1148 yet seen a newline, so must continue */
1149 } while (*pLastChar != '\0' && *pLastChar != '\n');
1150 }
1151 fclose(fp);
1152 if (i == lineno) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 PyObject *res;
Martin Panterca3263c2016-12-11 00:18:36 +00001154 res = PyUnicode_FromString(linebuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (res == NULL)
1156 PyErr_Clear();
1157 return res;
1158 }
1159 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001160}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001161
Victor Stinner14e461d2013-08-26 22:28:21 +02001162PyObject *
1163PyErr_ProgramText(const char *filename, int lineno)
1164{
1165 FILE *fp;
1166 if (filename == NULL || *filename == '\0' || lineno <= 0)
1167 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001168 fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001169 return err_programtext(fp, lineno);
1170}
1171
1172PyObject *
1173PyErr_ProgramTextObject(PyObject *filename, int lineno)
1174{
1175 FILE *fp;
1176 if (filename == NULL || lineno <= 0)
1177 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001178 fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
Victor Stinnere42ccd22015-03-18 01:39:23 +01001179 if (fp == NULL) {
1180 PyErr_Clear();
1181 return NULL;
1182 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001183 return err_programtext(fp, lineno);
1184}
1185
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001186#ifdef __cplusplus
1187}
1188#endif