errors.c 31.5 KB
Newer Older
1

2
/* Error handling */
Guido van Rossum's avatar
Guido van Rossum committed
3

4
#include "Python.h"
5

Guido van Rossum's avatar
Guido van Rossum committed
6
#ifndef __STDC__
7
#ifndef MS_WINDOWS
8
extern char *strerror(int);
Guido van Rossum's avatar
Guido van Rossum committed
9
#endif
10
#endif
11

12
#ifdef MS_WINDOWS
13 14
#include <windows.h>
#include <winbase.h>
15 16
#endif

17 18
#include <ctype.h>

19 20 21 22
#ifdef __cplusplus
extern "C" {
#endif

23 24 25
_Py_IDENTIFIER(builtins);
_Py_IDENTIFIER(stderr);

26

Guido van Rossum's avatar
Guido van Rossum committed
27
void
28
PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
Guido van Rossum's avatar
Guido van Rossum committed
29
{
30 31
    PyThreadState *tstate = PyThreadState_GET();
    PyObject *oldtype, *oldvalue, *oldtraceback;
32

33 34 35 36 37 38
    if (traceback != NULL && !PyTraceBack_Check(traceback)) {
        /* XXX Should never happen -- fatal error instead? */
        /* Well, it could be None. */
        Py_DECREF(traceback);
        traceback = NULL;
    }
39

40 41 42 43 44
    /* Save these in locals to safeguard against recursive
       invocation through Py_XDECREF */
    oldtype = tstate->curexc_type;
    oldvalue = tstate->curexc_value;
    oldtraceback = tstate->curexc_traceback;
45

46 47 48
    tstate->curexc_type = type;
    tstate->curexc_value = value;
    tstate->curexc_traceback = traceback;
49

50 51 52
    Py_XDECREF(oldtype);
    Py_XDECREF(oldvalue);
    Py_XDECREF(oldtraceback);
53 54
}

55 56 57 58 59 60 61 62 63 64
static PyObject*
_PyErr_CreateException(PyObject *exception, PyObject *value)
{
    if (value == NULL || value == Py_None) {
        return _PyObject_CallNoArg(exception);
    }
    else if (PyTuple_Check(value)) {
        return PyObject_Call(exception, value, NULL);
    }
    else {
65
        return PyObject_CallFunctionObjArgs(exception, value, NULL);
66 67 68
    }
}

69
void
70
PyErr_SetObject(PyObject *exception, PyObject *value)
71
{
72 73 74 75 76 77 78 79 80 81 82
    PyThreadState *tstate = PyThreadState_GET();
    PyObject *exc_value;
    PyObject *tb = NULL;

    if (exception != NULL &&
        !PyExceptionClass_Check(exception)) {
        PyErr_Format(PyExc_SystemError,
                     "exception %R not a BaseException subclass",
                     exception);
        return;
    }
83

84 85 86 87 88 89 90
    Py_XINCREF(value);
    exc_value = tstate->exc_value;
    if (exc_value != NULL && exc_value != Py_None) {
        /* Implicit exception chaining */
        Py_INCREF(exc_value);
        if (value == NULL || !PyExceptionInstance_Check(value)) {
            /* We must normalize the value right now */
91
            PyObject *fixed_value;
92

93
            /* Issue #23571: functions must not be called with an
94
               exception set */
95
            PyErr_Clear();
96

97
            fixed_value = _PyErr_CreateException(exception, value);
98
            Py_XDECREF(value);
99
            if (fixed_value == NULL) {
100
                return;
101 102
            }

103 104
            value = fixed_value;
        }
105

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        /* Avoid reference cycles through the context chain.
           This is O(chain length) but context chains are
           usually very short. Sensitive readers may try
           to inline the call to PyException_GetContext. */
        if (exc_value != value) {
            PyObject *o = exc_value, *context;
            while ((context = PyException_GetContext(o))) {
                Py_DECREF(context);
                if (context == value) {
                    PyException_SetContext(o, NULL);
                    break;
                }
                o = context;
            }
            PyException_SetContext(value, exc_value);
121 122
        }
        else {
123 124 125 126 127 128 129
            Py_DECREF(exc_value);
        }
    }
    if (value != NULL && PyExceptionInstance_Check(value))
        tb = PyException_GetTraceback(value);
    Py_XINCREF(exception);
    PyErr_Restore(exception, value, tb);
Guido van Rossum's avatar
Guido van Rossum committed
130 131
}

132 133 134 135 136 137 138 139 140 141 142 143 144 145
/* Set a key error with the specified argument, wrapping it in a
 * tuple automatically so that tuple keys are not unpacked as the
 * exception arguments. */
void
_PyErr_SetKeyError(PyObject *arg)
{
    PyObject *tup;
    tup = PyTuple_Pack(1, arg);
    if (!tup)
        return; /* caller will expect error to be set anyway */
    PyErr_SetObject(PyExc_KeyError, tup);
    Py_DECREF(tup);
}

Guido van Rossum's avatar
Guido van Rossum committed
146
void
147
PyErr_SetNone(PyObject *exception)
Guido van Rossum's avatar
Guido van Rossum committed
148
{
149
    PyErr_SetObject(exception, (PyObject *)NULL);
Guido van Rossum's avatar
Guido van Rossum committed
150 151 152
}

void
153
PyErr_SetString(PyObject *exception, const char *string)
Guido van Rossum's avatar
Guido van Rossum committed
154
{
155 156 157
    PyObject *value = PyUnicode_FromString(string);
    PyErr_SetObject(exception, value);
    Py_XDECREF(value);
Guido van Rossum's avatar
Guido van Rossum committed
158 159
}

160

161
PyObject* _Py_HOT_FUNCTION
162
PyErr_Occurred(void)
Guido van Rossum's avatar
Guido van Rossum committed
163
{
164
    PyThreadState *tstate = PyThreadState_GET();
165
    return tstate == NULL ? NULL : tstate->curexc_type;
Guido van Rossum's avatar
Guido van Rossum committed
166 167
}

168 169

int
170
PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
171
{
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    if (err == NULL || exc == NULL) {
        /* maybe caused by "import exceptions" that failed early on */
        return 0;
    }
    if (PyTuple_Check(exc)) {
        Py_ssize_t i, n;
        n = PyTuple_Size(exc);
        for (i = 0; i < n; i++) {
            /* Test recursively */
             if (PyErr_GivenExceptionMatches(
                 err, PyTuple_GET_ITEM(exc, i)))
             {
                 return 1;
             }
        }
        return 0;
    }
    /* err might be an instance, so check its class. */
    if (PyExceptionInstance_Check(err))
        err = PyExceptionInstance_Class(err);

    if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
        int res = 0;
        PyObject *exception, *value, *tb;
        PyErr_Fetch(&exception, &value, &tb);
        /* PyObject_IsSubclass() can recurse and therefore is
           not safe (see test_bad_getattr in test.pickletester). */
        res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
        /* This function must not fail, so print the error here */
        if (res == -1) {
            PyErr_WriteUnraisable(err);
            res = 0;
        }
        PyErr_Restore(exception, value, tb);
        return res;
    }

    return err == exc;
210
}
211

