faulthandler.c 32.4 KB
Newer Older
1 2 3 4 5 6
#include "Python.h"
#include "pythread.h"
#include <signal.h>
#include <object.h>
#include <frameobject.h>
#include <signal.h>
7
#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
8 9 10 11 12 13 14
#  include <pthread.h>
#endif
#ifdef MS_WINDOWS
#  include <windows.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
#  include <sys/resource.h>
15 16
#endif

17 18 19
/* Allocate at maximum 100 MB of the stack to raise the stack overflow */
#define STACK_OVERFLOW_MAX_SIZE (100*1024*1024)

20 21 22 23 24
#ifdef WITH_THREAD
#  define FAULTHANDLER_LATER
#endif

#ifndef MS_WINDOWS
25 26 27
   /* register() is useless on Windows, because only SIGSEGV, SIGABRT and
      SIGILL can be handled by the process, and these signals can only be used
      with enable(), not using register() */
28 29 30
#  define FAULTHANDLER_USER
#endif

31 32 33
/* cast size_t to int because write() takes an int on Windows
   (anyway, the length is smaller than 30 characters) */
#define PUTS(fd, str) write(fd, str, (int)strlen(str))
34

35 36 37 38 39
_Py_IDENTIFIER(enable);
_Py_IDENTIFIER(fileno);
_Py_IDENTIFIER(flush);
_Py_IDENTIFIER(stderr);

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#ifdef HAVE_SIGACTION
typedef struct sigaction _Py_sighandler_t;
#else
typedef PyOS_sighandler_t _Py_sighandler_t;
#endif

typedef struct {
    int signum;
    int enabled;
    const char* name;
    _Py_sighandler_t previous;
    int all_threads;
} fault_handler_t;

static struct {
    int enabled;
    PyObject *file;
    int fd;
    int all_threads;
59
    PyInterpreterState *interp;
60 61 62 63 64 65
} fatal_error = {0, NULL, -1, 0};

#ifdef FAULTHANDLER_LATER
static struct {
    PyObject *file;
    int fd;
66
    PY_TIMEOUT_T timeout_us;   /* timeout in microseconds */
67 68 69
    int repeat;
    PyInterpreterState *interp;
    int exit;
70 71
    char *header;
    size_t header_len;
72 73
    /* The main thread always holds this lock. It is only released when
       faulthandler_thread() is interrupted before this thread exits, or at
74
       Python exit. */
75 76
    PyThread_type_lock cancel_event;
    /* released by child thread when joined */
77
    PyThread_type_lock running;
78 79 80 81 82 83 84 85 86
} thread;
#endif

#ifdef FAULTHANDLER_USER
typedef struct {
    int enabled;
    PyObject *file;
    int fd;
    int all_threads;
87
    int chain;
88
    _Py_sighandler_t previous;
89
    PyInterpreterState *interp;
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
} user_signal_t;

static user_signal_t *user_signals;

/* the following macros come from Python: Modules/signalmodule.c */
#ifndef NSIG
# if defined(_NSIG)
#  define NSIG _NSIG            /* For BSD/SysV */
# elif defined(_SIGMAX)
#  define NSIG (_SIGMAX + 1)    /* For QNX */
# elif defined(SIGMAX)
#  define NSIG (SIGMAX + 1)     /* For djgpp */
# else
#  define NSIG 64               /* Use a reasonable default value */
# endif
#endif

107
static void faulthandler_user(int signum);
108 109 110 111 112 113 114 115 116 117 118
#endif /* FAULTHANDLER_USER */


static fault_handler_t faulthandler_handlers[] = {
#ifdef SIGBUS
    {SIGBUS, 0, "Bus error", },
#endif
#ifdef SIGILL
    {SIGILL, 0, "Illegal instruction", },
#endif
    {SIGFPE, 0, "Floating point exception", },
119
    {SIGABRT, 0, "Aborted", },
120 121 122 123 124
    /* define SIGSEGV at the end to make it the default choice if searching the
       handler fails in faulthandler_fatal_error() */
    {SIGSEGV, 0, "Segmentation fault", }
};
static const unsigned char faulthandler_nsignals = \
125
    Py_ARRAY_LENGTH(faulthandler_handlers);
126 127 128 129 130 131 132 133 134 135

#ifdef HAVE_SIGALTSTACK
static stack_t stack;
#endif


/* Get the file descriptor of a file by calling its fileno() method and then
   call its flush() method.

   If file is NULL or Py_None, use sys.stderr as the new file.
136
   If file is an integer, it will be treated as file descriptor.
137

138 139
   On success, return the file descriptor and write the new file into *file_ptr.
   On error, return -1. */
