blob: 6cc0c20cd55dde62303e3dc97c6fec00d06d2260 [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
55void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000056PyErr_SetObject(PyObject *exception, PyObject *value)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 PyThreadState *tstate = PyThreadState_GET();
59 PyObject *exc_value;
60 PyObject *tb = NULL;
Guido van Rossumb4fb6e42008-06-14 20:20:24 +000061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 if (exception != NULL &&
63 !PyExceptionClass_Check(exception)) {
64 PyErr_Format(PyExc_SystemError,
65 "exception %R not a BaseException subclass",
66 exception);
67 return;
68 }
69 Py_XINCREF(value);
70 exc_value = tstate->exc_value;
71 if (exc_value != NULL && exc_value != Py_None) {
72 /* Implicit exception chaining */
73 Py_INCREF(exc_value);
74 if (value == NULL || !PyExceptionInstance_Check(value)) {
75 /* We must normalize the value right now */
76 PyObject *args, *fixed_value;
Victor Stinnerde821be2015-03-24 12:41:23 +010077
78 /* Issue #23571: PyEval_CallObject() must not be called with an
79 exception set */
Victor Stinnerace47d72013-07-18 01:41:08 +020080 PyErr_Clear();
Victor Stinnerde821be2015-03-24 12:41:23 +010081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 if (value == NULL || value == Py_None)
83 args = PyTuple_New(0);
84 else if (PyTuple_Check(value)) {
85 Py_INCREF(value);
86 args = value;
87 }
88 else
89 args = PyTuple_Pack(1, value);
90 fixed_value = args ?
91 PyEval_CallObject(exception, args) : NULL;
92 Py_XDECREF(args);
93 Py_XDECREF(value);
94 if (fixed_value == NULL)
95 return;
96 value = fixed_value;
97 }
98 /* Avoid reference cycles through the context chain.
99 This is O(chain length) but context chains are
100 usually very short. Sensitive readers may try
101 to inline the call to PyException_GetContext. */
102 if (exc_value != value) {
103 PyObject *o = exc_value, *context;
104 while ((context = PyException_GetContext(o))) {
105 Py_DECREF(context);
106 if (context == value) {
107 PyException_SetContext(o, NULL);
108 break;
109 }
110 o = context;
111 }
112 PyException_SetContext(value, exc_value);
113 } else {
114 Py_DECREF(exc_value);
115 }
116 }
117 if (value != NULL && PyExceptionInstance_Check(value))
118 tb = PyException_GetTraceback(value);
119 Py_XINCREF(exception);
120 PyErr_Restore(exception, value, tb);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121}
122
Raymond Hettinger69492da2013-09-02 15:59:26 -0700123/* Set a key error with the specified argument, wrapping it in a
124 * tuple automatically so that tuple keys are not unpacked as the
125 * exception arguments. */
126void
127_PyErr_SetKeyError(PyObject *arg)
128{
129 PyObject *tup;
130 tup = PyTuple_Pack(1, arg);
131 if (!tup)
132 return; /* caller will expect error to be set anyway */
133 PyErr_SetObject(PyExc_KeyError, tup);
134 Py_DECREF(tup);
135}
136
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000138PyErr_SetNone(PyObject *exception)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141}
142
143void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000144PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 PyObject *value = PyUnicode_FromString(string);
147 PyErr_SetObject(exception, value);
148 Py_XDECREF(value);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149}
150
Guido van Rossum3a241811994-08-29 12:14:12 +0000151
Guido van Rossum373c8691997-04-29 18:22:47 +0000152PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000153PyErr_Occurred(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154{
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100155 PyThreadState *tstate = _PyThreadState_UncheckedGet();
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +0000156 return tstate == NULL ? NULL : tstate->curexc_type;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157}
158
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000159
160int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000161PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 if (err == NULL || exc == NULL) {
164 /* maybe caused by "import exceptions" that failed early on */
165 return 0;
166 }
167 if (PyTuple_Check(exc)) {
168 Py_ssize_t i, n;
169 n = PyTuple_Size(exc);
170 for (i = 0; i < n; i++) {
171 /* Test recursively */
172 if (PyErr_GivenExceptionMatches(
173 err, PyTuple_GET_ITEM(exc, i)))
174 {
175 return 1;
176 }
177 }
178 return 0;
179 }
180 /* err might be an instance, so check its class. */
181 if (PyExceptionInstance_Check(err))
182 err = PyExceptionInstance_Class(err);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
185 int res = 0;
186 PyObject *exception, *value, *tb;
187 PyErr_Fetch(&exception, &value, &tb);
188 /* PyObject_IsSubclass() can recurse and therefore is
189 not safe (see test_bad_getattr in test.pickletester). */
190 res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
191 /* This function must not fail, so print the error here */
192 if (res == -1) {
193 PyErr_WriteUnraisable(err);
194 res = 0;
195 }
196 PyErr_Restore(exception, value, tb);
197 return res;
198 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 return err == exc;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000201}
Guido van Rossum743007d1999-04-21 15:27:31 +0000202
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000203
204int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000205PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000208}
209
210
211/* Used in many places to normalize a raised exception, including in
212 eval_code2(), do_raise(), and PyErr_Print()
Benjamin Petersone6528212008-07-15 15:32:09 +0000213
214 XXX: should PyErr_NormalizeException() also call
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 PyException_SetTraceback() with the resulting value and tb?
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000216*/
217void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000218PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 PyObject *type = *exc;
221 PyObject *value = *val;
222 PyObject *inclass = NULL;
223 PyObject *initial_tb = NULL;
224 PyThreadState *tstate = NULL;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (type == NULL) {
227 /* There was no exception, so nothing to do. */
228 return;
229 }
Guido van Rossumed473a42000-08-07 19:18:27 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 /* If PyErr_SetNone() was used, the value will have been actually
232 set to NULL.
233 */
234 if (!value) {
235 value = Py_None;
236 Py_INCREF(value);
237 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (PyExceptionInstance_Check(value))
240 inclass = PyExceptionInstance_Class(value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 /* Normalize the exception so that if the type is a class, the
243 value will be an instance.
244 */
245 if (PyExceptionClass_Check(type)) {
Victor Stinner74a7fa62013-07-17 00:44:53 +0200246 int is_subclass;
247 if (inclass) {
248 is_subclass = PyObject_IsSubclass(inclass, type);
249 if (is_subclass < 0)
250 goto finally;
251 }
252 else
253 is_subclass = 0;
254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 /* if the value was not an instance, or is not an instance
256 whose class is (or is derived from) type, then use the
257 value as an argument to instantiation of the type
258 class.
259 */
Victor Stinner74a7fa62013-07-17 00:44:53 +0200260 if (!inclass || !is_subclass) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 PyObject *args, *res;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 if (value == Py_None)
264 args = PyTuple_New(0);
265 else if (PyTuple_Check(value)) {
266 Py_INCREF(value);
267 args = value;
268 }
269 else
270 args = PyTuple_Pack(1, value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (args == NULL)
273 goto finally;
274 res = PyEval_CallObject(type, args);
275 Py_DECREF(args);
276 if (res == NULL)
277 goto finally;
278 Py_DECREF(value);
279 value = res;
280 }
281 /* if the class of the instance doesn't exactly match the
282 class of the type, believe the instance
283 */
284 else if (inclass != type) {
285 Py_DECREF(type);
286 type = inclass;
287 Py_INCREF(type);
288 }
289 }
290 *exc = type;
291 *val = value;
292 return;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000293finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 Py_DECREF(type);
295 Py_DECREF(value);
296 /* If the new exception doesn't set a traceback and the old
297 exception had a traceback, use the old traceback for the
298 new exception. It's better than nothing.
299 */
300 initial_tb = *tb;
301 PyErr_Fetch(exc, val, tb);
302 if (initial_tb != NULL) {
303 if (*tb == NULL)
304 *tb = initial_tb;
305 else
306 Py_DECREF(initial_tb);
307 }
308 /* normalize recursively */
309 tstate = PyThreadState_GET();
310 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
311 --tstate->recursion_depth;
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200312 /* throw away the old exception and use the recursion error instead */
313 Py_INCREF(PyExc_RecursionError);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300314 Py_SETREF(*exc, PyExc_RecursionError);
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200315 Py_INCREF(PyExc_RecursionErrorInst);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300316 Py_SETREF(*val, PyExc_RecursionErrorInst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 /* just keeping the old traceback */
318 return;
319 }
320 PyErr_NormalizeException(exc, val, tb);
321 --tstate->recursion_depth;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000322}
323
324
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000326PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 *p_type = tstate->curexc_type;
331 *p_value = tstate->curexc_value;
332 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 tstate->curexc_type = NULL;
335 tstate->curexc_value = NULL;
336 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337}
338
339void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000340PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000344
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200345void
346PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
347{
348 PyThreadState *tstate = PyThreadState_GET();
349
350 *p_type = tstate->exc_type;
351 *p_value = tstate->exc_value;
352 *p_traceback = tstate->exc_traceback;
353
354 Py_XINCREF(*p_type);
355 Py_XINCREF(*p_value);
356 Py_XINCREF(*p_traceback);
357}
358
359void
360PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
361{
362 PyObject *oldtype, *oldvalue, *oldtraceback;
363 PyThreadState *tstate = PyThreadState_GET();
364
365 oldtype = tstate->exc_type;
366 oldvalue = tstate->exc_value;
367 oldtraceback = tstate->exc_traceback;
368
369 tstate->exc_type = p_type;
370 tstate->exc_value = p_value;
371 tstate->exc_traceback = p_traceback;
372
373 Py_XDECREF(oldtype);
374 Py_XDECREF(oldvalue);
375 Py_XDECREF(oldtraceback);
376}
377
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300378/* Like PyErr_Restore(), but if an exception is already set,
379 set the context associated with it.
380 */
381void
382_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
383{
384 if (exc == NULL)
385 return;
386
387 if (PyErr_Occurred()) {
388 PyObject *exc2, *val2, *tb2;
389 PyErr_Fetch(&exc2, &val2, &tb2);
390 PyErr_NormalizeException(&exc, &val, &tb);
Serhiy Storchaka9e373be2016-10-21 16:19:59 +0300391 if (tb != NULL) {
392 PyException_SetTraceback(val, tb);
393 Py_DECREF(tb);
394 }
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300395 Py_DECREF(exc);
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300396 PyErr_NormalizeException(&exc2, &val2, &tb2);
397 PyException_SetContext(val2, val);
398 PyErr_Restore(exc2, val2, tb2);
399 }
400 else {
401 PyErr_Restore(exc, val, tb);
402 }
403}
404
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000405/* Convenience functions to set a type error exception and return 0 */
406
407int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000408PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyErr_SetString(PyExc_TypeError,
411 "bad argument type for built-in operation");
412 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000413}
414
Guido van Rossum373c8691997-04-29 18:22:47 +0000415PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000416PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000417{
Victor Stinnerf54a5742013-07-22 22:28:37 +0200418 if (Py_TYPE(PyExc_MemoryError) == NULL) {
419 /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
420 initialized by _PyExc_Init() */
421 Py_FatalError("Out of memory and PyExc_MemoryError is not "
422 "initialized yet");
423 }
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000424 PyErr_SetNone(PyExc_MemoryError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000426}
427
Guido van Rossum373c8691997-04-29 18:22:47 +0000428PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000429PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000430{
Larry Hastingsb0827312014-02-09 22:05:19 -0800431 return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
432}
433
434PyObject *
435PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PyObject *message;
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200438 PyObject *v, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 int i = errno;
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100440#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 WCHAR *s_buf = NULL;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000442#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000443
Guido van Rossume9fbc091995-02-18 14:52:19 +0000444#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (i == EINTR && PyErr_CheckSignals())
446 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000447#endif
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000448
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000449#ifndef MS_WINDOWS
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100450 if (i != 0) {
451 char *s = strerror(i);
Victor Stinner1b579672011-12-17 05:47:23 +0100452 message = PyUnicode_DecodeLocale(s, "surrogateescape");
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100453 }
454 else {
455 /* Sometimes errno didn't get set */
456 message = PyUnicode_FromString("Error");
457 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000458#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (i == 0)
460 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
461 else
462 {
463 /* Note that the Win32 errors do not lineup with the
464 errno error. So if the error is in the MSVC error
465 table, we use it, otherwise we assume it really _is_
466 a Win32 error code
467 */
468 if (i > 0 && i < _sys_nerr) {
469 message = PyUnicode_FromString(_sys_errlist[i]);
470 }
471 else {
472 int len = FormatMessageW(
473 FORMAT_MESSAGE_ALLOCATE_BUFFER |
474 FORMAT_MESSAGE_FROM_SYSTEM |
475 FORMAT_MESSAGE_IGNORE_INSERTS,
476 NULL, /* no message source */
477 i,
478 MAKELANGID(LANG_NEUTRAL,
479 SUBLANG_DEFAULT),
480 /* Default language */
481 (LPWSTR) &s_buf,
482 0, /* size not used */
483 NULL); /* no args */
484 if (len==0) {
485 /* Only ever seen this in out-of-mem
486 situations */
487 s_buf = NULL;
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300488 message = PyUnicode_FromFormat("Windows Error 0x%x", i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 } else {
490 /* remove trailing cr/lf and dots */
491 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
492 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200493 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 }
495 }
496 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000497#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 if (message == NULL)
500 {
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000501#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 LocalFree(s_buf);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000503#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return NULL;
505 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000506
Larry Hastingsb0827312014-02-09 22:05:19 -0800507 if (filenameObject != NULL) {
508 if (filenameObject2 != NULL)
509 args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
510 else
511 args = Py_BuildValue("(iOO)", i, message, filenameObject);
512 } else {
513 assert(filenameObject2 == NULL);
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200514 args = Py_BuildValue("(iO)", i, message);
Larry Hastingsb0827312014-02-09 22:05:19 -0800515 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000517
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200518 if (args != NULL) {
519 v = PyObject_Call(exc, args, NULL);
520 Py_DECREF(args);
521 if (v != NULL) {
522 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
523 Py_DECREF(v);
524 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000526#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000528#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000530}
Guido van Rossum743007d1999-04-21 15:27:31 +0000531
Barry Warsaw97d95151998-07-23 16:05:56 +0000532PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000533PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800536 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 Py_XDECREF(name);
538 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000539}
540
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000541#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000542PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000543PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 PyObject *name = filename ?
546 PyUnicode_FromUnicode(filename, wcslen(filename)) :
547 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800548 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 Py_XDECREF(name);
550 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000551}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000552#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000553
554PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000555PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000556{
Larry Hastingsb0827312014-02-09 22:05:19 -0800557 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000558}
Guido van Rossum683a0721990-10-21 22:09:12 +0000559
Brett Cannonbf364092006-03-01 04:25:17 +0000560#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000561/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000562PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 PyObject *exc,
564 int ierr,
565 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000566{
Larry Hastingsb0827312014-02-09 22:05:19 -0800567 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
568 filenameObject, NULL);
569}
570
571PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
572 PyObject *exc,
573 int ierr,
574 PyObject *filenameObject,
575 PyObject *filenameObject2)
576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 int len;
578 WCHAR *s_buf = NULL; /* Free via LocalFree */
579 PyObject *message;
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200580 PyObject *args, *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 DWORD err = (DWORD)ierr;
582 if (err==0) err = GetLastError();
583 len = FormatMessageW(
584 /* Error API error */
585 FORMAT_MESSAGE_ALLOCATE_BUFFER |
586 FORMAT_MESSAGE_FROM_SYSTEM |
587 FORMAT_MESSAGE_IGNORE_INSERTS,
588 NULL, /* no message source */
589 err,
590 MAKELANGID(LANG_NEUTRAL,
591 SUBLANG_DEFAULT), /* Default language */
592 (LPWSTR) &s_buf,
593 0, /* size not used */
594 NULL); /* no args */
595 if (len==0) {
596 /* Only seen this in out of mem situations */
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300597 message = PyUnicode_FromFormat("Windows Error 0x%x", err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 s_buf = NULL;
599 } else {
600 /* remove trailing cr/lf and dots */
601 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
602 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200603 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (message == NULL)
607 {
608 LocalFree(s_buf);
609 return NULL;
610 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000611
Larry Hastingsb0827312014-02-09 22:05:19 -0800612 if (filenameObject == NULL) {
613 assert(filenameObject2 == NULL);
614 filenameObject = filenameObject2 = Py_None;
615 }
616 else if (filenameObject2 == NULL)
617 filenameObject2 = Py_None;
618 /* This is the constructor signature for OSError.
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200619 The POSIX translation will be figured out by the constructor. */
Larry Hastingsb0827312014-02-09 22:05:19 -0800620 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000622
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200623 if (args != NULL) {
624 v = PyObject_Call(exc, args, NULL);
625 Py_DECREF(args);
626 if (v != NULL) {
627 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
628 Py_DECREF(v);
629 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 }
631 LocalFree(s_buf);
632 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000633}
634
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000635PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyObject *exc,
637 int ierr,
638 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000639{
Victor Stinner92be9392010-12-28 00:28:21 +0000640 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800641 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800643 name,
644 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 Py_XDECREF(name);
646 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000647}
648
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000649PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyObject *exc,
651 int ierr,
652 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyObject *name = filename ?
655 PyUnicode_FromUnicode(filename, wcslen(filename)) :
656 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800657 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800659 name,
660 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 Py_XDECREF(name);
662 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000663}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000664
Thomas Heller085358a2002-07-29 14:27:41 +0000665PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
666{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800667 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000668}
669
Guido van Rossum795e1892000-02-17 15:19:15 +0000670PyObject *PyErr_SetFromWindowsErr(int ierr)
671{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800672 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
673 ierr, NULL);
Larry Hastingsb0827312014-02-09 22:05:19 -0800674}
675
Thomas Heller085358a2002-07-29 14:27:41 +0000676PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 int ierr,
678 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +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 *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200682 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800683 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 Py_XDECREF(name);
685 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000686}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000687
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000688PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 int ierr,
690 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyObject *name = filename ?
693 PyUnicode_FromUnicode(filename, wcslen(filename)) :
694 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800695 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200696 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800697 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 Py_XDECREF(name);
699 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000700}
Guido van Rossum795e1892000-02-17 15:19:15 +0000701#endif /* MS_WINDOWS */
702
Brett Cannon79ec55e2012-04-12 20:24:54 -0400703PyObject *
Brett Cannon82da8882013-07-04 17:48:16 -0400704PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Brett Cannon79ec55e2012-04-12 20:24:54 -0400705{
Brian Curtin09b86d12012-04-17 16:57:09 -0500706 PyObject *args, *kwargs, *error;
707
Brett Cannon82da8882013-07-04 17:48:16 -0400708 if (msg == NULL)
Brian Curtin94c001b2012-04-18 08:30:51 -0500709 return NULL;
710
Antoine Pitrouec9bac42012-04-18 16:57:54 +0200711 args = PyTuple_New(1);
Brian Curtin09b86d12012-04-17 16:57:09 -0500712 if (args == NULL)
713 return NULL;
714
715 kwargs = PyDict_New();
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400716 if (kwargs == NULL) {
717 Py_DECREF(args);
Brian Curtin09b86d12012-04-17 16:57:09 -0500718 return NULL;
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400719 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500720
Brian Curtin94c001b2012-04-18 08:30:51 -0500721 if (name == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500722 name = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500723 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500724
Brian Curtin94c001b2012-04-18 08:30:51 -0500725 if (path == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500726 path = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500727 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500728
729 Py_INCREF(msg);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400730 PyTuple_SET_ITEM(args, 0, msg);
Victor Stinner479054b2013-07-17 21:54:25 +0200731
732 if (PyDict_SetItemString(kwargs, "name", name) < 0)
Berker Peksagec766d32016-05-01 09:06:36 +0300733 goto done;
Victor Stinner479054b2013-07-17 21:54:25 +0200734 if (PyDict_SetItemString(kwargs, "path", path) < 0)
Berker Peksagec766d32016-05-01 09:06:36 +0300735 goto done;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400736
Brett Cannon82da8882013-07-04 17:48:16 -0400737 error = PyObject_Call(PyExc_ImportError, args, kwargs);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400738 if (error != NULL) {
739 PyErr_SetObject((PyObject *)Py_TYPE(error), error);
Brian Curtin09b86d12012-04-17 16:57:09 -0500740 Py_DECREF(error);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400741 }
742
Berker Peksagec766d32016-05-01 09:06:36 +0300743done:
Brett Cannon79ec55e2012-04-12 20:24:54 -0400744 Py_DECREF(args);
745 Py_DECREF(kwargs);
Brian Curtin09b86d12012-04-17 16:57:09 -0500746 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400747}
748
Guido van Rossum683a0721990-10-21 22:09:12 +0000749void
Neal Norwitzb382b842007-08-24 20:00:37 +0000750_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyErr_Format(PyExc_SystemError,
753 "%s:%d: bad argument to internal function",
754 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000755}
756
757/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
758 export the entry point for existing object code: */
759#undef PyErr_BadInternalCall
760void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000761PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000762{
Victor Stinnerfb3a6302013-07-12 00:37:30 +0200763 assert(0 && "bad argument to internal function");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyErr_Format(PyExc_SystemError,
765 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000766}
Fred Drake6d63adf2000-08-24 22:38:39 +0000767#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
768
Guido van Rossum1548bac1997-02-14 17:09:47 +0000769
Guido van Rossum1548bac1997-02-14 17:09:47 +0000770PyObject *
Antoine Pitrou0676a402014-09-30 21:16:27 +0200771PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000774
Victor Stinnerde821be2015-03-24 12:41:23 +0100775 /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
776 exception set, it calls arbitrary Python code like PyObject_Repr() */
Victor Stinnerace47d72013-07-18 01:41:08 +0200777 PyErr_Clear();
Victor Stinnerace47d72013-07-18 01:41:08 +0200778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 string = PyUnicode_FromFormatV(format, vargs);
Victor Stinnerde821be2015-03-24 12:41:23 +0100780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyErr_SetObject(exception, string);
782 Py_XDECREF(string);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000784}
Guido van Rossum7617e051997-09-16 18:43:50 +0000785
786
Antoine Pitrou0676a402014-09-30 21:16:27 +0200787PyObject *
788PyErr_Format(PyObject *exception, const char *format, ...)
789{
790 va_list vargs;
791#ifdef HAVE_STDARG_PROTOTYPES
792 va_start(vargs, format);
793#else
794 va_start(vargs);
795#endif
796 PyErr_FormatV(exception, format, vargs);
797 va_end(vargs);
798 return NULL;
799}
800
Thomas Wouters477c8d52006-05-27 19:21:47 +0000801
Guido van Rossum7617e051997-09-16 18:43:50 +0000802PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000803PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 const char *dot;
806 PyObject *modulename = NULL;
807 PyObject *classname = NULL;
808 PyObject *mydict = NULL;
809 PyObject *bases = NULL;
810 PyObject *result = NULL;
811 dot = strrchr(name, '.');
812 if (dot == NULL) {
813 PyErr_SetString(PyExc_SystemError,
814 "PyErr_NewException: name must be module.class");
815 return NULL;
816 }
817 if (base == NULL)
818 base = PyExc_Exception;
819 if (dict == NULL) {
820 dict = mydict = PyDict_New();
821 if (dict == NULL)
822 goto failure;
823 }
824 if (PyDict_GetItemString(dict, "__module__") == NULL) {
825 modulename = PyUnicode_FromStringAndSize(name,
826 (Py_ssize_t)(dot-name));
827 if (modulename == NULL)
828 goto failure;
829 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
830 goto failure;
831 }
832 if (PyTuple_Check(base)) {
833 bases = base;
834 /* INCREF as we create a new ref in the else branch */
835 Py_INCREF(bases);
836 } else {
837 bases = PyTuple_Pack(1, base);
838 if (bases == NULL)
839 goto failure;
840 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100841 /* Create a real class. */
Victor Stinner7eeb5b52010-06-07 19:57:46 +0000842 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000844 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 Py_XDECREF(bases);
846 Py_XDECREF(mydict);
847 Py_XDECREF(classname);
848 Py_XDECREF(modulename);
849 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000850}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000851
Georg Brandl1e28a272009-12-28 08:41:01 +0000852
853/* Create an exception with docstring */
854PyObject *
855PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 int result;
859 PyObject *ret = NULL;
860 PyObject *mydict = NULL; /* points to the dict only if we create it */
861 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (dict == NULL) {
864 dict = mydict = PyDict_New();
865 if (dict == NULL) {
866 return NULL;
867 }
868 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (doc != NULL) {
871 docobj = PyUnicode_FromString(doc);
872 if (docobj == NULL)
873 goto failure;
874 result = PyDict_SetItemString(dict, "__doc__", docobj);
875 Py_DECREF(docobj);
876 if (result < 0)
877 goto failure;
878 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000881 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 Py_XDECREF(mydict);
883 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000884}
885
886
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000887/* Call when an exception has occurred but there is no way for Python
888 to handle it. Examples: exception in __del__ or during GC. */
889void
890PyErr_WriteUnraisable(PyObject *obj)
891{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200892 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 PyObject *f, *t, *v, *tb;
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200894 PyObject *moduleName = NULL;
895 char* className;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000896
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200897 PyErr_Fetch(&t, &v, &tb);
898
Victor Stinnerbd303c12013-11-07 23:07:29 +0100899 f = _PySys_GetObjectId(&PyId_stderr);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200900 if (f == NULL || f == Py_None)
901 goto done;
902
903 if (obj) {
904 if (PyFile_WriteString("Exception ignored in: ", f) < 0)
905 goto done;
Martin Panter3263f682016-02-28 03:16:11 +0000906 if (PyFile_WriteObject(obj, f, 0) < 0) {
907 PyErr_Clear();
908 if (PyFile_WriteString("<object repr() failed>", f) < 0) {
909 goto done;
910 }
911 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200912 if (PyFile_WriteString("\n", f) < 0)
913 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200915
916 if (PyTraceBack_Print(tb, f) < 0)
917 goto done;
918
919 if (!t)
920 goto done;
921
922 assert(PyExceptionClass_Check(t));
923 className = PyExceptionClass_Name(t);
924 if (className != NULL) {
925 char *dot = strrchr(className, '.');
926 if (dot != NULL)
927 className = dot+1;
928 }
929
930 moduleName = _PyObject_GetAttrId(t, &PyId___module__);
931 if (moduleName == NULL) {
932 PyErr_Clear();
933 if (PyFile_WriteString("<unknown>", f) < 0)
934 goto done;
935 }
936 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100937 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200938 if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
939 goto done;
940 if (PyFile_WriteString(".", f) < 0)
941 goto done;
942 }
943 }
944 if (className == NULL) {
945 if (PyFile_WriteString("<unknown>", f) < 0)
946 goto done;
947 }
948 else {
949 if (PyFile_WriteString(className, f) < 0)
950 goto done;
951 }
952
953 if (v && v != Py_None) {
954 if (PyFile_WriteString(": ", f) < 0)
955 goto done;
Martin Panter3263f682016-02-28 03:16:11 +0000956 if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
957 PyErr_Clear();
958 if (PyFile_WriteString("<exception str() failed>", f) < 0) {
959 goto done;
960 }
961 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200962 }
963 if (PyFile_WriteString("\n", f) < 0)
964 goto done;
965
966done:
967 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 Py_XDECREF(t);
969 Py_XDECREF(v);
970 Py_XDECREF(tb);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200971 PyErr_Clear(); /* Just in case */
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000972}
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000973
Armin Rigo092381a2003-10-25 14:29:27 +0000974extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000975
Guido van Rossum2fd45652001-02-28 21:46:24 +0000976
Benjamin Peterson2c539712010-09-20 22:42:10 +0000977void
Victor Stinner14e461d2013-08-26 22:28:21 +0200978PyErr_SyntaxLocation(const char *filename, int lineno)
979{
Benjamin Peterson2c539712010-09-20 22:42:10 +0000980 PyErr_SyntaxLocationEx(filename, lineno, -1);
981}
982
983
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000984/* Set file and line information for the current exception.
985 If the exception is not a SyntaxError, also sets additional attributes
986 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +0000987
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000988void
Victor Stinner14e461d2013-08-26 22:28:21 +0200989PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyObject *exc, *v, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200992 _Py_IDENTIFIER(filename);
993 _Py_IDENTIFIER(lineno);
994 _Py_IDENTIFIER(msg);
995 _Py_IDENTIFIER(offset);
996 _Py_IDENTIFIER(print_file_and_line);
997 _Py_IDENTIFIER(text);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* add attributes for the line number and filename for the error */
1000 PyErr_Fetch(&exc, &v, &tb);
1001 PyErr_NormalizeException(&exc, &v, &tb);
1002 /* XXX check that it is, indeed, a syntax error. It might not
1003 * be, though. */
1004 tmp = PyLong_FromLong(lineno);
1005 if (tmp == NULL)
1006 PyErr_Clear();
1007 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001008 if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 PyErr_Clear();
1010 Py_DECREF(tmp);
1011 }
Benjamin Peterson2c539712010-09-20 22:42:10 +00001012 if (col_offset >= 0) {
1013 tmp = PyLong_FromLong(col_offset);
1014 if (tmp == NULL)
1015 PyErr_Clear();
1016 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001017 if (_PyObject_SetAttrId(v, &PyId_offset, tmp))
Benjamin Peterson2c539712010-09-20 22:42:10 +00001018 PyErr_Clear();
1019 Py_DECREF(tmp);
1020 }
1021 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (filename != NULL) {
Victor Stinner14e461d2013-08-26 22:28:21 +02001023 if (_PyObject_SetAttrId(v, &PyId_filename, filename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 PyErr_Clear();
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001025
Victor Stinner14e461d2013-08-26 22:28:21 +02001026 tmp = PyErr_ProgramTextObject(filename, lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001028 if (_PyObject_SetAttrId(v, &PyId_text, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyErr_Clear();
1030 Py_DECREF(tmp);
1031 }
1032 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001033 if (_PyObject_SetAttrId(v, &PyId_offset, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 PyErr_Clear();
1035 }
1036 if (exc != PyExc_SyntaxError) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001037 if (!_PyObject_HasAttrId(v, &PyId_msg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 tmp = PyObject_Str(v);
1039 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001040 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 PyErr_Clear();
1042 Py_DECREF(tmp);
1043 } else {
1044 PyErr_Clear();
1045 }
1046 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001047 if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1048 if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1049 Py_None))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 PyErr_Clear();
1051 }
1052 }
1053 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001054}
1055
Victor Stinner14e461d2013-08-26 22:28:21 +02001056void
1057PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1058{
1059 PyObject *fileobj;
1060 if (filename != NULL) {
1061 fileobj = PyUnicode_DecodeFSDefault(filename);
1062 if (fileobj == NULL)
1063 PyErr_Clear();
1064 }
1065 else
1066 fileobj = NULL;
1067 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1068 Py_XDECREF(fileobj);
1069}
1070
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001071/* Attempt to load the line of text that the exception refers to. If it
1072 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001073
1074 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001075 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001076
Antoine Pitrou409b5382013-10-12 22:41:17 +02001077static PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001078err_programtext(FILE *fp, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 int i;
1081 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 if (fp == NULL)
1084 return NULL;
1085 for (i = 0; i < lineno; i++) {
1086 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1087 do {
1088 *pLastChar = '\0';
1089 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1090 fp, NULL) == NULL)
1091 break;
1092 /* fgets read *something*; if it didn't get as
1093 far as pLastChar, it must have found a newline
1094 or hit the end of the file; if pLastChar is \n,
1095 it obviously found a newline; else we haven't
1096 yet seen a newline, so must continue */
1097 } while (*pLastChar != '\0' && *pLastChar != '\n');
1098 }
1099 fclose(fp);
1100 if (i == lineno) {
1101 char *p = linebuf;
1102 PyObject *res;
1103 while (*p == ' ' || *p == '\t' || *p == '\014')
1104 p++;
1105 res = PyUnicode_FromString(p);
1106 if (res == NULL)
1107 PyErr_Clear();
1108 return res;
1109 }
1110 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001111}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001112
Victor Stinner14e461d2013-08-26 22:28:21 +02001113PyObject *
1114PyErr_ProgramText(const char *filename, int lineno)
1115{
1116 FILE *fp;
1117 if (filename == NULL || *filename == '\0' || lineno <= 0)
1118 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001119 fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001120 return err_programtext(fp, lineno);
1121}
1122
1123PyObject *
1124PyErr_ProgramTextObject(PyObject *filename, int lineno)
1125{
1126 FILE *fp;
1127 if (filename == NULL || lineno <= 0)
1128 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001129 fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
Victor Stinnere42ccd22015-03-18 01:39:23 +01001130 if (fp == NULL) {
1131 PyErr_Clear();
1132 return NULL;
1133 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001134 return err_programtext(fp, lineno);
1135}
1136
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001137#ifdef __cplusplus
1138}
1139#endif