212 213

int
214
PyErr_ExceptionMatches(PyObject *exc)
215
{
216
    return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
217 218 219 220 221
}


/* Used in many places to normalize a raised exception, including in
   eval_code2(), do_raise(), and PyErr_Print()
222 223

   XXX: should PyErr_NormalizeException() also call
224
            PyException_SetTraceback() with the resulting value and tb?
225 226
*/
void
227
PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
228
{
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    PyObject *type = *exc;
    PyObject *value = *val;
    PyObject *inclass = NULL;
    PyObject *initial_tb = NULL;
    PyThreadState *tstate = NULL;

    if (type == NULL) {
        /* There was no exception, so nothing to do. */
        return;
    }

    /* If PyErr_SetNone() was used, the value will have been actually
       set to NULL.
    */
    if (!value) {
        value = Py_None;
        Py_INCREF(value);
    }

    if (PyExceptionInstance_Check(value))
        inclass = PyExceptionInstance_Class(value);

    /* Normalize the exception so that if the type is a class, the
       value will be an instance.
    */
    if (PyExceptionClass_Check(type)) {
255 256 257 258 259 260 261 262 263
        int is_subclass;
        if (inclass) {
            is_subclass = PyObject_IsSubclass(inclass, type);
            if (is_subclass < 0)
                goto finally;
        }
        else
            is_subclass = 0;

264 265 266 267 268
        /* if the value was not an instance, or is not an instance
           whose class is (or is derived from) type, then use the
           value as an argument to instantiation of the type
           class.
        */
269
        if (!inclass || !is_subclass) {
270
            PyObject *fixed_value;
271

272 273 274
            fixed_value = _PyErr_CreateException(type, value);
            if (fixed_value == NULL) {
                goto finally;
275 276 277
            }

            Py_DECREF(value);
278
            value = fixed_value;
279 280 281 282 283 284 285 286 287 288 289 290 291
        }
        /* if the class of the instance doesn't exactly match the
           class of the type, believe the instance
        */
        else if (inclass != type) {
            Py_DECREF(type);
            type = inclass;
            Py_INCREF(type);
        }
    }
    *exc = type;
    *val = value;
    return;
292
finally:
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    Py_DECREF(type);
    Py_DECREF(value);
    /* If the new exception doesn't set a traceback and the old
       exception had a traceback, use the old traceback for the
       new exception.  It's better than nothing.
    */
    initial_tb = *tb;
    PyErr_Fetch(exc, val, tb);
    if (initial_tb != NULL) {
        if (*tb == NULL)
            *tb = initial_tb;
        else
            Py_DECREF(initial_tb);
    }
    /* normalize recursively */
    tstate = PyThreadState_GET();
    if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
        --tstate->recursion_depth;
311 312
        /* throw away the old exception and use the recursion error instead */
        Py_INCREF(PyExc_RecursionError);
313
        Py_SETREF(*exc, PyExc_RecursionError);
314
        Py_INCREF(PyExc_RecursionErrorInst);
315
        Py_SETREF(*val, PyExc_RecursionErrorInst);
316 317 318 319 320
        /* just keeping the old traceback */
        return;
    }
    PyErr_NormalizeException(exc, val, tb);
    --tstate->recursion_depth;