140

141 142
static int
faulthandler_get_fileno(PyObject **file_ptr)
143 144 145 146
{
    PyObject *result;
    long fd_long;
    int fd;
147
    PyObject *file = *file_ptr;
148 149

    if (file == NULL || file == Py_None) {
150
        file = _PySys_GetObjectId(&PyId_stderr);
151 152
        if (file == NULL) {
            PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
153
            return -1;
154
        }
155 156
        if (file == Py_None) {
            PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
157
            return -1;
158
        }
159
    }
160 161 162 163 164 165 166 167 168 169 170 171
    else if (PyLong_Check(file)) {
        fd = _PyLong_AsInt(file);
        if (fd == -1 && PyErr_Occurred())
            return -1;
        if (fd < 0 || !_PyVerify_fd(fd)) {
            PyErr_SetString(PyExc_ValueError,
                            "file is not a valid file descripter");
            return -1;
        }
        *file_ptr = NULL;
        return fd;
    }
172

173
    result = _PyObject_CallMethodId(file, &PyId_fileno, "");
174
    if (result == NULL)
175
        return -1;
176 177 178 179 180 181 182 183 184 185 186 187

    fd = -1;
    if (PyLong_Check(result)) {
        fd_long = PyLong_AsLong(result);
        if (0 <= fd_long && fd_long < INT_MAX)
            fd = (int)fd_long;
    }
    Py_DECREF(result);

    if (fd == -1) {
        PyErr_SetString(PyExc_RuntimeError,
                        "file.fileno() is not a valid file descriptor");
188
        return -1;
189 190
    }

191
    result = _PyObject_CallMethodId(file, &PyId_flush, "");
192 193 194 195 196 197
    if (result != NULL)
        Py_DECREF(result);
    else {
        /* ignore flush() error */
        PyErr_Clear();
    }
198 199
    *file_ptr = file;
    return fd;
200 201
}

202 203 204 205 206 207 208 209 210 211 212 213 214 215
/* Get the state of the current thread: only call this function if the current
   thread holds the GIL. Raise an exception on error. */
static PyThreadState*
get_thread_state(void)
{
    PyThreadState *tstate = PyThreadState_Get();
    if (tstate == NULL) {
        PyErr_SetString(PyExc_RuntimeError,
                        "unable to get the current thread state");
        return NULL;
    }
    return tstate;
}

216 217 218 219 220 221
static PyObject*
faulthandler_dump_traceback_py(PyObject *self,
                               PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"file", "all_threads", NULL};
    PyObject *file = NULL;
222
    int all_threads = 1;
223 224 225 226 227 228 229 230 231
    PyThreadState *tstate;
    const char *errmsg;
    int fd;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
        "|Oi:dump_traceback", kwlist,
        &file, &all_threads))
        return NULL;

232 233
    fd = faulthandler_get_fileno(&file);
    if (fd < 0)
234 235
        return NULL;

236 237
    tstate = get_thread_state();
    if (tstate == NULL)
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
        return NULL;

    if (all_threads) {
        errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
        if (errmsg != NULL) {
            PyErr_SetString(PyExc_RuntimeError, errmsg);
            return NULL;
        }
    }
    else {
        _Py_DumpTraceback(fd, tstate);
    }
    Py_RETURN_NONE;
}


254
/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
255 256 257 258

   Display the current Python traceback, restore the previous handler and call
   the previous handler.

259
   On Windows, don't explicitly call the previous handler, because the Windows
260 261 262 263 264
   signal handler would not be called (for an unknown reason). The execution of
   the program continues at faulthandler_fatal_error() exit, but the same
   instruction will raise the same fault (signal), and so the previous handler
   will be called.

265
   This function is signal-safe and should only call signal-safe functions. */
266 267

