blob: 3785e6981c6498db88aa6402fca2cb3315f399c3 [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 {
Victor Stinner7bfb42d2016-12-05 17:04:32 +010065 return PyObject_CallFunctionObjArgs(exception, value, NULL);
Victor Stinner3a840972016-08-22 23:59:08 +020066 }
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
Victor Stinnerc6944e72016-11-11 02:13:35 +0100161PyObject* _Py_HOT_FUNCTION
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000162PyErr_Occurred(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163{
Victor Stinner0cae6092016-11-11 01:43:56 +0100164 PyThreadState *tstate = PyThreadState_GET();
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{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200585 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800586 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 Py_XDECREF(name);
588 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000589}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000590#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000591
592PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000593PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000594{
Larry Hastingsb0827312014-02-09 22:05:19 -0800595 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000596}
Guido van Rossum683a0721990-10-21 22:09:12 +0000597
Brett Cannonbf364092006-03-01 04:25:17 +0000598#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000599/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000600PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyObject *exc,
602 int ierr,
603 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000604{
Larry Hastingsb0827312014-02-09 22:05:19 -0800605 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
606 filenameObject, NULL);
607}
608
609PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
610 PyObject *exc,
611 int ierr,
612 PyObject *filenameObject,
613 PyObject *filenameObject2)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 int len;
616 WCHAR *s_buf = NULL; /* Free via LocalFree */
617 PyObject *message;
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200618 PyObject *args, *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 DWORD err = (DWORD)ierr;
620 if (err==0) err = GetLastError();
621 len = FormatMessageW(
622 /* Error API error */
623 FORMAT_MESSAGE_ALLOCATE_BUFFER |
624 FORMAT_MESSAGE_FROM_SYSTEM |
625 FORMAT_MESSAGE_IGNORE_INSERTS,
626 NULL, /* no message source */
627 err,
628 MAKELANGID(LANG_NEUTRAL,
629 SUBLANG_DEFAULT), /* Default language */
630 (LPWSTR) &s_buf,
631 0, /* size not used */
632 NULL); /* no args */
633 if (len==0) {
634 /* Only seen this in out of mem situations */
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300635 message = PyUnicode_FromFormat("Windows Error 0x%x", err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 s_buf = NULL;
637 } else {
638 /* remove trailing cr/lf and dots */
639 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
640 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200641 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (message == NULL)
645 {
646 LocalFree(s_buf);
647 return NULL;
648 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000649
Larry Hastingsb0827312014-02-09 22:05:19 -0800650 if (filenameObject == NULL) {
651 assert(filenameObject2 == NULL);
652 filenameObject = filenameObject2 = Py_None;
653 }
654 else if (filenameObject2 == NULL)
655 filenameObject2 = Py_None;
656 /* This is the constructor signature for OSError.
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200657 The POSIX translation will be figured out by the constructor. */
Larry Hastingsb0827312014-02-09 22:05:19 -0800658 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000660
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200661 if (args != NULL) {
662 v = PyObject_Call(exc, args, NULL);
663 Py_DECREF(args);
664 if (v != NULL) {
665 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
666 Py_DECREF(v);
667 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 }
669 LocalFree(s_buf);
670 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000671}
672
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000673PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyObject *exc,
675 int ierr,
676 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000677{
Victor Stinner92be9392010-12-28 00:28:21 +0000678 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800679 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800681 name,
682 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 Py_XDECREF(name);
684 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000685}
686
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000687PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PyObject *exc,
689 int ierr,
690 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000691{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200692 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800693 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800695 name,
696 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 Py_XDECREF(name);
698 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000699}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000700
Thomas Heller085358a2002-07-29 14:27:41 +0000701PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
702{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800703 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000704}
705
Guido van Rossum795e1892000-02-17 15:19:15 +0000706PyObject *PyErr_SetFromWindowsErr(int ierr)
707{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800708 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
709 ierr, NULL);
Larry Hastingsb0827312014-02-09 22:05:19 -0800710}
711
Thomas Heller085358a2002-07-29 14:27:41 +0000712PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 int ierr,
714 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000715{
Victor Stinner92be9392010-12-28 00:28:21 +0000716 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800717 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200718 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800719 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 Py_XDECREF(name);
721 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000722}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000723
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000724PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 int ierr,
726 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000727{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200728 PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800729 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200730 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800731 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 Py_XDECREF(name);
733 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000734}
Guido van Rossum795e1892000-02-17 15:19:15 +0000735#endif /* MS_WINDOWS */
736
Brett Cannon79ec55e2012-04-12 20:24:54 -0400737PyObject *
Eric Snow46f97b82016-09-07 16:56:15 -0700738PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
739 PyObject *name, PyObject *path)
Brett Cannon79ec55e2012-04-12 20:24:54 -0400740{
Eric Snow46f97b82016-09-07 16:56:15 -0700741 int issubclass;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200742 PyObject *kwargs, *error;
Brian Curtin09b86d12012-04-17 16:57:09 -0500743
Eric Snow46f97b82016-09-07 16:56:15 -0700744 issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
745 if (issubclass < 0) {
746 return NULL;
747 }
748 else if (!issubclass) {
749 PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError");
Brian Curtin94c001b2012-04-18 08:30:51 -0500750 return NULL;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200751 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500752
Eric Snow46f97b82016-09-07 16:56:15 -0700753 if (msg == NULL) {
754 PyErr_SetString(PyExc_TypeError, "expected a message argument");
Brian Curtin09b86d12012-04-17 16:57:09 -0500755 return NULL;
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400756 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500757
Brian Curtin94c001b2012-04-18 08:30:51 -0500758 if (name == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500759 name = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500760 }
Brian Curtin94c001b2012-04-18 08:30:51 -0500761 if (path == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500762 path = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500763 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500764
Eric Snow46f97b82016-09-07 16:56:15 -0700765 kwargs = PyDict_New();
766 if (kwargs == NULL) {
767 return NULL;
768 }
Victor Stinnerf45a5612016-08-23 00:04:41 +0200769 if (PyDict_SetItemString(kwargs, "name", name) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300770 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200771 }
772 if (PyDict_SetItemString(kwargs, "path", path) < 0) {
Berker Peksagec766d32016-05-01 09:06:36 +0300773 goto done;
Victor Stinnerf45a5612016-08-23 00:04:41 +0200774 }
Brett Cannon79ec55e2012-04-12 20:24:54 -0400775
Eric Snow46f97b82016-09-07 16:56:15 -0700776 error = _PyObject_FastCallDict(exception, &msg, 1, kwargs);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400777 if (error != NULL) {
778 PyErr_SetObject((PyObject *)Py_TYPE(error), error);
Brian Curtin09b86d12012-04-17 16:57:09 -0500779 Py_DECREF(error);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400780 }
781
Berker Peksagec766d32016-05-01 09:06:36 +0300782done:
Brett Cannon79ec55e2012-04-12 20:24:54 -0400783 Py_DECREF(kwargs);
Brian Curtin09b86d12012-04-17 16:57:09 -0500784 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400785}
786
Eric Snow46f97b82016-09-07 16:56:15 -0700787PyObject *
788PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
789{
790 return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
791}
792
Guido van Rossum683a0721990-10-21 22:09:12 +0000793void
Neal Norwitzb382b842007-08-24 20:00:37 +0000794_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyErr_Format(PyExc_SystemError,
797 "%s:%d: bad argument to internal function",
798 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000799}
800
801/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
802 export the entry point for existing object code: */
803#undef PyErr_BadInternalCall
804void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000805PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000806{
Victor Stinnerfb3a6302013-07-12 00:37:30 +0200807 assert(0 && "bad argument to internal function");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyErr_Format(PyExc_SystemError,
809 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000810}
Fred Drake6d63adf2000-08-24 22:38:39 +0000811#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
812
Guido van Rossum1548bac1997-02-14 17:09:47 +0000813
Guido van Rossum1548bac1997-02-14 17:09:47 +0000814PyObject *
Antoine Pitrou0676a402014-09-30 21:16:27 +0200815PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000818
Victor Stinnerde821be2015-03-24 12:41:23 +0100819 /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
820 exception set, it calls arbitrary Python code like PyObject_Repr() */
Victor Stinnerace47d72013-07-18 01:41:08 +0200821 PyErr_Clear();
Victor Stinnerace47d72013-07-18 01:41:08 +0200822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 string = PyUnicode_FromFormatV(format, vargs);
Victor Stinnerde821be2015-03-24 12:41:23 +0100824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 PyErr_SetObject(exception, string);
826 Py_XDECREF(string);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000828}
Guido van Rossum7617e051997-09-16 18:43:50 +0000829
830
Antoine Pitrou0676a402014-09-30 21:16:27 +0200831PyObject *
832PyErr_Format(PyObject *exception, const char *format, ...)
833{
834 va_list vargs;
835#ifdef HAVE_STDARG_PROTOTYPES
836 va_start(vargs, format);
837#else
838 va_start(vargs);
839#endif
840 PyErr_FormatV(exception, format, vargs);
841 va_end(vargs);
842 return NULL;
843}
844
Thomas Wouters477c8d52006-05-27 19:21:47 +0000845
Guido van Rossum7617e051997-09-16 18:43:50 +0000846PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000847PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 const char *dot;
850 PyObject *modulename = NULL;
851 PyObject *classname = NULL;
852 PyObject *mydict = NULL;
853 PyObject *bases = NULL;
854 PyObject *result = NULL;
855 dot = strrchr(name, '.');
856 if (dot == NULL) {
857 PyErr_SetString(PyExc_SystemError,
858 "PyErr_NewException: name must be module.class");
859 return NULL;
860 }
861 if (base == NULL)
862 base = PyExc_Exception;
863 if (dict == NULL) {
864 dict = mydict = PyDict_New();
865 if (dict == NULL)
866 goto failure;
867 }
868 if (PyDict_GetItemString(dict, "__module__") == NULL) {
869 modulename = PyUnicode_FromStringAndSize(name,
870 (Py_ssize_t)(dot-name));
871 if (modulename == NULL)
872 goto failure;
873 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
874 goto failure;
875 }
876 if (PyTuple_Check(base)) {
877 bases = base;
878 /* INCREF as we create a new ref in the else branch */
879 Py_INCREF(bases);
880 } else {
881 bases = PyTuple_Pack(1, base);
882 if (bases == NULL)
883 goto failure;
884 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100885 /* Create a real class. */
Victor Stinner7eeb5b52010-06-07 19:57:46 +0000886 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000888 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 Py_XDECREF(bases);
890 Py_XDECREF(mydict);
891 Py_XDECREF(classname);
892 Py_XDECREF(modulename);
893 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000894}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000895
Georg Brandl1e28a272009-12-28 08:41:01 +0000896
897/* Create an exception with docstring */
898PyObject *
899PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 int result;
903 PyObject *ret = NULL;
904 PyObject *mydict = NULL; /* points to the dict only if we create it */
905 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 if (dict == NULL) {
908 dict = mydict = PyDict_New();
909 if (dict == NULL) {
910 return NULL;
911 }
912 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (doc != NULL) {
915 docobj = PyUnicode_FromString(doc);
916 if (docobj == NULL)
917 goto failure;
918 result = PyDict_SetItemString(dict, "__doc__", docobj);
919 Py_DECREF(docobj);
920 if (result < 0)
921 goto failure;
922 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000925 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 Py_XDECREF(mydict);
927 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000928}
929
930
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000931/* Call when an exception has occurred but there is no way for Python
932 to handle it. Examples: exception in __del__ or during GC. */
933void
934PyErr_WriteUnraisable(PyObject *obj)
935{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200936 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 PyObject *f, *t, *v, *tb;
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200938 PyObject *moduleName = NULL;
939 char* className;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000940
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200941 PyErr_Fetch(&t, &v, &tb);
942
Victor Stinnerbd303c12013-11-07 23:07:29 +0100943 f = _PySys_GetObjectId(&PyId_stderr);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200944 if (f == NULL || f == Py_None)
945 goto done;
946
947 if (obj) {
948 if (PyFile_WriteString("Exception ignored in: ", f) < 0)
949 goto done;
Martin Panter3263f682016-02-28 03:16:11 +0000950 if (PyFile_WriteObject(obj, f, 0) < 0) {
951 PyErr_Clear();
952 if (PyFile_WriteString("<object repr() failed>", f) < 0) {
953 goto done;
954 }
955 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200956 if (PyFile_WriteString("\n", f) < 0)
957 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200959
960 if (PyTraceBack_Print(tb, f) < 0)
961 goto done;
962
963 if (!t)
964 goto done;
965
966 assert(PyExceptionClass_Check(t));
967 className = PyExceptionClass_Name(t);
968 if (className != NULL) {
969 char *dot = strrchr(className, '.');
970 if (dot != NULL)
971 className = dot+1;
972 }
973
974 moduleName = _PyObject_GetAttrId(t, &PyId___module__);
975 if (moduleName == NULL) {
976 PyErr_Clear();
977 if (PyFile_WriteString("<unknown>", f) < 0)
978 goto done;
979 }
980 else {
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +0200981 if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200982 if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
983 goto done;
984 if (PyFile_WriteString(".", f) < 0)
985 goto done;
986 }
987 }
988 if (className == NULL) {
989 if (PyFile_WriteString("<unknown>", f) < 0)
990 goto done;
991 }
992 else {
993 if (PyFile_WriteString(className, f) < 0)
994 goto done;
995 }
996
997 if (v && v != Py_None) {
998 if (PyFile_WriteString(": ", f) < 0)
999 goto done;
Martin Panter3263f682016-02-28 03:16:11 +00001000 if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
1001 PyErr_Clear();
1002 if (PyFile_WriteString("<exception str() failed>", f) < 0) {
1003 goto done;
1004 }
1005 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001006 }
1007 if (PyFile_WriteString("\n", f) < 0)
1008 goto done;
1009
1010done:
1011 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 Py_XDECREF(t);
1013 Py_XDECREF(v);
1014 Py_XDECREF(tb);
Victor Stinnerc82bfd82013-08-26 14:04:10 +02001015 PyErr_Clear(); /* Just in case */
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001016}
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001017
Armin Rigo092381a2003-10-25 14:29:27 +00001018extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +00001019
Guido van Rossum2fd45652001-02-28 21:46:24 +00001020
Benjamin Peterson2c539712010-09-20 22:42:10 +00001021void
Victor Stinner14e461d2013-08-26 22:28:21 +02001022PyErr_SyntaxLocation(const char *filename, int lineno)
1023{
Benjamin Peterson2c539712010-09-20 22:42:10 +00001024 PyErr_SyntaxLocationEx(filename, lineno, -1);
1025}
1026
1027
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +00001028/* Set file and line information for the current exception.
1029 If the exception is not a SyntaxError, also sets additional attributes
1030 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +00001031
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001032void
Victor Stinner14e461d2013-08-26 22:28:21 +02001033PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyObject *exc, *v, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001036 _Py_IDENTIFIER(filename);
1037 _Py_IDENTIFIER(lineno);
1038 _Py_IDENTIFIER(msg);
1039 _Py_IDENTIFIER(offset);
1040 _Py_IDENTIFIER(print_file_and_line);
1041 _Py_IDENTIFIER(text);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 /* add attributes for the line number and filename for the error */
1044 PyErr_Fetch(&exc, &v, &tb);
1045 PyErr_NormalizeException(&exc, &v, &tb);
1046 /* XXX check that it is, indeed, a syntax error. It might not
1047 * be, though. */
1048 tmp = PyLong_FromLong(lineno);
1049 if (tmp == NULL)
1050 PyErr_Clear();
1051 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001052 if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyErr_Clear();
1054 Py_DECREF(tmp);
1055 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001056 tmp = NULL;
Benjamin Peterson2c539712010-09-20 22:42:10 +00001057 if (col_offset >= 0) {
1058 tmp = PyLong_FromLong(col_offset);
1059 if (tmp == NULL)
1060 PyErr_Clear();
Benjamin Peterson2c539712010-09-20 22:42:10 +00001061 }
Serhiy Storchaka8b583392016-12-11 14:39:01 +02001062 if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
1063 PyErr_Clear();
1064 Py_XDECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (filename != NULL) {
Victor Stinner14e461d2013-08-26 22:28:21 +02001066 if (_PyObject_SetAttrId(v, &PyId_filename, filename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyErr_Clear();
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001068
Victor Stinner14e461d2013-08-26 22:28:21 +02001069 tmp = PyErr_ProgramTextObject(filename, lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001071 if (_PyObject_SetAttrId(v, &PyId_text, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 PyErr_Clear();
1073 Py_DECREF(tmp);
1074 }
1075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (exc != PyExc_SyntaxError) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001077 if (!_PyObject_HasAttrId(v, &PyId_msg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 tmp = PyObject_Str(v);
1079 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001080 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 PyErr_Clear();
1082 Py_DECREF(tmp);
1083 } else {
1084 PyErr_Clear();
1085 }
1086 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001087 if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1088 if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1089 Py_None))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 PyErr_Clear();
1091 }
1092 }
1093 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001094}
1095
Victor Stinner14e461d2013-08-26 22:28:21 +02001096void
1097PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1098{
1099 PyObject *fileobj;
1100 if (filename != NULL) {
1101 fileobj = PyUnicode_DecodeFSDefault(filename);
1102 if (fileobj == NULL)
1103 PyErr_Clear();
1104 }
1105 else
1106 fileobj = NULL;
1107 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1108 Py_XDECREF(fileobj);
1109}
1110
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001111/* Attempt to load the line of text that the exception refers to. If it
1112 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001113
1114 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001115 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001116
Antoine Pitrou409b5382013-10-12 22:41:17 +02001117static PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001118err_programtext(FILE *fp, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 int i;
1121 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (fp == NULL)
1124 return NULL;
1125 for (i = 0; i < lineno; i++) {
1126 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1127 do {
1128 *pLastChar = '\0';
1129 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1130 fp, NULL) == NULL)
1131 break;
1132 /* fgets read *something*; if it didn't get as
1133 far as pLastChar, it must have found a newline
1134 or hit the end of the file; if pLastChar is \n,
1135 it obviously found a newline; else we haven't
1136 yet seen a newline, so must continue */
1137 } while (*pLastChar != '\0' && *pLastChar != '\n');
1138 }
1139 fclose(fp);
1140 if (i == lineno) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyObject *res;
Martin Panterca3263c2016-12-11 00:18:36 +00001142 res = PyUnicode_FromString(linebuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (res == NULL)
1144 PyErr_Clear();
1145 return res;
1146 }
1147 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001148}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001149
Victor Stinner14e461d2013-08-26 22:28:21 +02001150PyObject *
1151PyErr_ProgramText(const char *filename, int lineno)
1152{
1153 FILE *fp;
1154 if (filename == NULL || *filename == '\0' || lineno <= 0)
1155 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001156 fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001157 return err_programtext(fp, lineno);
1158}
1159
1160PyObject *
1161PyErr_ProgramTextObject(PyObject *filename, int lineno)
1162{
1163 FILE *fp;
1164 if (filename == NULL || lineno <= 0)
1165 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001166 fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
Victor Stinnere42ccd22015-03-18 01:39:23 +01001167 if (fp == NULL) {
1168 PyErr_Clear();
1169 return NULL;
1170 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001171 return err_programtext(fp, lineno);
1172}
1173
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001174#ifdef __cplusplus
1175}
1176#endif