321 322 323
}


Guido van Rossum's avatar
Guido van Rossum committed
324
void
325
PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
Guido van Rossum's avatar
Guido van Rossum committed
326
{
327
    PyThreadState *tstate = PyThreadState_GET();
328

329 330 331
    *p_type = tstate->curexc_type;
    *p_value = tstate->curexc_value;
    *p_traceback = tstate->curexc_traceback;
332

333 334 335
    tstate->curexc_type = NULL;
    tstate->curexc_value = NULL;
    tstate->curexc_traceback = NULL;
Guido van Rossum's avatar
Guido van Rossum committed
336 337 338
}

void
339
PyErr_Clear(void)
Guido van Rossum's avatar
Guido van Rossum committed
340
{
341
    PyErr_Restore(NULL, NULL, NULL);
Guido van Rossum's avatar
Guido van Rossum committed
342
}
343

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
void
PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
{
    PyThreadState *tstate = PyThreadState_GET();

    *p_type = tstate->exc_type;
    *p_value = tstate->exc_value;
    *p_traceback = tstate->exc_traceback;

    Py_XINCREF(*p_type);
    Py_XINCREF(*p_value);
    Py_XINCREF(*p_traceback);
}

void
PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback)
{
    PyObject *oldtype, *oldvalue, *oldtraceback;
    PyThreadState *tstate = PyThreadState_GET();

    oldtype = tstate->exc_type;
    oldvalue = tstate->exc_value;
    oldtraceback = tstate->exc_traceback;

    tstate->exc_type = p_type;
    tstate->exc_value = p_value;
    tstate->exc_traceback = p_traceback;

    Py_XDECREF(oldtype);
    Py_XDECREF(oldvalue);
    Py_XDECREF(oldtraceback);
}

377 378 379 380 381 382 383 384 385 386 387 388 389
/* Like PyErr_Restore(), but if an exception is already set,
   set the context associated with it.
 */
void
_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
{
    if (exc == NULL)
        return;

    if (PyErr_Occurred()) {
        PyObject *exc2, *val2, *tb2;
        PyErr_Fetch(&exc2, &val2, &tb2);
        PyErr_NormalizeException(&exc, &val, &tb);
390 391 392 393
        if (tb != NULL) {
            PyException_SetTraceback(val, tb);
            Py_DECREF(tb);
        }
394 395 396 397 398 399 400 401 402 403
        Py_DECREF(exc);
        PyErr_NormalizeException(&exc2, &val2, &tb2);
        PyException_SetContext(val2, val);
        PyErr_Restore(exc2, val2, tb2);
    }
    else {
        PyErr_Restore(exc, val, tb);
    }
}

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
static PyObject *
_PyErr_FormatVFromCause(PyObject *exception, const char *format, va_list vargs)
{
    PyObject *exc, *val, *val2, *tb;

    assert(PyErr_Occurred());
    PyErr_Fetch(&exc, &val, &tb);
    PyErr_NormalizeException(&exc, &val, &tb);
    if (tb != NULL) {
        PyException_SetTraceback(val, tb);
        Py_DECREF(tb);
    }
    Py_DECREF(exc);
    assert(!PyErr_Occurred());

    PyErr_FormatV(exception, format, vargs);

    PyErr_Fetch(&exc, &val2, &tb);
    PyErr_NormalizeException(&exc, &val2, &tb);
    Py_INCREF(val);
    PyException_SetCause(val2, val);
    PyException_SetContext(val2, val);
    PyErr_Restore(exc, val2, tb);

    return NULL;
}