static void
268
faulthandler_fatal_error(int signum)
269 270 271 272 273
{
    const int fd = fatal_error.fd;
    unsigned int i;
    fault_handler_t *handler = NULL;
    PyThreadState *tstate;
274
    int save_errno = errno;
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

    if (!fatal_error.enabled)
        return;

    for (i=0; i < faulthandler_nsignals; i++) {
        handler = &faulthandler_handlers[i];
        if (handler->signum == signum)
            break;
    }
    if (handler == NULL) {
        /* faulthandler_nsignals == 0 (unlikely) */
        return;
    }

    /* restore the previous handler */
#ifdef HAVE_SIGACTION
291
    (void)sigaction(signum, &handler->previous, NULL);
292
#else
293
    (void)signal(signum, handler->previous);
294 295 296 297 298 299 300
#endif
    handler->enabled = 0;

    PUTS(fd, "Fatal Python error: ");
    PUTS(fd, handler->name);
    PUTS(fd, "\n\n");

301
#ifdef WITH_THREAD
302
    /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
303
       are thus delivered to the thread that caused the fault. Get the Python
304
       thread state of the current thread.
305 306 307 308 309 310

       PyThreadState_Get() doesn't give the state of the thread that caused the
       fault if the thread released the GIL, and so this function cannot be
       used. Read the thread local storage (TLS) instead: call
       PyGILState_GetThisThreadState(). */
    tstate = PyGILState_GetThisThreadState();
311 312 313
#else
    tstate = PyThreadState_Get();
#endif
314 315

    if (fatal_error.all_threads)
316 317 318 319 320
        _Py_DumpTracebackThreads(fd, fatal_error.interp, tstate);
    else {
        if (tstate != NULL)
            _Py_DumpTraceback(fd, tstate);
    }
321

322
    errno = save_errno;
323 324
#ifdef MS_WINDOWS
    if (signum == SIGSEGV) {
325
        /* don't explicitly call the previous handler for SIGSEGV in this signal
326 327 328
           handler, because the Windows signal handler would not be called */
        return;
    }
329
#endif
330
    /* call the previous signal handler: it is called immediately if we use
331 332
       sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
    raise(signum);
333 334
}

335
/* Install the handler for fatal signals, faulthandler_fatal_error(). */
336 337 338 339 340 341

static PyObject*
faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"file", "all_threads", NULL};
    PyObject *file = NULL;
342
    int all_threads = 1;
343 344 345 346 347 348 349
    unsigned int i;
    fault_handler_t *handler;
#ifdef HAVE_SIGACTION
    struct sigaction action;
#endif
    int err;
    int fd;
350
    PyThreadState *tstate;
351 352 353 354 355

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
        "|Oi:enable", kwlist, &file, &all_threads))
        return NULL;

356 357
    fd = faulthandler_get_fileno(&file);
    if (fd < 0)
358 359
        return NULL;

360 361 362 363
    tstate = get_thread_state();
    if (tstate == NULL)
        return NULL;

364
    Py_XDECREF(fatal_error.file);
365
    Py_XINCREF(file);
366 367 368
    fatal_error.file = file;
    fatal_error.fd = fd;
    fatal_error.all_threads = all_threads;
369
    fatal_error.interp = tstate->interp;
370 371 372 373 374 375 376

    if (!fatal_error.enabled) {
        fatal_error.enabled = 1;

        for (i=0; i < faulthandler_nsignals; i++) {
            handler = &faulthandler_handlers[i];
#ifdef HAVE_SIGACTION
377
            action.sa_handler = faulthandler_fatal_error;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 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 445 446 447 448 449 450 451 452 453 454 455
            sigemptyset(&action.sa_mask);
            /* Do not prevent the signal from being received from within
               its own signal handler */
            action.sa_flags = SA_NODEFER;
#ifdef HAVE_SIGALTSTACK
            if (stack.ss_sp != NULL) {
                /* Call the signal handler on an alternate signal stack
                   provided by sigaltstack() */
                action.sa_flags |= SA_ONSTACK;
            }
#endif
            err = sigaction(handler->signum, &action, &handler->previous);
#else
            handler->previous = signal(handler->signum,
                                       faulthandler_fatal_error);
            err = (handler->previous == SIG_ERR);
#endif
            if (err) {
                PyErr_SetFromErrno(PyExc_RuntimeError);
                return NULL;
            }
            handler->enabled = 1;
        }
    }
    Py_RETURN_NONE;
}

static void
faulthandler_disable(void)
{
    unsigned int i;
    fault_handler_t *handler;

    if (fatal_error.enabled) {
        fatal_error.enabled = 0;
        for (i=0; i < faulthandler_nsignals; i++) {
            handler = &faulthandler_handlers[i];
            if (!handler->enabled)
                continue;
#ifdef HAVE_SIGACTION
            (void)sigaction(handler->signum, &handler->previous, NULL);
#else
            (void)signal(handler->signum, handler->previous);
#endif
            handler->enabled = 0;
        }
    }

    Py_CLEAR(fatal_error.file);
}

static PyObject*
faulthandler_disable_py(PyObject *self)
{
    if (!fatal_error.enabled) {
        Py_INCREF(Py_False);
        return Py_False;
    }
    faulthandler_disable();
    Py_INCREF(Py_True);
    return Py_True;
}

