signalmodule.c 42.4 KB
Newer Older
1

2
/* Signal module -- many thanks to Lance Ellinghaus */
3

4 5
/* XXX Signals should be recorded per thread, now we have thread state. */

6
#include "Python.h"
7 8 9
#ifndef MS_WINDOWS
#include "posixmodule.h"
#endif
10 11 12
#ifdef MS_WINDOWS
#include "socketmodule.h"   /* needed for SOCKET_T */
#endif
13

14
#ifdef MS_WINDOWS
15
#include <windows.h>
Benjamin Peterson's avatar
Benjamin Peterson committed
16
#ifdef HAVE_PROCESS_H
17 18
#include <process.h>
#endif
Benjamin Peterson's avatar
Benjamin Peterson committed
19
#endif
20

Benjamin Peterson's avatar
Benjamin Peterson committed
21
#ifdef HAVE_SIGNAL_H
22
#include <signal.h>
Benjamin Peterson's avatar
Benjamin Peterson committed
23 24
#endif
#ifdef HAVE_SYS_STAT_H
25
#include <sys/stat.h>
Benjamin Peterson's avatar
Benjamin Peterson committed
26
#endif
27
#ifdef HAVE_SYS_TIME_H
28
#include <sys/time.h>
29
#endif
30

31 32 33 34 35 36 37 38
#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
#  define PYPTHREAD_SIGMASK
#endif

#if defined(PYPTHREAD_SIGMASK) && defined(HAVE_PTHREAD_H)
#  include <pthread.h>
#endif

39
#ifndef SIG_ERR
40
#define SIG_ERR ((PyOS_sighandler_t)(-1))
41 42
#endif

43
#ifndef NSIG
44
# if defined(_NSIG)
45
#  define NSIG _NSIG            /* For BSD/SysV */
46
# elif defined(_SIGMAX)
47
#  define NSIG (_SIGMAX + 1)    /* For QNX */
48
# elif defined(SIGMAX)
49
#  define NSIG (SIGMAX + 1)     /* For djgpp */
50
# else
51
#  define NSIG 64               /* Use a reasonable default value */
52
# endif
53 54
#endif

55 56 57 58 59 60 61
#include "clinic/signalmodule.c.h"

/*[clinic input]
module signal
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b0301a3bde5fe9d3]*/

62 63 64 65 66 67 68 69
/*[python input]

class sigset_t_converter(CConverter):
    type = 'sigset_t'
    converter = '_Py_Sigset_Converter'

[python start generated code]*/
/*[python end generated code: output=da39a3ee5e6b4b0d input=b5689d14466b6823]*/
70

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
/*
   NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS

   When threads are supported, we want the following semantics:

   - only the main thread can set a signal handler
   - any thread can get a signal handler
   - signals are only delivered to the main thread

   I.e. we don't support "synchronous signals" like SIGFPE (catching
   this doesn't make much sense in Python anyway) nor do we support
   signals as a means of inter-thread communication, since not all
   thread implementations support that (at least our thread library
   doesn't).

   We still have the problem that in some implementations signals
   generated by the keyboard (e.g. SIGINT) are delivered to all
   threads (e.g. SGI), while in others (e.g. Solaris) such signals are
   delivered to one random thread (an intermediate possibility would
Guido van Rossum's avatar
Guido van Rossum committed
90
   be to deliver it to the main thread -- POSIX?).  For now, we have
91 92 93 94 95
   a working implementation that works in all three cases -- the
   handler ignores signals if getpid() isn't the same as in the main
   thread.  XXX This is a hack.
*/

96
#include <sys/types.h> /* For pid_t */
97
#include "pythread.h"
98
static unsigned long main_thread;
99 100
static pid_t main_pid;

101
static volatile struct {
102
    _Py_atomic_int tripped;
103
    PyObject *func;
Barry Warsaw's avatar
Barry Warsaw committed
104 105
} Handlers[NSIG];

106 107 108 109 110
#ifdef MS_WINDOWS
#define INVALID_FD ((SOCKET_T)-1)

static volatile struct {
    SOCKET_T fd;
111
    int warn_on_full_buffer;
112
    int use_send;
113
} wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1, .use_send = 0};
114 115
#else
#define INVALID_FD (-1)
116 117 118 119
static volatile struct {
    sig_atomic_t fd;
    int warn_on_full_buffer;
} wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1};
120
#endif
121

122
/* Speed up sigcheck() when none tripped */
123
static _Py_atomic_int is_tripped;
124

Barry Warsaw's avatar
Barry Warsaw committed
125 126 127
static PyObject *DefaultHandler;
static PyObject *IgnoreHandler;
static PyObject *IntHandler;
128

129 130 131 132
#ifdef MS_WINDOWS
static HANDLE sigint_event = NULL;
#endif

133 134 135
#ifdef HAVE_GETITIMER
static PyObject *ItimerError;

136 137 138
/* auxiliary functions for setitimer */
static int
timeval_from_double(PyObject *obj, struct timeval *tv)
139
{
140 141 142 143
    if (obj == NULL) {
        tv->tv_sec = 0;
        tv->tv_usec = 0;
        return 0;
144
    }
145 146 147 148 149 150

    _PyTime_t t;
    if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_CEILING) < 0) {
        return -1;
    }
    return _PyTime_AsTimeval(t, tv, _PyTime_ROUND_CEILING);
151 152
}

153
Py_LOCAL_INLINE(double)
154 155 156 157 158 159 160 161 162 163 164 165
double_from_timeval(struct timeval *tv)
{
    return tv->tv_sec + (double)(tv->tv_usec / 1000000.0);
}

static PyObject *
itimer_retval(struct itimerval *iv)
{
    PyObject *r, *v;

    r = PyTuple_New(2);
    if (r == NULL)
166
        return NULL;
167 168

    if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
169 170
        Py_DECREF(r);
        return NULL;
171 172 173 174 175
    }

    PyTuple_SET_ITEM(r, 0, v);

    if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) {
176 177
        Py_DECREF(r);
        return NULL;
178 179 180 181 182 183 184
    }

    PyTuple_SET_ITEM(r, 1, v);

    return r;
}
#endif
185

186
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
187
signal_default_int_handler(PyObject *self, PyObject *args)
188
{
189 190
    PyErr_SetNone(PyExc_KeyboardInterrupt);
    return NULL;
191 192
}

