blob: 15e6ba057143371ff08ba07120ee5b76384ae688 [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) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 return;
Victor Stinner3a840972016-08-22 23:59:08 +0200114 }
115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 value = fixed_value;
117 }
Victor Stinner3a840972016-08-22 23:59:08 +0200118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 /* Avoid reference cycles through the context chain.
120 This is O(chain length) but context chains are
121 usually very short. Sensitive readers may try
122 to inline the call to PyException_GetContext. */
123 if (exc_value != value) {
124 PyObject *o = exc_value, *context;
125 while ((context = PyException_GetContext(o))) {
126 Py_DECREF(context);
127 if (context == value) {
128 PyException_SetContext(o, NULL);
129 break;
130 }
131 o = context;
132 }
133 PyException_SetContext(value, exc_value);
Victor Stinner3a840972016-08-22 23:59:08 +0200134 }
135 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 Py_DECREF(exc_value);
137 }
138 }
139 if (value != NULL && PyExceptionInstance_Check(value))
140 tb = PyException_GetTraceback(value);
141 Py_XINCREF(exception);
142 PyErr_Restore(exception, value, tb);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143}
144
Raymond Hettinger69492da2013-09-02 15:59:26 -0700145/* Set a key error with the specified argument, wrapping it in a
146 * tuple automatically so that tuple keys are not unpacked as the
147 * exception arguments. */
148void
149_PyErr_SetKeyError(PyObject *arg)
150{
151 PyObject *tup;
152 tup = PyTuple_Pack(1, arg);
153 if (!tup)
154 return; /* caller will expect error to be set anyway */
155 PyErr_SetObject(PyExc_KeyError, tup);
156 Py_DECREF(tup);
157}
158
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000160PyErr_SetNone(PyObject *exception)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
165void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000166PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 PyObject *value = PyUnicode_FromString(string);
169 PyErr_SetObject(exception, value);
170 Py_XDECREF(value);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000171}
172
Guido van Rossum3a241811994-08-29 12:14:12 +0000173
Victor Stinnerc6944e72016-11-11 02:13:35 +0100174PyObject* _Py_HOT_FUNCTION
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000175PyErr_Occurred(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000176{
Victor Stinner0cae6092016-11-11 01:43:56 +0100177 PyThreadState *tstate = PyThreadState_GET();
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +0000178 return tstate == NULL ? NULL : tstate->curexc_type;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179}
180
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000181
182int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000183PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 if (err == NULL || exc == NULL) {
186 /* maybe caused by "import exceptions" that failed early on */
187 return 0;
188 }
189 if (PyTuple_Check(exc)) {
190 Py_ssize_t i, n;
191 n = PyTuple_Size(exc);
192 for (i = 0; i < n; i++) {
193 /* Test recursively */
194 if (PyErr_GivenExceptionMatches(
195 err, PyTuple_GET_ITEM(exc, i)))
196 {
197 return 1;
198 }
199 }
200 return 0;
201 }
202 /* err might be an instance, so check its class. */
203 if (PyExceptionInstance_Check(err))
204 err = PyExceptionInstance_Class(err);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
scodere4c06bc2017-07-31 22:27:46 +0200207 return PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 return err == exc;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000211}
Guido van Rossum743007d1999-04-21 15:27:31 +0000212
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000213
214int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000215PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000218}
219
220
xdegaye56d1f5c2017-10-26 15:09:06 +0200221#ifndef Py_NORMALIZE_RECURSION_LIMIT
222#define Py_NORMALIZE_RECURSION_LIMIT 32
223#endif
224
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000225/* Used in many places to normalize a raised exception, including in
226 eval_code2(), do_raise(), and PyErr_Print()
Benjamin Petersone6528212008-07-15 15:32:09 +0000227
228 XXX: should PyErr_NormalizeException() also call
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 PyException_SetTraceback() with the resulting value and tb?
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000230*/
Serhiy Storchakacf296532017-11-05 11:27:48 +0200231void
232PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000233{
Serhiy Storchakacf296532017-11-05 11:27:48 +0200234 int recursion_depth = 0;
235 PyObject *type, *value, *initial_tb;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000236
Serhiy Storchakacf296532017-11-05 11:27:48 +0200237 restart:
238 type = *exc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (type == NULL) {
240 /* There was no exception, so nothing to do. */
241 return;
242 }
Guido van Rossumed473a42000-08-07 19:18:27 +0000243
Serhiy Storchakacf296532017-11-05 11:27:48 +0200244 value = *val;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 /* If PyErr_SetNone() was used, the value will have been actually
246 set to NULL.
247 */
248 if (!value) {
249 value = Py_None;
250 Py_INCREF(value);
251 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 /* Normalize the exception so that if the type is a class, the
254 value will be an instance.
255 */
256 if (PyExceptionClass_Check(type)) {
Serhiy Storchakacf296532017-11-05 11:27:48 +0200257 PyObject *inclass = NULL;
258 int is_subclass = 0;
Victor Stinner74a7fa62013-07-17 00:44:53 +0200259
Serhiy Storchakacf296532017-11-05 11:27:48 +0200260 if (PyExceptionInstance_Check(value)) {
261 inclass = PyExceptionInstance_Class(value);
262 is_subclass = PyObject_IsSubclass(inclass, type);
263 if (is_subclass < 0) {
264 goto error;
265 }
266 }
267
268 /* If the value was not an instance, or is not an instance
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 whose class is (or is derived from) type, then use the
270 value as an argument to instantiation of the type
271 class.
272 */
Serhiy Storchakacf296532017-11-05 11:27:48 +0200273 if (!is_subclass) {
274 PyObject *fixed_value = _PyErr_CreateException(type, value);
Victor Stinner3a840972016-08-22 23:59:08 +0200275 if (fixed_value == NULL) {
Serhiy Storchakacf296532017-11-05 11:27:48 +0200276 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 Py_DECREF(value);
Victor Stinner3a840972016-08-22 23:59:08 +0200279 value = fixed_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 }
Serhiy Storchakacf296532017-11-05 11:27:48 +0200281 /* If the class of the instance doesn't exactly match the
282 class of the type, believe the instance.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 */
284 else if (inclass != type) {
Serhiy Storchakacf296532017-11-05 11:27:48 +0200285 Py_INCREF(inclass);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 Py_DECREF(type);
287 type = inclass;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 }
289 }
290 *exc = type;
291 *val = value;
292 return;
Serhiy Storchakacf296532017-11-05 11:27:48 +0200293
294 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_DECREF(type);
296 Py_DECREF(value);
Serhiy Storchakacf296532017-11-05 11:27:48 +0200297 recursion_depth++;
298 if (recursion_depth == Py_NORMALIZE_RECURSION_LIMIT) {
xdegaye56d1f5c2017-10-26 15:09:06 +0200299 PyErr_SetString(PyExc_RecursionError, "maximum recursion depth "
300 "exceeded while normalizing an exception");
301 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 /* 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);
Serhiy Storchakacf296532017-11-05 11:27:48 +0200308 assert(*exc != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (initial_tb != NULL) {
310 if (*tb == NULL)
311 *tb = initial_tb;
312 else
313 Py_DECREF(initial_tb);
314 }
Serhiy Storchakacf296532017-11-05 11:27:48 +0200315 /* Abort when Py_NORMALIZE_RECURSION_LIMIT has been exceeded, and the
316 corresponding RecursionError could not be normalized, and the
317 MemoryError raised when normalize this RecursionError could not be
318 normalized. */
319 if (recursion_depth >= Py_NORMALIZE_RECURSION_LIMIT + 2) {
xdegaye56d1f5c2017-10-26 15:09:06 +0200320 if (PyErr_GivenExceptionMatches(*exc, PyExc_MemoryError)) {
321 Py_FatalError("Cannot recover from MemoryErrors "
322 "while normalizing exceptions.");
323 }
324 else {
325 Py_FatalError("Cannot recover from the recursive normalization "
326 "of an exception.");
327 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 }
Serhiy Storchakacf296532017-11-05 11:27:48 +0200329 goto restart;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000330}
331
332
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000334PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 *p_type = tstate->curexc_type;
339 *p_value = tstate->curexc_value;
340 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 tstate->curexc_type = NULL;
343 tstate->curexc_value = NULL;
344 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345}
346
347void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000348PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000352
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200353void
354PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
355{
356 PyThreadState *tstate = PyThreadState_GET();
357
Mark Shannonae3087c2017-10-22 22:41:51 +0100358 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
359 *p_type = exc_info->exc_type;
360 *p_value = exc_info->exc_value;
361 *p_traceback = exc_info->exc_traceback;
362
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200363
364 Py_XINCREF(*p_type);
365 Py_XINCREF(*p_value);
366 Py_XINCREF(*p_traceback);
367}
368
369void
370PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
371{
372 PyObject *oldtype, *oldvalue, *oldtraceback;
373 PyThreadState *tstate = PyThreadState_GET();
374
Mark Shannonae3087c2017-10-22 22:41:51 +0100375 oldtype = tstate->exc_info->exc_type;
376 oldvalue = tstate->exc_info->exc_value;
377 oldtraceback = tstate->exc_info->exc_traceback;
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200378
Mark Shannonae3087c2017-10-22 22:41:51 +0100379 tstate->exc_info->exc_type = p_type;
380 tstate->exc_info->exc_value = p_value;
381 tstate->exc_info->exc_traceback = p_traceback;
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200382
383 Py_XDECREF(oldtype);
384 Py_XDECREF(oldvalue);
385 Py_XDECREF(oldtraceback);
386}
387
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300388/* Like PyErr_Restore(), but if an exception is already set,
389 set the context associated with it.
390 */
391void
392_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
393{
394 if (exc == NULL)
395 return;
396
397 if (PyErr_Occurred()) {
398 PyObject *exc2, *val2, *tb2;
399 PyErr_Fetch(&exc2, &val2, &tb2);
400 PyErr_NormalizeException(&exc, &val, &tb);
Serhiy Storchaka9e373be2016-10-21 16:19:59 +0300401 if (tb != NULL) {
402 PyException_SetTraceback(val, tb);
403 Py_DECREF(tb);
404 }
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300405 Py_DECREF(exc);
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300406 PyErr_NormalizeException(&exc2, &val2, &tb2);
407 PyException_SetContext(val2, val);
408 PyErr_Restore(exc2, val2, tb2);
409 }
410 else {
411 PyErr_Restore(exc, val, tb);
412 }
413}
414
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300415static PyObject *
416_PyErr_FormatVFromCause(PyObject *exception, const char *format, va_list vargs)
417{
418 PyObject *exc, *val, *val2, *tb;
419
420 assert(PyErr_Occurred());
421 PyErr_Fetch(&exc, &val, &tb);
422 PyErr_NormalizeException(&exc, &val, &tb);
423 if (tb != NULL) {
424 PyException_SetTraceback(val, tb);
425 Py_DECREF(tb);
426 }
427 Py_DECREF(exc);
428 assert(!PyErr_Occurred());
429
430 PyErr_FormatV(exception, format, vargs);
431
432 PyErr_Fetch(&exc, &val2, &tb);
433 PyErr_NormalizeException(&exc, &val2, &tb);
434 Py_INCREF(val);
435 PyException_SetCause(val2, val);
436 PyException_SetContext(val2, val);
437 PyErr_Restore(exc, val2, tb);
438
439 return NULL;
440}
441
442PyObject *
443_PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
444{
445 va_list vargs;
446#ifdef HAVE_STDARG_PROTOTYPES
447 va_start(vargs, format);
448#else
449 va_start(vargs);
450#endif
451 _PyErr_FormatVFromCause(exception, format, vargs);
452 va_end(vargs);
453 return NULL;
454}
455
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000456/* Convenience functions to set a type error exception and return 0 */
457
458int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000459PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyErr_SetString(PyExc_TypeError,
462 "bad argument type for built-in operation");
463 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000464}
465
Guido van Rossum373c8691997-04-29 18:22:47 +0000466PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000467PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000468{
Victor Stinnerf54a5742013-07-22 22:28:37 +0200469 if (Py_TYPE(PyExc_MemoryError) == NULL) {
470 /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
471 initialized by _PyExc_Init() */
472 Py_FatalError("Out of memory and PyExc_MemoryError is not "
473 "initialized yet");
474 }
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000475 PyErr_SetNone(PyExc_MemoryError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000477}
478
Guido van Rossum373c8691997-04-29 18:22:47 +0000479PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000480PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000481{
Larry Hastingsb0827312014-02-09 22:05:19 -0800482 return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
483}
484
485PyObject *
486PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 PyObject *message;
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200489 PyObject *v, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 int i = errno;
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100491#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 WCHAR *s_buf = NULL;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000493#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000494
Guido van Rossume9fbc091995-02-18 14:52:19 +0000495#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (i == EINTR && PyErr_CheckSignals())
497 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000498#endif
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000499
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000500#ifndef MS_WINDOWS
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100501 if (i != 0) {
502 char *s = strerror(i);
Victor Stinner1b579672011-12-17 05:47:23 +0100503 message = PyUnicode_DecodeLocale(s, "surrogateescape");
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100504 }
505 else {
506 /* Sometimes errno didn't get set */
507 message = PyUnicode_FromString("Error");
508 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000509#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (i == 0)
511 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
512 else
513 {
514 /* Note that the Win32 errors do not lineup with the
515 errno error. So if the error is in the MSVC error
516 table, we use it, otherwise we assume it really _is_
517 a Win32 error code
518 */
519 if (i > 0 && i < _sys_nerr) {
520 message = PyUnicode_FromString(_sys_errlist[i]);
521 }
522 else {
523 int len = FormatMessageW(
524 FORMAT_MESSAGE_ALLOCATE_BUFFER |
525 FORMAT_MESSAGE_FROM_SYSTEM |
526 FORMAT_MESSAGE_IGNORE_INSERTS,
527 NULL, /* no message source */
528 i,
529 MAKELANGID(LANG_NEUTRAL,
530 SUBLANG_DEFAULT),
531 /* Default language */
532 (LPWSTR) &s_buf,
533 0, /* size not used */
534 NULL); /* no args */
535 if (len==0) {
536 /* Only ever seen this in out-of-mem
537 situations */
538 s_buf = NULL;
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300539 message = PyUnicode_FromFormat("Windows Error 0x%x", i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 } else {
541 /* remove trailing cr/lf and dots */
542 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
543 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200544 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 }
546 }
547 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000548#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (message == NULL)
551 {
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000552#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 LocalFree(s_buf);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000554#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return NULL;
556 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000557
Larry Hastingsb0827312014-02-09 22:05:19 -0800558 if (filenameObject != NULL) {
559 if (filenameObject2 != NULL)
560 args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
561 else
562 args = Py_BuildValue("(iOO)", i, message, filenameObject);
563 } else {
564 assert(filenameObject2 == NULL);
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200565 args = Py_BuildValue("(iO)", i, message);
Larry Hastingsb0827312014-02-09 22:05:19 -0800566 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000568
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200569 if (args != NULL) {
570 v = PyObject_Call(exc, args, NULL);
571 Py_DECREF(args);
572 if (v != NULL) {
573 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
574 Py_DECREF(v);
575 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000577#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000579#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000581}
Guido van Rossum743007d1999-04-21 15:27:31 +0000582
Barry Warsaw97d95151998-07-23 16:05:56 +0000583PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000584PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800587 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 Py_XDECREF(name);
589 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000590}
591
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000592#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000593PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000594PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000595{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200596 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800597 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 Py_XDECREF(name);
599 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000600}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000601#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000602
603PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000604PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000605{
Larry Hastingsb0827312014-02-09 22:05:19 -0800606 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000607}
Guido van Rossum683a0721990-10-21 22:09:12 +0000608
Brett Cannonbf364092006-03-01 04:25:17 +0000609#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000610/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000611PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyObject *exc,
613 int ierr,
614 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000615{
Larry Hastingsb0827312014-02-09 22:05:19 -0800616 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
617 filenameObject, NULL);
618}
619
620PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
621 PyObject *exc,
622 int ierr,
623 PyObject *filenameObject,
624 PyObject *filenameObject2)
625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 int len;
627 WCHAR *s_buf = NULL; /* Free via LocalFree */
628 PyObject *message;
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200629 PyObject *args, *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 DWORD err = (DWORD)ierr;
631 if (err==0) err = GetLastError();
632 len = FormatMessageW(
633 /* Error API error */
634 FORMAT_MESSAGE_ALLOCATE_BUFFER |
635 FORMAT_MESSAGE_FROM_SYSTEM |
636 FORMAT_MESSAGE_IGNORE_INSERTS,
637 NULL, /* no message source */
638 err,
639 MAKELANGID(LANG_NEUTRAL,
640 SUBLANG_DEFAULT), /* Default language */
641 (LPWSTR) &s_buf,
642 0, /* size not used */
643 NULL); /* no args */
644 if (len==0) {
645 /* Only seen this in out of mem situations */
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300646 message = PyUnicode_FromFormat("Windows Error 0x%x", err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 s_buf = NULL;
648 } else {
649 /* remove trailing cr/lf and dots */
650 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
651 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200652 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 if (message == NULL)
656 {
657 LocalFree(s_buf);
658 return NULL;
659 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000660
Larry Hastingsb0827312014-02-09 22:05:19 -0800661 if (filenameObject == NULL) {
662 assert(filenameObject2 == NULL);
663 filenameObject = filenameObject2 = Py_None;
664 }
665 else if (filenameObject2 == NULL)
666 filenameObject2 = Py_None;
667 /* This is the constructor signature for OSError.
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200668 The POSIX translation will be figured out by the constructor. */
Larry Hastingsb0827312014-02-09 22:05:19 -0800669 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000671
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200672 if (args != NULL) {
673 v = PyObject_Call(exc, args, NULL);
674 Py_DECREF(args);
675 if (v != NULL) {
676 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
677 Py_DECREF(v);
678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
680 LocalFree(s_buf);
681 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000682}
683
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000684PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyObject *exc,
686 int ierr,
687 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000688{
Victor Stinner92be9392010-12-28 00:28:21 +0000689 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800690 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800692 name,
693 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 Py_XDECREF(name);
695 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000696}
697
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000698PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyObject *exc,
700 int ierr,
701 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000702{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200703 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800704 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800706 name,
707 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 Py_XDECREF(name);
709 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000710}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000711
Thomas Heller085358a2002-07-29 14:27:41 +0000712PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
713{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800714 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000715}
716
Guido van Rossum795e1892000-02-17 15:19:15 +0000717PyObject *PyErr_SetFromWindowsErr(int ierr)
718{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800719 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
720 ierr, NULL);
Larry Hastingsb0827312014-02-09 22:05:19 -0800721}
722
Thomas Heller085358a2002-07-29 14:27:41 +0000723PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 int ierr,
725 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000726{
Victor Stinner92be9392010-12-28 00:28:21 +0000727 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800728 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200729 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800730 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 Py_XDECREF(name);
732 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000733}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000734
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000735PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 int ierr,
737 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000738{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200739 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800740 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200741 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800742 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 Py_XDECREF(name);
744 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000745}
Guido van Rossum795e1892000-02-17 15:19:15 +0000746#endif /* MS_WINDOWS */
747
Brett Cannon79ec55e2012-04-12 20:24:54 -0400748PyObject *
Eric Snow46f97b82016-09-07 16:56:15 -0700749PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
750 PyObject *name, PyObject *path)
Brett Cannon79ec55e2012-04-12 20:24:54 -0400751{
Eric Snow46f97b82016-09-07 16:56:15 -0700752 int issubclass;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200753 PyObject *kwargs, *error;
Brian Curtin09b86d12012-04-17 16:57:09 -0500754
Eric Snow46f97b82016-09-07 16:56:15 -0700755 issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
756 if (issubclass < 0) {
757 return NULL;
758 }
759 else if (!issubclass) {
760 PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError");
Brian Curtin94c001b2012-04-18 08:30:51 -0500761 return NULL;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200762 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500763
Eric Snow46f97b82016-09-07 16:56:15 -0700764 if (msg == NULL) {
765 PyErr_SetString(PyExc_TypeError, "expected a message argument");
Brian Curtin09b86d12012-04-17 16:57:09 -0500766 return NULL;
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400767 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500768
Brian Curtin94c001b2012-04-18 08:30:51 -0500769 if (name == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500770 name = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500771 }
Brian Curtin94c001b2012-04-18 08:30:51 -0500772 if (path == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500773 path = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500774 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500775
Eric Snow46f97b82016-09-07 16:56:15 -0700776 kwargs = PyDict_New();
777 if (kwargs == NULL) {
778 return NULL;
779 }
Victor Stinnerf45a5612016-08-23 00:04:41 +0200780 if (PyDict_SetItemString(kwargs, "name", name) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300781 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200782 }
783 if (PyDict_SetItemString(kwargs, "path", path) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300784 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200785 }
Brett Cannon79ec55e2012-04-12 20:24:54 -0400786
Eric Snow46f97b82016-09-07 16:56:15 -0700787 error = _PyObject_FastCallDict(exception, &msg, 1, kwargs);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400788 if (error != NULL) {
789 PyErr_SetObject((PyObject *)Py_TYPE(error), error);
Brian Curtin09b86d12012-04-17 16:57:09 -0500790 Py_DECREF(error);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400791 }
792
Berker Peksagec766d32016-05-01 09:06:36 +0300793done:
Brett Cannon79ec55e2012-04-12 20:24:54 -0400794 Py_DECREF(kwargs);
Brian Curtin09b86d12012-04-17 16:57:09 -0500795 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400796}
797
Eric Snow46f97b82016-09-07 16:56:15 -0700798PyObject *
799PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
800{
801 return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
802}
803
Guido van Rossum683a0721990-10-21 22:09:12 +0000804void
Neal Norwitzb382b842007-08-24 20:00:37 +0000805_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 PyErr_Format(PyExc_SystemError,
808 "%s:%d: bad argument to internal function",
809 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000810}
811
812/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
813 export the entry point for existing object code: */
814#undef PyErr_BadInternalCall
815void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000816PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000817{
Victor Stinnerfb3a6302013-07-12 00:37:30 +0200818 assert(0 && "bad argument to internal function");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 PyErr_Format(PyExc_SystemError,
820 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000821}
Fred Drake6d63adf2000-08-24 22:38:39 +0000822#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
823
Guido van Rossum1548bac1997-02-14 17:09:47 +0000824
Guido van Rossum1548bac1997-02-14 17:09:47 +0000825PyObject *
Antoine Pitrou0676a402014-09-30 21:16:27 +0200826PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000829
Victor Stinnerde821be2015-03-24 12:41:23 +0100830 /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
831 exception set, it calls arbitrary Python code like PyObject_Repr() */
Victor Stinnerace47d72013-07-18 01:41:08 +0200832 PyErr_Clear();
Victor Stinnerace47d72013-07-18 01:41:08 +0200833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 string = PyUnicode_FromFormatV(format, vargs);
Victor Stinnerde821be2015-03-24 12:41:23 +0100835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyErr_SetObject(exception, string);
837 Py_XDECREF(string);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000839}
Guido van Rossum7617e051997-09-16 18:43:50 +0000840
841
Antoine Pitrou0676a402014-09-30 21:16:27 +0200842PyObject *
843PyErr_Format(PyObject *exception, const char *format, ...)
844{
845 va_list vargs;
846#ifdef HAVE_STDARG_PROTOTYPES
847 va_start(vargs, format);
848#else
849 va_start(vargs);
850#endif
851 PyErr_FormatV(exception, format, vargs);
852 va_end(vargs);
853 return NULL;
854}
855
Thomas Wouters477c8d52006-05-27 19:21:47 +0000856
Guido van Rossum7617e051997-09-16 18:43:50 +0000857PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000858PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 const char *dot;
861 PyObject *modulename = NULL;
862 PyObject *classname = NULL;
863 PyObject *mydict = NULL;
864 PyObject *bases = NULL;
865 PyObject *result = NULL;
866 dot = strrchr(name, '.');
867 if (dot == NULL) {
868 PyErr_SetString(PyExc_SystemError,
869 "PyErr_NewException: name must be module.class");
870 return NULL;
871 }
872 if (base == NULL)
873 base = PyExc_Exception;
874 if (dict == NULL) {
875 dict = mydict = PyDict_New();
876 if (dict == NULL)
877 goto failure;
878 }
879 if (PyDict_GetItemString(dict, "__module__") == NULL) {
880 modulename = PyUnicode_FromStringAndSize(name,
881 (Py_ssize_t)(dot-name));
882 if (modulename == NULL)
883 goto failure;
884 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
885 goto failure;
886 }
887 if (PyTuple_Check(base)) {
888 bases = base;
889 /* INCREF as we create a new ref in the else branch */
890 Py_INCREF(bases);
891 } else {
892 bases = PyTuple_Pack(1, base);
893 if (bases == NULL)
894 goto failure;
895 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100896 /* Create a real class. */
Victor Stinner7eeb5b52010-06-07 19:57:46 +0000897 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000899 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 Py_XDECREF(bases);
901 Py_XDECREF(mydict);
902 Py_XDECREF(classname);
903 Py_XDECREF(modulename);
904 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000905}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000906
Georg Brandl1e28a272009-12-28 08:41:01 +0000907
908/* Create an exception with docstring */
909PyObject *
910PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 int result;
914 PyObject *ret = NULL;
915 PyObject *mydict = NULL; /* points to the dict only if we create it */
916 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (dict == NULL) {
919 dict = mydict = PyDict_New();
920 if (dict == NULL) {
921 return NULL;
922 }
923 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 if (doc != NULL) {
926 docobj = PyUnicode_FromString(doc);
927 if (docobj == NULL)
928 goto failure;
929 result = PyDict_SetItemString(dict, "__doc__", docobj);
930 Py_DECREF(docobj);
931 if (result < 0)
932 goto failure;
933 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000936 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 Py_XDECREF(mydict);
938 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000939}
940
941
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000942/* Call when an exception has occurred but there is no way for Python
943 to handle it. Examples: exception in __del__ or during GC. */
944void
945PyErr_WriteUnraisable(PyObject *obj)
946{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200947 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 PyObject *f, *t, *v, *tb;
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200949 PyObject *moduleName = NULL;
950 char* className;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000951
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200952 PyErr_Fetch(&t, &v, &tb);
953
Victor Stinnerbd303c12013-11-07 23:07:29 +0100954 f = _PySys_GetObjectId(&PyId_stderr);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200955 if (f == NULL || f == Py_None)
956 goto done;
957
958 if (obj) {
959 if (PyFile_WriteString("Exception ignored in: ", f) < 0)
960 goto done;
Martin Panter3263f682016-02-28 03:16:11 +0000961 if (PyFile_WriteObject(obj, f, 0) < 0) {
962 PyErr_Clear();
963 if (PyFile_WriteString("<object repr() failed>", f) < 0) {
964 goto done;
965 }
966 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200967 if (PyFile_WriteString("\n", f) < 0)
968 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200970
971 if (PyTraceBack_Print(tb, f) < 0)
972 goto done;
973
974 if (!t)
975 goto done;
976
977 assert(PyExceptionClass_Check(t));
978 className = PyExceptionClass_Name(t);
979 if (className != NULL) {
980 char *dot = strrchr(className, '.');
981 if (dot != NULL)
982 className = dot+1;
983 }
984
985 moduleName = _PyObject_GetAttrId(t, &PyId___module__);
Oren Milmanf6e61df2017-09-14 01:30:05 +0300986 if (moduleName == NULL || !PyUnicode_Check(moduleName)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200987 PyErr_Clear();
988 if (PyFile_WriteString("<unknown>", f) < 0)
989 goto done;
990 }
991 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200992 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200993 if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
994 goto done;
995 if (PyFile_WriteString(".", f) < 0)
996 goto done;
997 }
998 }
999 if (className == NULL) {
1000 if (PyFile_WriteString("<unknown>", f) < 0)
1001 goto done;
1002 }
1003 else {
1004 if (PyFile_WriteString(className, f) < 0)
1005 goto done;
1006 }
1007
1008 if (v && v != Py_None) {
1009 if (PyFile_WriteString(": ", f) < 0)
1010 goto done;
Martin Panter3263f682016-02-28 03:16:11 +00001011 if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
1012 PyErr_Clear();
1013 if (PyFile_WriteString("<exception str() failed>", f) < 0) {
1014 goto done;
1015 }
1016 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001017 }
1018 if (PyFile_WriteString("\n", f) < 0)
1019 goto done;
1020
1021done:
1022 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 Py_XDECREF(t);
1024 Py_XDECREF(v);
1025 Py_XDECREF(tb);
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001026 PyErr_Clear(); /* Just in case */
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001027}
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001028
Armin Rigo092381a2003-10-25 14:29:27 +00001029extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001030
Guido van Rossum2fd45652001-02-28 21:46:24 +00001031
Benjamin Peterson2c539712010-09-20 22:42:10 +00001032void
Victor Stinner14e461d2013-08-26 22:28:21 +02001033PyErr_SyntaxLocation(const char *filename, int lineno)
1034{
Benjamin Peterson2c539712010-09-20 22:42:10 +00001035 PyErr_SyntaxLocationEx(filename, lineno, -1);
1036}
1037
1038
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001039/* Set file and line information for the current exception.
1040 If the exception is not a SyntaxError, also sets additional attributes
1041 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +00001042
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001043void
Victor Stinner14e461d2013-08-26 22:28:21 +02001044PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 PyObject *exc, *v, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001047 _Py_IDENTIFIER(filename);
1048 _Py_IDENTIFIER(lineno);
1049 _Py_IDENTIFIER(msg);
1050 _Py_IDENTIFIER(offset);
1051 _Py_IDENTIFIER(print_file_and_line);
1052 _Py_IDENTIFIER(text);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 /* add attributes for the line number and filename for the error */
1055 PyErr_Fetch(&exc, &v, &tb);
1056 PyErr_NormalizeException(&exc, &v, &tb);
1057 /* XXX check that it is, indeed, a syntax error. It might not
1058 * be, though. */
1059 tmp = PyLong_FromLong(lineno);
1060 if (tmp == NULL)
1061 PyErr_Clear();
1062 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001063 if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 PyErr_Clear();
1065 Py_DECREF(tmp);
1066 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001067 tmp = NULL;
Benjamin Peterson2c539712010-09-20 22:42:10 +00001068 if (col_offset >= 0) {
1069 tmp = PyLong_FromLong(col_offset);
1070 if (tmp == NULL)
1071 PyErr_Clear();
Benjamin Peterson2c539712010-09-20 22:42:10 +00001072 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001073 if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
1074 PyErr_Clear();
1075 Py_XDECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (filename != NULL) {
Victor Stinner14e461d2013-08-26 22:28:21 +02001077 if (_PyObject_SetAttrId(v, &PyId_filename, filename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyErr_Clear();
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001079
Victor Stinner14e461d2013-08-26 22:28:21 +02001080 tmp = PyErr_ProgramTextObject(filename, lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001082 if (_PyObject_SetAttrId(v, &PyId_text, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyErr_Clear();
1084 Py_DECREF(tmp);
1085 }
1086 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (exc != PyExc_SyntaxError) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001088 if (!_PyObject_HasAttrId(v, &PyId_msg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 tmp = PyObject_Str(v);
1090 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001091 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyErr_Clear();
1093 Py_DECREF(tmp);
1094 } else {
1095 PyErr_Clear();
1096 }
1097 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001098 if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1099 if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1100 Py_None))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyErr_Clear();
1102 }
1103 }
1104 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001105}
1106
Victor Stinner14e461d2013-08-26 22:28:21 +02001107void
1108PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1109{
1110 PyObject *fileobj;
1111 if (filename != NULL) {
1112 fileobj = PyUnicode_DecodeFSDefault(filename);
1113 if (fileobj == NULL)
1114 PyErr_Clear();
1115 }
1116 else
1117 fileobj = NULL;
1118 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1119 Py_XDECREF(fileobj);
1120}
1121
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001122/* Attempt to load the line of text that the exception refers to. If it
1123 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001124
1125 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001126 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001127
Antoine Pitrou409b5382013-10-12 22:41:17 +02001128static PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001129err_programtext(FILE *fp, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 int i;
1132 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 if (fp == NULL)
1135 return NULL;
1136 for (i = 0; i < lineno; i++) {
1137 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1138 do {
1139 *pLastChar = '\0';
1140 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1141 fp, NULL) == NULL)
1142 break;
1143 /* fgets read *something*; if it didn't get as
1144 far as pLastChar, it must have found a newline
1145 or hit the end of the file; if pLastChar is \n,
1146 it obviously found a newline; else we haven't
1147 yet seen a newline, so must continue */
1148 } while (*pLastChar != '\0' && *pLastChar != '\n');
1149 }
1150 fclose(fp);
1151 if (i == lineno) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 PyObject *res;
Martin Panterca3263c2016-12-11 00:18:36 +00001153 res = PyUnicode_FromString(linebuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (res == NULL)
1155 PyErr_Clear();
1156 return res;
1157 }
1158 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001159}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001160
Victor Stinner14e461d2013-08-26 22:28:21 +02001161PyObject *
1162PyErr_ProgramText(const char *filename, int lineno)
1163{
1164 FILE *fp;
1165 if (filename == NULL || *filename == '\0' || lineno <= 0)
1166 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001167 fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001168 return err_programtext(fp, lineno);
1169}
1170
1171PyObject *
1172PyErr_ProgramTextObject(PyObject *filename, int lineno)
1173{
1174 FILE *fp;
1175 if (filename == NULL || lineno <= 0)
1176 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001177 fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
Victor Stinnere42ccd22015-03-18 01:39:23 +01001178 if (fp == NULL) {
1179 PyErr_Clear();
1180 return NULL;
1181 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001182 return err_programtext(fp, lineno);
1183}
1184
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001185#ifdef __cplusplus
1186}
1187#endif