static PyObject*
faulthandler_is_enabled(PyObject *self)
{
    return PyBool_FromLong(fatal_error.enabled);
}

#ifdef FAULTHANDLER_LATER

static void
faulthandler_thread(void *unused)
{
    PyLockStatus st;
    const char* errmsg;
    PyThreadState *current;
    int ok;
456
#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
457 458 459 460 461 462
    sigset_t set;

    /* we don't want to receive any signal */
    sigfillset(&set);
    pthread_sigmask(SIG_SETMASK, &set, NULL);
#endif
463 464 465

    do {
        st = PyThread_acquire_lock_timed(thread.cancel_event,
466
                                         thread.timeout_us, 0);
467
        if (st == PY_LOCK_ACQUIRED) {
468
            PyThread_release_lock(thread.cancel_event);
469 470 471 472 473 474
            break;
        }
        /* Timeout => dump traceback */
        assert(st == PY_LOCK_FAILURE);

        /* get the thread holding the GIL, NULL if no thread hold the GIL */
475
        current = (PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current);
476

477
        write(thread.fd, thread.header, (int)thread.header_len);
478

479 480 481 482 483 484 485 486
        errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
        ok = (errmsg == NULL);

        if (thread.exit)
            _exit(1);
    } while (ok && thread.repeat);

    /* The only way out */
487
    PyThread_release_lock(thread.running);
488 489 490
}

static void
491
cancel_dump_traceback_later(void)
492
{
493
    /* Notify cancellation */
494 495
    PyThread_release_lock(thread.cancel_event);

496
    /* Wait for thread to join */
497 498 499 500 501 502
    PyThread_acquire_lock(thread.running, 1);
    PyThread_release_lock(thread.running);

    /* The main thread should always hold the cancel_event lock */
    PyThread_acquire_lock(thread.cancel_event, 1);

503
    Py_CLEAR(thread.file);
504
    if (thread.header) {
505
        PyMem_Free(thread.header);
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
        thread.header = NULL;
    }
}

static char*
format_timeout(double timeout)
{
    unsigned long us, sec, min, hour;
    double intpart, fracpart;
    char buffer[100];

    fracpart = modf(timeout, &intpart);
    sec = (unsigned long)intpart;
    us = (unsigned long)(fracpart * 1e6);
    min = sec / 60;
    sec %= 60;
    hour = min / 60;
    min %= 60;

    if (us != 0)
        PyOS_snprintf(buffer, sizeof(buffer),
                      "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
                      hour, min, sec, us);
    else
        PyOS_snprintf(buffer, sizeof(buffer),
                      "Timeout (%lu:%02lu:%02lu)!\n",
                      hour, min, sec);

534
    return _PyMem_Strdup(buffer);
535 536 537
}

static PyObject*
538
faulthandler_dump_traceback_later(PyObject *self,
539
                                   PyObject *args, PyObject *kwargs)
540 541 542
{
    static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
    double timeout;
543
    PY_TIMEOUT_T timeout_us;
544 545 546 547
    int repeat = 0;
    PyObject *file = NULL;
    int fd;
    int exit = 0;
548
    PyThreadState *tstate;
549 550
    char *header;
    size_t header_len;
551 552

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
553
        "d|iOi:dump_traceback_later", kwlist,
554 555
        &timeout, &repeat, &file, &exit))
        return NULL;
556
    if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
557 558 559
        PyErr_SetString(PyExc_OverflowError,  "timeout value is too large");
        return NULL;
    }
560
    timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
561
    if (timeout_us <= 0) {
562 563 564 565
        PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
        return NULL;
    }

566 567
    tstate = get_thread_state();
    if (tstate == NULL)
568 569
        return NULL;

570 571
    fd = faulthandler_get_fileno(&file);
    if (fd < 0)
572 573
        return NULL;

574 575 576 577 578 579
    /* format the timeout */
    header = format_timeout(timeout);
    if (header == NULL)
        return PyErr_NoMemory();
    header_len = strlen(header);

580
    /* Cancel previous thread, if running */
581
    cancel_dump_traceback_later();
582 583

    Py_XDECREF(thread.file);
584
    Py_XINCREF(file);
585 586
    thread.file = file;
    thread.fd = fd;
587
    thread.timeout_us = timeout_us;
588
    thread.repeat = repeat;
589
    thread.interp = tstate->interp;
590
    thread.exit = exit;
591 592
    thread.header = header;
    thread.header_len = header_len;
593 594

    /* Arm these locks to serve as events when released */
595
    PyThread_acquire_lock(thread.running, 1);