193
PyDoc_STRVAR(default_int_handler_doc,
Guido van Rossum's avatar
Guido van Rossum committed
194 195
"default_int_handler(...)\n\
\n\
Michael W. Hudson's avatar
Michael W. Hudson committed
196
The default handler for SIGINT installed by Python.\n\
197
It raises KeyboardInterrupt.");
Guido van Rossum's avatar
Guido van Rossum committed
198

199

200
static int
201
report_wakeup_write_error(void *data)
202 203
{
    int save_errno = errno;
204
    errno = (int) (intptr_t) data;
205 206 207 208 209 210 211 212
    PyErr_SetFromErrno(PyExc_OSError);
    PySys_WriteStderr("Exception ignored when trying to write to the "
                      "signal wakeup fd:\n");
    PyErr_WriteUnraisable(NULL);
    errno = save_errno;
    return 0;
}

213 214
#ifdef MS_WINDOWS
static int
215
report_wakeup_send_error(void* data)
216
{
217 218 219 220
    /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
       recognizes the error codes used by both GetLastError() and
       WSAGetLastError */
    PyErr_SetExcFromWindowsErr(PyExc_OSError, (int) (intptr_t) data);
221 222 223 224 225 226 227
    PySys_WriteStderr("Exception ignored when trying to send to the "
                      "signal wakeup fd:\n");
    PyErr_WriteUnraisable(NULL);
    return 0;
}
#endif   /* MS_WINDOWS */

228 229 230
static void
trip_signal(int sig_num)
{
231
    unsigned char byte;
232 233
    int fd;
    Py_ssize_t rc;
234

235
    _Py_atomic_store_relaxed(&Handlers[sig_num].tripped, 1);
236

237 238
    /* Set is_tripped after setting .tripped, as it gets
       cleared in PyErr_CheckSignals() before .tripped. */
239 240 241
    _Py_atomic_store(&is_tripped, 1);

    /* Notify ceval.c */
242
    _PyEval_SignalReceived();
243 244

    /* And then write to the wakeup fd *after* setting all the globals and
245 246 247
       doing the _PyEval_SignalReceived. We used to write to the wakeup fd
       and then set the flag, but this allowed the following sequence of events
       (especially on windows, where trip_signal may run in a new thread):
248

249
       - main thread blocks on select([wakeup.fd], ...)
250 251 252 253 254 255 256 257 258 259 260 261 262
       - signal arrives
       - trip_signal writes to the wakeup fd
       - the main thread wakes up
       - the main thread checks the signal flags, sees that they're unset
       - the main thread empties the wakeup fd
       - the main thread goes back to sleep
       - trip_signal sets the flags to request the Python-level signal handler
         be run
       - the main thread doesn't notice, because it's asleep

       See bpo-30038 for more details.
    */

263 264 265
#ifdef MS_WINDOWS
    fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
#else
266
    fd = wakeup.fd;
267 268 269
#endif

    if (fd != INVALID_FD) {
270
        byte = (unsigned char)sig_num;
271 272
#ifdef MS_WINDOWS
        if (wakeup.use_send) {
273 274 275 276 277 278 279 280 281 282 283 284
            rc = send(fd, &byte, 1, 0);

            if (rc < 0) {
                int last_error = GetLastError();
                if (wakeup.warn_on_full_buffer ||
                    last_error != WSAEWOULDBLOCK)
                {
                    /* Py_AddPendingCall() isn't signal-safe, but we
                       still use it for this exceptional case. */
                    Py_AddPendingCall(report_wakeup_send_error,
                                      (void *)(intptr_t) last_error);
                }
285 286 287 288 289
            }
        }
        else
#endif
        {
290 291 292
            /* _Py_write_noraise() retries write() if write() is interrupted by
               a signal (fails with EINTR). */
            rc = _Py_write_noraise(fd, &byte, 1);
293 294

            if (rc < 0) {
295 296 297 298 299 300 301 302
                if (wakeup.warn_on_full_buffer ||
                    (errno != EWOULDBLOCK && errno != EAGAIN))
                {
                    /* Py_AddPendingCall() isn't signal-safe, but we
                       still use it for this exceptional case. */
                    Py_AddPendingCall(report_wakeup_write_error,
                                      (void *)(intptr_t)errno);
                }
303 304 305
            }
        }
    }
306 307
}

308
static void
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
309
signal_handler(int sig_num)
310
{
311 312
    int save_errno = errno;

313
    /* See NOTES section above */
314 315
    if (getpid() == main_pid)
    {
316
        trip_signal(sig_num);
317
    }
318 319

#ifndef HAVE_SIGACTION
320
#ifdef SIGCHLD
321 322 323 324 325
    /* To avoid infinite recursion, this signal remains
       reset until explicit re-instated.
       Don't clear the 'func' field as it is our pointer
       to the Python handler... */
    if (sig_num != SIGCHLD)
326
#endif
327
    /* If the handler was not set up with sigaction, reinstall it.  See
328
     * Python/pylifecycle.c for the implementation of PyOS_setsig which
329 330
     * makes this true.  See also issue8354. */
    PyOS_setsig(sig_num, signal_handler);
331
#endif
332 333 334 335

    /* Issue #10311: asynchronously executing signal handlers should not
       mutate errno under the feet of unsuspecting C code. */
    errno = save_errno;
336 337 338 339 340

#ifdef MS_WINDOWS
    if (sig_num == SIGINT)
        SetEvent(sigint_event);
#endif
341
}
342

343

344
#ifdef HAVE_ALARM
345 346 347 348 349 350 351 352 353 354 355

/*[clinic input]
signal.alarm -> long

    seconds: int
    /

Arrange for SIGALRM to arrive after the given number of seconds.
[clinic start generated code]*/

static long
356 357
signal_alarm_impl(PyObject *module, int seconds)
/*[clinic end generated code: output=144232290814c298 input=0d5e97e0e6f39e86]*/
358
{
359
    /* alarm() returns the number of seconds remaining */
360
    return (long)alarm(seconds);
361
}
Guido van Rossum's avatar
Guido van Rossum committed
362

363
#endif
364

365
#ifdef HAVE_PAUSE
366 367 368 369 370 371 372

/*[clinic input]
signal.pause

Wait until a signal arrives.
[clinic start generated code]*/

373
static PyObject *
374 375
signal_pause_impl(PyObject *module)
/*[clinic end generated code: output=391656788b3c3929 input=f03de0f875752062]*/
376
{
377 378 379 380 381 382 383 384 385
    Py_BEGIN_ALLOW_THREADS
    (void)pause();
    Py_END_ALLOW_THREADS
    /* make sure that any exceptions that got raised are propagated
     * back into Python
     */
    if (PyErr_CheckSignals())
        return NULL;

386
    Py_RETURN_NONE;
387
}
Guido van Rossum's avatar
Guido van Rossum committed
388

389
#endif
390

391

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
/*[clinic input]
signal.signal

    signalnum: int
    handler:   object
    /

Set the action for the given signal.

The action can be SIG_DFL, SIG_IGN, or a callable Python object.
The previous action is returned.  See getsignal() for possible return values.

*** IMPORTANT NOTICE ***
A signal handler function is called with two arguments:
the first is the signal number, the second is the interrupted stack frame.
[clinic start generated code]*/

409
static PyObject *
410 411
signal_signal_impl(PyObject *module, int signalnum, PyObject *handler)
/*[clinic end generated code: output=b44cfda43780f3a1 input=deee84af5fa0432c]*/
412
{
413 414
    PyObject *old_handler;
    void (*func)(int);
415
#ifdef MS_WINDOWS
416 417
    /* Validate that signalnum is one of the allowable signals */
    switch (signalnum) {
418
        case SIGABRT: break;
419 420 421 422 423
#ifdef SIGBREAK
        /* Issue #10003: SIGBREAK is not documented as permitted, but works
           and corresponds to CTRL_BREAK_EVENT. */
        case SIGBREAK: break;
#endif
424 425 426 427 428 429 430 431
        case SIGFPE: break;
        case SIGILL: break;
        case SIGINT: break;
        case SIGSEGV: break;
        case SIGTERM: break;
        default:
            PyErr_SetString(PyExc_ValueError, "invalid signal value");
            return NULL;
432 433
    }
#endif
434 435 436 437 438
    if (PyThread_get_thread_ident() != main_thread) {
        PyErr_SetString(PyExc_ValueError,
                        "signal only works in main thread");
        return NULL;
    }
439
    if (signalnum < 1 || signalnum >= NSIG) {
440 441 442 443
        PyErr_SetString(PyExc_ValueError,
                        "signal number out of range");
        return NULL;
    }
444
    if (handler == IgnoreHandler)
445
        func = SIG_IGN;
446
    else if (handler == DefaultHandler)
447
        func = SIG_DFL;
448
    else if (!PyCallable_Check(handler)) {
449
        PyErr_SetString(PyExc_TypeError,
450
"signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object");
451 452 453 454
                return NULL;
    }
    else
        func = signal_handler;
455 456 457 458
    /* Check for pending signals before changing signal handler */
    if (PyErr_CheckSignals()) {
        return NULL;
    }
459
    if (PyOS_setsig(signalnum, func) == SIG_ERR) {
460
        PyErr_SetFromErrno(PyExc_OSError);
461 462
        return NULL;
    }
463 464 465
    old_handler = Handlers[signalnum].func;
    Py_INCREF(handler);
    Handlers[signalnum].func = handler;
466 467 468 469
    if (old_handler != NULL)
        return old_handler;
    else
        Py_RETURN_NONE;
470 471
}

Guido van Rossum's avatar
Guido van Rossum committed
472

473 474 475 476 477 478 479 480 481 482 483 484 485 486
/*[clinic input]
signal.getsignal

    signalnum: int
    /

Return the current action for the given signal.

The return value can be:
  SIG_IGN -- if the signal is being ignored
  SIG_DFL -- if the default action for the signal is in effect
  None    -- if an unknown handler is in effect
  anything else -- the callable Python object used as a handler
[clinic start generated code]*/
487

488
static PyObject *
489 490
signal_getsignal_impl(PyObject *module, int signalnum)
/*[clinic end generated code: output=35b3e0e796fd555e input=ac23a00f19dfa509]*/
491
{
492
    PyObject *old_handler;
493
    if (signalnum < 1 || signalnum >= NSIG) {
494 495 496 497
        PyErr_SetString(PyExc_ValueError,
                        "signal number out of range");
        return NULL;
    }
498
    old_handler = Handlers[signalnum].func;
499 500 501 502 503 504 505
    if (old_handler != NULL) {
        Py_INCREF(old_handler);
        return old_handler;
    }
    else {
        Py_RETURN_NONE;
    }
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 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567

/*[clinic input]
signal.strsignal

    signalnum: int
    /

Return the system description of the given signal.

The return values can be such as "Interrupt", "Segmentation fault", etc.
Returns None if the signal is not recognized.
[clinic start generated code]*/

static PyObject *
signal_strsignal_impl(PyObject *module, int signalnum)
/*[clinic end generated code: output=44e12e1e3b666261 input=b77914b03f856c74]*/
{
    char *res;

    if (signalnum < 1 || signalnum >= NSIG) {
        PyErr_SetString(PyExc_ValueError,
                "signal number out of range");
        return NULL;
    }

#ifdef MS_WINDOWS
    /* Custom redefinition of POSIX signals allowed on Windows */
    switch (signalnum) {
        case SIGINT:
            res = "Interrupt";
            break;
        case SIGILL:
            res = "Illegal instruction";
            break;
        case SIGABRT:
            res = "Aborted";
            break;
        case SIGFPE:
            res = "Floating point exception";
            break;
        case SIGSEGV:
            res = "Segmentation fault";
            break;
        case SIGTERM:
            res = "Terminated";
            break;
        default:
            Py_RETURN_NONE;
    }
#else
    errno = 0;
    res = strsignal(signalnum);

    if (errno || res == NULL || strstr(res, "Unknown signal") != NULL)
        Py_RETURN_NONE;
#endif

    return Py_BuildValue("s", res);
}

Christian Heimes's avatar
Christian Heimes committed
568
#ifdef HAVE_SIGINTERRUPT
569 570 571 572 573 574 575 576 577 578 579 580 581

/*[clinic input]
signal.siginterrupt

    signalnum: int
    flag:      int
    /

Change system call restart behaviour.

If flag is False, system calls will be restarted when interrupted by
signal sig, else system calls will be interrupted.
[clinic start generated code]*/
Christian Heimes's avatar
Christian Heimes committed
582 583

static PyObject *
584 585
signal_siginterrupt_impl(PyObject *module, int signalnum, int flag)
/*[clinic end generated code: output=063816243d85dd19 input=4160acacca3e2099]*/
Christian Heimes's avatar
Christian Heimes committed
586
{
587
    if (signalnum < 1 || signalnum >= NSIG) {
588 589 590 591
        PyErr_SetString(PyExc_ValueError,
                        "signal number out of range");
        return NULL;
    }
592
    if (siginterrupt(signalnum, flag)<0) {
593
        PyErr_SetFromErrno(PyExc_OSError);
594 595
        return NULL;
    }
596
    Py_RETURN_NONE;
Christian Heimes's avatar
Christian Heimes committed
597 598 599
}

#endif
600

601 602

static PyObject*
603
signal_set_wakeup_fd(PyObject *self, PyObject *args, PyObject *kwds)
604
{
605
    struct _Py_stat_struct status;
606 607 608 609
    static char *kwlist[] = {
        "", "warn_on_full_buffer", NULL,
    };
    int warn_on_full_buffer = 1;
610 611
#ifdef MS_WINDOWS
    PyObject *fdobj;
612
    SOCKET_T sockfd, old_sockfd;
613 614 615 616 617
    int res;
    int res_size = sizeof res;
    PyObject *mod;
    int is_socket;

618 619
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|$p:set_wakeup_fd", kwlist,
                                     &fdobj, &warn_on_full_buffer))
620 621
        return NULL;

622 623
    sockfd = PyLong_AsSocket_t(fdobj);
    if (sockfd == (SOCKET_T)(-1) && PyErr_Occurred())
624 625
        return NULL;
#else
626
    int fd, old_fd;
627

628 629
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "i|$p:set_wakeup_fd", kwlist,
                                     &fd, &warn_on_full_buffer))
