blob: 5709fddb58411516b13989a085005f90a6194620 [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
Victor Stinner3a840972016-08-22 23:59:08 +020056static PyObject*
57_PyErr_CreateException(PyObject *exception, PyObject *value)
58{
59 if (value == NULL || value == Py_None) {
60 return _PyObject_CallNoArg(exception);
61 }
62 else if (PyTuple_Check(value)) {
63 return PyObject_Call(exception, value, NULL);
64 }
65 else {
Victor Stinner7bfb42d2016-12-05 17:04:32 +010066 return PyObject_CallFunctionObjArgs(exception, value, NULL);
Victor Stinner3a840972016-08-22 23:59:08 +020067 }
68}
69
Guido van Rossum1ae940a1995-01-02 19:04:15 +000070void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000071PyErr_SetObject(PyObject *exception, PyObject *value)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 PyThreadState *tstate = PyThreadState_GET();
74 PyObject *exc_value;
75 PyObject *tb = NULL;
Guido van Rossumb4fb6e42008-06-14 20:20:24 +000076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 if (exception != NULL &&
78 !PyExceptionClass_Check(exception)) {
79 PyErr_Format(PyExc_SystemError,
80 "exception %R not a BaseException subclass",
81 exception);
82 return;
83 }
Victor Stinner3a840972016-08-22 23:59:08 +020084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 Py_XINCREF(value);
86 exc_value = tstate->exc_value;
87 if (exc_value != NULL && exc_value != Py_None) {
88 /* Implicit exception chaining */
89 Py_INCREF(exc_value);
90 if (value == NULL || !PyExceptionInstance_Check(value)) {
91 /* We must normalize the value right now */
Victor Stinner3a840972016-08-22 23:59:08 +020092 PyObject *fixed_value;
Victor Stinnerde821be2015-03-24 12:41:23 +010093
Victor Stinner3a840972016-08-22 23:59:08 +020094 /* Issue #23571: functions must not be called with an
Victor Stinnerde821be2015-03-24 12:41:23 +010095 exception set */
Victor Stinnerace47d72013-07-18 01:41:08 +020096 PyErr_Clear();
Victor Stinnerde821be2015-03-24 12:41:23 +010097
Victor Stinner3a840972016-08-22 23:59:08 +020098 fixed_value = _PyErr_CreateException(exception, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 Py_XDECREF(value);
Victor Stinner3a840972016-08-22 23:59:08 +0200100 if (fixed_value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 return;
Victor Stinner3a840972016-08-22 23:59:08 +0200102 }
103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 value = fixed_value;
105 }
Victor Stinner3a840972016-08-22 23:59:08 +0200106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 /* Avoid reference cycles through the context chain.
108 This is O(chain length) but context chains are
109 usually very short. Sensitive readers may try
110 to inline the call to PyException_GetContext. */
111 if (exc_value != value) {
112 PyObject *o = exc_value, *context;
113 while ((context = PyException_GetContext(o))) {
114 Py_DECREF(context);
115 if (context == value) {
116 PyException_SetContext(o, NULL);
117 break;
118 }
119 o = context;
120 }
121 PyException_SetContext(value, exc_value);
Victor Stinner3a840972016-08-22 23:59:08 +0200122 }
123 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 Py_DECREF(exc_value);
125 }
126 }
127 if (value != NULL && PyExceptionInstance_Check(value))
128 tb = PyException_GetTraceback(value);
129 Py_XINCREF(exception);
130 PyErr_Restore(exception, value, tb);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131}
132
Raymond Hettinger69492da2013-09-02 15:59:26 -0700133/* Set a key error with the specified argument, wrapping it in a
134 * tuple automatically so that tuple keys are not unpacked as the
135 * exception arguments. */
136void
137_PyErr_SetKeyError(PyObject *arg)
138{
139 PyObject *tup;
140 tup = PyTuple_Pack(1, arg);
141 if (!tup)
142 return; /* caller will expect error to be set anyway */
143 PyErr_SetObject(PyExc_KeyError, tup);
144 Py_DECREF(tup);
145}
146
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000148PyErr_SetNone(PyObject *exception)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151}
152
153void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000154PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 PyObject *value = PyUnicode_FromString(string);
157 PyErr_SetObject(exception, value);
158 Py_XDECREF(value);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Guido van Rossum3a241811994-08-29 12:14:12 +0000161
Victor Stinnerc6944e72016-11-11 02:13:35 +0100162PyObject* _Py_HOT_FUNCTION
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000163PyErr_Occurred(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164{
Victor Stinner0cae6092016-11-11 01:43:56 +0100165 PyThreadState *tstate = PyThreadState_GET();
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +0000166 return tstate == NULL ? NULL : tstate->curexc_type;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167}
168
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000169
170int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000171PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 if (err == NULL || exc == NULL) {
174 /* maybe caused by "import exceptions" that failed early on */
175 return 0;
176 }
177 if (PyTuple_Check(exc)) {
178 Py_ssize_t i, n;
179 n = PyTuple_Size(exc);
180 for (i = 0; i < n; i++) {
181 /* Test recursively */
182 if (PyErr_GivenExceptionMatches(
183 err, PyTuple_GET_ITEM(exc, i)))
184 {
185 return 1;
186 }
187 }
188 return 0;
189 }
190 /* err might be an instance, so check its class. */
191 if (PyExceptionInstance_Check(err))
192 err = PyExceptionInstance_Class(err);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
scodere4c06bc2017-07-31 22:27:46 +0200195 return PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 return err == exc;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000199}
Guido van Rossum743007d1999-04-21 15:27:31 +0000200
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000201
202int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000203PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000206}
207
208
209/* Used in many places to normalize a raised exception, including in
210 eval_code2(), do_raise(), and PyErr_Print()
Benjamin Petersone6528212008-07-15 15:32:09 +0000211
212 XXX: should PyErr_NormalizeException() also call
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 PyException_SetTraceback() with the resulting value and tb?
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000214*/
215void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000216PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 PyObject *type = *exc;
219 PyObject *value = *val;
220 PyObject *inclass = NULL;
221 PyObject *initial_tb = NULL;
222 PyThreadState *tstate = NULL;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (type == NULL) {
225 /* There was no exception, so nothing to do. */
226 return;
227 }
Guido van Rossumed473a42000-08-07 19:18:27 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 /* If PyErr_SetNone() was used, the value will have been actually
230 set to NULL.
231 */
232 if (!value) {
233 value = Py_None;
234 Py_INCREF(value);
235 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (PyExceptionInstance_Check(value))
238 inclass = PyExceptionInstance_Class(value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 /* Normalize the exception so that if the type is a class, the
241 value will be an instance.
242 */
243 if (PyExceptionClass_Check(type)) {
Victor Stinner74a7fa62013-07-17 00:44:53 +0200244 int is_subclass;
245 if (inclass) {
246 is_subclass = PyObject_IsSubclass(inclass, type);
247 if (is_subclass < 0)
248 goto finally;
249 }
250 else
251 is_subclass = 0;
252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 /* if the value was not an instance, or is not an instance
254 whose class is (or is derived from) type, then use the
255 value as an argument to instantiation of the type
256 class.
257 */
Victor Stinner74a7fa62013-07-17 00:44:53 +0200258 if (!inclass || !is_subclass) {
Victor Stinner3a840972016-08-22 23:59:08 +0200259 PyObject *fixed_value;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000260
Victor Stinner3a840972016-08-22 23:59:08 +0200261 fixed_value = _PyErr_CreateException(type, value);
262 if (fixed_value == NULL) {
263 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 Py_DECREF(value);
Victor Stinner3a840972016-08-22 23:59:08 +0200267 value = fixed_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 }
269 /* if the class of the instance doesn't exactly match the
270 class of the type, believe the instance
271 */
272 else if (inclass != type) {
273 Py_DECREF(type);
274 type = inclass;
275 Py_INCREF(type);
276 }
277 }
278 *exc = type;
279 *val = value;
280 return;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000281finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 Py_DECREF(type);
283 Py_DECREF(value);
284 /* If the new exception doesn't set a traceback and the old
285 exception had a traceback, use the old traceback for the
286 new exception. It's better than nothing.
287 */
288 initial_tb = *tb;
289 PyErr_Fetch(exc, val, tb);
290 if (initial_tb != NULL) {
291 if (*tb == NULL)
292 *tb = initial_tb;
293 else
294 Py_DECREF(initial_tb);
295 }
296 /* normalize recursively */
297 tstate = PyThreadState_GET();
298 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
299 --tstate->recursion_depth;
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200300 /* throw away the old exception and use the recursion error instead */
301 Py_INCREF(PyExc_RecursionError);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300302 Py_SETREF(*exc, PyExc_RecursionError);
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200303 Py_INCREF(PyExc_RecursionErrorInst);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300304 Py_SETREF(*val, PyExc_RecursionErrorInst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 /* just keeping the old traceback */
306 return;
307 }
308 PyErr_NormalizeException(exc, val, tb);
309 --tstate->recursion_depth;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000310}
311
312
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000314PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 *p_type = tstate->curexc_type;
319 *p_value = tstate->curexc_value;
320 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 tstate->curexc_type = NULL;
323 tstate->curexc_value = NULL;
324 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325}
326
327void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000328PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000332
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200333void
334PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
335{
336 PyThreadState *tstate = PyThreadState_GET();
337
338 *p_type = tstate->exc_type;
339 *p_value = tstate->exc_value;
340 *p_traceback = tstate->exc_traceback;
341
342 Py_XINCREF(*p_type);
343 Py_XINCREF(*p_value);
344 Py_XINCREF(*p_traceback);
345}
346
347void
348PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
349{
350 PyObject *oldtype, *oldvalue, *oldtraceback;
351 PyThreadState *tstate = PyThreadState_GET();
352
353 oldtype = tstate->exc_type;
354 oldvalue = tstate->exc_value;
355 oldtraceback = tstate->exc_traceback;
356
357 tstate->exc_type = p_type;
358 tstate->exc_value = p_value;
359 tstate->exc_traceback = p_traceback;
360
361 Py_XDECREF(oldtype);
362 Py_XDECREF(oldvalue);
363 Py_XDECREF(oldtraceback);
364}
365
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300366/* Like PyErr_Restore(), but if an exception is already set,
367 set the context associated with it.
368 */
369void
370_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
371{
372 if (exc == NULL)
373 return;
374
375 if (PyErr_Occurred()) {
376 PyObject *exc2, *val2, *tb2;
377 PyErr_Fetch(&exc2, &val2, &tb2);
378 PyErr_NormalizeException(&exc, &val, &tb);
Serhiy Storchaka9e373be2016-10-21 16:19:59 +0300379 if (tb != NULL) {
380 PyException_SetTraceback(val, tb);
381 Py_DECREF(tb);
382 }
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300383 Py_DECREF(exc);
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300384 PyErr_NormalizeException(&exc2, &val2, &tb2);
385 PyException_SetContext(val2, val);
386 PyErr_Restore(exc2, val2, tb2);
387 }
388 else {
389 PyErr_Restore(exc, val, tb);
390 }
391}
392
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300393static PyObject *
394_PyErr_FormatVFromCause(PyObject *exception, const char *format, va_list vargs)
395{
396 PyObject *exc, *val, *val2, *tb;
397
398 assert(PyErr_Occurred());
399 PyErr_Fetch(&exc, &val, &tb);
400 PyErr_NormalizeException(&exc, &val, &tb);
401 if (tb != NULL) {
402 PyException_SetTraceback(val, tb);
403 Py_DECREF(tb);
404 }
405 Py_DECREF(exc);
406 assert(!PyErr_Occurred());
407
408 PyErr_FormatV(exception, format, vargs);
409
410 PyErr_Fetch(&exc, &val2, &tb);
411 PyErr_NormalizeException(&exc, &val2, &tb);
412 Py_INCREF(val);
413 PyException_SetCause(val2, val);
414 PyException_SetContext(val2, val);
415 PyErr_Restore(exc, val2, tb);
416
417 return NULL;
418}
419
420PyObject *
421_PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
422{
423 va_list vargs;
424#ifdef HAVE_STDARG_PROTOTYPES
425 va_start(vargs, format);
426#else
427 va_start(vargs);
428#endif
429 _PyErr_FormatVFromCause(exception, format, vargs);
430 va_end(vargs);
431 return NULL;
432}
433
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000434/* Convenience functions to set a type error exception and return 0 */
435
436int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000437PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyErr_SetString(PyExc_TypeError,
440 "bad argument type for built-in operation");
441 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000442}
443
Guido van Rossum373c8691997-04-29 18:22:47 +0000444PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000445PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000446{
Victor Stinnerf54a5742013-07-22 22:28:37 +0200447 if (Py_TYPE(PyExc_MemoryError) == NULL) {
448 /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
449 initialized by _PyExc_Init() */
450 Py_FatalError("Out of memory and PyExc_MemoryError is not "
451 "initialized yet");
452 }
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000453 PyErr_SetNone(PyExc_MemoryError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000455}
456
Guido van Rossum373c8691997-04-29 18:22:47 +0000457PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000458PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000459{
Larry Hastingsb0827312014-02-09 22:05:19 -0800460 return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
461}
462
463PyObject *
464PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyObject *message;
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200467 PyObject *v, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 int i = errno;
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100469#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 WCHAR *s_buf = NULL;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000471#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000472
Guido van Rossume9fbc091995-02-18 14:52:19 +0000473#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (i == EINTR && PyErr_CheckSignals())
475 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000476#endif
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000477
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000478#ifndef MS_WINDOWS
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100479 if (i != 0) {
480 char *s = strerror(i);
Victor Stinner1b579672011-12-17 05:47:23 +0100481 message = PyUnicode_DecodeLocale(s, "surrogateescape");
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100482 }
483 else {
484 /* Sometimes errno didn't get set */
485 message = PyUnicode_FromString("Error");
486 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000487#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (i == 0)
489 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
490 else
491 {
492 /* Note that the Win32 errors do not lineup with the
493 errno error. So if the error is in the MSVC error
494 table, we use it, otherwise we assume it really _is_
495 a Win32 error code
496 */
497 if (i > 0 && i < _sys_nerr) {
498 message = PyUnicode_FromString(_sys_errlist[i]);
499 }
500 else {
501 int len = FormatMessageW(
502 FORMAT_MESSAGE_ALLOCATE_BUFFER |
503 FORMAT_MESSAGE_FROM_SYSTEM |
504 FORMAT_MESSAGE_IGNORE_INSERTS,
505 NULL, /* no message source */
506 i,
507 MAKELANGID(LANG_NEUTRAL,
508 SUBLANG_DEFAULT),
509 /* Default language */
510 (LPWSTR) &s_buf,
511 0, /* size not used */
512 NULL); /* no args */
513 if (len==0) {
514 /* Only ever seen this in out-of-mem
515 situations */
516 s_buf = NULL;
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300517 message = PyUnicode_FromFormat("Windows Error 0x%x", i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 } else {
519 /* remove trailing cr/lf and dots */
520 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
521 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200522 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 }
524 }
525 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000526#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (message == NULL)
529 {
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000530#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 LocalFree(s_buf);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000532#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return NULL;
534 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000535
Larry Hastingsb0827312014-02-09 22:05:19 -0800536 if (filenameObject != NULL) {
537 if (filenameObject2 != NULL)
538 args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
539 else
540 args = Py_BuildValue("(iOO)", i, message, filenameObject);
541 } else {
542 assert(filenameObject2 == NULL);
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200543 args = Py_BuildValue("(iO)", i, message);
Larry Hastingsb0827312014-02-09 22:05:19 -0800544 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000546
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200547 if (args != NULL) {
548 v = PyObject_Call(exc, args, NULL);
549 Py_DECREF(args);
550 if (v != NULL) {
551 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
552 Py_DECREF(v);
553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000555#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000557#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000559}
Guido van Rossum743007d1999-04-21 15:27:31 +0000560
Barry Warsaw97d95151998-07-23 16:05:56 +0000561PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000562PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800565 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 Py_XDECREF(name);
567 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000568}
569
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000570#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000571PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000572PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000573{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200574 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800575 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 Py_XDECREF(name);
577 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000578}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000579#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000580
581PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000582PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000583{
Larry Hastingsb0827312014-02-09 22:05:19 -0800584 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000585}
Guido van Rossum683a0721990-10-21 22:09:12 +0000586
Brett Cannonbf364092006-03-01 04:25:17 +0000587#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000588/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000589PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 PyObject *exc,
591 int ierr,
592 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000593{
Larry Hastingsb0827312014-02-09 22:05:19 -0800594 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
595 filenameObject, NULL);
596}
597
598PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
599 PyObject *exc,
600 int ierr,
601 PyObject *filenameObject,
602 PyObject *filenameObject2)
603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 int len;
605 WCHAR *s_buf = NULL; /* Free via LocalFree */
606 PyObject *message;
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200607 PyObject *args, *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 DWORD err = (DWORD)ierr;
609 if (err==0) err = GetLastError();
610 len = FormatMessageW(
611 /* Error API error */
612 FORMAT_MESSAGE_ALLOCATE_BUFFER |
613 FORMAT_MESSAGE_FROM_SYSTEM |
614 FORMAT_MESSAGE_IGNORE_INSERTS,
615 NULL, /* no message source */
616 err,
617 MAKELANGID(LANG_NEUTRAL,
618 SUBLANG_DEFAULT), /* Default language */
619 (LPWSTR) &s_buf,
620 0, /* size not used */
621 NULL); /* no args */
622 if (len==0) {
623 /* Only seen this in out of mem situations */
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300624 message = PyUnicode_FromFormat("Windows Error 0x%x", err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 s_buf = NULL;
626 } else {
627 /* remove trailing cr/lf and dots */
628 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
629 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200630 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (message == NULL)
634 {
635 LocalFree(s_buf);
636 return NULL;
637 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000638
Larry Hastingsb0827312014-02-09 22:05:19 -0800639 if (filenameObject == NULL) {
640 assert(filenameObject2 == NULL);
641 filenameObject = filenameObject2 = Py_None;
642 }
643 else if (filenameObject2 == NULL)
644 filenameObject2 = Py_None;
645 /* This is the constructor signature for OSError.
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200646 The POSIX translation will be figured out by the constructor. */
Larry Hastingsb0827312014-02-09 22:05:19 -0800647 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000649
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200650 if (args != NULL) {
651 v = PyObject_Call(exc, args, NULL);
652 Py_DECREF(args);
653 if (v != NULL) {
654 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
655 Py_DECREF(v);
656 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 }
658 LocalFree(s_buf);
659 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000660}
661
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000662PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyObject *exc,
664 int ierr,
665 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000666{
Victor Stinner92be9392010-12-28 00:28:21 +0000667 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800668 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800670 name,
671 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 Py_XDECREF(name);
673 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000674}
675
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000676PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyObject *exc,
678 int ierr,
679 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000680{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200681 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800682 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800684 name,
685 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 Py_XDECREF(name);
687 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000688}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000689
Thomas Heller085358a2002-07-29 14:27:41 +0000690PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
691{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800692 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000693}
694
Guido van Rossum795e1892000-02-17 15:19:15 +0000695PyObject *PyErr_SetFromWindowsErr(int ierr)
696{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800697 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
698 ierr, NULL);
Larry Hastingsb0827312014-02-09 22:05:19 -0800699}
700
Thomas Heller085358a2002-07-29 14:27:41 +0000701PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 int ierr,
703 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000704{
Victor Stinner92be9392010-12-28 00:28:21 +0000705 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800706 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200707 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800708 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 Py_XDECREF(name);
710 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000711}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000712
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000713PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 int ierr,
715 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000716{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200717 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800718 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200719 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800720 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 Py_XDECREF(name);
722 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000723}
Guido van Rossum795e1892000-02-17 15:19:15 +0000724#endif /* MS_WINDOWS */
725
Brett Cannon79ec55e2012-04-12 20:24:54 -0400726PyObject *
Eric Snow46f97b82016-09-07 16:56:15 -0700727PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
728 PyObject *name, PyObject *path)
Brett Cannon79ec55e2012-04-12 20:24:54 -0400729{
Eric Snow46f97b82016-09-07 16:56:15 -0700730 int issubclass;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200731 PyObject *kwargs, *error;
Brian Curtin09b86d12012-04-17 16:57:09 -0500732
Eric Snow46f97b82016-09-07 16:56:15 -0700733 issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
734 if (issubclass < 0) {
735 return NULL;
736 }
737 else if (!issubclass) {
738 PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError");
Brian Curtin94c001b2012-04-18 08:30:51 -0500739 return NULL;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200740 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500741
Eric Snow46f97b82016-09-07 16:56:15 -0700742 if (msg == NULL) {
743 PyErr_SetString(PyExc_TypeError, "expected a message argument");
Brian Curtin09b86d12012-04-17 16:57:09 -0500744 return NULL;
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400745 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500746
Brian Curtin94c001b2012-04-18 08:30:51 -0500747 if (name == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500748 name = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500749 }
Brian Curtin94c001b2012-04-18 08:30:51 -0500750 if (path == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500751 path = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500752 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500753
Eric Snow46f97b82016-09-07 16:56:15 -0700754 kwargs = PyDict_New();
755 if (kwargs == NULL) {
756 return NULL;
757 }
Victor Stinnerf45a5612016-08-23 00:04:41 +0200758 if (PyDict_SetItemString(kwargs, "name", name) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300759 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200760 }
761 if (PyDict_SetItemString(kwargs, "path", path) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300762 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200763 }
Brett Cannon79ec55e2012-04-12 20:24:54 -0400764
Eric Snow46f97b82016-09-07 16:56:15 -0700765 error = _PyObject_FastCallDict(exception, &msg, 1, kwargs);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400766 if (error != NULL) {
767 PyErr_SetObject((PyObject *)Py_TYPE(error), error);
Brian Curtin09b86d12012-04-17 16:57:09 -0500768 Py_DECREF(error);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400769 }
770
Berker Peksagec766d32016-05-01 09:06:36 +0300771done:
Brett Cannon79ec55e2012-04-12 20:24:54 -0400772 Py_DECREF(kwargs);
Brian Curtin09b86d12012-04-17 16:57:09 -0500773 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400774}
775
Eric Snow46f97b82016-09-07 16:56:15 -0700776PyObject *
777PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
778{
779 return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
780}
781
Guido van Rossum683a0721990-10-21 22:09:12 +0000782void
Neal Norwitzb382b842007-08-24 20:00:37 +0000783_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 PyErr_Format(PyExc_SystemError,
786 "%s:%d: bad argument to internal function",
787 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000788}
789
790/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
791 export the entry point for existing object code: */
792#undef PyErr_BadInternalCall
793void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000794PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000795{
Victor Stinnerfb3a6302013-07-12 00:37:30 +0200796 assert(0 && "bad argument to internal function");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 PyErr_Format(PyExc_SystemError,
798 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000799}
Fred Drake6d63adf2000-08-24 22:38:39 +0000800#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
801
Guido van Rossum1548bac1997-02-14 17:09:47 +0000802
Guido van Rossum1548bac1997-02-14 17:09:47 +0000803PyObject *
Antoine Pitrou0676a402014-09-30 21:16:27 +0200804PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000807
Victor Stinnerde821be2015-03-24 12:41:23 +0100808 /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
809 exception set, it calls arbitrary Python code like PyObject_Repr() */
Victor Stinnerace47d72013-07-18 01:41:08 +0200810 PyErr_Clear();
Victor Stinnerace47d72013-07-18 01:41:08 +0200811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 string = PyUnicode_FromFormatV(format, vargs);
Victor Stinnerde821be2015-03-24 12:41:23 +0100813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyErr_SetObject(exception, string);
815 Py_XDECREF(string);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000817}
Guido van Rossum7617e051997-09-16 18:43:50 +0000818
819
Antoine Pitrou0676a402014-09-30 21:16:27 +0200820PyObject *
821PyErr_Format(PyObject *exception, const char *format, ...)
822{
823 va_list vargs;
824#ifdef HAVE_STDARG_PROTOTYPES
825 va_start(vargs, format);
826#else
827 va_start(vargs);
828#endif
829 PyErr_FormatV(exception, format, vargs);
830 va_end(vargs);
831 return NULL;
832}
833
Thomas Wouters477c8d52006-05-27 19:21:47 +0000834
Guido van Rossum7617e051997-09-16 18:43:50 +0000835PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000836PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 const char *dot;
839 PyObject *modulename = NULL;
840 PyObject *classname = NULL;
841 PyObject *mydict = NULL;
842 PyObject *bases = NULL;
843 PyObject *result = NULL;
844 dot = strrchr(name, '.');
845 if (dot == NULL) {
846 PyErr_SetString(PyExc_SystemError,
847 "PyErr_NewException: name must be module.class");
848 return NULL;
849 }
850 if (base == NULL)
851 base = PyExc_Exception;
852 if (dict == NULL) {
853 dict = mydict = PyDict_New();
854 if (dict == NULL)
855 goto failure;
856 }
857 if (PyDict_GetItemString(dict, "__module__") == NULL) {
858 modulename = PyUnicode_FromStringAndSize(name,
859 (Py_ssize_t)(dot-name));
860 if (modulename == NULL)
861 goto failure;
862 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
863 goto failure;
864 }
865 if (PyTuple_Check(base)) {
866 bases = base;
867 /* INCREF as we create a new ref in the else branch */
868 Py_INCREF(bases);
869 } else {
870 bases = PyTuple_Pack(1, base);
871 if (bases == NULL)
872 goto failure;
873 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100874 /* Create a real class. */
Victor Stinner7eeb5b52010-06-07 19:57:46 +0000875 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000877 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 Py_XDECREF(bases);
879 Py_XDECREF(mydict);
880 Py_XDECREF(classname);
881 Py_XDECREF(modulename);
882 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000883}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000884
Georg Brandl1e28a272009-12-28 08:41:01 +0000885
886/* Create an exception with docstring */
887PyObject *
888PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 int result;
892 PyObject *ret = NULL;
893 PyObject *mydict = NULL; /* points to the dict only if we create it */
894 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (dict == NULL) {
897 dict = mydict = PyDict_New();
898 if (dict == NULL) {
899 return NULL;
900 }
901 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (doc != NULL) {
904 docobj = PyUnicode_FromString(doc);
905 if (docobj == NULL)
906 goto failure;
907 result = PyDict_SetItemString(dict, "__doc__", docobj);
908 Py_DECREF(docobj);
909 if (result < 0)
910 goto failure;
911 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000914 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 Py_XDECREF(mydict);
916 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000917}
918
919
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000920/* Call when an exception has occurred but there is no way for Python
921 to handle it. Examples: exception in __del__ or during GC. */
922void
923PyErr_WriteUnraisable(PyObject *obj)
924{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200925 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 PyObject *f, *t, *v, *tb;
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200927 PyObject *moduleName = NULL;
928 char* className;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000929
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200930 PyErr_Fetch(&t, &v, &tb);
931
Victor Stinnerbd303c12013-11-07 23:07:29 +0100932 f = _PySys_GetObjectId(&PyId_stderr);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200933 if (f == NULL || f == Py_None)
934 goto done;
935
936 if (obj) {
937 if (PyFile_WriteString("Exception ignored in: ", f) < 0)
938 goto done;
Martin Panter3263f682016-02-28 03:16:11 +0000939 if (PyFile_WriteObject(obj, f, 0) < 0) {
940 PyErr_Clear();
941 if (PyFile_WriteString("<object repr() failed>", f) < 0) {
942 goto done;
943 }
944 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200945 if (PyFile_WriteString("\n", f) < 0)
946 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200948
949 if (PyTraceBack_Print(tb, f) < 0)
950 goto done;
951
952 if (!t)
953 goto done;
954
955 assert(PyExceptionClass_Check(t));
956 className = PyExceptionClass_Name(t);
957 if (className != NULL) {
958 char *dot = strrchr(className, '.');
959 if (dot != NULL)
960 className = dot+1;
961 }
962
963 moduleName = _PyObject_GetAttrId(t, &PyId___module__);
Oren Milmanf6e61df2017-09-14 01:30:05 +0300964 if (moduleName == NULL || !PyUnicode_Check(moduleName)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200965 PyErr_Clear();
966 if (PyFile_WriteString("<unknown>", f) < 0)
967 goto done;
968 }
969 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200970 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200971 if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
972 goto done;
973 if (PyFile_WriteString(".", f) < 0)
974 goto done;
975 }
976 }
977 if (className == NULL) {
978 if (PyFile_WriteString("<unknown>", f) < 0)
979 goto done;
980 }
981 else {
982 if (PyFile_WriteString(className, f) < 0)
983 goto done;
984 }
985
986 if (v && v != Py_None) {
987 if (PyFile_WriteString(": ", f) < 0)
988 goto done;
Martin Panter3263f682016-02-28 03:16:11 +0000989 if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
990 PyErr_Clear();
991 if (PyFile_WriteString("<exception str() failed>", f) < 0) {
992 goto done;
993 }
994 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200995 }
996 if (PyFile_WriteString("\n", f) < 0)
997 goto done;
998
999done:
1000 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 Py_XDECREF(t);
1002 Py_XDECREF(v);
1003 Py_XDECREF(tb);
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001004 PyErr_Clear(); /* Just in case */
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001005}
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001006
Armin Rigo092381a2003-10-25 14:29:27 +00001007extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001008
Guido van Rossum2fd45652001-02-28 21:46:24 +00001009
Benjamin Peterson2c539712010-09-20 22:42:10 +00001010void
Victor Stinner14e461d2013-08-26 22:28:21 +02001011PyErr_SyntaxLocation(const char *filename, int lineno)
1012{
Benjamin Peterson2c539712010-09-20 22:42:10 +00001013 PyErr_SyntaxLocationEx(filename, lineno, -1);
1014}
1015
1016
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001017/* Set file and line information for the current exception.
1018 If the exception is not a SyntaxError, also sets additional attributes
1019 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +00001020
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001021void
Victor Stinner14e461d2013-08-26 22:28:21 +02001022PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 PyObject *exc, *v, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001025 _Py_IDENTIFIER(filename);
1026 _Py_IDENTIFIER(lineno);
1027 _Py_IDENTIFIER(msg);
1028 _Py_IDENTIFIER(offset);
1029 _Py_IDENTIFIER(print_file_and_line);
1030 _Py_IDENTIFIER(text);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 /* add attributes for the line number and filename for the error */
1033 PyErr_Fetch(&exc, &v, &tb);
1034 PyErr_NormalizeException(&exc, &v, &tb);
1035 /* XXX check that it is, indeed, a syntax error. It might not
1036 * be, though. */
1037 tmp = PyLong_FromLong(lineno);
1038 if (tmp == NULL)
1039 PyErr_Clear();
1040 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001041 if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyErr_Clear();
1043 Py_DECREF(tmp);
1044 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001045 tmp = NULL;
Benjamin Peterson2c539712010-09-20 22:42:10 +00001046 if (col_offset >= 0) {
1047 tmp = PyLong_FromLong(col_offset);
1048 if (tmp == NULL)
1049 PyErr_Clear();
Benjamin Peterson2c539712010-09-20 22:42:10 +00001050 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001051 if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
1052 PyErr_Clear();
1053 Py_XDECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (filename != NULL) {
Victor Stinner14e461d2013-08-26 22:28:21 +02001055 if (_PyObject_SetAttrId(v, &PyId_filename, filename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 PyErr_Clear();
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001057
Victor Stinner14e461d2013-08-26 22:28:21 +02001058 tmp = PyErr_ProgramTextObject(filename, lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001060 if (_PyObject_SetAttrId(v, &PyId_text, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 PyErr_Clear();
1062 Py_DECREF(tmp);
1063 }
1064 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (exc != PyExc_SyntaxError) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001066 if (!_PyObject_HasAttrId(v, &PyId_msg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 tmp = PyObject_Str(v);
1068 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001069 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyErr_Clear();
1071 Py_DECREF(tmp);
1072 } else {
1073 PyErr_Clear();
1074 }
1075 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001076 if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1077 if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1078 Py_None))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 PyErr_Clear();
1080 }
1081 }
1082 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001083}
1084
Victor Stinner14e461d2013-08-26 22:28:21 +02001085void
1086PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1087{
1088 PyObject *fileobj;
1089 if (filename != NULL) {
1090 fileobj = PyUnicode_DecodeFSDefault(filename);
1091 if (fileobj == NULL)
1092 PyErr_Clear();
1093 }
1094 else
1095 fileobj = NULL;
1096 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1097 Py_XDECREF(fileobj);
1098}
1099
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001100/* Attempt to load the line of text that the exception refers to. If it
1101 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001102
1103 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001104 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001105
Antoine Pitrou409b5382013-10-12 22:41:17 +02001106static PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001107err_programtext(FILE *fp, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 int i;
1110 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 if (fp == NULL)
1113 return NULL;
1114 for (i = 0; i < lineno; i++) {
1115 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1116 do {
1117 *pLastChar = '\0';
1118 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1119 fp, NULL) == NULL)
1120 break;
1121 /* fgets read *something*; if it didn't get as
1122 far as pLastChar, it must have found a newline
1123 or hit the end of the file; if pLastChar is \n,
1124 it obviously found a newline; else we haven't
1125 yet seen a newline, so must continue */
1126 } while (*pLastChar != '\0' && *pLastChar != '\n');
1127 }
1128 fclose(fp);
1129 if (i == lineno) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyObject *res;
Martin Panterca3263c2016-12-11 00:18:36 +00001131 res = PyUnicode_FromString(linebuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (res == NULL)
1133 PyErr_Clear();
1134 return res;
1135 }
1136 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001137}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001138
Victor Stinner14e461d2013-08-26 22:28:21 +02001139PyObject *
1140PyErr_ProgramText(const char *filename, int lineno)
1141{
1142 FILE *fp;
1143 if (filename == NULL || *filename == '\0' || lineno <= 0)
1144 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001145 fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001146 return err_programtext(fp, lineno);
1147}
1148
1149PyObject *
1150PyErr_ProgramTextObject(PyObject *filename, int lineno)
1151{
1152 FILE *fp;
1153 if (filename == NULL || lineno <= 0)
1154 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001155 fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
Victor Stinnere42ccd22015-03-18 01:39:23 +01001156 if (fp == NULL) {
1157 PyErr_Clear();
1158 return NULL;
1159 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001160 return err_programtext(fp, lineno);
1161}
1162
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001163#ifdef __cplusplus
1164}
1165#endif