PyObject *
_PyErr_FormatFromCause(PyObject *exception, const char *format, ...)
{
    va_list vargs;
#ifdef HAVE_STDARG_PROTOTYPES
    va_start(vargs, format);
#else
    va_start(vargs);
#endif
    _PyErr_FormatVFromCause(exception, format, vargs);
    va_end(vargs);
    return NULL;
}

445 446 447
/* Convenience functions to set a type error exception and return 0 */

int
448
PyErr_BadArgument(void)
449
{
450 451 452
    PyErr_SetString(PyExc_TypeError,
                    "bad argument type for built-in operation");
    return 0;
453 454
}

455
PyObject *
456
PyErr_NoMemory(void)
457
{
458 459 460 461 462 463
    if (Py_TYPE(PyExc_MemoryError) == NULL) {
        /* PyErr_NoMemory() has been called before PyExc_MemoryError has been
           initialized by _PyExc_Init() */
        Py_FatalError("Out of memory and PyExc_MemoryError is not "
                      "initialized yet");
    }
464
    PyErr_SetNone(PyExc_MemoryError);
465
    return NULL;
466 467
}

468
PyObject *
469
PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
470 471 472 473 474 475
{
    return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL);
}

PyObject *
PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
476
{
477
    PyObject *message;
478
    PyObject *v, *args;
479
    int i = errno;
480
#ifdef MS_WINDOWS
481
    WCHAR *s_buf = NULL;
482 483
#endif /* Unix/Windows */

484
#ifdef EINTR
485 486
    if (i == EINTR && PyErr_CheckSignals())
        return NULL;
487
#endif
488 489

#ifndef MS_WINDOWS
490 491
    if (i != 0) {
        char *s = strerror(i);
492
        message = PyUnicode_DecodeLocale(s, "surrogateescape");
493 494 495 496 497
    }
    else {
        /* Sometimes errno didn't get set */
        message = PyUnicode_FromString("Error");
    }
498
#else
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
    if (i == 0)
        message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
    else
    {
        /* Note that the Win32 errors do not lineup with the
           errno error.  So if the error is in the MSVC error
           table, we use it, otherwise we assume it really _is_
           a Win32 error code
        */
        if (i > 0 && i < _sys_nerr) {
            message = PyUnicode_FromString(_sys_errlist[i]);
        }
        else {
            int len = FormatMessageW(
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,                   /* no message source */
                i,
                MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_DEFAULT),
                           /* Default language */
                (LPWSTR) &s_buf,
                0,                      /* size not used */
                NULL);                  /* no args */
            if (len==0) {
                /* Only ever seen this in out-of-mem
                   situations */
                s_buf = NULL;
528
                message = PyUnicode_FromFormat("Windows Error 0x%x", i);
529 530 531 532
            } else {
                /* remove trailing cr/lf and dots */
                while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
                    s_buf[--len] = L'\0';
Martin v. Löwis's avatar
Martin v. Löwis committed
533
                message = PyUnicode_FromWideChar(s_buf, len);
534 535 536
            }
        }
    }
537
#endif /* Unix/Windows */
538

539 540
    if (message == NULL)
    {
541
#ifdef MS_WINDOWS
542
        LocalFree(s_buf);
543
#endif
544 545 546
        return NULL;
    }

547 548 549 550 551 552 553
    if (filenameObject != NULL) {
        if (filenameObject2 != NULL)
            args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
        else
            args = Py_BuildValue("(iOO)", i, message, filenameObject);
    } else {
        assert(filenameObject2 == NULL);
554
        args = Py_BuildValue("(iO)", i, message);
555
    }
556 557
    Py_DECREF(message);

558 559 560 561 562 563 564
    if (args != NULL) {
        v = PyObject_Call(exc, args, NULL);
        Py_DECREF(args);
        if (v != NULL) {
            PyErr_SetObject((PyObject *) Py_TYPE(v), v);
            Py_DECREF(v);
        }
565
    }
566
#ifdef MS_WINDOWS
567
    LocalFree(s_buf);
568
#endif
569
    return NULL;
570
}
571

572
PyObject *
573
PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
574
{
575
    PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
576
    PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
577 578
    Py_XDECREF(name);
    return result;
579 580
}