630
        return NULL;
631 632
#endif

633 634 635 636 637
    if (PyThread_get_thread_ident() != main_thread) {
        PyErr_SetString(PyExc_ValueError,
                        "set_wakeup_fd only works in main thread");
        return NULL;
    }
638

639 640
#ifdef MS_WINDOWS
    is_socket = 0;
641
    if (sockfd != INVALID_FD) {
642 643 644 645 646 647 648
        /* Import the _socket module to call WSAStartup() */
        mod = PyImport_ImportModuleNoBlock("_socket");
        if (mod == NULL)
            return NULL;
        Py_DECREF(mod);

        /* test the socket */
649
        if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
650
                       (char *)&res, &res_size) != 0) {
651 652 653
            int fd, err;

            err = WSAGetLastError();
654 655 656 657 658
            if (err != WSAENOTSOCK) {
                PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
                return NULL;
            }

659
            fd = (int)sockfd;
660
            if ((SOCKET_T)fd != sockfd) {
661 662 663 664
                PyErr_SetString(PyExc_ValueError, "invalid fd");
                return NULL;
            }

665
            if (_Py_fstat(fd, &status) != 0)
666
                return NULL;
667 668

            /* on Windows, a file cannot be set to non-blocking mode */
669
        }
670
        else {
671
            is_socket = 1;
672 673 674 675

            /* Windows does not provide a function to test if a socket
               is in non-blocking mode */
        }
