blob: 60958438152afa8445cd0ee4ebb1760f227b6154 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum373c8691997-04-29 18:22:47 +00002/* Error handling */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossum373c8691997-04-29 18:22:47 +00004#include "Python.h"
Guido van Rossumf22120a1990-12-20 23:05:40 +00005
Guido van Rossum53e8d441995-03-09 12:11:31 +00006#ifndef __STDC__
Guido van Rossum7844e381997-04-11 20:44:04 +00007#ifndef MS_WINDOWS
Tim Petersdbd9ba62000-07-09 03:09:57 +00008extern char *strerror(int);
Guido van Rossum53e8d441995-03-09 12:11:31 +00009#endif
Guido van Rossum7844e381997-04-11 20:44:04 +000010#endif
Guido van Rossumf5401bd1990-11-02 17:50:28 +000011
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000012#ifdef MS_WINDOWS
Martin v. Löwis5d12abe2007-09-03 07:40:24 +000013#include <windows.h>
14#include <winbase.h>
Guido van Rossum743007d1999-04-21 15:27:31 +000015#endif
16
Jeremy Hyltonb69a27e2000-09-01 03:49:47 +000017#include <ctype.h>
18
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019#ifdef __cplusplus
20extern "C" {
21#endif
22
Victor Stinnerbd303c12013-11-07 23:07:29 +010023_Py_IDENTIFIER(builtins);
24_Py_IDENTIFIER(stderr);
25
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000026
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000027void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000028PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
Guido van Rossum1ae940a1995-01-02 19:04:15 +000029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 PyThreadState *tstate = PyThreadState_GET();
31 PyObject *oldtype, *oldvalue, *oldtraceback;
Guido van Rossum1ae940a1995-01-02 19:04:15 +000032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 if (traceback != NULL && !PyTraceBack_Check(traceback)) {
34 /* XXX Should never happen -- fatal error instead? */
35 /* Well, it could be None. */
36 Py_DECREF(traceback);
37 traceback = NULL;
38 }
Guido van Rossuma027efa1997-05-05 20:56:21 +000039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 /* Save these in locals to safeguard against recursive
41 invocation through Py_XDECREF */
42 oldtype = tstate->curexc_type;
43 oldvalue = tstate->curexc_value;
44 oldtraceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +000045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 tstate->curexc_type = type;
47 tstate->curexc_value = value;
48 tstate->curexc_traceback = traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +000049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 Py_XDECREF(oldtype);
51 Py_XDECREF(oldvalue);
52 Py_XDECREF(oldtraceback);
Guido van Rossum1ae940a1995-01-02 19:04:15 +000053}
54
Victor Stinner3a840972016-08-22 23:59:08 +020055static PyObject*
56_PyErr_CreateException(PyObject *exception, PyObject *value)
57{
58 if (value == NULL || value == Py_None) {
59 return _PyObject_CallNoArg(exception);
60 }
61 else if (PyTuple_Check(value)) {
62 return PyObject_Call(exception, value, NULL);
63 }
64 else {
65 return _PyObject_CallArg1(exception, value);
66 }
67}
68
Guido van Rossum1ae940a1995-01-02 19:04:15 +000069void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000070PyErr_SetObject(PyObject *exception, PyObject *value)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 PyThreadState *tstate = PyThreadState_GET();
73 PyObject *exc_value;
74 PyObject *tb = NULL;
Guido van Rossumb4fb6e42008-06-14 20:20:24 +000075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 if (exception != NULL &&
77 !PyExceptionClass_Check(exception)) {
78 PyErr_Format(PyExc_SystemError,
79 "exception %R not a BaseException subclass",
80 exception);
81 return;
82 }
Victor Stinner3a840972016-08-22 23:59:08 +020083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 Py_XINCREF(value);
85 exc_value = tstate->exc_value;
86 if (exc_value != NULL && exc_value != Py_None) {
87 /* Implicit exception chaining */
88 Py_INCREF(exc_value);
89 if (value == NULL || !PyExceptionInstance_Check(value)) {
90 /* We must normalize the value right now */
Victor Stinner3a840972016-08-22 23:59:08 +020091 PyObject *fixed_value;
Victor Stinnerde821be2015-03-24 12:41:23 +010092
Victor Stinner3a840972016-08-22 23:59:08 +020093 /* Issue #23571: functions must not be called with an
Victor Stinnerde821be2015-03-24 12:41:23 +010094 exception set */
Victor Stinnerace47d72013-07-18 01:41:08 +020095 PyErr_Clear();
Victor Stinnerde821be2015-03-24 12:41:23 +010096
Victor Stinner3a840972016-08-22 23:59:08 +020097 fixed_value = _PyErr_CreateException(exception, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 Py_XDECREF(value);
Victor Stinner3a840972016-08-22 23:59:08 +020099 if (fixed_value == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 return;
Victor Stinner3a840972016-08-22 23:59:08 +0200101 }
102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 value = fixed_value;
104 }
Victor Stinner3a840972016-08-22 23:59:08 +0200105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 /* Avoid reference cycles through the context chain.
107 This is O(chain length) but context chains are
108 usually very short. Sensitive readers may try
109 to inline the call to PyException_GetContext. */
110 if (exc_value != value) {
111 PyObject *o = exc_value, *context;
112 while ((context = PyException_GetContext(o))) {
113 Py_DECREF(context);
114 if (context == value) {
115 PyException_SetContext(o, NULL);
116 break;
117 }
118 o = context;
119 }
120 PyException_SetContext(value, exc_value);
Victor Stinner3a840972016-08-22 23:59:08 +0200121 }
122 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 Py_DECREF(exc_value);
124 }
125 }
126 if (value != NULL && PyExceptionInstance_Check(value))
127 tb = PyException_GetTraceback(value);
128 Py_XINCREF(exception);
129 PyErr_Restore(exception, value, tb);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130}
131
Raymond Hettinger69492da2013-09-02 15:59:26 -0700132/* Set a key error with the specified argument, wrapping it in a
133 * tuple automatically so that tuple keys are not unpacked as the
134 * exception arguments. */
135void
136_PyErr_SetKeyError(PyObject *arg)
137{
138 PyObject *tup;
139 tup = PyTuple_Pack(1, arg);
140 if (!tup)
141 return; /* caller will expect error to be set anyway */
142 PyErr_SetObject(PyExc_KeyError, tup);
143 Py_DECREF(tup);
144}
145
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000147PyErr_SetNone(PyObject *exception)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150}
151
152void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000153PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 PyObject *value = PyUnicode_FromString(string);
156 PyErr_SetObject(exception, value);
157 Py_XDECREF(value);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158}
159
Guido van Rossum3a241811994-08-29 12:14:12 +0000160
Guido van Rossum373c8691997-04-29 18:22:47 +0000161PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000162PyErr_Occurred(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163{
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100164 PyThreadState *tstate = _PyThreadState_UncheckedGet();
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +0000165 return tstate == NULL ? NULL : tstate->curexc_type;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000166}
167
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000168
169int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000170PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 if (err == NULL || exc == NULL) {
173 /* maybe caused by "import exceptions" that failed early on */
174 return 0;
175 }
176 if (PyTuple_Check(exc)) {
177 Py_ssize_t i, n;
178 n = PyTuple_Size(exc);
179 for (i = 0; i < n; i++) {
180 /* Test recursively */
181 if (PyErr_GivenExceptionMatches(
182 err, PyTuple_GET_ITEM(exc, i)))
183 {
184 return 1;
185 }
186 }
187 return 0;
188 }
189 /* err might be an instance, so check its class. */
190 if (PyExceptionInstance_Check(err))
191 err = PyExceptionInstance_Class(err);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
194 int res = 0;
195 PyObject *exception, *value, *tb;
196 PyErr_Fetch(&exception, &value, &tb);
197 /* PyObject_IsSubclass() can recurse and therefore is
198 not safe (see test_bad_getattr in test.pickletester). */
199 res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
200 /* This function must not fail, so print the error here */
201 if (res == -1) {
202 PyErr_WriteUnraisable(err);
203 res = 0;
204 }
205 PyErr_Restore(exception, value, tb);
206 return res;
207 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 return err == exc;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000210}
Guido van Rossum743007d1999-04-21 15:27:31 +0000211
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000212
213int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000214PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000217}
218
219
220/* Used in many places to normalize a raised exception, including in
221 eval_code2(), do_raise(), and PyErr_Print()
Benjamin Petersone6528212008-07-15 15:32:09 +0000222
223 XXX: should PyErr_NormalizeException() also call
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 PyException_SetTraceback() with the resulting value and tb?
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000225*/
226void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000227PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 PyObject *type = *exc;
230 PyObject *value = *val;
231 PyObject *inclass = NULL;
232 PyObject *initial_tb = NULL;
233 PyThreadState *tstate = NULL;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (type == NULL) {
236 /* There was no exception, so nothing to do. */
237 return;
238 }
Guido van Rossumed473a42000-08-07 19:18:27 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 /* If PyErr_SetNone() was used, the value will have been actually
241 set to NULL.
242 */
243 if (!value) {
244 value = Py_None;
245 Py_INCREF(value);
246 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (PyExceptionInstance_Check(value))
249 inclass = PyExceptionInstance_Class(value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 /* Normalize the exception so that if the type is a class, the
252 value will be an instance.
253 */
254 if (PyExceptionClass_Check(type)) {
Victor Stinner74a7fa62013-07-17 00:44:53 +0200255 int is_subclass;
256 if (inclass) {
257 is_subclass = PyObject_IsSubclass(inclass, type);
258 if (is_subclass < 0)
259 goto finally;
260 }
261 else
262 is_subclass = 0;
263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 /* if the value was not an instance, or is not an instance
265 whose class is (or is derived from) type, then use the
266 value as an argument to instantiation of the type
267 class.
268 */
Victor Stinner74a7fa62013-07-17 00:44:53 +0200269 if (!inclass || !is_subclass) {
Victor Stinner3a840972016-08-22 23:59:08 +0200270 PyObject *fixed_value;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000271
Victor Stinner3a840972016-08-22 23:59:08 +0200272 fixed_value = _PyErr_CreateException(type, value);
273 if (fixed_value == NULL) {
274 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 Py_DECREF(value);
Victor Stinner3a840972016-08-22 23:59:08 +0200278 value = fixed_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 }
280 /* if the class of the instance doesn't exactly match the
281 class of the type, believe the instance
282 */
283 else if (inclass != type) {
284 Py_DECREF(type);
285 type = inclass;
286 Py_INCREF(type);
287 }
288 }
289 *exc = type;
290 *val = value;
291 return;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000292finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 Py_DECREF(type);
294 Py_DECREF(value);
295 /* If the new exception doesn't set a traceback and the old
296 exception had a traceback, use the old traceback for the
297 new exception. It's better than nothing.
298 */
299 initial_tb = *tb;
300 PyErr_Fetch(exc, val, tb);
301 if (initial_tb != NULL) {
302 if (*tb == NULL)
303 *tb = initial_tb;
304 else
305 Py_DECREF(initial_tb);
306 }
307 /* normalize recursively */
308 tstate = PyThreadState_GET();
309 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
310 --tstate->recursion_depth;
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200311 /* throw away the old exception and use the recursion error instead */
312 Py_INCREF(PyExc_RecursionError);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300313 Py_SETREF(*exc, PyExc_RecursionError);
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200314 Py_INCREF(PyExc_RecursionErrorInst);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300315 Py_SETREF(*val, PyExc_RecursionErrorInst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 /* just keeping the old traceback */
317 return;
318 }
319 PyErr_NormalizeException(exc, val, tb);
320 --tstate->recursion_depth;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000321}
322
323
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000325PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 *p_type = tstate->curexc_type;
330 *p_value = tstate->curexc_value;
331 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 tstate->curexc_type = NULL;
334 tstate->curexc_value = NULL;
335 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336}
337
338void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000339PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000343
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200344void
345PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
346{
347 PyThreadState *tstate = PyThreadState_GET();
348
349 *p_type = tstate->exc_type;
350 *p_value = tstate->exc_value;
351 *p_traceback = tstate->exc_traceback;
352
353 Py_XINCREF(*p_type);
354 Py_XINCREF(*p_value);
355 Py_XINCREF(*p_traceback);
356}
357
358void
359PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
360{
361 PyObject *oldtype, *oldvalue, *oldtraceback;
362 PyThreadState *tstate = PyThreadState_GET();
363
364 oldtype = tstate->exc_type;
365 oldvalue = tstate->exc_value;
366 oldtraceback = tstate->exc_traceback;
367
368 tstate->exc_type = p_type;
369 tstate->exc_value = p_value;
370 tstate->exc_traceback = p_traceback;
371
372 Py_XDECREF(oldtype);
373 Py_XDECREF(oldvalue);
374 Py_XDECREF(oldtraceback);
375}
376
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300377/* Like PyErr_Restore(), but if an exception is already set,
378 set the context associated with it.
379 */
380void
381_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
382{
383 if (exc == NULL)
384 return;
385
386 if (PyErr_Occurred()) {
387 PyObject *exc2, *val2, *tb2;
388 PyErr_Fetch(&exc2, &val2, &tb2);
389 PyErr_NormalizeException(&exc, &val, &tb);
Serhiy Storchaka9e373be2016-10-21 16:19:59 +0300390 if (tb != NULL) {
391 PyException_SetTraceback(val, tb);
392 Py_DECREF(tb);
393 }
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300394 Py_DECREF(exc);
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300395 PyErr_NormalizeException(&exc2, &val2, &tb2);
396 PyException_SetContext(val2, val);
397 PyErr_Restore(exc2, val2, tb2);
398 }
399 else {
400 PyErr_Restore(exc, val, tb);
401 }
402}
403
Serhiy Storchaka467ab192016-10-21 17:09:17 +0300404static PyObject *
405_PyErr_FormatVFromCause(PyObject *exception, const char *format, va_list vargs)
406{
407 PyObject *exc, *val, *val2, *tb;
408
409 assert(PyErr_Occurred());
410 PyErr_Fetch(&exc, &val, &tb);
411 PyErr_NormalizeException(&exc, &val, &tb);
412 if (tb != NULL) {
413 PyException_SetTraceback(val, tb);
414 Py_DECREF(tb);
415 }
416 Py_DECREF(exc);
417 assert(!PyErr_Occurred());
418
419 PyErr_FormatV(exception, format, vargs);
420
421 PyErr_Fetch(&exc, &val2, &tb);
422 PyErr_NormalizeException(&exc, &val2, &tb);
423 Py_INCREF(val);
424 PyException_SetCause(val2, val);
425 PyException_SetContext(val2, val);
426 PyErr_Restore(exc, val2, tb);
427
428 return NULL;
429}
430
431PyObject *
432_PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
433{
434 va_list vargs;
435#ifdef HAVE_STDARG_PROTOTYPES
436 va_start(vargs, format);
437#else
438 va_start(vargs);
439#endif
440 _PyErr_FormatVFromCause(exception, format, vargs);
441 va_end(vargs);
442 return NULL;
443}
444
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000445/* Convenience functions to set a type error exception and return 0 */
446
447int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000448PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 PyErr_SetString(PyExc_TypeError,
451 "bad argument type for built-in operation");
452 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000453}
454
Guido van Rossum373c8691997-04-29 18:22:47 +0000455PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000456PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000457{
Victor Stinnerf54a5742013-07-22 22:28:37 +0200458 if (Py_TYPE(PyExc_MemoryError) == NULL) {
459 /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
460 initialized by _PyExc_Init() */
461 Py_FatalError("Out of memory and PyExc_MemoryError is not "
462 "initialized yet");
463 }
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000464 PyErr_SetNone(PyExc_MemoryError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000466}
467
Guido van Rossum373c8691997-04-29 18:22:47 +0000468PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000469PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000470{
Larry Hastingsb0827312014-02-09 22:05:19 -0800471 return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
472}
473
474PyObject *
475PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 PyObject *message;
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200478 PyObject *v, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 int i = errno;
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100480#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 WCHAR *s_buf = NULL;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000482#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000483
Guido van Rossume9fbc091995-02-18 14:52:19 +0000484#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 if (i == EINTR && PyErr_CheckSignals())
486 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000487#endif
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000488
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000489#ifndef MS_WINDOWS
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100490 if (i != 0) {
491 char *s = strerror(i);
Victor Stinner1b579672011-12-17 05:47:23 +0100492 message = PyUnicode_DecodeLocale(s, "surrogateescape");
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100493 }
494 else {
495 /* Sometimes errno didn't get set */
496 message = PyUnicode_FromString("Error");
497 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000498#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 if (i == 0)
500 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
501 else
502 {
503 /* Note that the Win32 errors do not lineup with the
504 errno error. So if the error is in the MSVC error
505 table, we use it, otherwise we assume it really _is_
506 a Win32 error code
507 */
508 if (i > 0 && i < _sys_nerr) {
509 message = PyUnicode_FromString(_sys_errlist[i]);
510 }
511 else {
512 int len = FormatMessageW(
513 FORMAT_MESSAGE_ALLOCATE_BUFFER |
514 FORMAT_MESSAGE_FROM_SYSTEM |
515 FORMAT_MESSAGE_IGNORE_INSERTS,
516 NULL, /* no message source */
517 i,
518 MAKELANGID(LANG_NEUTRAL,
519 SUBLANG_DEFAULT),
520 /* Default language */
521 (LPWSTR) &s_buf,
522 0, /* size not used */
523 NULL); /* no args */
524 if (len==0) {
525 /* Only ever seen this in out-of-mem
526 situations */
527 s_buf = NULL;
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300528 message = PyUnicode_FromFormat("Windows Error 0x%x", i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 } else {
530 /* remove trailing cr/lf and dots */
531 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
532 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200533 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 }
535 }
536 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000537#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 if (message == NULL)
540 {
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000541#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 LocalFree(s_buf);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000543#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 return NULL;
545 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000546
Larry Hastingsb0827312014-02-09 22:05:19 -0800547 if (filenameObject != NULL) {
548 if (filenameObject2 != NULL)
549 args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
550 else
551 args = Py_BuildValue("(iOO)", i, message, filenameObject);
552 } else {
553 assert(filenameObject2 == NULL);
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200554 args = Py_BuildValue("(iO)", i, message);
Larry Hastingsb0827312014-02-09 22:05:19 -0800555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000557
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200558 if (args != NULL) {
559 v = PyObject_Call(exc, args, NULL);
560 Py_DECREF(args);
561 if (v != NULL) {
562 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
563 Py_DECREF(v);
564 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000566#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000568#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000570}
Guido van Rossum743007d1999-04-21 15:27:31 +0000571
Barry Warsaw97d95151998-07-23 16:05:56 +0000572PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000573PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800576 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 Py_XDECREF(name);
578 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000579}
580
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000581#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000582PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000583PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 PyObject *name = filename ?
586 PyUnicode_FromUnicode(filename, wcslen(filename)) :
587 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800588 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 Py_XDECREF(name);
590 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000591}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000592#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000593
594PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000595PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000596{
Larry Hastingsb0827312014-02-09 22:05:19 -0800597 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000598}
Guido van Rossum683a0721990-10-21 22:09:12 +0000599
Brett Cannonbf364092006-03-01 04:25:17 +0000600#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000601/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000602PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 PyObject *exc,
604 int ierr,
605 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000606{
Larry Hastingsb0827312014-02-09 22:05:19 -0800607 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
608 filenameObject, NULL);
609}
610
611PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
612 PyObject *exc,
613 int ierr,
614 PyObject *filenameObject,
615 PyObject *filenameObject2)
616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 int len;
618 WCHAR *s_buf = NULL; /* Free via LocalFree */
619 PyObject *message;
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200620 PyObject *args, *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 DWORD err = (DWORD)ierr;
622 if (err==0) err = GetLastError();
623 len = FormatMessageW(
624 /* Error API error */
625 FORMAT_MESSAGE_ALLOCATE_BUFFER |
626 FORMAT_MESSAGE_FROM_SYSTEM |
627 FORMAT_MESSAGE_IGNORE_INSERTS,
628 NULL, /* no message source */
629 err,
630 MAKELANGID(LANG_NEUTRAL,
631 SUBLANG_DEFAULT), /* Default language */
632 (LPWSTR) &s_buf,
633 0, /* size not used */
634 NULL); /* no args */
635 if (len==0) {
636 /* Only seen this in out of mem situations */
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300637 message = PyUnicode_FromFormat("Windows Error 0x%x", err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 s_buf = NULL;
639 } else {
640 /* remove trailing cr/lf and dots */
641 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
642 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200643 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (message == NULL)
647 {
648 LocalFree(s_buf);
649 return NULL;
650 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000651
Larry Hastingsb0827312014-02-09 22:05:19 -0800652 if (filenameObject == NULL) {
653 assert(filenameObject2 == NULL);
654 filenameObject = filenameObject2 = Py_None;
655 }
656 else if (filenameObject2 == NULL)
657 filenameObject2 = Py_None;
658 /* This is the constructor signature for OSError.
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200659 The POSIX translation will be figured out by the constructor. */
Larry Hastingsb0827312014-02-09 22:05:19 -0800660 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000662
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200663 if (args != NULL) {
664 v = PyObject_Call(exc, args, NULL);
665 Py_DECREF(args);
666 if (v != NULL) {
667 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
668 Py_DECREF(v);
669 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 }
671 LocalFree(s_buf);
672 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000673}
674
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000675PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyObject *exc,
677 int ierr,
678 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000679{
Victor Stinner92be9392010-12-28 00:28:21 +0000680 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800681 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800683 name,
684 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 Py_XDECREF(name);
686 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000687}
688
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000689PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 PyObject *exc,
691 int ierr,
692 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyObject *name = filename ?
695 PyUnicode_FromUnicode(filename, wcslen(filename)) :
696 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800697 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800699 name,
700 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 Py_XDECREF(name);
702 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000703}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000704
Thomas Heller085358a2002-07-29 14:27:41 +0000705PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
706{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800707 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000708}
709
Guido van Rossum795e1892000-02-17 15:19:15 +0000710PyObject *PyErr_SetFromWindowsErr(int ierr)
711{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800712 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
713 ierr, NULL);
Larry Hastingsb0827312014-02-09 22:05:19 -0800714}
715
Thomas Heller085358a2002-07-29 14:27:41 +0000716PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 int ierr,
718 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000719{
Victor Stinner92be9392010-12-28 00:28:21 +0000720 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800721 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200722 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800723 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 Py_XDECREF(name);
725 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000726}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000727
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000728PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 int ierr,
730 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject *name = filename ?
733 PyUnicode_FromUnicode(filename, wcslen(filename)) :
734 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800735 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200736 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800737 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 Py_XDECREF(name);
739 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000740}
Guido van Rossum795e1892000-02-17 15:19:15 +0000741#endif /* MS_WINDOWS */
742
Brett Cannon79ec55e2012-04-12 20:24:54 -0400743PyObject *
Eric Snow46f97b82016-09-07 16:56:15 -0700744PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
745 PyObject *name, PyObject *path)
Brett Cannon79ec55e2012-04-12 20:24:54 -0400746{
Eric Snow46f97b82016-09-07 16:56:15 -0700747 int issubclass;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200748 PyObject *kwargs, *error;
Brian Curtin09b86d12012-04-17 16:57:09 -0500749
Eric Snow46f97b82016-09-07 16:56:15 -0700750 issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
751 if (issubclass < 0) {
752 return NULL;
753 }
754 else if (!issubclass) {
755 PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError");
Brian Curtin94c001b2012-04-18 08:30:51 -0500756 return NULL;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200757 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500758
Eric Snow46f97b82016-09-07 16:56:15 -0700759 if (msg == NULL) {
760 PyErr_SetString(PyExc_TypeError, "expected a message argument");
Brian Curtin09b86d12012-04-17 16:57:09 -0500761 return NULL;
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400762 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500763
Brian Curtin94c001b2012-04-18 08:30:51 -0500764 if (name == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500765 name = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500766 }
Brian Curtin94c001b2012-04-18 08:30:51 -0500767 if (path == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500768 path = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500769 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500770
Eric Snow46f97b82016-09-07 16:56:15 -0700771 kwargs = PyDict_New();
772 if (kwargs == NULL) {
773 return NULL;
774 }
Victor Stinnerf45a5612016-08-23 00:04:41 +0200775 if (PyDict_SetItemString(kwargs, "name", name) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300776 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200777 }
778 if (PyDict_SetItemString(kwargs, "path", path) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300779 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200780 }
Brett Cannon79ec55e2012-04-12 20:24:54 -0400781
Eric Snow46f97b82016-09-07 16:56:15 -0700782 error = _PyObject_FastCallDict(exception, &msg, 1, kwargs);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400783 if (error != NULL) {
784 PyErr_SetObject((PyObject *)Py_TYPE(error), error);
Brian Curtin09b86d12012-04-17 16:57:09 -0500785 Py_DECREF(error);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400786 }
787
Berker Peksagec766d32016-05-01 09:06:36 +0300788done:
Brett Cannon79ec55e2012-04-12 20:24:54 -0400789 Py_DECREF(kwargs);
Brian Curtin09b86d12012-04-17 16:57:09 -0500790 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400791}
792
Eric Snow46f97b82016-09-07 16:56:15 -0700793PyObject *
794PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
795{
796 return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
797}
798
Guido van Rossum683a0721990-10-21 22:09:12 +0000799void
Neal Norwitzb382b842007-08-24 20:00:37 +0000800_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PyErr_Format(PyExc_SystemError,
803 "%s:%d: bad argument to internal function",
804 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000805}
806
807/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
808 export the entry point for existing object code: */
809#undef PyErr_BadInternalCall
810void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000811PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000812{
Victor Stinnerfb3a6302013-07-12 00:37:30 +0200813 assert(0 && "bad argument to internal function");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyErr_Format(PyExc_SystemError,
815 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000816}
Fred Drake6d63adf2000-08-24 22:38:39 +0000817#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
818
Guido van Rossum1548bac1997-02-14 17:09:47 +0000819
Guido van Rossum1548bac1997-02-14 17:09:47 +0000820PyObject *
Antoine Pitrou0676a402014-09-30 21:16:27 +0200821PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000824
Victor Stinnerde821be2015-03-24 12:41:23 +0100825 /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
826 exception set, it calls arbitrary Python code like PyObject_Repr() */
Victor Stinnerace47d72013-07-18 01:41:08 +0200827 PyErr_Clear();
Victor Stinnerace47d72013-07-18 01:41:08 +0200828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 string = PyUnicode_FromFormatV(format, vargs);
Victor Stinnerde821be2015-03-24 12:41:23 +0100830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyErr_SetObject(exception, string);
832 Py_XDECREF(string);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000834}
Guido van Rossum7617e051997-09-16 18:43:50 +0000835
836
Antoine Pitrou0676a402014-09-30 21:16:27 +0200837PyObject *
838PyErr_Format(PyObject *exception, const char *format, ...)
839{
840 va_list vargs;
841#ifdef HAVE_STDARG_PROTOTYPES
842 va_start(vargs, format);
843#else
844 va_start(vargs);
845#endif
846 PyErr_FormatV(exception, format, vargs);
847 va_end(vargs);
848 return NULL;
849}
850
Thomas Wouters477c8d52006-05-27 19:21:47 +0000851
Guido van Rossum7617e051997-09-16 18:43:50 +0000852PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000853PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 const char *dot;
856 PyObject *modulename = NULL;
857 PyObject *classname = NULL;
858 PyObject *mydict = NULL;
859 PyObject *bases = NULL;
860 PyObject *result = NULL;
861 dot = strrchr(name, '.');
862 if (dot == NULL) {
863 PyErr_SetString(PyExc_SystemError,
864 "PyErr_NewException: name must be module.class");
865 return NULL;
866 }
867 if (base == NULL)
868 base = PyExc_Exception;
869 if (dict == NULL) {
870 dict = mydict = PyDict_New();
871 if (dict == NULL)
872 goto failure;
873 }
874 if (PyDict_GetItemString(dict, "__module__") == NULL) {
875 modulename = PyUnicode_FromStringAndSize(name,
876 (Py_ssize_t)(dot-name));
877 if (modulename == NULL)
878 goto failure;
879 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
880 goto failure;
881 }
882 if (PyTuple_Check(base)) {
883 bases = base;
884 /* INCREF as we create a new ref in the else branch */
885 Py_INCREF(bases);
886 } else {
887 bases = PyTuple_Pack(1, base);
888 if (bases == NULL)
889 goto failure;
890 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100891 /* Create a real class. */
Victor Stinner7eeb5b52010-06-07 19:57:46 +0000892 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000894 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 Py_XDECREF(bases);
896 Py_XDECREF(mydict);
897 Py_XDECREF(classname);
898 Py_XDECREF(modulename);
899 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000900}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000901
Georg Brandl1e28a272009-12-28 08:41:01 +0000902
903/* Create an exception with docstring */
904PyObject *
905PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 int result;
909 PyObject *ret = NULL;
910 PyObject *mydict = NULL; /* points to the dict only if we create it */
911 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (dict == NULL) {
914 dict = mydict = PyDict_New();
915 if (dict == NULL) {
916 return NULL;
917 }
918 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (doc != NULL) {
921 docobj = PyUnicode_FromString(doc);
922 if (docobj == NULL)
923 goto failure;
924 result = PyDict_SetItemString(dict, "__doc__", docobj);
925 Py_DECREF(docobj);
926 if (result < 0)
927 goto failure;
928 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000931 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 Py_XDECREF(mydict);
933 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000934}
935
936
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000937/* Call when an exception has occurred but there is no way for Python
938 to handle it. Examples: exception in __del__ or during GC. */
939void
940PyErr_WriteUnraisable(PyObject *obj)
941{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200942 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyObject *f, *t, *v, *tb;
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200944 PyObject *moduleName = NULL;
945 char* className;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000946
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200947 PyErr_Fetch(&t, &v, &tb);
948
Victor Stinnerbd303c12013-11-07 23:07:29 +0100949 f = _PySys_GetObjectId(&PyId_stderr);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200950 if (f == NULL || f == Py_None)
951 goto done;
952
953 if (obj) {
954 if (PyFile_WriteString("Exception ignored in: ", f) < 0)
955 goto done;
Martin Panter3263f682016-02-28 03:16:11 +0000956 if (PyFile_WriteObject(obj, f, 0) < 0) {
957 PyErr_Clear();
958 if (PyFile_WriteString("<object repr() failed>", f) < 0) {
959 goto done;
960 }
961 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200962 if (PyFile_WriteString("\n", f) < 0)
963 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200965
966 if (PyTraceBack_Print(tb, f) < 0)
967 goto done;
968
969 if (!t)
970 goto done;
971
972 assert(PyExceptionClass_Check(t));
973 className = PyExceptionClass_Name(t);
974 if (className != NULL) {
975 char *dot = strrchr(className, '.');
976 if (dot != NULL)
977 className = dot+1;
978 }
979
980 moduleName = _PyObject_GetAttrId(t, &PyId___module__);
981 if (moduleName == NULL) {
982 PyErr_Clear();
983 if (PyFile_WriteString("<unknown>", f) < 0)
984 goto done;
985 }
986 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200987 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200988 if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
989 goto done;
990 if (PyFile_WriteString(".", f) < 0)
991 goto done;
992 }
993 }
994 if (className == NULL) {
995 if (PyFile_WriteString("<unknown>", f) < 0)
996 goto done;
997 }
998 else {
999 if (PyFile_WriteString(className, f) < 0)
1000 goto done;
1001 }
1002
1003 if (v && v != Py_None) {
1004 if (PyFile_WriteString(": ", f) < 0)
1005 goto done;
Martin Panter3263f682016-02-28 03:16:11 +00001006 if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
1007 PyErr_Clear();
1008 if (PyFile_WriteString("<exception str() failed>", f) < 0) {
1009 goto done;
1010 }
1011 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001012 }
1013 if (PyFile_WriteString("\n", f) < 0)
1014 goto done;
1015
1016done:
1017 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 Py_XDECREF(t);
1019 Py_XDECREF(v);
1020 Py_XDECREF(tb);
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001021 PyErr_Clear(); /* Just in case */
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001022}
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001023
Armin Rigo092381a2003-10-25 14:29:27 +00001024extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001025
Guido van Rossum2fd45652001-02-28 21:46:24 +00001026
Benjamin Peterson2c539712010-09-20 22:42:10 +00001027void
Victor Stinner14e461d2013-08-26 22:28:21 +02001028PyErr_SyntaxLocation(const char *filename, int lineno)
1029{
Benjamin Peterson2c539712010-09-20 22:42:10 +00001030 PyErr_SyntaxLocationEx(filename, lineno, -1);
1031}
1032
1033
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001034/* Set file and line information for the current exception.
1035 If the exception is not a SyntaxError, also sets additional attributes
1036 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +00001037
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001038void
Victor Stinner14e461d2013-08-26 22:28:21 +02001039PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 PyObject *exc, *v, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001042 _Py_IDENTIFIER(filename);
1043 _Py_IDENTIFIER(lineno);
1044 _Py_IDENTIFIER(msg);
1045 _Py_IDENTIFIER(offset);
1046 _Py_IDENTIFIER(print_file_and_line);
1047 _Py_IDENTIFIER(text);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 /* add attributes for the line number and filename for the error */
1050 PyErr_Fetch(&exc, &v, &tb);
1051 PyErr_NormalizeException(&exc, &v, &tb);
1052 /* XXX check that it is, indeed, a syntax error. It might not
1053 * be, though. */
1054 tmp = PyLong_FromLong(lineno);
1055 if (tmp == NULL)
1056 PyErr_Clear();
1057 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001058 if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 PyErr_Clear();
1060 Py_DECREF(tmp);
1061 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001062 tmp = NULL;
Benjamin Peterson2c539712010-09-20 22:42:10 +00001063 if (col_offset >= 0) {
1064 tmp = PyLong_FromLong(col_offset);
1065 if (tmp == NULL)
1066 PyErr_Clear();
Benjamin Peterson2c539712010-09-20 22:42:10 +00001067 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001068 if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
1069 PyErr_Clear();
1070 Py_XDECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (filename != NULL) {
Victor Stinner14e461d2013-08-26 22:28:21 +02001072 if (_PyObject_SetAttrId(v, &PyId_filename, filename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyErr_Clear();
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001074
Victor Stinner14e461d2013-08-26 22:28:21 +02001075 tmp = PyErr_ProgramTextObject(filename, lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001077 if (_PyObject_SetAttrId(v, &PyId_text, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyErr_Clear();
1079 Py_DECREF(tmp);
1080 }
1081 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (exc != PyExc_SyntaxError) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001083 if (!_PyObject_HasAttrId(v, &PyId_msg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 tmp = PyObject_Str(v);
1085 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001086 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 PyErr_Clear();
1088 Py_DECREF(tmp);
1089 } else {
1090 PyErr_Clear();
1091 }
1092 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001093 if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1094 if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1095 Py_None))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 PyErr_Clear();
1097 }
1098 }
1099 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001100}
1101
Victor Stinner14e461d2013-08-26 22:28:21 +02001102void
1103PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1104{
1105 PyObject *fileobj;
1106 if (filename != NULL) {
1107 fileobj = PyUnicode_DecodeFSDefault(filename);
1108 if (fileobj == NULL)
1109 PyErr_Clear();
1110 }
1111 else
1112 fileobj = NULL;
1113 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1114 Py_XDECREF(fileobj);
1115}
1116
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001117/* Attempt to load the line of text that the exception refers to. If it
1118 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001119
1120 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001121 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001122
Antoine Pitrou409b5382013-10-12 22:41:17 +02001123static PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001124err_programtext(FILE *fp, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 int i;
1127 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (fp == NULL)
1130 return NULL;
1131 for (i = 0; i < lineno; i++) {
1132 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1133 do {
1134 *pLastChar = '\0';
1135 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1136 fp, NULL) == NULL)
1137 break;
1138 /* fgets read *something*; if it didn't get as
1139 far as pLastChar, it must have found a newline
1140 or hit the end of the file; if pLastChar is \n,
1141 it obviously found a newline; else we haven't
1142 yet seen a newline, so must continue */
1143 } while (*pLastChar != '\0' && *pLastChar != '\n');
1144 }
1145 fclose(fp);
1146 if (i == lineno) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyObject *res;
Martin Panterca3263c2016-12-11 00:18:36 +00001148 res = PyUnicode_FromString(linebuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (res == NULL)
1150 PyErr_Clear();
1151 return res;
1152 }
1153 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001154}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001155
Victor Stinner14e461d2013-08-26 22:28:21 +02001156PyObject *
1157PyErr_ProgramText(const char *filename, int lineno)
1158{
1159 FILE *fp;
1160 if (filename == NULL || *filename == '\0' || lineno <= 0)
1161 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001162 fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001163 return err_programtext(fp, lineno);
1164}
1165
1166PyObject *
1167PyErr_ProgramTextObject(PyObject *filename, int lineno)
1168{
1169 FILE *fp;
1170 if (filename == NULL || lineno <= 0)
1171 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001172 fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
Victor Stinnere42ccd22015-03-18 01:39:23 +01001173 if (fp == NULL) {
1174 PyErr_Clear();
1175 return NULL;
1176 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001177 return err_programtext(fp, lineno);
1178}
1179
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001180#ifdef __cplusplus
1181}
1182#endif