581
#ifdef MS_WINDOWS
582
PyObject *
583
PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
584
{
585
    PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
586
    PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL);
587 588
    Py_XDECREF(name);
    return result;
589
}
590
#endif /* MS_WINDOWS */
591

592
PyObject *
593
PyErr_SetFromErrno(PyObject *exc)
594
{
595
    return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL);
596
}
Guido van Rossum's avatar
Guido van Rossum committed
597

598
#ifdef MS_WINDOWS
599
/* Windows specific error code handling */
600
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
601 602 603
    PyObject *exc,
    int ierr,
    PyObject *filenameObject)
604 605 606 607 608 609 610 611 612 613
{
    return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr,
        filenameObject, NULL);
}

PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
    PyObject *exc,
    int ierr,
    PyObject *filenameObject,
    PyObject *filenameObject2)
614
{
615 616 617
    int len;
    WCHAR *s_buf = NULL; /* Free via LocalFree */
    PyObject *message;
618
    PyObject *args, *v;
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
    DWORD err = (DWORD)ierr;
    if (err==0) err = GetLastError();
    len = FormatMessageW(
        /* Error API error */
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,           /* no message source */
        err,
        MAKELANGID(LANG_NEUTRAL,
        SUBLANG_DEFAULT), /* Default language */
        (LPWSTR) &s_buf,
        0,              /* size not used */
        NULL);          /* no args */
    if (len==0) {
        /* Only seen this in out of mem situations */
635
        message = PyUnicode_FromFormat("Windows Error 0x%x", err);
636 637 638 639 640
        s_buf = NULL;
    } else {
        /* remove trailing cr/lf and dots */
        while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
            s_buf[--len] = L'\0';
Martin v. Löwis's avatar
Martin v. Löwis committed
641
        message = PyUnicode_FromWideChar(s_buf, len);
642 643 644 645 646 647 648 649
    }

    if (message == NULL)
    {
        LocalFree(s_buf);
        return NULL;
    }

650 651 652 653 654 655 656
    if (filenameObject == NULL) {
        assert(filenameObject2 == NULL);
        filenameObject = filenameObject2 = Py_None;
    }
    else if (filenameObject2 == NULL)
        filenameObject2 = Py_None;
    /* This is the constructor signature for OSError.
657
       The POSIX translation will be figured out by the constructor. */
658
    args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
659 660
    Py_DECREF(message);

661 662 663 664 665 666 667
    if (args != NULL) {
        v = PyObject_Call(exc, args, NULL);
        Py_DECREF(args);
        if (v != NULL) {
            PyErr_SetObject((PyObject *) Py_TYPE(v), v);
            Py_DECREF(v);
        }
668 669 670
    }
    LocalFree(s_buf);
    return NULL;
671 672
}

673
PyObject *PyErr_SetExcFromWindowsErrWithFilename(
674 675 676
    PyObject *exc,
    int ierr,
    const char *filename)
677
{
678
    PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
679
    PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
680
                                                                 ierr,
681 682
                                                                 name,
                                                                 NULL);
683 684
    Py_XDECREF(name);
    return ret;
685 686 687
}

PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
688 689 690
    PyObject *exc,
    int ierr,
    const Py_UNICODE *filename)
691
{
692
    PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
693 694 695 696 697 698 699 700
    PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc,
                                                                 ierr,
                                                                 name,
                                                                 NULL);
    Py_XDECREF(name);
    return ret;
}

701 702
PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
{
703
    return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
704 705
}

706 707
PyObject *PyErr_SetFromWindowsErr(int ierr)
{
708 709
    return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError,
                                                  ierr, NULL);
710
}
711

712
PyObject *PyErr_SetFromWindowsErrWithFilename(
713 714
    int ierr,
    const char *filename)
715
{
716
    PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
717
    PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
718
                                                  PyExc_OSError,
719
                                                  ierr, name, NULL);
720 721
    Py_XDECREF(name);
    return result;
722 723 724
}

PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
725 726
    int ierr,
    const Py_UNICODE *filename)
727
{
728
    PyObject *name = filename ? PyUnicode_FromWideChar(filename, -1) : NULL;
729 730 731 732 733 734
    PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects(
                                                  PyExc_OSError,
                                                  ierr, name, NULL);
    Py_XDECREF(name);
    return result;
}
735 736
#endif /* MS_WINDOWS */

737
PyObject *
738 739
PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg,
    PyObject *name, PyObject *path)