596 597

    if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
598
        PyThread_release_lock(thread.running);
599
        Py_CLEAR(thread.file);
600
        PyMem_Free(header);
601
        thread.header = NULL;
602 603 604 605 606 607 608 609 610
        PyErr_SetString(PyExc_RuntimeError,
                        "unable to start watchdog thread");
        return NULL;
    }

    Py_RETURN_NONE;
}

static PyObject*
611
faulthandler_cancel_dump_traceback_later_py(PyObject *self)
612
{
613
    cancel_dump_traceback_later();
614 615
    Py_RETURN_NONE;
}
616
#endif  /* FAULTHANDLER_LATER */
617 618

#ifdef FAULTHANDLER_USER
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
static int
faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
{
#ifdef HAVE_SIGACTION
    struct sigaction action;
    action.sa_handler = faulthandler_user;
    sigemptyset(&action.sa_mask);
    /* if the signal is received while the kernel is executing a system
       call, try to restart the system call instead of interrupting it and
       return EINTR. */
    action.sa_flags = SA_RESTART;
    if (chain) {
        /* do not prevent the signal from being received from within its
           own signal handler */
        action.sa_flags = SA_NODEFER;
    }
#ifdef HAVE_SIGALTSTACK
    if (stack.ss_sp != NULL) {
        /* Call the signal handler on an alternate signal stack
           provided by sigaltstack() */
        action.sa_flags |= SA_ONSTACK;
    }
#endif
    return sigaction(signum, &action, p_previous);
#else
    _Py_sighandler_t previous;
    previous = signal(signum, faulthandler_user);
    if (p_previous != NULL)
        *p_previous = previous;
    return (previous == SIG_ERR);
#endif
}

652 653 654 655 656 657 658 659 660 661 662 663
/* Handler of user signals (e.g. SIGUSR1).

   Dump the traceback of the current thread, or of all threads if
   thread.all_threads is true.

   This function is signal safe and should only call signal safe functions. */

static void
faulthandler_user(int signum)
{
    user_signal_t *user;
    PyThreadState *tstate;
664
    int save_errno = errno;
665 666 667 668 669

    user = &user_signals[signum];
    if (!user->enabled)
        return;

670
#ifdef WITH_THREAD
671 672 673 674
    /* PyThreadState_Get() doesn't give the state of the current thread if
       the thread doesn't hold the GIL. Read the thread local storage (TLS)
       instead: call PyGILState_GetThisThreadState(). */
    tstate = PyGILState_GetThisThreadState();
675 676 677
#else
    tstate = PyThreadState_Get();
#endif
678 679

    if (user->all_threads)
680 681
        _Py_DumpTracebackThreads(user->fd, user->interp, tstate);
    else {
682 683
        if (tstate != NULL)
            _Py_DumpTraceback(user->fd, tstate);
684
    }
685 686 687
#ifdef HAVE_SIGACTION
    if (user->chain) {
        (void)sigaction(signum, &user->previous, NULL);
688 689
        errno = save_errno;

690 691
        /* call the previous signal handler */
        raise(signum);
692 693

        save_errno = errno;
694
        (void)faulthandler_register(signum, user->chain, NULL);
695
        errno = save_errno;
696 697 698
    }
#else
    if (user->chain) {
699
        errno = save_errno;
700 701 702 703
        /* call the previous signal handler */
        user->previous(signum);
    }
#endif
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
}

static int
check_signum(int signum)
{
    unsigned int i;

    for (i=0; i < faulthandler_nsignals; i++) {
        if (faulthandler_handlers[i].signum == signum) {
            PyErr_Format(PyExc_RuntimeError,
                         "signal %i cannot be registered, "
                         "use enable() instead",
                         signum);
            return 0;
        }
    }
    if (signum < 1 || NSIG <= signum) {
        PyErr_SetString(PyExc_ValueError, "signal number out of range");
        return 0;
    }
    return 1;
725 726 727
}

static PyObject*
728 729
faulthandler_register_py(PyObject *self,
                         PyObject *args, PyObject *kwargs)
730
{
731
    static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
732 733
    int signum;
    PyObject *file = NULL;
734
    int all_threads = 1;
735
    int chain = 0;
736 737 738
    int fd;
    user_signal_t *user;
    _Py_sighandler_t previous;
739
    PyThreadState *tstate;
740 741 742
    int err;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
743 744
        "i|Oii:register", kwlist,
        &signum, &file, &all_threads, &chain))
745 746
        return NULL;

747
    if (!check_signum(signum))
748 749
        return NULL;