676 677
    }

678 679
    old_sockfd = wakeup.fd;
    wakeup.fd = sockfd;
680
    wakeup.warn_on_full_buffer = warn_on_full_buffer;
681 682
    wakeup.use_send = is_socket;

683 684
    if (old_sockfd != INVALID_FD)
        return PyLong_FromSocket_t(old_sockfd);
685 686 687
    else
        return PyLong_FromLong(-1);
#else
Victor Stinner's avatar
Victor Stinner committed
688
    if (fd != -1) {
689 690
        int blocking;

691
        if (_Py_fstat(fd, &status) != 0)
692
            return NULL;
693 694 695 696 697 698 699 700 701 702

        blocking = _Py_get_blocking(fd);
        if (blocking < 0)
            return NULL;
        if (blocking) {
            PyErr_Format(PyExc_ValueError,
                         "the fd %i must be in non-blocking mode",
                         fd);
            return NULL;
        }
703
    }
704

705 706 707
    old_fd = wakeup.fd;
    wakeup.fd = fd;
    wakeup.warn_on_full_buffer = warn_on_full_buffer;
708

709
    return PyLong_FromLong(old_fd);
710
#endif
711 712 713
}

PyDoc_STRVAR(set_wakeup_fd_doc,
714
"set_wakeup_fd(fd, *, warn_on_full_buffer=True) -> fd\n\
715
\n\
716
Sets the fd to be written to (with the signal number) when a signal\n\
717
comes in.  A library can use this to wakeup select or poll.\n\
718
The previous fd or -1 is returned.\n\
719 720 721 722 723 724 725
\n\
The fd must be non-blocking.");

/* C API for the same, without all the error checking */
int
PySignal_SetWakeupFd(int fd)
{
726
    int old_fd;
727 728
    if (fd < 0)
        fd = -1;
729 730 731 732

#ifdef MS_WINDOWS
    old_fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
#else
733
    old_fd = wakeup.fd;
734
#endif
735 736
    wakeup.fd = fd;
    wakeup.warn_on_full_buffer = 1;
737
    return old_fd;
738 739 740
}


741
#ifdef HAVE_SETITIMER
742 743 744 745 746

/*[clinic input]
signal.setitimer

    which:    int
747 748
    seconds:  object
    interval: object(c_default="NULL") = 0.0
749 750 751 752 753 754 755 756 757 758
    /

Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF).

The timer will fire after value seconds and after that every interval seconds.
The itimer can be cleared by setting seconds to zero.

Returns old values as a tuple: (delay, interval).
[clinic start generated code]*/

759
static PyObject *
760 761 762
signal_setitimer_impl(PyObject *module, int which, PyObject *seconds,
                      PyObject *interval)
/*[clinic end generated code: output=65f9dcbddc35527b input=de43daf194e6f66f]*/
763 764 765
{
    struct itimerval new, old;

766 767 768 769 770 771 772
    if (timeval_from_double(seconds, &new.it_value) < 0) {
        return NULL;
    }
    if (timeval_from_double(interval, &new.it_interval) < 0) {
        return NULL;
    }

773 774
    /* Let OS check "which" value */
    if (setitimer(which, &new, &old) != 0) {
775 776
        PyErr_SetFromErrno(ItimerError);
        return NULL;
777 778 779 780 781 782 783 784 785
    }

    return itimer_retval(&old);
}

#endif


#ifdef HAVE_GETITIMER
786 787 788 789 790 791 792 793 794 795

/*[clinic input]
signal.getitimer

    which:    int
    /

Returns current value of given itimer.
[clinic start generated code]*/

796
static PyObject *
797 798
signal_getitimer_impl(PyObject *module, int which)
/*[clinic end generated code: output=9e053175d517db40 input=f7d21d38f3490627]*/
799 800 801 802
{
    struct itimerval old;

    if (getitimer(which, &old) != 0) {
803 804
        PyErr_SetFromErrno(ItimerError);
        return NULL;
805 806 807 808 809 810 811
    }

    return itimer_retval(&old);
}

#endif

812
#if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGPENDING)
813 814
static PyObject*
sigset_to_set(sigset_t mask)
815
{
816 817
    PyObject *signum, *result;
    int sig;
818

819
    result = PySet_New(0);
820 821 822 823
    if (result == NULL)
        return NULL;

    for (sig = 1; sig < NSIG; sig++) {
824
        if (sigismember(&mask, sig) != 1)
825 826 827 828 829 830 831 832 833 834 835 836
            continue;

        /* Handle the case where it is a member by adding the signal to
           the result list.  Ignore the other cases because they mean the
           signal isn't a member of the mask or the signal was invalid,
           and an invalid signal must have been our fault in constructing
           the loop boundaries. */
        signum = PyLong_FromLong(sig);
        if (signum == NULL) {
            Py_DECREF(result);
            return NULL;
        }
837
        if (PySet_Add(result, signum) == -1) {
838 839 840 841 842 843 844 845
            Py_DECREF(signum);
            Py_DECREF(result);
            return NULL;
        }
        Py_DECREF(signum);
    }
    return result;
}
846
#endif
847

848
#ifdef PYPTHREAD_SIGMASK
849 850 851 852 853

/*[clinic input]
signal.pthread_sigmask

    how:  int
854
    mask: sigset_t
855 856 857 858 859
    /

Fetch and/or change the signal mask of the calling thread.
[clinic start generated code]*/

860
static PyObject *
861 862
signal_pthread_sigmask_impl(PyObject *module, int how, sigset_t mask)
/*[clinic end generated code: output=0562c0fb192981a8 input=85bcebda442fa77f]*/
863
{
864
    sigset_t previous;
865 866
    int err;

867
    err = pthread_sigmask(how, &mask, &previous);
868 869
    if (err != 0) {
        errno = err;
870
        PyErr_SetFromErrno(PyExc_OSError);
871 872 873 874 875 876 877 878 879 880
        return NULL;
    }

    /* if signals was unblocked, signal handlers have been called */
    if (PyErr_CheckSignals())
        return NULL;

    return sigset_to_set(previous);
}

881 882
#endif   /* #ifdef PYPTHREAD_SIGMASK */

883

884
#ifdef HAVE_SIGPENDING
885 886 887 888 889 890 891 892 893 894

/*[clinic input]
signal.sigpending

Examine pending signals.

Returns a set of signal numbers that are pending for delivery to
the calling thread.
[clinic start generated code]*/

895
static PyObject *
896 897
signal_sigpending_impl(PyObject *module)
/*[clinic end generated code: output=53375ffe89325022 input=e0036c016f874e29]*/
898 899 900 901 902 903 904 905 906 907 908 909 910
{
    int err;
    sigset_t mask;
    err = sigpending(&mask);
    if (err)
        return PyErr_SetFromErrno(PyExc_OSError);
    return sigset_to_set(mask);
}

#endif   /* #ifdef HAVE_SIGPENDING */


#ifdef HAVE_SIGWAIT
911 912 913 914

/*[clinic input]
signal.sigwait

915
    sigset: sigset_t
916 917 918 919 920 921 922 923 924
    /

Wait for a signal.

Suspend execution of the calling thread until the delivery of one of the
signals specified in the signal set sigset.  The function accepts the signal
and returns the signal number.
[clinic start generated code]*/

925
static PyObject *
926 927
signal_sigwait_impl(PyObject *module, sigset_t sigset)
/*[clinic end generated code: output=f43770699d682f96 input=a6fbd47b1086d119]*/
928 929 930
{
    int err, signum;

931
    Py_BEGIN_ALLOW_THREADS
932
    err = sigwait(&sigset, &signum);
933
    Py_END_ALLOW_THREADS
934 935 936 937 938 939 940 941
    if (err) {
        errno = err;
        return PyErr_SetFromErrno(PyExc_OSError);
    }

    return PyLong_FromLong(signum);
}

942 943
#endif   /* #ifdef HAVE_SIGWAIT */

944

945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
#if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)

/*[clinic input]
signal.valid_signals

Return a set of valid signal numbers on this platform.

The signal numbers returned by this function can be safely passed to
functions like `pthread_sigmask`.
[clinic start generated code]*/

static PyObject *
signal_valid_signals_impl(PyObject *module)
/*[clinic end generated code: output=1609cffbcfcf1314 input=86a3717ff25288f2]*/
{
#ifdef MS_WINDOWS
#ifdef SIGBREAK
    PyObject *tup = Py_BuildValue("(iiiiiii)", SIGABRT, SIGBREAK, SIGFPE,
                                  SIGILL, SIGINT, SIGSEGV, SIGTERM);
#else
    PyObject *tup = Py_BuildValue("(iiiiii)", SIGABRT, SIGFPE, SIGILL,
                                  SIGINT, SIGSEGV, SIGTERM);
#endif
    if (tup == NULL) {
        return NULL;
    }
    PyObject *set = PySet_New(tup);
    Py_DECREF(tup);
    return set;
#else
    sigset_t mask;
    if (sigemptyset(&mask) || sigfillset(&mask)) {
        return PyErr_SetFromErrno(PyExc_OSError);
    }
    return sigset_to_set(mask);
#endif
}

#endif   /* #if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS) */


986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
static int initialized;
static PyStructSequence_Field struct_siginfo_fields[] = {
    {"si_signo",        "signal number"},
    {"si_code",         "signal code"},
    {"si_errno",        "errno associated with this signal"},
    {"si_pid",          "sending process ID"},
    {"si_uid",          "real user ID of sending process"},
    {"si_status",       "exit value or signal"},
    {"si_band",         "band event for SIGPOLL"},
    {0}
};

PyDoc_STRVAR(struct_siginfo__doc__,
"struct_siginfo: Result from sigwaitinfo or sigtimedwait.\n\n\
This object may be accessed either as a tuple of\n\
(si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band),\n\
or via the attributes si_signo, si_code, and so on.");

static PyStructSequence_Desc struct_siginfo_desc = {
    "signal.struct_siginfo",           /* name */
    struct_siginfo__doc__,       /* doc */
    struct_siginfo_fields,       /* fields */
    7          /* n_in_sequence */
};

static PyTypeObject SiginfoType;

static PyObject *
fill_siginfo(siginfo_t *si)
{
    PyObject *result = PyStructSequence_New(&SiginfoType);
    if (!result)
        return NULL;

    PyStructSequence_SET_ITEM(result, 0, PyLong_FromLong((long)(si->si_signo)));
    PyStructSequence_SET_ITEM(result, 1, PyLong_FromLong((long)(si->si_code)));
    PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si->si_errno)));
    PyStructSequence_SET_ITEM(result, 3, PyLong_FromPid(si->si_pid));