740
{
741
    int issubclass;
742
    PyObject *kwargs, *error;
743

744 745 746 747 748 749
    issubclass = PyObject_IsSubclass(exception, PyExc_ImportError);
    if (issubclass < 0) {
        return NULL;
    }
    else if (!issubclass) {
        PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError");
750
        return NULL;
751
    }
752

753 754
    if (msg == NULL) {
        PyErr_SetString(PyExc_TypeError, "expected a message argument");
755
        return NULL;
756
    }
757

758
    if (name == NULL) {
759
        name = Py_None;
760 761
    }
    if (path == NULL) {
762
        path = Py_None;
763
    }
764

765 766 767 768
    kwargs = PyDict_New();
    if (kwargs == NULL) {
        return NULL;
    }
769
    if (PyDict_SetItemString(kwargs, "name", name) < 0) {
770
        goto done;
771 772
    }
    if (PyDict_SetItemString(kwargs, "path", path) < 0) {
773
        goto done;
774
    }
775

776
    error = _PyObject_FastCallDict(exception, &msg, 1, kwargs);
777 778
    if (error != NULL) {
        PyErr_SetObject((PyObject *)Py_TYPE(error), error);
779 780
        Py_DECREF(error);
    }
781

782
done:
783
    Py_DECREF(kwargs);
784
    return NULL;
785 786
}

787 788 789 790 791 792
PyObject *
PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
{
    return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path);
}

793
void
794
_PyErr_BadInternalCall(const char *filename, int lineno)
795
{
796 797 798
    PyErr_Format(PyExc_SystemError,
                 "%s:%d: bad argument to internal function",
                 filename, lineno);
799 800 801 802 803
}

/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
   export the entry point for existing object code: */
#undef PyErr_BadInternalCall
Guido van Rossum's avatar
Guido van Rossum committed
804
void
805
PyErr_BadInternalCall(void)
Guido van Rossum's avatar
Guido van Rossum committed
806
{
807
    assert(0 && "bad argument to internal function");
808 809
    PyErr_Format(PyExc_SystemError,
                 "bad argument to internal function");
Guido van Rossum's avatar
Guido van Rossum committed
810
}
811 812
#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)

813 814

PyObject *
815
PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
816
{
817
    PyObject* string;
818

819 820
    /* Issue #23571: PyUnicode_FromFormatV() must not be called with an
       exception set, it calls arbitrary Python code like PyObject_Repr() */
821 822
    PyErr_Clear();

823
    string = PyUnicode_FromFormatV(format, vargs);
824

825 826 827
    PyErr_SetObject(exception, string);
    Py_XDECREF(string);
    return NULL;
828
}
829 830


831 832 833 834 835 836 837 838 839 840 841 842 843 844
PyObject *
PyErr_Format(PyObject *exception, const char *format, ...)
{
    va_list vargs;
#ifdef HAVE_STDARG_PROTOTYPES
    va_start(vargs, format);
#else
    va_start(vargs);
#endif
    PyErr_FormatV(exception, format, vargs);
    va_end(vargs);
    return NULL;
}

845

846
PyObject *
847
PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
848
{
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    const char *dot;
    PyObject *modulename = NULL;
    PyObject *classname = NULL;
    PyObject *mydict = NULL;
    PyObject *bases = NULL;
    PyObject *result = NULL;
    dot = strrchr(name, '.');
    if (dot == NULL) {
        PyErr_SetString(PyExc_SystemError,
            "PyErr_NewException: name must be module.class");
        return NULL;
    }
    if (base == NULL)
        base = PyExc_Exception;
    if (dict == NULL) {
        dict = mydict = PyDict_New();
        if (dict == NULL)
            goto failure;
    }
    if (PyDict_GetItemString(dict, "__module__") == NULL) {
        modulename = PyUnicode_FromStringAndSize(name,
                                             (Py_ssize_t)(dot-name));
        if (modulename == NULL)
            goto failure;
        if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
            goto failure;
    }
    if (PyTuple_Check(base)) {
        bases = base;
        /* INCREF as we create a new ref in the else branch */
        Py_INCREF(bases);
    } else {
        bases = PyTuple_Pack(1, base);
        if (bases == NULL)
            goto failure;
    }
885
    /* Create a real class. */
886
    result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
887
                                   dot+1, bases, dict);
888
  failure:
889 890 891 892 893
    Py_XDECREF(bases);
    Py_XDECREF(mydict);
    Py_XDECREF(classname);
    Py_XDECREF(modulename);
    return result;
894
}
895

896 897 898 899

/* Create an exception with docstring */
PyObject *
PyErr_NewExceptionWithDoc(const char *name, const char *doc,
900
                          PyObject *base, PyObject *dict)