750 751
    tstate = get_thread_state();
    if (tstate == NULL)
752
        return NULL;
753

754 755
    fd = faulthandler_get_fileno(&file);
    if (fd < 0)
756 757 758
        return NULL;

    if (user_signals == NULL) {
759
        user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
760 761
        if (user_signals == NULL)
            return PyErr_NoMemory();
762
        memset(user_signals, 0, NSIG * sizeof(user_signal_t));
763 764 765 766
    }
    user = &user_signals[signum];

    if (!user->enabled) {
767
        err = faulthandler_register(signum, chain, &previous);
768 769 770 771
        if (err) {
            PyErr_SetFromErrno(PyExc_OSError);
            return NULL;
        }
772 773

        user->previous = previous;
774 775 776
    }

    Py_XDECREF(user->file);
777
    Py_XINCREF(file);
778 779 780
    user->file = file;
    user->fd = fd;
    user->all_threads = all_threads;
781
    user->chain = chain;
782
    user->interp = tstate->interp;
783 784 785 786 787 788 789 790
    user->enabled = 1;

    Py_RETURN_NONE;
}

static int
faulthandler_unregister(user_signal_t *user, int signum)
{
791
    if (!user->enabled)
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
        return 0;
    user->enabled = 0;
#ifdef HAVE_SIGACTION
    (void)sigaction(signum, &user->previous, NULL);
#else
    (void)signal(signum, user->previous);
#endif
    Py_CLEAR(user->file);
    user->fd = -1;
    return 1;
}

static PyObject*
faulthandler_unregister_py(PyObject *self, PyObject *args)
{
    int signum;
    user_signal_t *user;
    int change;

    if (!PyArg_ParseTuple(args, "i:unregister", &signum))
        return NULL;

814
    if (!check_signum(signum))
815 816
        return NULL;

817 818 819
    if (user_signals == NULL)
        Py_RETURN_FALSE;

820 821 822 823 824 825 826
    user = &user_signals[signum];
    change = faulthandler_unregister(user, signum);
    return PyBool_FromLong(change);
}
#endif   /* FAULTHANDLER_USER */


827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
static void
faulthandler_suppress_crash_report(void)
{
#ifdef MS_WINDOWS
    UINT mode;

    /* Configure Windows to not display the Windows Error Reporting dialog */
    mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
    SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
#endif

#ifdef HAVE_SYS_RESOURCE_H
    struct rlimit rl;

    /* Disable creation of core dump */
    if (getrlimit(RLIMIT_CORE, &rl) != 0) {
        rl.rlim_cur = 0;
        setrlimit(RLIMIT_CORE, &rl);
    }
#endif

#ifdef _MSC_VER
    /* Visual Studio: configure abort() to not display an error message nor
       open a popup asking to report the fault. */
    _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
}

855 856 857
static PyObject *
faulthandler_read_null(PyObject *self, PyObject *args)
{
858 859 860
    volatile int *x;
    volatile int y;

861
    faulthandler_suppress_crash_report();
862
    x = NULL;
863
    y = *x;
864 865 866 867
    return PyLong_FromLong(y);

}

868 869
static void
faulthandler_raise_sigsegv(void)
870
{
871
    faulthandler_suppress_crash_report();
872
#if defined(MS_WINDOWS)
873 874
    /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
       handler and then gives back the execution flow to the program (without
875
       explicitly calling the previous error handler). In a normal case, the
876 877 878 879 880 881 882 883 884 885 886 887 888
       SIGSEGV was raised by the kernel because of a fault, and so if the
       program retries to execute the same instruction, the fault will be
       raised again.

       Here the fault is simulated by a fake SIGSEGV signal raised by the
       application. We have to raise SIGSEGV at lease twice: once for
       faulthandler_fatal_error(), and one more time for the previous signal
       handler. */
    while(1)
        raise(SIGSEGV);
#else
    raise(SIGSEGV);
#endif
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
}

static PyObject *
faulthandler_sigsegv(PyObject *self, PyObject *args)
{
    int release_gil = 0;
    if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
        return NULL;

    if (release_gil) {
        Py_BEGIN_ALLOW_THREADS
        faulthandler_raise_sigsegv();
        Py_END_ALLOW_THREADS
    } else {
        faulthandler_raise_sigsegv();
    }
905 906 907 908 909 910 911 912 913
    Py_RETURN_NONE;
}