1025
    PyStructSequence_SET_ITEM(result, 4, _PyLong_FromUid(si->si_uid));
1026 1027
    PyStructSequence_SET_ITEM(result, 5,
                                PyLong_FromLong((long)(si->si_status)));
1028
#ifdef HAVE_SIGINFO_T_SI_BAND
1029
    PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(si->si_band));
1030 1031 1032
#else
    PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(0L));
#endif
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    if (PyErr_Occurred()) {
        Py_DECREF(result);
        return NULL;
    }

    return result;
}
#endif

#ifdef HAVE_SIGWAITINFO
1043 1044 1045 1046

/*[clinic input]
signal.sigwaitinfo

1047
    sigset: sigset_t
1048 1049 1050 1051 1052 1053 1054
    /

Wait synchronously until one of the signals in *sigset* is delivered.

Returns a struct_siginfo containing information about the signal.
[clinic start generated code]*/

1055
static PyObject *
1056 1057
signal_sigwaitinfo_impl(PyObject *module, sigset_t sigset)
/*[clinic end generated code: output=1eb2f1fa236fdbca input=3d1a7e1f27fc664c]*/
1058 1059 1060
{
    siginfo_t si;
    int err;
1061
    int async_err = 0;
1062

1063 1064
    do {
        Py_BEGIN_ALLOW_THREADS
1065
        err = sigwaitinfo(&sigset, &si);
1066 1067 1068
        Py_END_ALLOW_THREADS
    } while (err == -1
             && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1069
    if (err == -1)
1070
        return (!async_err) ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
1071 1072 1073 1074 1075 1076 1077

    return fill_siginfo(&si);
}

#endif   /* #ifdef HAVE_SIGWAITINFO */

#ifdef HAVE_SIGTIMEDWAIT
1078 1079 1080 1081

/*[clinic input]
signal.sigtimedwait

1082
    sigset: sigset_t
1083
    timeout as timeout_obj: object
1084 1085 1086 1087 1088 1089 1090
    /

Like sigwaitinfo(), but with a timeout.

The timeout is specified in seconds, with floating point numbers allowed.
[clinic start generated code]*/

1091
static PyObject *
1092
signal_sigtimedwait_impl(PyObject *module, sigset_t sigset,
1093
                         PyObject *timeout_obj)
1094
/*[clinic end generated code: output=59c8971e8ae18a64 input=87fd39237cf0b7ba]*/
1095
{
1096
    struct timespec ts;
1097
    siginfo_t si;
1098
    int res;
1099 1100
    _PyTime_t timeout, deadline, monotonic;

1101 1102
    if (_PyTime_FromSecondsObject(&timeout,
                                  timeout_obj, _PyTime_ROUND_CEILING) < 0)
1103 1104
        return NULL;

1105
    if (timeout < 0) {
1106 1107 1108 1109
        PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
        return NULL;
    }

1110
    deadline = _PyTime_GetMonotonicClock() + timeout;
1111 1112

    do {
1113 1114
        if (_PyTime_AsTimespec(timeout, &ts) < 0)
            return NULL;
1115 1116

        Py_BEGIN_ALLOW_THREADS
1117
        res = sigtimedwait(&sigset, &si, &ts);
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
        Py_END_ALLOW_THREADS

        if (res != -1)
            break;

        if (errno != EINTR) {
            if (errno == EAGAIN)
                Py_RETURN_NONE;
            else
                return PyErr_SetFromErrno(PyExc_OSError);
        }

        /* sigtimedwait() was interrupted by a signal (EINTR) */
        if (PyErr_CheckSignals())
            return NULL;

1134 1135
        monotonic = _PyTime_GetMonotonicClock();
        timeout = deadline - monotonic;
1136
        if (timeout < 0)
1137 1138
            break;
    } while (1);
1139 1140 1141 1142 1143 1144

    return fill_siginfo(&si);
}

#endif   /* #ifdef HAVE_SIGTIMEDWAIT */

1145

1146
#if defined(HAVE_PTHREAD_KILL)
1147 1148 1149 1150

/*[clinic input]
signal.pthread_kill

1151
    thread_id:  unsigned_long(bitwise=True)
1152 1153 1154 1155 1156 1157
    signalnum:  int
    /

Send a signal to a thread.
[clinic start generated code]*/

1158
static PyObject *
1159 1160 1161
signal_pthread_kill_impl(PyObject *module, unsigned long thread_id,
                         int signalnum)
/*[clinic end generated code: output=7629919b791bc27f input=1d901f2c7bb544ff]*/
1162 1163 1164
{
    int err;

1165
    err = pthread_kill((pthread_t)thread_id, signalnum);
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    if (err != 0) {
        errno = err;
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }

    /* the signal may have been send to the current thread */
    if (PyErr_CheckSignals())
        return NULL;

    Py_RETURN_NONE;
}

1179
#endif   /* #if defined(HAVE_PTHREAD_KILL) */
1180 1181 1182



1183 1184
/* List of functions defined in the module -- some of the methoddefs are
   defined to nothing if the corresponding C function is not available. */
Barry Warsaw's avatar
Barry Warsaw committed
1185
static PyMethodDef signal_methods[] = {
1186 1187 1188 1189 1190
    {"default_int_handler", signal_default_int_handler, METH_VARARGS, default_int_handler_doc},
    SIGNAL_ALARM_METHODDEF
    SIGNAL_SETITIMER_METHODDEF
    SIGNAL_GETITIMER_METHODDEF
    SIGNAL_SIGNAL_METHODDEF
1191
    SIGNAL_STRSIGNAL_METHODDEF
1192
    SIGNAL_GETSIGNAL_METHODDEF
1193
    {"set_wakeup_fd", (PyCFunction)signal_set_wakeup_fd, METH_VARARGS | METH_KEYWORDS, set_wakeup_fd_doc},
1194 1195 1196 1197 1198 1199 1200 1201
    SIGNAL_SIGINTERRUPT_METHODDEF
    SIGNAL_PAUSE_METHODDEF
    SIGNAL_PTHREAD_KILL_METHODDEF
    SIGNAL_PTHREAD_SIGMASK_METHODDEF
    SIGNAL_SIGPENDING_METHODDEF
    SIGNAL_SIGWAIT_METHODDEF
    SIGNAL_SIGWAITINFO_METHODDEF
    SIGNAL_SIGTIMEDWAIT_METHODDEF
1202 1203 1204
#if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)
    SIGNAL_VALID_SIGNALS_METHODDEF
#endif
1205
    {NULL, NULL}           /* sentinel */
1206 1207
};

Barry Warsaw's avatar
Barry Warsaw committed
1208

1209
PyDoc_STRVAR(module_doc,
Guido van Rossum's avatar
Guido van Rossum committed
1210 1211 1212 1213 1214
"This module provides mechanisms to use signal handlers in Python.\n\
\n\
Functions:\n\
\n\
alarm() -- cause SIGALRM after a specified time [Unix only]\n\
1215 1216 1217
setitimer() -- cause a signal (described below) after a specified\n\
               float time and the timer may restart then [Unix only]\n\
getitimer() -- get current value of timer [Unix only]\n\
Guido van Rossum's avatar
Guido van Rossum committed
1218 1219 1220 1221 1222
signal() -- set the action for a given signal\n\
getsignal() -- get the signal action for a given signal\n\
pause() -- wait until a signal arrives [Unix only]\n\
default_int_handler() -- default SIGINT handler\n\
\n\
1223
signal constants:\n\
Guido van Rossum's avatar
Guido van Rossum committed
1224 1225 1226 1227 1228
SIG_DFL -- used to refer to the system default handler\n\
SIG_IGN -- used to ignore the signal\n\
NSIG -- number of defined signals\n\
SIGINT, SIGTERM, etc. -- signal numbers\n\
\n\
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
itimer constants:\n\
ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\
               expiration\n\
ITIMER_VIRTUAL -- decrements only when the process is executing,\n\
               and delivers SIGVTALRM upon expiration\n\
ITIMER_PROF -- decrements both when the process is executing and\n\
               when the system is executing on behalf of the process.\n\
               Coupled with ITIMER_VIRTUAL, this timer is usually\n\
               used to profile the time spent by the application\n\
               in user and kernel space. SIGPROF is delivered upon\n\
               expiration.\n\
\n\n\
Guido van Rossum's avatar
Guido van Rossum committed
1241 1242
*** IMPORTANT NOTICE ***\n\
A signal handler function is called with two arguments:\n\
1243
the first is the signal number, the second is the interrupted stack frame.");
Guido van Rossum's avatar
Guido van Rossum committed
1244

1245
static struct PyModuleDef signalmodule = {
1246
    PyModuleDef_HEAD_INIT,
1247
    "_signal",
1248 1249 1250 1251 1252 1253 1254
    module_doc,
    -1,
    signal_methods,
    NULL,
    NULL,
    NULL,
    NULL
1255 1256
};

1257
PyMODINIT_FUNC
1258
PyInit__signal(void)
1259
{
1260 1261
    PyObject *m, *d, *x;
    int i;
1262

1263 1264 1265 1266 1267 1268 1269 1270
    main_thread = PyThread_get_thread_ident();
    main_pid = getpid();

    /* Create the module and add the functions */
    m = PyModule_Create(&signalmodule);
    if (m == NULL)
        return NULL;

1271
#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
1272 1273 1274 1275
    if (!initialized) {
        if (PyStructSequence_InitType2(&SiginfoType, &struct_siginfo_desc) < 0)
            return NULL;
    }
1276 1277 1278 1279 1280
    Py_INCREF((PyObject*) &SiginfoType);
    PyModule_AddObject(m, "struct_siginfo", (PyObject*) &SiginfoType);
    initialized = 1;
#endif

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    /* Add some symbolic constants to the module */
    d = PyModule_GetDict(m);

    x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL);
    if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0)
        goto finally;

    x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN);
    if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0)
        goto finally;

    x = PyLong_FromLong((long)NSIG);
    if (!x || PyDict_SetItemString(d, "NSIG", x) < 0)
        goto finally;
    Py_DECREF(x);

