blob: 13ebb192c547f687167f641a7b4cbe8fd6a287fd [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*/
xdegaye56d1f5c2017-10-26 15:09:06 +0200231static void
232PyErr_NormalizeExceptionEx(PyObject **exc, PyObject **val,
233 PyObject **tb, int recursion_depth)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 PyObject *type = *exc;
236 PyObject *value = *val;
237 PyObject *inclass = NULL;
238 PyObject *initial_tb = NULL;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000239
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
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 if (PyExceptionInstance_Check(value))
254 inclass = PyExceptionInstance_Class(value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 /* Normalize the exception so that if the type is a class, the
257 value will be an instance.
258 */
259 if (PyExceptionClass_Check(type)) {
Victor Stinner74a7fa62013-07-17 00:44:53 +0200260 int is_subclass;
261 if (inclass) {
262 is_subclass = PyObject_IsSubclass(inclass, type);
263 if (is_subclass < 0)
264 goto finally;
265 }
266 else
267 is_subclass = 0;
268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 /* if the value was not an instance, or is not an instance
270 whose class is (or is derived from) type, then use the
271 value as an argument to instantiation of the type
272 class.
273 */
Victor Stinner74a7fa62013-07-17 00:44:53 +0200274 if (!inclass || !is_subclass) {
Victor Stinner3a840972016-08-22 23:59:08 +0200275 PyObject *fixed_value;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000276
Victor Stinner3a840972016-08-22 23:59:08 +0200277 fixed_value = _PyErr_CreateException(type, value);
278 if (fixed_value == NULL) {
279 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 Py_DECREF(value);
Victor Stinner3a840972016-08-22 23:59:08 +0200283 value = fixed_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 }
285 /* if the class of the instance doesn't exactly match the
286 class of the type, believe the instance
287 */
288 else if (inclass != type) {
289 Py_DECREF(type);
290 type = inclass;
291 Py_INCREF(type);
292 }
293 }
294 *exc = type;
295 *val = value;
296 return;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000297finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 Py_DECREF(type);
299 Py_DECREF(value);
xdegaye56d1f5c2017-10-26 15:09:06 +0200300 if (recursion_depth + 1 == Py_NORMALIZE_RECURSION_LIMIT) {
301 PyErr_SetString(PyExc_RecursionError, "maximum recursion depth "
302 "exceeded while normalizing an exception");
303 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 /* If the new exception doesn't set a traceback and the old
305 exception had a traceback, use the old traceback for the
306 new exception. It's better than nothing.
307 */
308 initial_tb = *tb;
309 PyErr_Fetch(exc, val, tb);
310 if (initial_tb != NULL) {
311 if (*tb == NULL)
312 *tb = initial_tb;
313 else
314 Py_DECREF(initial_tb);
315 }
xdegaye56d1f5c2017-10-26 15:09:06 +0200316 /* Normalize recursively.
317 * Abort when Py_NORMALIZE_RECURSION_LIMIT has been exceeded and the
318 * corresponding RecursionError could not be normalized.*/
319 if (++recursion_depth > Py_NORMALIZE_RECURSION_LIMIT) {
320 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 }
xdegaye56d1f5c2017-10-26 15:09:06 +0200329 PyErr_NormalizeExceptionEx(exc, val, tb, recursion_depth);
330}
331
332void
333PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
334{
335 PyErr_NormalizeExceptionEx(exc, val, tb, 0);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000336}
337
338
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000340PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 *p_type = tstate->curexc_type;
345 *p_value = tstate->curexc_value;
346 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 tstate->curexc_type = NULL;
349 tstate->curexc_value = NULL;
350 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351}
352
353void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000354PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000358
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200359void
360PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
361{
362 PyThreadState *tstate = PyThreadState_GET();
363
Mark Shannonae3087c2017-10-22 22:41:51 +0100364 _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
365 *p_type = exc_info->exc_type;
366 *p_value = exc_info->exc_value;
367 *p_traceback = exc_info->exc_traceback;
368
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200369
370 Py_XINCREF(*p_type);
371 Py_XINCREF(*p_value);
372 Py_XINCREF(*p_traceback);
373}
374
375void
376PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
377{
378 PyObject *oldtype, *oldvalue, *oldtraceback;
379 PyThreadState *tstate = PyThreadState_GET();
380
Mark Shannonae3087c2017-10-22 22:41:51 +0100381 oldtype = tstate->exc_info->exc_type;
382 oldvalue = tstate->exc_info->exc_value;
383 oldtraceback = tstate->exc_info->exc_traceback;
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200384
Mark Shannonae3087c2017-10-22 22:41:51 +0100385 tstate->exc_info->exc_type = p_type;
386 tstate->exc_info->exc_value = p_value;
387 tstate->exc_info->exc_traceback = p_traceback;
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200388
389 Py_XDECREF(oldtype);
390 Py_XDECREF(oldvalue);
391 Py_XDECREF(oldtraceback);
392}
393
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300394/* Like PyErr_Restore(), but if an exception is already set,
395 set the context associated with it.
396 */
397void
398_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
399{
400 if (exc == NULL)
401 return;
402
403 if (PyErr_Occurred()) {
404 PyObject *exc2, *val2, *tb2;
405 PyErr_Fetch(&exc2, &val2, &tb2);
406 PyErr_NormalizeException(&exc, &val, &tb);
Serhiy Storchaka9e373be2016-10-21 16:19:59 +0300407 if (tb != NULL) {
408 PyException_SetTraceback(val, tb);
409 Py_DECREF(tb);
410 }
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300411 Py_DECREF(exc);
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300412 PyErr_NormalizeException(&exc2, &val2, &tb2);
413 PyException_SetContext(val2, val);
414 PyErr_Restore(exc2, val2, tb2);
415 }
416 else {
417 PyErr_Restore(exc, val, tb);
418 }
419}
420
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300421static PyObject *
422_PyErr_FormatVFromCause(PyObject *exception, const char *format, va_list vargs)
423{
424 PyObject *exc, *val, *val2, *tb;
425
426 assert(PyErr_Occurred());
427 PyErr_Fetch(&exc, &val, &tb);
428 PyErr_NormalizeException(&exc, &val, &tb);
429 if (tb != NULL) {
430 PyException_SetTraceback(val, tb);
431 Py_DECREF(tb);
432 }
433 Py_DECREF(exc);
434 assert(!PyErr_Occurred());
435
436 PyErr_FormatV(exception, format, vargs);
437
438 PyErr_Fetch(&exc, &val2, &tb);
439 PyErr_NormalizeException(&exc, &val2, &tb);
440 Py_INCREF(val);
441 PyException_SetCause(val2, val);
442 PyException_SetContext(val2, val);
443 PyErr_Restore(exc, val2, tb);
444
445 return NULL;
446}
447
448PyObject *
449_PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
450{
451 va_list vargs;
452#ifdef HAVE_STDARG_PROTOTYPES
453 va_start(vargs, format);
454#else
455 va_start(vargs);
456#endif
457 _PyErr_FormatVFromCause(exception, format, vargs);
458 va_end(vargs);
459 return NULL;
460}
461
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000462/* Convenience functions to set a type error exception and return 0 */
463
464int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000465PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 PyErr_SetString(PyExc_TypeError,
468 "bad argument type for built-in operation");
469 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000470}
471
Guido van Rossum373c8691997-04-29 18:22:47 +0000472PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000473PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000474{
Victor Stinnerf54a5742013-07-22 22:28:37 +0200475 if (Py_TYPE(PyExc_MemoryError) == NULL) {
476 /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
477 initialized by _PyExc_Init() */
478 Py_FatalError("Out of memory and PyExc_MemoryError is not "
479 "initialized yet");
480 }
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000481 PyErr_SetNone(PyExc_MemoryError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000483}
484
Guido van Rossum373c8691997-04-29 18:22:47 +0000485PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000486PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000487{
Larry Hastingsb0827312014-02-09 22:05:19 -0800488 return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
489}
490
491PyObject *
492PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 PyObject *message;
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200495 PyObject *v, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 int i = errno;
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100497#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 WCHAR *s_buf = NULL;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000499#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000500
Guido van Rossume9fbc091995-02-18 14:52:19 +0000501#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (i == EINTR && PyErr_CheckSignals())
503 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000504#endif
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000505
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000506#ifndef MS_WINDOWS
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100507 if (i != 0) {
508 char *s = strerror(i);
Victor Stinner1b579672011-12-17 05:47:23 +0100509 message = PyUnicode_DecodeLocale(s, "surrogateescape");
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100510 }
511 else {
512 /* Sometimes errno didn't get set */
513 message = PyUnicode_FromString("Error");
514 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000515#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (i == 0)
517 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
518 else
519 {
520 /* Note that the Win32 errors do not lineup with the
521 errno error. So if the error is in the MSVC error
522 table, we use it, otherwise we assume it really _is_
523 a Win32 error code
524 */
525 if (i > 0 && i < _sys_nerr) {
526 message = PyUnicode_FromString(_sys_errlist[i]);
527 }
528 else {
529 int len = FormatMessageW(
530 FORMAT_MESSAGE_ALLOCATE_BUFFER |
531 FORMAT_MESSAGE_FROM_SYSTEM |
532 FORMAT_MESSAGE_IGNORE_INSERTS,
533 NULL, /* no message source */
534 i,
535 MAKELANGID(LANG_NEUTRAL,
536 SUBLANG_DEFAULT),
537 /* Default language */
538 (LPWSTR) &s_buf,
539 0, /* size not used */
540 NULL); /* no args */
541 if (len==0) {
542 /* Only ever seen this in out-of-mem
543 situations */
544 s_buf = NULL;
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300545 message = PyUnicode_FromFormat("Windows Error 0x%x", i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 } else {
547 /* remove trailing cr/lf and dots */
548 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
549 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200550 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 }
552 }
553 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000554#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (message == NULL)
557 {
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000558#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 LocalFree(s_buf);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000560#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return NULL;
562 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000563
Larry Hastingsb0827312014-02-09 22:05:19 -0800564 if (filenameObject != NULL) {
565 if (filenameObject2 != NULL)
566 args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
567 else
568 args = Py_BuildValue("(iOO)", i, message, filenameObject);
569 } else {
570 assert(filenameObject2 == NULL);
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200571 args = Py_BuildValue("(iO)", i, message);
Larry Hastingsb0827312014-02-09 22:05:19 -0800572 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000574
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200575 if (args != NULL) {
576 v = PyObject_Call(exc, args, NULL);
577 Py_DECREF(args);
578 if (v != NULL) {
579 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
580 Py_DECREF(v);
581 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000583#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000585#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000587}
Guido van Rossum743007d1999-04-21 15:27:31 +0000588
Barry Warsaw97d95151998-07-23 16:05:56 +0000589PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000590PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800593 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 Py_XDECREF(name);
595 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000596}
597
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000598#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000599PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000600PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000601{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200602 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800603 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 Py_XDECREF(name);
605 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000606}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000607#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000608
609PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000610PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000611{
Larry Hastingsb0827312014-02-09 22:05:19 -0800612 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000613}
Guido van Rossum683a0721990-10-21 22:09:12 +0000614
Brett Cannonbf364092006-03-01 04:25:17 +0000615#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000616/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000617PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 PyObject *exc,
619 int ierr,
620 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000621{
Larry Hastingsb0827312014-02-09 22:05:19 -0800622 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
623 filenameObject, NULL);
624}
625
626PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
627 PyObject *exc,
628 int ierr,
629 PyObject *filenameObject,
630 PyObject *filenameObject2)
631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 int len;
633 WCHAR *s_buf = NULL; /* Free via LocalFree */
634 PyObject *message;
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200635 PyObject *args, *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 DWORD err = (DWORD)ierr;
637 if (err==0) err = GetLastError();
638 len = FormatMessageW(
639 /* Error API error */
640 FORMAT_MESSAGE_ALLOCATE_BUFFER |
641 FORMAT_MESSAGE_FROM_SYSTEM |
642 FORMAT_MESSAGE_IGNORE_INSERTS,
643 NULL, /* no message source */
644 err,
645 MAKELANGID(LANG_NEUTRAL,
646 SUBLANG_DEFAULT), /* Default language */
647 (LPWSTR) &s_buf,
648 0, /* size not used */
649 NULL); /* no args */
650 if (len==0) {
651 /* Only seen this in out of mem situations */
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300652 message = PyUnicode_FromFormat("Windows Error 0x%x", err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 s_buf = NULL;
654 } else {
655 /* remove trailing cr/lf and dots */
656 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
657 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200658 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (message == NULL)
662 {
663 LocalFree(s_buf);
664 return NULL;
665 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000666
Larry Hastingsb0827312014-02-09 22:05:19 -0800667 if (filenameObject == NULL) {
668 assert(filenameObject2 == NULL);
669 filenameObject = filenameObject2 = Py_None;
670 }
671 else if (filenameObject2 == NULL)
672 filenameObject2 = Py_None;
673 /* This is the constructor signature for OSError.
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200674 The POSIX translation will be figured out by the constructor. */
Larry Hastingsb0827312014-02-09 22:05:19 -0800675 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000677
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200678 if (args != NULL) {
679 v = PyObject_Call(exc, args, NULL);
680 Py_DECREF(args);
681 if (v != NULL) {
682 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
683 Py_DECREF(v);
684 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 }
686 LocalFree(s_buf);
687 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000688}
689
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000690PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 PyObject *exc,
692 int ierr,
693 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000694{
Victor Stinner92be9392010-12-28 00:28:21 +0000695 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800696 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800698 name,
699 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 Py_XDECREF(name);
701 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000702}
703
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000704PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyObject *exc,
706 int ierr,
707 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000708{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200709 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800710 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800712 name,
713 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 Py_XDECREF(name);
715 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000716}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000717
Thomas Heller085358a2002-07-29 14:27:41 +0000718PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
719{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800720 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000721}
722
Guido van Rossum795e1892000-02-17 15:19:15 +0000723PyObject *PyErr_SetFromWindowsErr(int ierr)
724{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800725 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
726 ierr, NULL);
Larry Hastingsb0827312014-02-09 22:05:19 -0800727}
728
Thomas Heller085358a2002-07-29 14:27:41 +0000729PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 int ierr,
731 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000732{
Victor Stinner92be9392010-12-28 00:28:21 +0000733 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800734 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200735 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800736 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 Py_XDECREF(name);
738 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000739}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000740
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000741PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 int ierr,
743 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000744{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200745 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800746 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200747 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800748 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 Py_XDECREF(name);
750 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000751}
Guido van Rossum795e1892000-02-17 15:19:15 +0000752#endif /* MS_WINDOWS */
753
Brett Cannon79ec55e2012-04-12 20:24:54 -0400754PyObject *
Eric Snow46f97b82016-09-07 16:56:15 -0700755PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
756 PyObject *name, PyObject *path)
Brett Cannon79ec55e2012-04-12 20:24:54 -0400757{
Eric Snow46f97b82016-09-07 16:56:15 -0700758 int issubclass;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200759 PyObject *kwargs, *error;
Brian Curtin09b86d12012-04-17 16:57:09 -0500760
Eric Snow46f97b82016-09-07 16:56:15 -0700761 issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
762 if (issubclass < 0) {
763 return NULL;
764 }
765 else if (!issubclass) {
766 PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError");
Brian Curtin94c001b2012-04-18 08:30:51 -0500767 return NULL;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200768 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500769
Eric Snow46f97b82016-09-07 16:56:15 -0700770 if (msg == NULL) {
771 PyErr_SetString(PyExc_TypeError, "expected a message argument");
Brian Curtin09b86d12012-04-17 16:57:09 -0500772 return NULL;
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400773 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500774
Brian Curtin94c001b2012-04-18 08:30:51 -0500775 if (name == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500776 name = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500777 }
Brian Curtin94c001b2012-04-18 08:30:51 -0500778 if (path == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500779 path = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500780 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500781
Eric Snow46f97b82016-09-07 16:56:15 -0700782 kwargs = PyDict_New();
783 if (kwargs == NULL) {
784 return NULL;
785 }
Victor Stinnerf45a5612016-08-23 00:04:41 +0200786 if (PyDict_SetItemString(kwargs, "name", name) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300787 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200788 }
789 if (PyDict_SetItemString(kwargs, "path", path) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300790 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200791 }
Brett Cannon79ec55e2012-04-12 20:24:54 -0400792
Eric Snow46f97b82016-09-07 16:56:15 -0700793 error = _PyObject_FastCallDict(exception, &msg, 1, kwargs);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400794 if (error != NULL) {
795 PyErr_SetObject((PyObject *)Py_TYPE(error), error);
Brian Curtin09b86d12012-04-17 16:57:09 -0500796 Py_DECREF(error);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400797 }
798
Berker Peksagec766d32016-05-01 09:06:36 +0300799done:
Brett Cannon79ec55e2012-04-12 20:24:54 -0400800 Py_DECREF(kwargs);
Brian Curtin09b86d12012-04-17 16:57:09 -0500801 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400802}
803
Eric Snow46f97b82016-09-07 16:56:15 -0700804PyObject *
805PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
806{
807 return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
808}
809
Guido van Rossum683a0721990-10-21 22:09:12 +0000810void
Neal Norwitzb382b842007-08-24 20:00:37 +0000811_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyErr_Format(PyExc_SystemError,
814 "%s:%d: bad argument to internal function",
815 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000816}
817
818/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
819 export the entry point for existing object code: */
820#undef PyErr_BadInternalCall
821void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000822PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000823{
Victor Stinnerfb3a6302013-07-12 00:37:30 +0200824 assert(0 && "bad argument to internal function");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 PyErr_Format(PyExc_SystemError,
826 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000827}
Fred Drake6d63adf2000-08-24 22:38:39 +0000828#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
829
Guido van Rossum1548bac1997-02-14 17:09:47 +0000830
Guido van Rossum1548bac1997-02-14 17:09:47 +0000831PyObject *
Antoine Pitrou0676a402014-09-30 21:16:27 +0200832PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000835
Victor Stinnerde821be2015-03-24 12:41:23 +0100836 /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
837 exception set, it calls arbitrary Python code like PyObject_Repr() */
Victor Stinnerace47d72013-07-18 01:41:08 +0200838 PyErr_Clear();
Victor Stinnerace47d72013-07-18 01:41:08 +0200839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 string = PyUnicode_FromFormatV(format, vargs);
Victor Stinnerde821be2015-03-24 12:41:23 +0100841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyErr_SetObject(exception, string);
843 Py_XDECREF(string);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000845}
Guido van Rossum7617e051997-09-16 18:43:50 +0000846
847
Antoine Pitrou0676a402014-09-30 21:16:27 +0200848PyObject *
849PyErr_Format(PyObject *exception, const char *format, ...)
850{
851 va_list vargs;
852#ifdef HAVE_STDARG_PROTOTYPES
853 va_start(vargs, format);
854#else
855 va_start(vargs);
856#endif
857 PyErr_FormatV(exception, format, vargs);
858 va_end(vargs);
859 return NULL;
860}
861
Thomas Wouters477c8d52006-05-27 19:21:47 +0000862
Guido van Rossum7617e051997-09-16 18:43:50 +0000863PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000864PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 const char *dot;
867 PyObject *modulename = NULL;
868 PyObject *classname = NULL;
869 PyObject *mydict = NULL;
870 PyObject *bases = NULL;
871 PyObject *result = NULL;
872 dot = strrchr(name, '.');
873 if (dot == NULL) {
874 PyErr_SetString(PyExc_SystemError,
875 "PyErr_NewException: name must be module.class");
876 return NULL;
877 }
878 if (base == NULL)
879 base = PyExc_Exception;
880 if (dict == NULL) {
881 dict = mydict = PyDict_New();
882 if (dict == NULL)
883 goto failure;
884 }
885 if (PyDict_GetItemString(dict, "__module__") == NULL) {
886 modulename = PyUnicode_FromStringAndSize(name,
887 (Py_ssize_t)(dot-name));
888 if (modulename == NULL)
889 goto failure;
890 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
891 goto failure;
892 }
893 if (PyTuple_Check(base)) {
894 bases = base;
895 /* INCREF as we create a new ref in the else branch */
896 Py_INCREF(bases);
897 } else {
898 bases = PyTuple_Pack(1, base);
899 if (bases == NULL)
900 goto failure;
901 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100902 /* Create a real class. */
Victor Stinner7eeb5b52010-06-07 19:57:46 +0000903 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000905 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 Py_XDECREF(bases);
907 Py_XDECREF(mydict);
908 Py_XDECREF(classname);
909 Py_XDECREF(modulename);
910 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000911}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000912
Georg Brandl1e28a272009-12-28 08:41:01 +0000913
914/* Create an exception with docstring */
915PyObject *
916PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 int result;
920 PyObject *ret = NULL;
921 PyObject *mydict = NULL; /* points to the dict only if we create it */
922 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (dict == NULL) {
925 dict = mydict = PyDict_New();
926 if (dict == NULL) {
927 return NULL;
928 }
929 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 if (doc != NULL) {
932 docobj = PyUnicode_FromString(doc);
933 if (docobj == NULL)
934 goto failure;
935 result = PyDict_SetItemString(dict, "__doc__", docobj);
936 Py_DECREF(docobj);
937 if (result < 0)
938 goto failure;
939 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000942 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 Py_XDECREF(mydict);
944 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000945}
946
947
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000948/* Call when an exception has occurred but there is no way for Python
949 to handle it. Examples: exception in __del__ or during GC. */
950void
951PyErr_WriteUnraisable(PyObject *obj)
952{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200953 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 PyObject *f, *t, *v, *tb;
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200955 PyObject *moduleName = NULL;
956 char* className;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000957
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200958 PyErr_Fetch(&t, &v, &tb);
959
Victor Stinnerbd303c12013-11-07 23:07:29 +0100960 f = _PySys_GetObjectId(&PyId_stderr);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200961 if (f == NULL || f == Py_None)
962 goto done;
963
964 if (obj) {
965 if (PyFile_WriteString("Exception ignored in: ", f) < 0)
966 goto done;
Martin Panter3263f682016-02-28 03:16:11 +0000967 if (PyFile_WriteObject(obj, f, 0) < 0) {
968 PyErr_Clear();
969 if (PyFile_WriteString("<object repr() failed>", f) < 0) {
970 goto done;
971 }
972 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200973 if (PyFile_WriteString("\n", f) < 0)
974 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200976
977 if (PyTraceBack_Print(tb, f) < 0)
978 goto done;
979
980 if (!t)
981 goto done;
982
983 assert(PyExceptionClass_Check(t));
984 className = PyExceptionClass_Name(t);
985 if (className != NULL) {
986 char *dot = strrchr(className, '.');
987 if (dot != NULL)
988 className = dot+1;
989 }
990
991 moduleName = _PyObject_GetAttrId(t, &PyId___module__);
Oren Milmanf6e61df2017-09-14 01:30:05 +0300992 if (moduleName == NULL || !PyUnicode_Check(moduleName)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200993 PyErr_Clear();
994 if (PyFile_WriteString("<unknown>", f) < 0)
995 goto done;
996 }
997 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200998 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200999 if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
1000 goto done;
1001 if (PyFile_WriteString(".", f) < 0)
1002 goto done;
1003 }
1004 }
1005 if (className == NULL) {
1006 if (PyFile_WriteString("<unknown>", f) < 0)
1007 goto done;
1008 }
1009 else {
1010 if (PyFile_WriteString(className, f) < 0)
1011 goto done;
1012 }
1013
1014 if (v && v != Py_None) {
1015 if (PyFile_WriteString(": ", f) < 0)
1016 goto done;
Martin Panter3263f682016-02-28 03:16:11 +00001017 if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
1018 PyErr_Clear();
1019 if (PyFile_WriteString("<exception str() failed>", f) < 0) {
1020 goto done;
1021 }
1022 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001023 }
1024 if (PyFile_WriteString("\n", f) < 0)
1025 goto done;
1026
1027done:
1028 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 Py_XDECREF(t);
1030 Py_XDECREF(v);
1031 Py_XDECREF(tb);
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001032 PyErr_Clear(); /* Just in case */
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001033}
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001034
Armin Rigo092381a2003-10-25 14:29:27 +00001035extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001036
Guido van Rossum2fd45652001-02-28 21:46:24 +00001037
Benjamin Peterson2c539712010-09-20 22:42:10 +00001038void
Victor Stinner14e461d2013-08-26 22:28:21 +02001039PyErr_SyntaxLocation(const char *filename, int lineno)
1040{
Benjamin Peterson2c539712010-09-20 22:42:10 +00001041 PyErr_SyntaxLocationEx(filename, lineno, -1);
1042}
1043
1044
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001045/* Set file and line information for the current exception.
1046 If the exception is not a SyntaxError, also sets additional attributes
1047 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +00001048
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001049void
Victor Stinner14e461d2013-08-26 22:28:21 +02001050PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyObject *exc, *v, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001053 _Py_IDENTIFIER(filename);
1054 _Py_IDENTIFIER(lineno);
1055 _Py_IDENTIFIER(msg);
1056 _Py_IDENTIFIER(offset);
1057 _Py_IDENTIFIER(print_file_and_line);
1058 _Py_IDENTIFIER(text);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 /* add attributes for the line number and filename for the error */
1061 PyErr_Fetch(&exc, &v, &tb);
1062 PyErr_NormalizeException(&exc, &v, &tb);
1063 /* XXX check that it is, indeed, a syntax error. It might not
1064 * be, though. */
1065 tmp = PyLong_FromLong(lineno);
1066 if (tmp == NULL)
1067 PyErr_Clear();
1068 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001069 if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyErr_Clear();
1071 Py_DECREF(tmp);
1072 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001073 tmp = NULL;
Benjamin Peterson2c539712010-09-20 22:42:10 +00001074 if (col_offset >= 0) {
1075 tmp = PyLong_FromLong(col_offset);
1076 if (tmp == NULL)
1077 PyErr_Clear();
Benjamin Peterson2c539712010-09-20 22:42:10 +00001078 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001079 if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
1080 PyErr_Clear();
1081 Py_XDECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (filename != NULL) {
Victor Stinner14e461d2013-08-26 22:28:21 +02001083 if (_PyObject_SetAttrId(v, &PyId_filename, filename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyErr_Clear();
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001085
Victor Stinner14e461d2013-08-26 22:28:21 +02001086 tmp = PyErr_ProgramTextObject(filename, lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001088 if (_PyObject_SetAttrId(v, &PyId_text, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyErr_Clear();
1090 Py_DECREF(tmp);
1091 }
1092 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (exc != PyExc_SyntaxError) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001094 if (!_PyObject_HasAttrId(v, &PyId_msg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 tmp = PyObject_Str(v);
1096 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001097 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyErr_Clear();
1099 Py_DECREF(tmp);
1100 } else {
1101 PyErr_Clear();
1102 }
1103 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001104 if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1105 if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1106 Py_None))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 PyErr_Clear();
1108 }
1109 }
1110 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001111}
1112
Victor Stinner14e461d2013-08-26 22:28:21 +02001113void
1114PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1115{
1116 PyObject *fileobj;
1117 if (filename != NULL) {
1118 fileobj = PyUnicode_DecodeFSDefault(filename);
1119 if (fileobj == NULL)
1120 PyErr_Clear();
1121 }
1122 else
1123 fileobj = NULL;
1124 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1125 Py_XDECREF(fileobj);
1126}
1127
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001128/* Attempt to load the line of text that the exception refers to. If it
1129 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001130
1131 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001132 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001133
Antoine Pitrou409b5382013-10-12 22:41:17 +02001134static PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001135err_programtext(FILE *fp, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 int i;
1138 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 if (fp == NULL)
1141 return NULL;
1142 for (i = 0; i < lineno; i++) {
1143 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1144 do {
1145 *pLastChar = '\0';
1146 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1147 fp, NULL) == NULL)
1148 break;
1149 /* fgets read *something*; if it didn't get as
1150 far as pLastChar, it must have found a newline
1151 or hit the end of the file; if pLastChar is \n,
1152 it obviously found a newline; else we haven't
1153 yet seen a newline, so must continue */
1154 } while (*pLastChar != '\0' && *pLastChar != '\n');
1155 }
1156 fclose(fp);
1157 if (i == lineno) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 PyObject *res;
Martin Panterca3263c2016-12-11 00:18:36 +00001159 res = PyUnicode_FromString(linebuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (res == NULL)
1161 PyErr_Clear();
1162 return res;
1163 }
1164 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001165}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001166
Victor Stinner14e461d2013-08-26 22:28:21 +02001167PyObject *
1168PyErr_ProgramText(const char *filename, int lineno)
1169{
1170 FILE *fp;
1171 if (filename == NULL || *filename == '\0' || lineno <= 0)
1172 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001173 fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001174 return err_programtext(fp, lineno);
1175}
1176
1177PyObject *
1178PyErr_ProgramTextObject(PyObject *filename, int lineno)
1179{
1180 FILE *fp;
1181 if (filename == NULL || lineno <= 0)
1182 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001183 fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
Victor Stinnere42ccd22015-03-18 01:39:23 +01001184 if (fp == NULL) {
1185 PyErr_Clear();
1186 return NULL;
1187 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001188 return err_programtext(fp, lineno);
1189}
1190
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001191#ifdef __cplusplus
1192}
1193#endif