static PyObject *
faulthandler_sigfpe(PyObject *self, PyObject *args)
{
    /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
       PowerPC. Use volatile to disable compile-time optimizations. */
    volatile int x = 1, y = 0, z;
914
    faulthandler_suppress_crash_report();
915
    z = x / y;
916 917
    /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
       raise it manually. */
918
    raise(SIGFPE);
919 920
    /* This line is never reached, but we pretend to make something with z
       to silence a compiler warning. */
921
    return PyLong_FromLong(z);
922 923
}

924 925 926
static PyObject *
faulthandler_sigabrt(PyObject *self, PyObject *args)
{
927
    faulthandler_suppress_crash_report();
928
    abort();
929 930 931
    Py_RETURN_NONE;
}

932 933 934 935 936 937
static PyObject *
faulthandler_fatal_error_py(PyObject *self, PyObject *args)
{
    char *message;
    if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
        return NULL;
938
    faulthandler_suppress_crash_report();
939 940 941 942 943
    Py_FatalError(message);
    Py_RETURN_NONE;
}

#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
944 945 946 947 948 949 950 951
#ifdef __INTEL_COMPILER
   /* Issue #23654: Turn off ICC's tail call optimization for the
    * stack_overflow generator. ICC turns the recursive tail call into
    * a loop. */
#  pragma intel optimization_level 0
#endif
static
Py_uintptr_t
952
stack_overflow(Py_uintptr_t min_sp, Py_uintptr_t max_sp, size_t *depth)
953 954 955
{
    /* allocate 4096 bytes on the stack at each call */
    unsigned char buffer[4096];
956
    Py_uintptr_t sp = (Py_uintptr_t)&buffer;
957 958 959
    *depth += 1;
    if (sp < min_sp || max_sp < sp)
        return sp;
960
    buffer[0] = 1;
961 962 963 964 965 966 967 968
    buffer[4095] = 0;
    return stack_overflow(min_sp, max_sp, depth);
}

static PyObject *
faulthandler_stack_overflow(PyObject *self)
{
    size_t depth, size;
969 970
    Py_uintptr_t sp = (Py_uintptr_t)&depth;
    Py_uintptr_t stop;
971

972
    faulthandler_suppress_crash_report();
973 974 975 976 977 978 979 980 981 982 983 984 985
    depth = 0;
    stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
                          sp + STACK_OVERFLOW_MAX_SIZE,
                          &depth);
    if (sp < stop)
        size = stop - sp;
    else
        size = sp - stop;
    PyErr_Format(PyExc_RuntimeError,
        "unable to raise a stack overflow (allocated %zu bytes "
        "on the stack, %zu recursive calls)",
        size, depth);
    return NULL;
986 987 988 989 990 991 992 993
}
#endif


static int
faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
{
#ifdef FAULTHANDLER_USER
994
    unsigned int signum;
995 996 997 998 999 1000 1001
#endif

#ifdef FAULTHANDLER_LATER
    Py_VISIT(thread.file);
#endif
#ifdef FAULTHANDLER_USER
    if (user_signals != NULL) {
1002 1003
        for (signum=0; signum < NSIG; signum++)
            Py_VISIT(user_signals[signum].file);
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    }
#endif
    Py_VISIT(fatal_error.file);
    return 0;
}

PyDoc_STRVAR(module_doc,
"faulthandler module.");