1297
#ifdef SIG_BLOCK
1298 1299
    if (PyModule_AddIntMacro(m, SIG_BLOCK))
         goto finally;
1300 1301
#endif
#ifdef SIG_UNBLOCK
1302 1303
    if (PyModule_AddIntMacro(m, SIG_UNBLOCK))
         goto finally;
1304 1305
#endif
#ifdef SIG_SETMASK
1306 1307
    if (PyModule_AddIntMacro(m, SIG_SETMASK))
         goto finally;
1308 1309
#endif

1310 1311 1312 1313 1314
    x = IntHandler = PyDict_GetItemString(d, "default_int_handler");
    if (!x)
        goto finally;
    Py_INCREF(IntHandler);

1315
    _Py_atomic_store_relaxed(&Handlers[0].tripped, 0);
1316 1317 1318
    for (i = 1; i < NSIG; i++) {
        void (*t)(int);
        t = PyOS_getsig(i);
1319
        _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
        if (t == SIG_DFL)
            Handlers[i].func = DefaultHandler;
        else if (t == SIG_IGN)
            Handlers[i].func = IgnoreHandler;
        else
            Handlers[i].func = Py_None; /* None of our business */
        Py_INCREF(Handlers[i].func);
    }
    if (Handlers[SIGINT].func == DefaultHandler) {
        /* Install default int handler */
        Py_INCREF(IntHandler);
1331
        Py_SETREF(Handlers[SIGINT].func, IntHandler);
1332
        PyOS_setsig(SIGINT, signal_handler);
1333
    }