901
{
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    int result;
    PyObject *ret = NULL;
    PyObject *mydict = NULL; /* points to the dict only if we create it */
    PyObject *docobj;

    if (dict == NULL) {
        dict = mydict = PyDict_New();
        if (dict == NULL) {
            return NULL;
        }
    }

    if (doc != NULL) {
        docobj = PyUnicode_FromString(doc);
        if (docobj == NULL)
            goto failure;
        result = PyDict_SetItemString(dict, "__doc__", docobj);
        Py_DECREF(docobj);
        if (result < 0)
            goto failure;
    }

    ret = PyErr_NewException(name, base, dict);
925
  failure:
926 927
    Py_XDECREF(mydict);
    return ret;
928 929 930
}


931 932 933 934 935
/* Call when an exception has occurred but there is no way for Python
   to handle it.  Examples: exception in __del__ or during GC. */
void
PyErr_WriteUnraisable(PyObject *obj)
{
936
    _Py_IDENTIFIER(__module__);
937
    PyObject *f, *t, *v, *tb;
938 939 940
    PyObject *moduleName = NULL;
    char* className;

941
    PyErr_Fetch(&t, &v, &tb);
942

943
    f = _PySys_GetObjectId(&PyId_stderr);
944 945 946 947 948 949
    if (f == NULL || f == Py_None)
        goto done;

    if (obj) {
        if (PyFile_WriteString("Exception ignored in: ", f) < 0)
            goto done;
950 951 952 953 954 955
        if (PyFile_WriteObject(obj, f, 0) < 0) {
            PyErr_Clear();
            if (PyFile_WriteString("<object repr() failed>", f) < 0) {
                goto done;
            }
        }
956 957 958
        if (PyFile_WriteString("\n", f) < 0)
            goto done;
    }
959

960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    if (PyTraceBack_Print(tb, f) < 0)
        goto done;

    if (!t)
        goto done;

    assert(PyExceptionClass_Check(t));
    className = PyExceptionClass_Name(t);
    if (className != NULL) {
        char *dot = strrchr(className, '.');
        if (dot != NULL)
            className = dot+1;
    }

    moduleName = _PyObject_GetAttrId(t, &PyId___module__);
    if (moduleName == NULL) {
        PyErr_Clear();
        if (PyFile_WriteString("<unknown>", f) < 0)
            goto done;
    }
    else {
981
        if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
982 983 984 985
            if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
                goto done;
            if (PyFile_WriteString(".", f) < 0)
                goto done;
986 987
        }
    }
988 989 990 991 992 993 994 995 996 997 998 999
    if (className == NULL) {
        if (PyFile_WriteString("<unknown>", f) < 0)
            goto done;
    }
    else {
        if (PyFile_WriteString(className, f) < 0)
            goto done;
    }

    if (v && v != Py_None) {
        if (PyFile_WriteString(": ", f) < 0)
            goto done;
1000 1001 1002 1003 1004 1005
        if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) {
            PyErr_Clear();
            if (PyFile_WriteString("<exception str() failed>", f) < 0) {
                goto done;
            }
        }
1006 1007 1008 1009 1010 1011
    }
    if (PyFile_WriteString("\n", f) < 0)
        goto done;

done:
    Py_XDECREF(moduleName);
1012 1013 1014
    Py_XDECREF(t);
    Py_XDECREF(v);
    Py_XDECREF(tb);
1015
    PyErr_Clear(); /* Just in case */
1016
}
Guido van Rossum's avatar
Guido van Rossum committed
1017

1018
extern PyObject *PyModule_GetWarningsModule(void);
Guido van Rossum's avatar
Guido van Rossum committed
1019

1020

1021
void
1022 1023
PyErr_SyntaxLocation(const char *filename, int lineno)
{
1024 1025 1026 1027
    PyErr_SyntaxLocationEx(filename, lineno, -1);
}


1028 1029 1030
/* Set file and line information for the current exception.
   If the exception is not a SyntaxError, also sets additional attributes
   to make printing of exceptions believe it is a syntax error. */
1031