static PyMethodDef module_methods[] = {
    {"enable",
     (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
1016
     PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
1017 1018 1019 1020 1021 1022 1023
               "enable the fault handler")},
    {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
     PyDoc_STR("disable(): disable the fault handler")},
    {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
     PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
    {"dump_traceback",
     (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
1024
     PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
1025 1026 1027
               "dump the traceback of the current thread, or of all threads "
               "if all_threads is True, into file")},
#ifdef FAULTHANDLER_LATER
1028 1029 1030
    {"dump_traceback_later",
     (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
     PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
1031
               "dump the traceback of all threads in timeout seconds,\n"
1032 1033
               "or each timeout seconds if repeat is True. If exit is True, "
               "call _exit(1) which is not safe.")},
1034 1035 1036 1037
    {"cancel_dump_traceback_later",
     (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
     PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
               "to dump_traceback_later().")},
1038 1039 1040 1041
#endif

#ifdef FAULTHANDLER_USER
    {"register",
1042 1043
     (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
     PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
1044 1045 1046 1047 1048 1049 1050 1051 1052
               "register an handler for the signal 'signum': dump the "
               "traceback of the current thread, or of all threads if "
               "all_threads is True, into file")},
    {"unregister",
     faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
     PyDoc_STR("unregister(signum): unregister the handler of the signal "
                "'signum' registered by register()")},
#endif

1053 1054
    {"_read_null", faulthandler_read_null, METH_NOARGS,
     PyDoc_STR("_read_null(): read from NULL, raise "
1055 1056
               "a SIGSEGV or SIGBUS signal depending on the platform")},
    {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
1057
     PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
1058
    {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
1059
     PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
1060 1061 1062 1063 1064 1065 1066 1067
    {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
     PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
    {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
     PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
    {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
     PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
#endif
1068
    {NULL, NULL}  /* sentinel */
1069 1070 1071 1072 1073 1074
};

static struct PyModuleDef module_def = {
    PyModuleDef_HEAD_INIT,
    "faulthandler",
    module_doc,
1075
    0, /* non-negative size to be able to unload the module */
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    module_methods,
    NULL,
    faulthandler_traverse,
    NULL,
    NULL
};

PyMODINIT_FUNC
PyInit_faulthandler(void)
{
    return PyModule_Create(&module_def);
}

1089 1090
/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
   is defined, or if sys._xoptions has a 'faulthandler' key. */
1091 1092 1093 1094 1095

static int
faulthandler_env_options(void)
{
    PyObject *xoptions, *key, *module, *res;
1096
    char *p;
1097

1098 1099 1100
    if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
        /* PYTHONFAULTHANDLER environment variable is missing
           or an empty string */
1101 1102
        int has_key;

1103 1104 1105 1106 1107 1108 1109 1110
        xoptions = PySys_GetXOptions();
        if (xoptions == NULL)
            return -1;

        key = PyUnicode_FromString("faulthandler");
        if (key == NULL)
            return -1;

1111
        has_key = PyDict_Contains(xoptions, key);
1112
        Py_DECREF(key);
1113
        if (!has_key)
1114 1115 1116 1117 1118 1119 1120
            return 0;
    }

    module = PyImport_ImportModule("faulthandler");
    if (module == NULL) {
        return -1;
    }
1121
    res = _PyObject_CallMethodId(module, &PyId_enable, "");
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    Py_DECREF(module);
    if (res == NULL)
        return -1;
    Py_DECREF(res);
    return 0;
}

int _PyFaulthandler_Init(void)
{
#ifdef HAVE_SIGALTSTACK
    int err;

    /* Try to allocate an alternate stack for faulthandler() signal handler to
     * be able to allocate memory on the stack, even on a stack overflow. If it
     * fails, ignore the error. */
    stack.ss_flags = 0;
    stack.ss_size = SIGSTKSZ;
    stack.ss_sp = PyMem_Malloc(stack.ss_size);
    if (stack.ss_sp != NULL) {
        err = sigaltstack(&stack, NULL);
        if (err) {
            PyMem_Free(stack.ss_sp);
            stack.ss_sp = NULL;
        }
    }
#endif
#ifdef FAULTHANDLER_LATER
    thread.file = NULL;
    thread.cancel_event = PyThread_allocate_lock();
1151 1152
    thread.running = PyThread_allocate_lock();
    if (!thread.cancel_event || !thread.running) {
1153 1154 1155 1156
        PyErr_SetString(PyExc_RuntimeError,
                        "could not allocate locks for faulthandler");
        return -1;
    }
1157
    PyThread_acquire_lock(thread.cancel_event, 1);
1158 1159 1160 1161 1162 1163 1164 1165
#endif

    return faulthandler_env_options();
}

void _PyFaulthandler_Fini(void)
{
#ifdef FAULTHANDLER_USER
1166
    unsigned int signum;
1167 1168 1169 1170 1171
#endif

#ifdef FAULTHANDLER_LATER
    /* later */
    if (thread.cancel_event) {
1172
        cancel_dump_traceback_later();
1173
        PyThread_release_lock(thread.cancel_event);
1174 1175 1176
        PyThread_free_lock(thread.cancel_event);
        thread.cancel_event = NULL;
    }
1177 1178 1179
    if (thread.running) {
        PyThread_free_lock(thread.running);
        thread.running = NULL;
1180 1181 1182 1183 1184 1185
    }
#endif

#ifdef FAULTHANDLER_USER
    /* user */
    if (user_signals != NULL) {
1186 1187
        for (signum=0; signum < NSIG; signum++)
            faulthandler_unregister(&user_signals[signum], signum);
1188
        PyMem_Free(user_signals);
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
        user_signals = NULL;
    }
#endif

    /* fatal */
    faulthandler_disable();
#ifdef HAVE_SIGALTSTACK
    if (stack.ss_sp != NULL) {
        PyMem_Free(stack.ss_sp);
        stack.ss_sp = NULL;
    }
#endif
}