blob: 7b675667275c5fbd9558355f38047929ece7cb18 [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{
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +0000155 /* If there is no thread state, PyThreadState_GET calls
156 Py_FatalError, which calls PyErr_Occurred. To avoid the
157 resulting infinite loop, we inline PyThreadState_GET here and
158 treat no thread as no error. */
159 PyThreadState *tstate =
160 ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current));
Guido van Rossuma027efa1997-05-05 20:56:21 +0000161
Jeffrey Yasskin8e0bdfd2010-05-13 18:31:05 +0000162 return tstate == NULL ? NULL : tstate->curexc_type;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000165
166int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000167PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 if (err == NULL || exc == NULL) {
170 /* maybe caused by "import exceptions" that failed early on */
171 return 0;
172 }
173 if (PyTuple_Check(exc)) {
174 Py_ssize_t i, n;
175 n = PyTuple_Size(exc);
176 for (i = 0; i < n; i++) {
177 /* Test recursively */
178 if (PyErr_GivenExceptionMatches(
179 err, PyTuple_GET_ITEM(exc, i)))
180 {
181 return 1;
182 }
183 }
184 return 0;
185 }
186 /* err might be an instance, so check its class. */
187 if (PyExceptionInstance_Check(err))
188 err = PyExceptionInstance_Class(err);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
191 int res = 0;
192 PyObject *exception, *value, *tb;
193 PyErr_Fetch(&exception, &value, &tb);
194 /* PyObject_IsSubclass() can recurse and therefore is
195 not safe (see test_bad_getattr in test.pickletester). */
196 res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
197 /* This function must not fail, so print the error here */
198 if (res == -1) {
199 PyErr_WriteUnraisable(err);
200 res = 0;
201 }
202 PyErr_Restore(exception, value, tb);
203 return res;
204 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 return err == exc;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000207}
Guido van Rossum743007d1999-04-21 15:27:31 +0000208
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000209
210int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000211PyErr_ExceptionMatches(PyObject *exc)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000214}
215
216
217/* Used in many places to normalize a raised exception, including in
218 eval_code2(), do_raise(), and PyErr_Print()
Benjamin Petersone6528212008-07-15 15:32:09 +0000219
220 XXX: should PyErr_NormalizeException() also call
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 PyException_SetTraceback() with the resulting value and tb?
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000222*/
223void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000224PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyObject *type = *exc;
227 PyObject *value = *val;
228 PyObject *inclass = NULL;
229 PyObject *initial_tb = NULL;
230 PyThreadState *tstate = NULL;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (type == NULL) {
233 /* There was no exception, so nothing to do. */
234 return;
235 }
Guido van Rossumed473a42000-08-07 19:18:27 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 /* If PyErr_SetNone() was used, the value will have been actually
238 set to NULL.
239 */
240 if (!value) {
241 value = Py_None;
242 Py_INCREF(value);
243 }
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (PyExceptionInstance_Check(value))
246 inclass = PyExceptionInstance_Class(value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 /* Normalize the exception so that if the type is a class, the
249 value will be an instance.
250 */
251 if (PyExceptionClass_Check(type)) {
Victor Stinner74a7fa62013-07-17 00:44:53 +0200252 int is_subclass;
253 if (inclass) {
254 is_subclass = PyObject_IsSubclass(inclass, type);
255 if (is_subclass < 0)
256 goto finally;
257 }
258 else
259 is_subclass = 0;
260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 /* if the value was not an instance, or is not an instance
262 whose class is (or is derived from) type, then use the
263 value as an argument to instantiation of the type
264 class.
265 */
Victor Stinner74a7fa62013-07-17 00:44:53 +0200266 if (!inclass || !is_subclass) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 PyObject *args, *res;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (value == Py_None)
270 args = PyTuple_New(0);
271 else if (PyTuple_Check(value)) {
272 Py_INCREF(value);
273 args = value;
274 }
275 else
276 args = PyTuple_Pack(1, value);
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 if (args == NULL)
279 goto finally;
280 res = PyEval_CallObject(type, args);
281 Py_DECREF(args);
282 if (res == NULL)
283 goto finally;
284 Py_DECREF(value);
285 value = res;
286 }
287 /* if the class of the instance doesn't exactly match the
288 class of the type, believe the instance
289 */
290 else if (inclass != type) {
291 Py_DECREF(type);
292 type = inclass;
293 Py_INCREF(type);
294 }
295 }
296 *exc = type;
297 *val = value;
298 return;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000299finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 Py_DECREF(type);
301 Py_DECREF(value);
302 /* If the new exception doesn't set a traceback and the old
303 exception had a traceback, use the old traceback for the
304 new exception. It's better than nothing.
305 */
306 initial_tb = *tb;
307 PyErr_Fetch(exc, val, tb);
308 if (initial_tb != NULL) {
309 if (*tb == NULL)
310 *tb = initial_tb;
311 else
312 Py_DECREF(initial_tb);
313 }
314 /* normalize recursively */
315 tstate = PyThreadState_GET();
316 if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
317 --tstate->recursion_depth;
Serhiy Storchaka191321d2015-12-27 15:41:34 +0200318 /* throw away the old exception and use the recursion error instead */
319 Py_INCREF(PyExc_RecursionError);
320 Py_SETREF(*exc, PyExc_RecursionError);
321 Py_INCREF(PyExc_RecursionErrorInst);
322 Py_SETREF(*val, PyExc_RecursionErrorInst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 /* just keeping the old traceback */
324 return;
325 }
326 PyErr_NormalizeException(exc, val, tb);
327 --tstate->recursion_depth;
Barry Warsawc0dc92a1997-08-22 21:22:58 +0000328}
329
330
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000332PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 *p_type = tstate->curexc_type;
337 *p_value = tstate->curexc_value;
338 *p_traceback = tstate->curexc_traceback;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 tstate->curexc_type = NULL;
341 tstate->curexc_value = NULL;
342 tstate->curexc_traceback = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343}
344
345void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000346PyErr_Clear(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349}
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000350
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +0200351void
352PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
353{
354 PyThreadState *tstate = PyThreadState_GET();
355
356 *p_type = tstate->exc_type;
357 *p_value = tstate->exc_value;
358 *p_traceback = tstate->exc_traceback;
359
360 Py_XINCREF(*p_type);
361 Py_XINCREF(*p_value);
362 Py_XINCREF(*p_traceback);
363}
364
365void
366PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
367{
368 PyObject *oldtype, *oldvalue, *oldtraceback;
369 PyThreadState *tstate = PyThreadState_GET();
370
371 oldtype = tstate->exc_type;
372 oldvalue = tstate->exc_value;
373 oldtraceback = tstate->exc_traceback;
374
375 tstate->exc_type = p_type;
376 tstate->exc_value = p_value;
377 tstate->exc_traceback = p_traceback;
378
379 Py_XDECREF(oldtype);
380 Py_XDECREF(oldvalue);
381 Py_XDECREF(oldtraceback);
382}
383
Serhiy Storchakae2bd2a72014-10-08 22:31:52 +0300384/* Like PyErr_Restore(), but if an exception is already set,
385 set the context associated with it.
386 */
387void
388_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
389{
390 if (exc == NULL)
391 return;
392
393 if (PyErr_Occurred()) {
394 PyObject *exc2, *val2, *tb2;
395 PyErr_Fetch(&exc2, &val2, &tb2);
396 PyErr_NormalizeException(&exc, &val, &tb);
397 Py_DECREF(exc);
398 Py_XDECREF(tb);
399 PyErr_NormalizeException(&exc2, &val2, &tb2);
400 PyException_SetContext(val2, val);
401 PyErr_Restore(exc2, val2, tb2);
402 }
403 else {
404 PyErr_Restore(exc, val, tb);
405 }
406}
407
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000408/* Convenience functions to set a type error exception and return 0 */
409
410int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000411PyErr_BadArgument(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 PyErr_SetString(PyExc_TypeError,
414 "bad argument type for built-in operation");
415 return 0;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000416}
417
Guido van Rossum373c8691997-04-29 18:22:47 +0000418PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000419PyErr_NoMemory(void)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000420{
Victor Stinnerf54a5742013-07-22 22:28:37 +0200421 if (Py_TYPE(PyExc_MemoryError) == NULL) {
422 /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
423 initialized by _PyExc_Init() */
424 Py_FatalError("Out of memory and PyExc_MemoryError is not "
425 "initialized yet");
426 }
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000427 PyErr_SetNone(PyExc_MemoryError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000429}
430
Guido van Rossum373c8691997-04-29 18:22:47 +0000431PyObject *
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000432PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000433{
Larry Hastingsb0827312014-02-09 22:05:19 -0800434 return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
435}
436
437PyObject *
438PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 PyObject *message;
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200441 PyObject *v, *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 int i = errno;
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100443#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 WCHAR *s_buf = NULL;
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000445#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000446
Guido van Rossume9fbc091995-02-18 14:52:19 +0000447#ifdef EINTR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (i == EINTR && PyErr_CheckSignals())
449 return NULL;
Guido van Rossume9fbc091995-02-18 14:52:19 +0000450#endif
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000451
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000452#ifndef MS_WINDOWS
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100453 if (i != 0) {
454 char *s = strerror(i);
Victor Stinner1b579672011-12-17 05:47:23 +0100455 message = PyUnicode_DecodeLocale(s, "surrogateescape");
Victor Stinner1f33f2b2011-12-17 04:45:09 +0100456 }
457 else {
458 /* Sometimes errno didn't get set */
459 message = PyUnicode_FromString("Error");
460 }
Guido van Rossum743007d1999-04-21 15:27:31 +0000461#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 if (i == 0)
463 message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
464 else
465 {
466 /* Note that the Win32 errors do not lineup with the
467 errno error. So if the error is in the MSVC error
468 table, we use it, otherwise we assume it really _is_
469 a Win32 error code
470 */
471 if (i > 0 && i < _sys_nerr) {
472 message = PyUnicode_FromString(_sys_errlist[i]);
473 }
474 else {
475 int len = FormatMessageW(
476 FORMAT_MESSAGE_ALLOCATE_BUFFER |
477 FORMAT_MESSAGE_FROM_SYSTEM |
478 FORMAT_MESSAGE_IGNORE_INSERTS,
479 NULL, /* no message source */
480 i,
481 MAKELANGID(LANG_NEUTRAL,
482 SUBLANG_DEFAULT),
483 /* Default language */
484 (LPWSTR) &s_buf,
485 0, /* size not used */
486 NULL); /* no args */
487 if (len==0) {
488 /* Only ever seen this in out-of-mem
489 situations */
490 s_buf = NULL;
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300491 message = PyUnicode_FromFormat("Windows Error 0x%x", i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 } else {
493 /* remove trailing cr/lf and dots */
494 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
495 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200496 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 }
498 }
499 }
Martin v. Löwis3484a182002-03-09 12:07:51 +0000500#endif /* Unix/Windows */
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (message == NULL)
503 {
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000504#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 LocalFree(s_buf);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000506#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 return NULL;
508 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000509
Larry Hastingsb0827312014-02-09 22:05:19 -0800510 if (filenameObject != NULL) {
511 if (filenameObject2 != NULL)
512 args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
513 else
514 args = Py_BuildValue("(iOO)", i, message, filenameObject);
515 } else {
516 assert(filenameObject2 == NULL);
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200517 args = Py_BuildValue("(iO)", i, message);
Larry Hastingsb0827312014-02-09 22:05:19 -0800518 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000520
Antoine Pitrou5d6fbe82011-10-12 19:39:57 +0200521 if (args != NULL) {
522 v = PyObject_Call(exc, args, NULL);
523 Py_DECREF(args);
524 if (v != NULL) {
525 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
526 Py_DECREF(v);
527 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000529#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 LocalFree(s_buf);
Guido van Rossum743007d1999-04-21 15:27:31 +0000531#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return NULL;
Guido van Rossum7d310eb1990-10-14 20:00:05 +0000533}
Guido van Rossum743007d1999-04-21 15:27:31 +0000534
Barry Warsaw97d95151998-07-23 16:05:56 +0000535PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000536PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800539 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 Py_XDECREF(name);
541 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000542}
543
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000544#ifdef MS_WINDOWS
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000545PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000546PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 PyObject *name = filename ?
549 PyUnicode_FromUnicode(filename, wcslen(filename)) :
550 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800551 PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 Py_XDECREF(name);
553 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000554}
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000555#endif /* MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000556
557PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000558PyErr_SetFromErrno(PyObject *exc)
Barry Warsaw97d95151998-07-23 16:05:56 +0000559{
Larry Hastingsb0827312014-02-09 22:05:19 -0800560 return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
Barry Warsaw97d95151998-07-23 16:05:56 +0000561}
Guido van Rossum683a0721990-10-21 22:09:12 +0000562
Brett Cannonbf364092006-03-01 04:25:17 +0000563#ifdef MS_WINDOWS
Guido van Rossum795e1892000-02-17 15:19:15 +0000564/* Windows specific error code handling */
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000565PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 PyObject *exc,
567 int ierr,
568 PyObject *filenameObject)
Guido van Rossum795e1892000-02-17 15:19:15 +0000569{
Larry Hastingsb0827312014-02-09 22:05:19 -0800570 return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
571 filenameObject, NULL);
572}
573
574PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
575 PyObject *exc,
576 int ierr,
577 PyObject *filenameObject,
578 PyObject *filenameObject2)
579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 int len;
581 WCHAR *s_buf = NULL; /* Free via LocalFree */
582 PyObject *message;
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200583 PyObject *args, *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 DWORD err = (DWORD)ierr;
585 if (err==0) err = GetLastError();
586 len = FormatMessageW(
587 /* Error API error */
588 FORMAT_MESSAGE_ALLOCATE_BUFFER |
589 FORMAT_MESSAGE_FROM_SYSTEM |
590 FORMAT_MESSAGE_IGNORE_INSERTS,
591 NULL, /* no message source */
592 err,
593 MAKELANGID(LANG_NEUTRAL,
594 SUBLANG_DEFAULT), /* Default language */
595 (LPWSTR) &s_buf,
596 0, /* size not used */
597 NULL); /* no args */
598 if (len==0) {
599 /* Only seen this in out of mem situations */
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300600 message = PyUnicode_FromFormat("Windows Error 0x%x", err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 s_buf = NULL;
602 } else {
603 /* remove trailing cr/lf and dots */
604 while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
605 s_buf[--len] = L'\0';
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200606 message = PyUnicode_FromWideChar(s_buf, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (message == NULL)
610 {
611 LocalFree(s_buf);
612 return NULL;
613 }
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000614
Larry Hastingsb0827312014-02-09 22:05:19 -0800615 if (filenameObject == NULL) {
616 assert(filenameObject2 == NULL);
617 filenameObject = filenameObject2 = Py_None;
618 }
619 else if (filenameObject2 == NULL)
620 filenameObject2 = Py_None;
621 /* This is the constructor signature for OSError.
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200622 The POSIX translation will be figured out by the constructor. */
Larry Hastingsb0827312014-02-09 22:05:19 -0800623 args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 Py_DECREF(message);
Martin v. Löwis5d12abe2007-09-03 07:40:24 +0000625
Victor Stinner9ea8e4c2011-10-17 20:18:58 +0200626 if (args != NULL) {
627 v = PyObject_Call(exc, args, NULL);
628 Py_DECREF(args);
629 if (v != NULL) {
630 PyErr_SetObject((PyObject *) Py_TYPE(v), v);
631 Py_DECREF(v);
632 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 }
634 LocalFree(s_buf);
635 return NULL;
Guido van Rossum795e1892000-02-17 15:19:15 +0000636}
637
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000638PyObject *PyErr_SetExcFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyObject *exc,
640 int ierr,
641 const char *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000642{
Victor Stinner92be9392010-12-28 00:28:21 +0000643 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800644 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800646 name,
647 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 Py_XDECREF(name);
649 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000650}
651
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000652PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 PyObject *exc,
654 int ierr,
655 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyObject *name = filename ?
658 PyUnicode_FromUnicode(filename, wcslen(filename)) :
659 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800660 PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 ierr,
Larry Hastingsb0827312014-02-09 22:05:19 -0800662 name,
663 NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 Py_XDECREF(name);
665 return ret;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000666}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000667
Thomas Heller085358a2002-07-29 14:27:41 +0000668PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
669{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800670 return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
Thomas Heller085358a2002-07-29 14:27:41 +0000671}
672
Guido van Rossum795e1892000-02-17 15:19:15 +0000673PyObject *PyErr_SetFromWindowsErr(int ierr)
674{
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800675 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
676 ierr, NULL);
Larry Hastingsb0827312014-02-09 22:05:19 -0800677}
678
Thomas Heller085358a2002-07-29 14:27:41 +0000679PyObject *PyErr_SetFromWindowsErrWithFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 int ierr,
681 const char *filename)
Thomas Heller085358a2002-07-29 14:27:41 +0000682{
Victor Stinner92be9392010-12-28 00:28:21 +0000683 PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800684 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200685 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800686 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 Py_XDECREF(name);
688 return result;
Guido van Rossum795e1892000-02-17 15:19:15 +0000689}
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000690
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000691PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 int ierr,
693 const Py_UNICODE *filename)
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 PyObject *name = filename ?
696 PyUnicode_FromUnicode(filename, wcslen(filename)) :
697 NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800698 PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200699 PyExc_OSError,
Larry Hastingsb0827312014-02-09 22:05:19 -0800700 ierr, name, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 Py_XDECREF(name);
702 return result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +0000703}
Guido van Rossum795e1892000-02-17 15:19:15 +0000704#endif /* MS_WINDOWS */
705
Brett Cannon79ec55e2012-04-12 20:24:54 -0400706PyObject *
Brett Cannon82da8882013-07-04 17:48:16 -0400707PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Brett Cannon79ec55e2012-04-12 20:24:54 -0400708{
Brian Curtin09b86d12012-04-17 16:57:09 -0500709 PyObject *args, *kwargs, *error;
710
Brett Cannon82da8882013-07-04 17:48:16 -0400711 if (msg == NULL)
Brian Curtin94c001b2012-04-18 08:30:51 -0500712 return NULL;
713
Antoine Pitrouec9bac42012-04-18 16:57:54 +0200714 args = PyTuple_New(1);
Brian Curtin09b86d12012-04-17 16:57:09 -0500715 if (args == NULL)
716 return NULL;
717
718 kwargs = PyDict_New();
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400719 if (kwargs == NULL) {
720 Py_DECREF(args);
Brian Curtin09b86d12012-04-17 16:57:09 -0500721 return NULL;
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400722 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500723
Brian Curtin94c001b2012-04-18 08:30:51 -0500724 if (name == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500725 name = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500726 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500727
Brian Curtin94c001b2012-04-18 08:30:51 -0500728 if (path == NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -0500729 path = Py_None;
Brian Curtin94c001b2012-04-18 08:30:51 -0500730 }
Brian Curtin09b86d12012-04-17 16:57:09 -0500731
732 Py_INCREF(msg);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400733 PyTuple_SET_ITEM(args, 0, msg);
Victor Stinner479054b2013-07-17 21:54:25 +0200734
735 if (PyDict_SetItemString(kwargs, "name", name) < 0)
736 return NULL;
737 if (PyDict_SetItemString(kwargs, "path", path) < 0)
738 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400739
Brett Cannon82da8882013-07-04 17:48:16 -0400740 error = PyObject_Call(PyExc_ImportError, args, kwargs);
Benjamin Petersonda20cd22012-04-18 10:48:00 -0400741 if (error != NULL) {
742 PyErr_SetObject((PyObject *)Py_TYPE(error), error);
Brian Curtin09b86d12012-04-17 16:57:09 -0500743 Py_DECREF(error);
Brett Cannon79ec55e2012-04-12 20:24:54 -0400744 }
745
Brett Cannon79ec55e2012-04-12 20:24:54 -0400746 Py_DECREF(args);
747 Py_DECREF(kwargs);
748
Brian Curtin09b86d12012-04-17 16:57:09 -0500749 return NULL;
Brett Cannon79ec55e2012-04-12 20:24:54 -0400750}
751
Guido van Rossum683a0721990-10-21 22:09:12 +0000752void
Neal Norwitzb382b842007-08-24 20:00:37 +0000753_PyErr_BadInternalCall(const char *filename, int lineno)
Fred Drake6d63adf2000-08-24 22:38:39 +0000754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 PyErr_Format(PyExc_SystemError,
756 "%s:%d: bad argument to internal function",
757 filename, lineno);
Fred Drake6d63adf2000-08-24 22:38:39 +0000758}
759
760/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
761 export the entry point for existing object code: */
762#undef PyErr_BadInternalCall
763void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000764PyErr_BadInternalCall(void)
Guido van Rossum683a0721990-10-21 22:09:12 +0000765{
Victor Stinnerfb3a6302013-07-12 00:37:30 +0200766 assert(0 && "bad argument to internal function");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyErr_Format(PyExc_SystemError,
768 "bad argument to internal function");
Guido van Rossum683a0721990-10-21 22:09:12 +0000769}
Fred Drake6d63adf2000-08-24 22:38:39 +0000770#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
771
Guido van Rossum1548bac1997-02-14 17:09:47 +0000772
Guido van Rossum1548bac1997-02-14 17:09:47 +0000773PyObject *
Antoine Pitrou0676a402014-09-30 21:16:27 +0200774PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Guido van Rossum1548bac1997-02-14 17:09:47 +0000775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyObject* string;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000777
Victor Stinnerde821be2015-03-24 12:41:23 +0100778 /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
779 exception set, it calls arbitrary Python code like PyObject_Repr() */
Victor Stinnerace47d72013-07-18 01:41:08 +0200780 PyErr_Clear();
Victor Stinnerace47d72013-07-18 01:41:08 +0200781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 string = PyUnicode_FromFormatV(format, vargs);
Victor Stinnerde821be2015-03-24 12:41:23 +0100783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyErr_SetObject(exception, string);
785 Py_XDECREF(string);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 return NULL;
Guido van Rossum1548bac1997-02-14 17:09:47 +0000787}
Guido van Rossum7617e051997-09-16 18:43:50 +0000788
789
Antoine Pitrou0676a402014-09-30 21:16:27 +0200790PyObject *
791PyErr_Format(PyObject *exception, const char *format, ...)
792{
793 va_list vargs;
794#ifdef HAVE_STDARG_PROTOTYPES
795 va_start(vargs, format);
796#else
797 va_start(vargs);
798#endif
799 PyErr_FormatV(exception, format, vargs);
800 va_end(vargs);
801 return NULL;
802}
803
Thomas Wouters477c8d52006-05-27 19:21:47 +0000804
Guido van Rossum7617e051997-09-16 18:43:50 +0000805PyObject *
Neal Norwitzb382b842007-08-24 20:00:37 +0000806PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Guido van Rossum7617e051997-09-16 18:43:50 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 const char *dot;
809 PyObject *modulename = NULL;
810 PyObject *classname = NULL;
811 PyObject *mydict = NULL;
812 PyObject *bases = NULL;
813 PyObject *result = NULL;
814 dot = strrchr(name, '.');
815 if (dot == NULL) {
816 PyErr_SetString(PyExc_SystemError,
817 "PyErr_NewException: name must be module.class");
818 return NULL;
819 }
820 if (base == NULL)
821 base = PyExc_Exception;
822 if (dict == NULL) {
823 dict = mydict = PyDict_New();
824 if (dict == NULL)
825 goto failure;
826 }
827 if (PyDict_GetItemString(dict, "__module__") == NULL) {
828 modulename = PyUnicode_FromStringAndSize(name,
829 (Py_ssize_t)(dot-name));
830 if (modulename == NULL)
831 goto failure;
832 if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
833 goto failure;
834 }
835 if (PyTuple_Check(base)) {
836 bases = base;
837 /* INCREF as we create a new ref in the else branch */
838 Py_INCREF(bases);
839 } else {
840 bases = PyTuple_Pack(1, base);
841 if (bases == NULL)
842 goto failure;
843 }
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100844 /* Create a real class. */
Victor Stinner7eeb5b52010-06-07 19:57:46 +0000845 result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 dot+1, bases, dict);
Guido van Rossum7617e051997-09-16 18:43:50 +0000847 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 Py_XDECREF(bases);
849 Py_XDECREF(mydict);
850 Py_XDECREF(classname);
851 Py_XDECREF(modulename);
852 return result;
Guido van Rossum7617e051997-09-16 18:43:50 +0000853}
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000854
Georg Brandl1e28a272009-12-28 08:41:01 +0000855
856/* Create an exception with docstring */
857PyObject *
858PyErr_NewExceptionWithDoc(const char *name, const char *doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 int result;
862 PyObject *ret = NULL;
863 PyObject *mydict = NULL; /* points to the dict only if we create it */
864 PyObject *docobj;
Georg Brandl1e28a272009-12-28 08:41:01 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (dict == NULL) {
867 dict = mydict = PyDict_New();
868 if (dict == NULL) {
869 return NULL;
870 }
871 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 if (doc != NULL) {
874 docobj = PyUnicode_FromString(doc);
875 if (docobj == NULL)
876 goto failure;
877 result = PyDict_SetItemString(dict, "__doc__", docobj);
878 Py_DECREF(docobj);
879 if (result < 0)
880 goto failure;
881 }
Georg Brandl1e28a272009-12-28 08:41:01 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 ret = PyErr_NewException(name, base, dict);
Georg Brandl1e28a272009-12-28 08:41:01 +0000884 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 Py_XDECREF(mydict);
886 return ret;
Georg Brandl1e28a272009-12-28 08:41:01 +0000887}
888
889
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000890/* Call when an exception has occurred but there is no way for Python
891 to handle it. Examples: exception in __del__ or during GC. */
892void
893PyErr_WriteUnraisable(PyObject *obj)
894{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200895 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyObject *f, *t, *v, *tb;
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200897 PyObject *moduleName = NULL;
898 char* className;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000899
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200900 PyErr_Fetch(&t, &v, &tb);
901
Victor Stinnerbd303c12013-11-07 23:07:29 +0100902 f = _PySys_GetObjectId(&PyId_stderr);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200903 if (f == NULL || f == Py_None)
904 goto done;
905
906 if (obj) {
907 if (PyFile_WriteString("Exception ignored in: ", f) < 0)
908 goto done;
909 if (PyFile_WriteObject(obj, f, 0) < 0)
910 goto done;
911 if (PyFile_WriteString("\n", f) < 0)
912 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 }
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200914
915 if (PyTraceBack_Print(tb, f) < 0)
916 goto done;
917
918 if (!t)
919 goto done;
920
921 assert(PyExceptionClass_Check(t));
922 className = PyExceptionClass_Name(t);
923 if (className != NULL) {
924 char *dot = strrchr(className, '.');
925 if (dot != NULL)
926 className = dot+1;
927 }
928
929 moduleName = _PyObject_GetAttrId(t, &PyId___module__);
930 if (moduleName == NULL) {
931 PyErr_Clear();
932 if (PyFile_WriteString("<unknown>", f) < 0)
933 goto done;
934 }
935 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100936 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0) {
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200937 if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
938 goto done;
939 if (PyFile_WriteString(".", f) < 0)
940 goto done;
941 }
942 }
943 if (className == NULL) {
944 if (PyFile_WriteString("<unknown>", f) < 0)
945 goto done;
946 }
947 else {
948 if (PyFile_WriteString(className, f) < 0)
949 goto done;
950 }
951
952 if (v && v != Py_None) {
953 if (PyFile_WriteString(": ", f) < 0)
954 goto done;
955 if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0)
956 goto done;
957 }
958 if (PyFile_WriteString("\n", f) < 0)
959 goto done;
960
961done:
962 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 Py_XDECREF(t);
964 Py_XDECREF(v);
965 Py_XDECREF(tb);
Victor Stinnerc82bfd82013-08-26 14:04:10 +0200966 PyErr_Clear(); /* Just in case */
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000967}
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000968
Armin Rigo092381a2003-10-25 14:29:27 +0000969extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossumcfd42b52000-12-15 21:58:52 +0000970
Guido van Rossum2fd45652001-02-28 21:46:24 +0000971
Benjamin Peterson2c539712010-09-20 22:42:10 +0000972void
Victor Stinner14e461d2013-08-26 22:28:21 +0200973PyErr_SyntaxLocation(const char *filename, int lineno)
974{
Benjamin Peterson2c539712010-09-20 22:42:10 +0000975 PyErr_SyntaxLocationEx(filename, lineno, -1);
976}
977
978
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000979/* Set file and line information for the current exception.
980 If the exception is not a SyntaxError, also sets additional attributes
981 to make printing of exceptions believe it is a syntax error. */
Guido van Rossum2fd45652001-02-28 21:46:24 +0000982
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000983void
Victor Stinner14e461d2013-08-26 22:28:21 +0200984PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *exc, *v, *tb, *tmp;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200987 _Py_IDENTIFIER(filename);
988 _Py_IDENTIFIER(lineno);
989 _Py_IDENTIFIER(msg);
990 _Py_IDENTIFIER(offset);
991 _Py_IDENTIFIER(print_file_and_line);
992 _Py_IDENTIFIER(text);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* add attributes for the line number and filename for the error */
995 PyErr_Fetch(&exc, &v, &tb);
996 PyErr_NormalizeException(&exc, &v, &tb);
997 /* XXX check that it is, indeed, a syntax error. It might not
998 * be, though. */
999 tmp = PyLong_FromLong(lineno);
1000 if (tmp == NULL)
1001 PyErr_Clear();
1002 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001003 if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyErr_Clear();
1005 Py_DECREF(tmp);
1006 }
Benjamin Peterson2c539712010-09-20 22:42:10 +00001007 if (col_offset >= 0) {
1008 tmp = PyLong_FromLong(col_offset);
1009 if (tmp == NULL)
1010 PyErr_Clear();
1011 else {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001012 if (_PyObject_SetAttrId(v, &PyId_offset, tmp))
Benjamin Peterson2c539712010-09-20 22:42:10 +00001013 PyErr_Clear();
1014 Py_DECREF(tmp);
1015 }
1016 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (filename != NULL) {
Victor Stinner14e461d2013-08-26 22:28:21 +02001018 if (_PyObject_SetAttrId(v, &PyId_filename, filename))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyErr_Clear();
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001020
Victor Stinner14e461d2013-08-26 22:28:21 +02001021 tmp = PyErr_ProgramTextObject(filename, lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001023 if (_PyObject_SetAttrId(v, &PyId_text, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 PyErr_Clear();
1025 Py_DECREF(tmp);
1026 }
1027 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001028 if (_PyObject_SetAttrId(v, &PyId_offset, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyErr_Clear();
1030 }
1031 if (exc != PyExc_SyntaxError) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001032 if (!_PyObject_HasAttrId(v, &PyId_msg)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 tmp = PyObject_Str(v);
1034 if (tmp) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001035 if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyErr_Clear();
1037 Py_DECREF(tmp);
1038 } else {
1039 PyErr_Clear();
1040 }
1041 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001042 if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
1043 if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
1044 Py_None))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyErr_Clear();
1046 }
1047 }
1048 PyErr_Restore(exc, v, tb);
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001049}
1050
Victor Stinner14e461d2013-08-26 22:28:21 +02001051void
1052PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
1053{
1054 PyObject *fileobj;
1055 if (filename != NULL) {
1056 fileobj = PyUnicode_DecodeFSDefault(filename);
1057 if (fileobj == NULL)
1058 PyErr_Clear();
1059 }
1060 else
1061 fileobj = NULL;
1062 PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
1063 Py_XDECREF(fileobj);
1064}
1065
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001066/* Attempt to load the line of text that the exception refers to. If it
1067 fails, it will return NULL but will not set an exception.
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001068
1069 XXX The functionality of this function is quite similar to the
Guido van Rossumebe8f8a2007-10-10 18:53:36 +00001070 functionality in tb_displayline() in traceback.c. */
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001071
Antoine Pitrou409b5382013-10-12 22:41:17 +02001072static PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02001073err_programtext(FILE *fp, int lineno)
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 int i;
1076 char linebuf[1000];
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 if (fp == NULL)
1079 return NULL;
1080 for (i = 0; i < lineno; i++) {
1081 char *pLastChar = &linebuf[sizeof(linebuf) - 2];
1082 do {
1083 *pLastChar = '\0';
1084 if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
1085 fp, NULL) == NULL)
1086 break;
1087 /* fgets read *something*; if it didn't get as
1088 far as pLastChar, it must have found a newline
1089 or hit the end of the file; if pLastChar is \n,
1090 it obviously found a newline; else we haven't
1091 yet seen a newline, so must continue */
1092 } while (*pLastChar != '\0' && *pLastChar != '\n');
1093 }
1094 fclose(fp);
1095 if (i == lineno) {
1096 char *p = linebuf;
1097 PyObject *res;
1098 while (*p == ' ' || *p == '\t' || *p == '\014')
1099 p++;
1100 res = PyUnicode_FromString(p);
1101 if (res == NULL)
1102 PyErr_Clear();
1103 return res;
1104 }
1105 return NULL;
Jeremy Hyltonad3d3f22001-02-28 17:47:12 +00001106}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001107
Victor Stinner14e461d2013-08-26 22:28:21 +02001108PyObject *
1109PyErr_ProgramText(const char *filename, int lineno)
1110{
1111 FILE *fp;
1112 if (filename == NULL || *filename == '\0' || lineno <= 0)
1113 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001114 fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
Victor Stinner14e461d2013-08-26 22:28:21 +02001115 return err_programtext(fp, lineno);
1116}
1117
1118PyObject *
1119PyErr_ProgramTextObject(PyObject *filename, int lineno)
1120{
1121 FILE *fp;
1122 if (filename == NULL || lineno <= 0)
1123 return NULL;
Victor Stinnerdaf45552013-08-28 00:53:59 +02001124 fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
Victor Stinnere42ccd22015-03-18 01:39:23 +01001125 if (fp == NULL) {
1126 PyErr_Clear();
1127 return NULL;
1128 }
Victor Stinner14e461d2013-08-26 22:28:21 +02001129 return err_programtext(fp, lineno);
1130}
1131
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001132#ifdef __cplusplus
1133}
1134#endif