1032
void
1033
PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
1034
{
1035
    PyObject *exc, *v, *tb, *tmp;
1036 1037 1038 1039 1040 1041
    _Py_IDENTIFIER(filename);
    _Py_IDENTIFIER(lineno);
    _Py_IDENTIFIER(msg);
    _Py_IDENTIFIER(offset);
    _Py_IDENTIFIER(print_file_and_line);
    _Py_IDENTIFIER(text);
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

    /* add attributes for the line number and filename for the error */
    PyErr_Fetch(&exc, &v, &tb);
    PyErr_NormalizeException(&exc, &v, &tb);
    /* XXX check that it is, indeed, a syntax error. It might not
     * be, though. */
    tmp = PyLong_FromLong(lineno);
    if (tmp == NULL)
        PyErr_Clear();
    else {
1052
        if (_PyObject_SetAttrId(v, &PyId_lineno, tmp))
1053 1054 1055
            PyErr_Clear();
        Py_DECREF(tmp);
    }
1056
    tmp = NULL;
1057 1058 1059 1060 1061
    if (col_offset >= 0) {
        tmp = PyLong_FromLong(col_offset);
        if (tmp == NULL)
            PyErr_Clear();
    }
1062 1063 1064
    if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
        PyErr_Clear();
    Py_XDECREF(tmp);
1065
    if (filename != NULL) {
1066
        if (_PyObject_SetAttrId(v, &PyId_filename, filename))
1067 1068
            PyErr_Clear();

1069
        tmp = PyErr_ProgramTextObject(filename, lineno);
1070
        if (tmp) {
1071
            if (_PyObject_SetAttrId(v, &PyId_text, tmp))
1072 1073 1074 1075 1076
                PyErr_Clear();
            Py_DECREF(tmp);
        }
    }
    if (exc != PyExc_SyntaxError) {
1077
        if (!_PyObject_HasAttrId(v, &PyId_msg)) {
1078 1079
            tmp = PyObject_Str(v);
            if (tmp) {
1080
                if (_PyObject_SetAttrId(v, &PyId_msg, tmp))
1081 1082 1083 1084 1085 1086
                    PyErr_Clear();
                Py_DECREF(tmp);
            } else {
                PyErr_Clear();
            }
        }
1087 1088 1089
        if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) {
            if (_PyObject_SetAttrId(v, &PyId_print_file_and_line,
                                    Py_None))
1090 1091 1092 1093
                PyErr_Clear();
        }
    }
    PyErr_Restore(exc, v, tb);
1094 1095
}

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
void
PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
{
    PyObject *fileobj;
    if (filename != NULL) {
        fileobj = PyUnicode_DecodeFSDefault(filename);
        if (fileobj == NULL)
            PyErr_Clear();
    }
    else
        fileobj = NULL;
    PyErr_SyntaxLocationObject(fileobj, lineno, col_offset);
    Py_XDECREF(fileobj);
}

1111 1112
/* Attempt to load the line of text that the exception refers to.  If it
   fails, it will return NULL but will not set an exception.
1113 1114

   XXX The functionality of this function is quite similar to the
1115
   functionality in tb_displayline() in traceback.c. */
1116

1117
static PyObject *
1118
err_programtext(FILE *fp, int lineno)
1119
{
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
    int i;
    char linebuf[1000];

    if (fp == NULL)
        return NULL;
    for (i = 0; i < lineno; i++) {
        char *pLastChar = &linebuf[sizeof(linebuf) - 2];
        do {
            *pLastChar = '\0';
            if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf,
                                         fp, NULL) == NULL)
                break;
            /* fgets read *something*; if it didn't get as
               far as pLastChar, it must have found a newline
               or hit the end of the file; if pLastChar is \n,
               it obviously found a newline; else we haven't
               yet seen a newline, so must continue */
        } while (*pLastChar != '\0' && *pLastChar != '\n');
    }
    fclose(fp);
    if (i == lineno) {
        PyObject *res;
1142
        res = PyUnicode_FromString(linebuf);
1143 1144 1145 1146 1147
        if (res == NULL)
            PyErr_Clear();
        return res;
    }
    return NULL;
1148
}
1149

1150 1151 1152 1153 1154 1155
PyObject *
PyErr_ProgramText(const char *filename, int lineno)
{
    FILE *fp;
    if (filename == NULL || *filename == '\0' || lineno <= 0)
        return NULL;
1156
    fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE);
1157 1158 1159 1160 1161 1162 1163 1164 1165
    return err_programtext(fp, lineno);
}

PyObject *
PyErr_ProgramTextObject(PyObject *filename, int lineno)
{
    FILE *fp;
    if (filename == NULL || lineno <= 0)
        return NULL;
1166
    fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE);
1167 1168 1169 1170
    if (fp == NULL) {
        PyErr_Clear();
        return NULL;
    }
1171 1172 1173
    return err_programtext(fp, lineno);
}

1174 1175 1176
#ifdef __cplusplus
}
#endif