1334 1335

#ifdef SIGHUP
1336 1337
    if (PyModule_AddIntMacro(m, SIGHUP))
         goto finally;
1338 1339
#endif
#ifdef SIGINT
1340 1341
    if (PyModule_AddIntMacro(m, SIGINT))
         goto finally;
1342
#endif
1343
#ifdef SIGBREAK
1344 1345
    if (PyModule_AddIntMacro(m, SIGBREAK))
         goto finally;
1346
#endif
1347
#ifdef SIGQUIT
1348 1349
    if (PyModule_AddIntMacro(m, SIGQUIT))
         goto finally;
1350 1351
#endif
#ifdef SIGILL
1352 1353
    if (PyModule_AddIntMacro(m, SIGILL))
         goto finally;
1354 1355
#endif
#ifdef SIGTRAP
1356 1357
    if (PyModule_AddIntMacro(m, SIGTRAP))
         goto finally;
1358 1359
#endif
#ifdef SIGIOT
1360 1361
    if (PyModule_AddIntMacro(m, SIGIOT))
         goto finally;
1362 1363
#endif
#ifdef SIGABRT
1364 1365
    if (PyModule_AddIntMacro(m, SIGABRT))
         goto finally;
1366 1367
#endif
#ifdef SIGEMT
1368 1369
    if (PyModule_AddIntMacro(m, SIGEMT))
         goto finally;
1370 1371
#endif
#ifdef SIGFPE
1372 1373
    if (PyModule_AddIntMacro(m, SIGFPE))
         goto finally;
1374 1375
#endif
#ifdef SIGKILL
1376 1377
    if (PyModule_AddIntMacro(m, SIGKILL))
         goto finally;
1378 1379
#endif
#ifdef SIGBUS
1380 1381
    if (PyModule_AddIntMacro(m, SIGBUS))
         goto finally;
1382 1383
#endif
#ifdef SIGSEGV
1384 1385
    if (PyModule_AddIntMacro(m, SIGSEGV))
         goto finally;
1386 1387
#endif
#ifdef SIGSYS
1388 1389
    if (PyModule_AddIntMacro(m, SIGSYS))
         goto finally;
1390 1391
#endif
#ifdef SIGPIPE
1392 1393
    if (PyModule_AddIntMacro(m, SIGPIPE))
         goto finally;
1394 1395
#endif
#ifdef SIGALRM
1396 1397
    if (PyModule_AddIntMacro(m, SIGALRM))
         goto finally;
1398 1399
#endif
#ifdef SIGTERM
1400 1401
    if (PyModule_AddIntMacro(m, SIGTERM))
         goto finally;
1402 1403
#endif
#ifdef SIGUSR1
1404 1405
    if (PyModule_AddIntMacro(m, SIGUSR1))
         goto finally;
1406 1407
#endif
#ifdef SIGUSR2
1408 1409
    if (PyModule_AddIntMacro(m, SIGUSR2))
         goto finally;
1410 1411
#endif
#ifdef SIGCLD
1412 1413
    if (PyModule_AddIntMacro(m, SIGCLD))
         goto finally;
1414 1415
#endif
#ifdef SIGCHLD
1416 1417
    if (PyModule_AddIntMacro(m, SIGCHLD))
         goto finally;
1418 1419
#endif
#ifdef SIGPWR
1420 1421
    if (PyModule_AddIntMacro(m, SIGPWR))
         goto finally;
1422 1423
#endif
#ifdef SIGIO
1424 1425
    if (PyModule_AddIntMacro(m, SIGIO))
         goto finally;
1426 1427
#endif
#ifdef SIGURG
1428 1429
    if (PyModule_AddIntMacro(m, SIGURG))
         goto finally;
1430 1431
#endif
#ifdef SIGWINCH
1432 1433
    if (PyModule_AddIntMacro(m, SIGWINCH))
         goto finally;
1434 1435
#endif
#ifdef SIGPOLL
1436 1437
    if (PyModule_AddIntMacro(m, SIGPOLL))
         goto finally;
1438 1439
#endif
#ifdef SIGSTOP
1440 1441
    if (PyModule_AddIntMacro(m, SIGSTOP))
         goto finally;
1442 1443
#endif
#ifdef SIGTSTP
1444 1445
    if (PyModule_AddIntMacro(m, SIGTSTP))
         goto finally;
1446 1447
#endif
#ifdef SIGCONT
1448 1449
    if (PyModule_AddIntMacro(m, SIGCONT))
         goto finally;
1450 1451
#endif
#ifdef SIGTTIN
1452 1453
    if (PyModule_AddIntMacro(m, SIGTTIN))
         goto finally;
1454 1455
#endif
#ifdef SIGTTOU
1456 1457
    if (PyModule_AddIntMacro(m, SIGTTOU))
         goto finally;
1458 1459
#endif
#ifdef SIGVTALRM
1460 1461
    if (PyModule_AddIntMacro(m, SIGVTALRM))
         goto finally;
1462 1463
#endif
#ifdef SIGPROF
1464 1465
    if (PyModule_AddIntMacro(m, SIGPROF))
         goto finally;
1466
#endif
1467
#ifdef SIGXCPU
1468 1469
    if (PyModule_AddIntMacro(m, SIGXCPU))
         goto finally;
1470 1471
#endif
#ifdef SIGXFSZ
1472 1473
    if (PyModule_AddIntMacro(m, SIGXFSZ))
         goto finally;
1474
#endif
1475
#ifdef SIGRTMIN
1476 1477
    if (PyModule_AddIntMacro(m, SIGRTMIN))
         goto finally;
1478 1479
#endif
#ifdef SIGRTMAX
1480 1481
    if (PyModule_AddIntMacro(m, SIGRTMAX))
         goto finally;
1482
#endif
1483
#ifdef SIGINFO
1484 1485
    if (PyModule_AddIntMacro(m, SIGINFO))
         goto finally;
1486
#endif
1487 1488

#ifdef ITIMER_REAL
1489 1490
    if (PyModule_AddIntMacro(m, ITIMER_REAL))
         goto finally;
1491 1492
#endif
#ifdef ITIMER_VIRTUAL
1493 1494
    if (PyModule_AddIntMacro(m, ITIMER_VIRTUAL))
         goto finally;
1495 1496
#endif
#ifdef ITIMER_PROF
1497 1498
    if (PyModule_AddIntMacro(m, ITIMER_PROF))
         goto finally;
1499 1500 1501
#endif

#if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER)
1502
    ItimerError = PyErr_NewException("signal.ItimerError",
1503
            PyExc_OSError, NULL);
1504
    if (ItimerError != NULL)
1505
        PyDict_SetItemString(d, "ItimerError", ItimerError);
1506 1507
#endif

1508
#ifdef CTRL_C_EVENT
1509 1510
    if (PyModule_AddIntMacro(m, CTRL_C_EVENT))
         goto finally;
1511 1512 1513
#endif

#ifdef CTRL_BREAK_EVENT
1514 1515
    if (PyModule_AddIntMacro(m, CTRL_BREAK_EVENT))
         goto finally;
1516 1517
#endif

1518 1519 1520 1521 1522
#ifdef MS_WINDOWS
    /* Create manual-reset event, initially unset */
    sigint_event = CreateEvent(NULL, TRUE, FALSE, FALSE);
#endif

1523
    if (PyErr_Occurred()) {
1524 1525
        Py_DECREF(m);
        m = NULL;
1526
    }
Barry Warsaw's avatar
Barry Warsaw committed
1527 1528

  finally:
1529
    return m;
1530 1531 1532
}

static void
1533
finisignal(void)
1534
{
1535 1536 1537 1538 1539
    int i;
    PyObject *func;

    for (i = 1; i < NSIG; i++) {
        func = Handlers[i].func;
1540
        _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1541
        Handlers[i].func = NULL;
1542
        if (func != NULL && func != Py_None &&
1543 1544 1545 1546 1547
            func != DefaultHandler && func != IgnoreHandler)
            PyOS_setsig(i, SIG_DFL);
        Py_XDECREF(func);
    }

1548 1549 1550
    Py_CLEAR(IntHandler);
    Py_CLEAR(DefaultHandler);
    Py_CLEAR(IgnoreHandler);
1551 1552
}

Barry Warsaw's avatar
Barry Warsaw committed
1553 1554

/* Declared in pyerrors.h */
1555
int
1556
PyErr_CheckSignals(void)
1557
{
1558 1559
    int i;
    PyObject *f;
Barry Warsaw's avatar
Barry Warsaw committed
1560

1561
    if (!_Py_atomic_load(&is_tripped))
1562
        return 0;
1563

1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
    if (PyThread_get_thread_ident() != main_thread)
        return 0;

    /*
     * The is_tripped variable is meant to speed up the calls to
     * PyErr_CheckSignals (both directly or via pending calls) when no
     * signal has arrived. This variable is set to 1 when a signal arrives
     * and it is set to 0 here, when we know some signals arrived. This way
     * we can run the registered handlers with no signals blocked.
     *
     * NOTE: with this approach we can have a situation where is_tripped is
     *       1 but we have no more signals to handle (Handlers[i].tripped
     *       is 0 for every signal i). This won't do us any harm (except
     *       we're gonna spent some cycles for nothing). This happens when
     *       we receive a signal i after we zero is_tripped and before we
     *       check Handlers[i].tripped.
     */
1581
    _Py_atomic_store(&is_tripped, 0);
1582 1583 1584 1585 1586

    if (!(f = (PyObject *)PyEval_GetFrame()))
        f = Py_None;

    for (i = 1; i < NSIG; i++) {
1587
        if (_Py_atomic_load_relaxed(&Handlers[i].tripped)) {
1588 1589
            PyObject *result = NULL;
            PyObject *arglist = Py_BuildValue("(iO)", i, f);
1590
            _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1591 1592 1593 1594 1595 1596

            if (arglist) {
                result = PyEval_CallObject(Handlers[i].func,
                                           arglist);
                Py_DECREF(arglist);
            }
1597
            if (!result) {
1598
                _Py_atomic_store(&is_tripped, 1);
1599
                return -1;
1600
            }
1601 1602 1603 1604 1605 1606

            Py_DECREF(result);
        }
    }

    return 0;
1607 1608
}

1609

Barry Warsaw's avatar
Barry Warsaw committed
1610 1611 1612 1613
/* Replacements for intrcheck.c functionality
 * Declared in pyerrors.h
 */
void
1614
PyErr_SetInterrupt(void)
Barry Warsaw's avatar
Barry Warsaw committed
1615
{
1616
    trip_signal(SIGINT);
Barry Warsaw's avatar
Barry Warsaw committed
1617
}
1618 1619

void
1620
PyOS_InitInterrupts(void)
1621
{
1622
    PyObject *m = PyImport_ImportModule("_signal");
1623 1624 1625
    if (m) {
        Py_DECREF(m);
    }
1626 1627 1628
}

void
1629
PyOS_FiniInterrupts(void)
1630
{
1631
    finisignal();
1632 1633 1634
}

int
1635
PyOS_InterruptOccurred(void)
1636
{
1637
    if (_Py_atomic_load_relaxed(&Handlers[SIGINT].tripped)) {
1638 1639
        if (PyThread_get_thread_ident() != main_thread)
            return 0;
1640
        _Py_atomic_store_relaxed(&Handlers[SIGINT].tripped, 0);
1641 1642 1643
        return 1;
    }
    return 0;
1644
}
1645

1646 1647 1648 1649
static void
_clear_pending_signals(void)
{
    int i;
1650
    if (!_Py_atomic_load(&is_tripped))
1651
        return;
1652
    _Py_atomic_store(&is_tripped, 0);
1653
    for (i = 1; i < NSIG; ++i) {
1654
        _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1655 1656 1657
    }
}

1658
void
1659
_PySignal_AfterFork(void)
1660
{
1661 1662 1663 1664
    /* Clear the signal flags after forking so that they aren't handled
     * in both processes if they came in just before the fork() but before
     * the interpreter had an opportunity to call the handlers.  issue9535. */
    _clear_pending_signals();
1665 1666
    main_thread = PyThread_get_thread_ident();
    main_pid = getpid();
1667
}
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685

int
_PyOS_IsMainThread(void)
{
    return PyThread_get_thread_ident() == main_thread;
}

#ifdef MS_WINDOWS
void *_PyOS_SigintEvent(void)
{
    /* Returns a manual-reset event which gets tripped whenever
       SIGINT is received.

       Python.h does not include windows.h so we do cannot use HANDLE
       as the return type of this function.  We use void* instead. */
    return sigint_event;
}
#endif