• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /* Signal module -- many thanks to Lance Ellinghaus */
3 
4 /* XXX Signals should be recorded per thread, now we have thread state. */
5 
6 #include "Python.h"
7 #include "pycore_atomic.h"
8 #include "pycore_call.h"
9 #include "pycore_ceval.h"
10 #include "pycore_pyerrors.h"
11 #include "pycore_pystate.h"    // _PyThreadState_GET()
12 
13 #ifndef MS_WINDOWS
14 #include "posixmodule.h"
15 #endif
16 #ifdef MS_WINDOWS
17 #include "socketmodule.h"   /* needed for SOCKET_T */
18 #endif
19 
20 #ifdef MS_WINDOWS
21 #include <windows.h>
22 #ifdef HAVE_PROCESS_H
23 #include <process.h>
24 #endif
25 #endif
26 
27 #ifdef HAVE_SIGNAL_H
28 #include <signal.h>
29 #endif
30 #ifdef HAVE_SYS_SYSCALL_H
31 #include <sys/syscall.h>
32 #endif
33 #ifdef HAVE_SYS_STAT_H
34 #include <sys/stat.h>
35 #endif
36 #ifdef HAVE_SYS_TIME_H
37 #include <sys/time.h>
38 #endif
39 
40 #if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
41 #  define PYPTHREAD_SIGMASK
42 #endif
43 
44 #if defined(PYPTHREAD_SIGMASK) && defined(HAVE_PTHREAD_H)
45 #  include <pthread.h>
46 #endif
47 
48 #ifndef SIG_ERR
49 #define SIG_ERR ((PyOS_sighandler_t)(-1))
50 #endif
51 
52 #ifndef NSIG
53 # if defined(_NSIG)
54 #  define NSIG _NSIG            /* For BSD/SysV */
55 # elif defined(_SIGMAX)
56 #  define NSIG (_SIGMAX + 1)    /* For QNX */
57 # elif defined(SIGMAX)
58 #  define NSIG (SIGMAX + 1)     /* For djgpp */
59 # else
60 #  define NSIG 64               /* Use a reasonable default value */
61 # endif
62 #endif
63 
64 #include "clinic/signalmodule.c.h"
65 
66 /*[clinic input]
67 module signal
68 [clinic start generated code]*/
69 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=b0301a3bde5fe9d3]*/
70 
71 /*[python input]
72 
73 class sigset_t_converter(CConverter):
74     type = 'sigset_t'
75     converter = '_Py_Sigset_Converter'
76 
77 [python start generated code]*/
78 /*[python end generated code: output=da39a3ee5e6b4b0d input=b5689d14466b6823]*/
79 
80 /*
81    NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS
82 
83    We want the following semantics:
84 
85    - only the main thread can set a signal handler
86    - only the main thread runs the signal handler
87    - signals can be delivered to any thread
88    - any thread can get a signal handler
89 
90    I.e. we don't support "synchronous signals" like SIGFPE (catching
91    this doesn't make much sense in Python anyway) nor do we support
92    signals as a means of inter-thread communication, since not all
93    thread implementations support that (at least our thread library
94    doesn't).
95 
96    We still have the problem that in some implementations signals
97    generated by the keyboard (e.g. SIGINT) are delivered to all
98    threads (e.g. SGI), while in others (e.g. Solaris) such signals are
99    delivered to one random thread. On Linux, signals are delivered to
100    the main thread (unless the main thread is blocking the signal, for
101    example because it's already handling the same signal).  Since we
102    allow signals to be delivered to any thread, this works fine. The
103    only oddity is that the thread executing the Python signal handler
104    may not be the thread that received the signal.
105 */
106 
107 static volatile struct {
108     _Py_atomic_int tripped;
109     PyObject *func;
110 } Handlers[NSIG];
111 
112 #ifdef MS_WINDOWS
113 #define INVALID_FD ((SOCKET_T)-1)
114 
115 static volatile struct {
116     SOCKET_T fd;
117     int warn_on_full_buffer;
118     int use_send;
119 } wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1, .use_send = 0};
120 #else
121 #define INVALID_FD (-1)
122 static volatile struct {
123     sig_atomic_t fd;
124     int warn_on_full_buffer;
125 } wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1};
126 #endif
127 
128 /* Speed up sigcheck() when none tripped */
129 static _Py_atomic_int is_tripped;
130 
131 static PyObject *DefaultHandler;
132 static PyObject *IgnoreHandler;
133 static PyObject *IntHandler;
134 
135 #ifdef MS_WINDOWS
136 static HANDLE sigint_event = NULL;
137 #endif
138 
139 #ifdef HAVE_GETITIMER
140 static PyObject *ItimerError;
141 
142 /* auxiliary functions for setitimer */
143 static int
timeval_from_double(PyObject * obj,struct timeval * tv)144 timeval_from_double(PyObject *obj, struct timeval *tv)
145 {
146     if (obj == NULL) {
147         tv->tv_sec = 0;
148         tv->tv_usec = 0;
149         return 0;
150     }
151 
152     _PyTime_t t;
153     if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_CEILING) < 0) {
154         return -1;
155     }
156     return _PyTime_AsTimeval(t, tv, _PyTime_ROUND_CEILING);
157 }
158 
159 Py_LOCAL_INLINE(double)
double_from_timeval(struct timeval * tv)160 double_from_timeval(struct timeval *tv)
161 {
162     return tv->tv_sec + (double)(tv->tv_usec / 1000000.0);
163 }
164 
165 static PyObject *
itimer_retval(struct itimerval * iv)166 itimer_retval(struct itimerval *iv)
167 {
168     PyObject *r, *v;
169 
170     r = PyTuple_New(2);
171     if (r == NULL)
172         return NULL;
173 
174     if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
175         Py_DECREF(r);
176         return NULL;
177     }
178 
179     PyTuple_SET_ITEM(r, 0, v);
180 
181     if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) {
182         Py_DECREF(r);
183         return NULL;
184     }
185 
186     PyTuple_SET_ITEM(r, 1, v);
187 
188     return r;
189 }
190 #endif
191 
192 static PyObject *
signal_default_int_handler(PyObject * self,PyObject * args)193 signal_default_int_handler(PyObject *self, PyObject *args)
194 {
195     PyErr_SetNone(PyExc_KeyboardInterrupt);
196     return NULL;
197 }
198 
199 PyDoc_STRVAR(default_int_handler_doc,
200 "default_int_handler(...)\n\
201 \n\
202 The default handler for SIGINT installed by Python.\n\
203 It raises KeyboardInterrupt.");
204 
205 
206 static int
report_wakeup_write_error(void * data)207 report_wakeup_write_error(void *data)
208 {
209     PyObject *exc, *val, *tb;
210     int save_errno = errno;
211     errno = (int) (intptr_t) data;
212     PyErr_Fetch(&exc, &val, &tb);
213     PyErr_SetFromErrno(PyExc_OSError);
214     PySys_WriteStderr("Exception ignored when trying to write to the "
215                       "signal wakeup fd:\n");
216     PyErr_WriteUnraisable(NULL);
217     PyErr_Restore(exc, val, tb);
218     errno = save_errno;
219     return 0;
220 }
221 
222 #ifdef MS_WINDOWS
223 static int
report_wakeup_send_error(void * data)224 report_wakeup_send_error(void* data)
225 {
226     PyObject *exc, *val, *tb;
227     PyErr_Fetch(&exc, &val, &tb);
228     /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
229        recognizes the error codes used by both GetLastError() and
230        WSAGetLastError */
231     PyErr_SetExcFromWindowsErr(PyExc_OSError, (int) (intptr_t) data);
232     PySys_WriteStderr("Exception ignored when trying to send to the "
233                       "signal wakeup fd:\n");
234     PyErr_WriteUnraisable(NULL);
235     PyErr_Restore(exc, val, tb);
236     return 0;
237 }
238 #endif   /* MS_WINDOWS */
239 
240 static void
trip_signal(int sig_num)241 trip_signal(int sig_num)
242 {
243     unsigned char byte;
244     int fd;
245     Py_ssize_t rc;
246 
247     _Py_atomic_store_relaxed(&Handlers[sig_num].tripped, 1);
248 
249     /* Set is_tripped after setting .tripped, as it gets
250        cleared in PyErr_CheckSignals() before .tripped. */
251     _Py_atomic_store(&is_tripped, 1);
252 
253     /* Signals are always handled by the main interpreter */
254     PyInterpreterState *interp = _PyRuntime.interpreters.main;
255 
256     /* Notify ceval.c */
257     _PyEval_SignalReceived(interp);
258 
259     /* And then write to the wakeup fd *after* setting all the globals and
260        doing the _PyEval_SignalReceived. We used to write to the wakeup fd
261        and then set the flag, but this allowed the following sequence of events
262        (especially on windows, where trip_signal may run in a new thread):
263 
264        - main thread blocks on select([wakeup.fd], ...)
265        - signal arrives
266        - trip_signal writes to the wakeup fd
267        - the main thread wakes up
268        - the main thread checks the signal flags, sees that they're unset
269        - the main thread empties the wakeup fd
270        - the main thread goes back to sleep
271        - trip_signal sets the flags to request the Python-level signal handler
272          be run
273        - the main thread doesn't notice, because it's asleep
274 
275        See bpo-30038 for more details.
276     */
277 
278 #ifdef MS_WINDOWS
279     fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
280 #else
281     fd = wakeup.fd;
282 #endif
283 
284     if (fd != INVALID_FD) {
285         byte = (unsigned char)sig_num;
286 #ifdef MS_WINDOWS
287         if (wakeup.use_send) {
288             rc = send(fd, &byte, 1, 0);
289 
290             if (rc < 0) {
291                 int last_error = GetLastError();
292                 if (wakeup.warn_on_full_buffer ||
293                     last_error != WSAEWOULDBLOCK)
294                 {
295                     /* _PyEval_AddPendingCall() isn't signal-safe, but we
296                        still use it for this exceptional case. */
297                     _PyEval_AddPendingCall(interp,
298                                            report_wakeup_send_error,
299                                            (void *)(intptr_t) last_error);
300                 }
301             }
302         }
303         else
304 #endif
305         {
306             /* _Py_write_noraise() retries write() if write() is interrupted by
307                a signal (fails with EINTR). */
308             rc = _Py_write_noraise(fd, &byte, 1);
309 
310             if (rc < 0) {
311                 if (wakeup.warn_on_full_buffer ||
312                     (errno != EWOULDBLOCK && errno != EAGAIN))
313                 {
314                     /* _PyEval_AddPendingCall() isn't signal-safe, but we
315                        still use it for this exceptional case. */
316                     _PyEval_AddPendingCall(interp,
317                                            report_wakeup_write_error,
318                                            (void *)(intptr_t)errno);
319                 }
320             }
321         }
322     }
323 }
324 
325 static void
signal_handler(int sig_num)326 signal_handler(int sig_num)
327 {
328     int save_errno = errno;
329 
330     trip_signal(sig_num);
331 
332 #ifndef HAVE_SIGACTION
333 #ifdef SIGCHLD
334     /* To avoid infinite recursion, this signal remains
335        reset until explicit re-instated.
336        Don't clear the 'func' field as it is our pointer
337        to the Python handler... */
338     if (sig_num != SIGCHLD)
339 #endif
340     /* If the handler was not set up with sigaction, reinstall it.  See
341      * Python/pylifecycle.c for the implementation of PyOS_setsig which
342      * makes this true.  See also issue8354. */
343     PyOS_setsig(sig_num, signal_handler);
344 #endif
345 
346     /* Issue #10311: asynchronously executing signal handlers should not
347        mutate errno under the feet of unsuspecting C code. */
348     errno = save_errno;
349 
350 #ifdef MS_WINDOWS
351     if (sig_num == SIGINT)
352         SetEvent(sigint_event);
353 #endif
354 }
355 
356 
357 #ifdef HAVE_ALARM
358 
359 /*[clinic input]
360 signal.alarm -> long
361 
362     seconds: int
363     /
364 
365 Arrange for SIGALRM to arrive after the given number of seconds.
366 [clinic start generated code]*/
367 
368 static long
signal_alarm_impl(PyObject * module,int seconds)369 signal_alarm_impl(PyObject *module, int seconds)
370 /*[clinic end generated code: output=144232290814c298 input=0d5e97e0e6f39e86]*/
371 {
372     /* alarm() returns the number of seconds remaining */
373     return (long)alarm(seconds);
374 }
375 
376 #endif
377 
378 #ifdef HAVE_PAUSE
379 
380 /*[clinic input]
381 signal.pause
382 
383 Wait until a signal arrives.
384 [clinic start generated code]*/
385 
386 static PyObject *
signal_pause_impl(PyObject * module)387 signal_pause_impl(PyObject *module)
388 /*[clinic end generated code: output=391656788b3c3929 input=f03de0f875752062]*/
389 {
390     Py_BEGIN_ALLOW_THREADS
391     (void)pause();
392     Py_END_ALLOW_THREADS
393     /* make sure that any exceptions that got raised are propagated
394      * back into Python
395      */
396     if (PyErr_CheckSignals())
397         return NULL;
398 
399     Py_RETURN_NONE;
400 }
401 
402 #endif
403 
404 /*[clinic input]
405 signal.raise_signal
406 
407     signalnum: int
408     /
409 
410 Send a signal to the executing process.
411 [clinic start generated code]*/
412 
413 static PyObject *
signal_raise_signal_impl(PyObject * module,int signalnum)414 signal_raise_signal_impl(PyObject *module, int signalnum)
415 /*[clinic end generated code: output=e2b014220aa6111d input=e90c0f9a42358de6]*/
416 {
417     int err;
418     Py_BEGIN_ALLOW_THREADS
419     _Py_BEGIN_SUPPRESS_IPH
420     err = raise(signalnum);
421     _Py_END_SUPPRESS_IPH
422     Py_END_ALLOW_THREADS
423 
424     if (err) {
425         return PyErr_SetFromErrno(PyExc_OSError);
426     }
427     Py_RETURN_NONE;
428 }
429 
430 /*[clinic input]
431 signal.signal
432 
433     signalnum: int
434     handler:   object
435     /
436 
437 Set the action for the given signal.
438 
439 The action can be SIG_DFL, SIG_IGN, or a callable Python object.
440 The previous action is returned.  See getsignal() for possible return values.
441 
442 *** IMPORTANT NOTICE ***
443 A signal handler function is called with two arguments:
444 the first is the signal number, the second is the interrupted stack frame.
445 [clinic start generated code]*/
446 
447 static PyObject *
signal_signal_impl(PyObject * module,int signalnum,PyObject * handler)448 signal_signal_impl(PyObject *module, int signalnum, PyObject *handler)
449 /*[clinic end generated code: output=b44cfda43780f3a1 input=deee84af5fa0432c]*/
450 {
451     PyObject *old_handler;
452     void (*func)(int);
453 #ifdef MS_WINDOWS
454     /* Validate that signalnum is one of the allowable signals */
455     switch (signalnum) {
456         case SIGABRT: break;
457 #ifdef SIGBREAK
458         /* Issue #10003: SIGBREAK is not documented as permitted, but works
459            and corresponds to CTRL_BREAK_EVENT. */
460         case SIGBREAK: break;
461 #endif
462         case SIGFPE: break;
463         case SIGILL: break;
464         case SIGINT: break;
465         case SIGSEGV: break;
466         case SIGTERM: break;
467         default:
468             PyErr_SetString(PyExc_ValueError, "invalid signal value");
469             return NULL;
470     }
471 #endif
472 
473     PyThreadState *tstate = _PyThreadState_GET();
474     if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
475         _PyErr_SetString(tstate, PyExc_ValueError,
476                          "signal only works in main thread "
477                          "of the main interpreter");
478         return NULL;
479     }
480     if (signalnum < 1 || signalnum >= NSIG) {
481         _PyErr_SetString(tstate, PyExc_ValueError,
482                          "signal number out of range");
483         return NULL;
484     }
485     if (handler == IgnoreHandler) {
486         func = SIG_IGN;
487     }
488     else if (handler == DefaultHandler) {
489         func = SIG_DFL;
490     }
491     else if (!PyCallable_Check(handler)) {
492         _PyErr_SetString(tstate, PyExc_TypeError,
493                          "signal handler must be signal.SIG_IGN, "
494                          "signal.SIG_DFL, or a callable object");
495         return NULL;
496     }
497     else {
498         func = signal_handler;
499     }
500 
501     /* Check for pending signals before changing signal handler */
502     if (_PyErr_CheckSignalsTstate(tstate)) {
503         return NULL;
504     }
505     if (PyOS_setsig(signalnum, func) == SIG_ERR) {
506         PyErr_SetFromErrno(PyExc_OSError);
507         return NULL;
508     }
509 
510     old_handler = Handlers[signalnum].func;
511     Py_INCREF(handler);
512     Handlers[signalnum].func = handler;
513 
514     if (old_handler != NULL) {
515         return old_handler;
516     }
517     else {
518         Py_RETURN_NONE;
519     }
520 }
521 
522 
523 /*[clinic input]
524 signal.getsignal
525 
526     signalnum: int
527     /
528 
529 Return the current action for the given signal.
530 
531 The return value can be:
532   SIG_IGN -- if the signal is being ignored
533   SIG_DFL -- if the default action for the signal is in effect
534   None    -- if an unknown handler is in effect
535   anything else -- the callable Python object used as a handler
536 [clinic start generated code]*/
537 
538 static PyObject *
signal_getsignal_impl(PyObject * module,int signalnum)539 signal_getsignal_impl(PyObject *module, int signalnum)
540 /*[clinic end generated code: output=35b3e0e796fd555e input=ac23a00f19dfa509]*/
541 {
542     PyObject *old_handler;
543     if (signalnum < 1 || signalnum >= NSIG) {
544         PyErr_SetString(PyExc_ValueError,
545                         "signal number out of range");
546         return NULL;
547     }
548     old_handler = Handlers[signalnum].func;
549     if (old_handler != NULL) {
550         Py_INCREF(old_handler);
551         return old_handler;
552     }
553     else {
554         Py_RETURN_NONE;
555     }
556 }
557 
558 
559 /*[clinic input]
560 signal.strsignal
561 
562     signalnum: int
563     /
564 
565 Return the system description of the given signal.
566 
567 The return values can be such as "Interrupt", "Segmentation fault", etc.
568 Returns None if the signal is not recognized.
569 [clinic start generated code]*/
570 
571 static PyObject *
signal_strsignal_impl(PyObject * module,int signalnum)572 signal_strsignal_impl(PyObject *module, int signalnum)
573 /*[clinic end generated code: output=44e12e1e3b666261 input=b77914b03f856c74]*/
574 {
575     char *res;
576 
577     if (signalnum < 1 || signalnum >= NSIG) {
578         PyErr_SetString(PyExc_ValueError,
579                 "signal number out of range");
580         return NULL;
581     }
582 
583 #ifndef HAVE_STRSIGNAL
584     switch (signalnum) {
585         /* Though being a UNIX, HP-UX does not provide strsignal(3). */
586 #ifndef MS_WINDOWS
587         case SIGHUP:
588             res = "Hangup";
589             break;
590         case SIGALRM:
591             res = "Alarm clock";
592             break;
593         case SIGPIPE:
594             res = "Broken pipe";
595             break;
596         case SIGQUIT:
597             res = "Quit";
598             break;
599         case SIGCHLD:
600             res = "Child exited";
601             break;
602 #endif
603         /* Custom redefinition of POSIX signals allowed on Windows. */
604         case SIGINT:
605             res = "Interrupt";
606             break;
607         case SIGILL:
608             res = "Illegal instruction";
609             break;
610         case SIGABRT:
611             res = "Aborted";
612             break;
613         case SIGFPE:
614             res = "Floating point exception";
615             break;
616         case SIGSEGV:
617             res = "Segmentation fault";
618             break;
619         case SIGTERM:
620             res = "Terminated";
621             break;
622         default:
623             Py_RETURN_NONE;
624     }
625 #else
626     errno = 0;
627     res = strsignal(signalnum);
628 
629     if (errno || res == NULL || strstr(res, "Unknown signal") != NULL)
630         Py_RETURN_NONE;
631 #endif
632 
633     return Py_BuildValue("s", res);
634 }
635 
636 #ifdef HAVE_SIGINTERRUPT
637 
638 /*[clinic input]
639 signal.siginterrupt
640 
641     signalnum: int
642     flag:      int
643     /
644 
645 Change system call restart behaviour.
646 
647 If flag is False, system calls will be restarted when interrupted by
648 signal sig, else system calls will be interrupted.
649 [clinic start generated code]*/
650 
651 static PyObject *
signal_siginterrupt_impl(PyObject * module,int signalnum,int flag)652 signal_siginterrupt_impl(PyObject *module, int signalnum, int flag)
653 /*[clinic end generated code: output=063816243d85dd19 input=4160acacca3e2099]*/
654 {
655     if (signalnum < 1 || signalnum >= NSIG) {
656         PyErr_SetString(PyExc_ValueError,
657                         "signal number out of range");
658         return NULL;
659     }
660     if (siginterrupt(signalnum, flag)<0) {
661         PyErr_SetFromErrno(PyExc_OSError);
662         return NULL;
663     }
664     Py_RETURN_NONE;
665 }
666 
667 #endif
668 
669 
670 static PyObject*
signal_set_wakeup_fd(PyObject * self,PyObject * args,PyObject * kwds)671 signal_set_wakeup_fd(PyObject *self, PyObject *args, PyObject *kwds)
672 {
673     struct _Py_stat_struct status;
674     static char *kwlist[] = {
675         "", "warn_on_full_buffer", NULL,
676     };
677     int warn_on_full_buffer = 1;
678 #ifdef MS_WINDOWS
679     PyObject *fdobj;
680     SOCKET_T sockfd, old_sockfd;
681     int res;
682     int res_size = sizeof res;
683     PyObject *mod;
684     int is_socket;
685 
686     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|$p:set_wakeup_fd", kwlist,
687                                      &fdobj, &warn_on_full_buffer))
688         return NULL;
689 
690     sockfd = PyLong_AsSocket_t(fdobj);
691     if (sockfd == (SOCKET_T)(-1) && PyErr_Occurred())
692         return NULL;
693 #else
694     int fd, old_fd;
695 
696     if (!PyArg_ParseTupleAndKeywords(args, kwds, "i|$p:set_wakeup_fd", kwlist,
697                                      &fd, &warn_on_full_buffer))
698         return NULL;
699 #endif
700 
701     PyThreadState *tstate = _PyThreadState_GET();
702     if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
703         _PyErr_SetString(tstate, PyExc_ValueError,
704                          "set_wakeup_fd only works in main thread "
705                          "of the main interpreter");
706         return NULL;
707     }
708 
709 #ifdef MS_WINDOWS
710     is_socket = 0;
711     if (sockfd != INVALID_FD) {
712         /* Import the _socket module to call WSAStartup() */
713         mod = PyImport_ImportModuleNoBlock("_socket");
714         if (mod == NULL)
715             return NULL;
716         Py_DECREF(mod);
717 
718         /* test the socket */
719         if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
720                        (char *)&res, &res_size) != 0) {
721             int fd, err;
722 
723             err = WSAGetLastError();
724             if (err != WSAENOTSOCK) {
725                 PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
726                 return NULL;
727             }
728 
729             fd = (int)sockfd;
730             if ((SOCKET_T)fd != sockfd) {
731                 _PyErr_SetString(tstate, PyExc_ValueError, "invalid fd");
732                 return NULL;
733             }
734 
735             if (_Py_fstat(fd, &status) != 0) {
736                 return NULL;
737             }
738 
739             /* on Windows, a file cannot be set to non-blocking mode */
740         }
741         else {
742             is_socket = 1;
743 
744             /* Windows does not provide a function to test if a socket
745                is in non-blocking mode */
746         }
747     }
748 
749     old_sockfd = wakeup.fd;
750     wakeup.fd = sockfd;
751     wakeup.warn_on_full_buffer = warn_on_full_buffer;
752     wakeup.use_send = is_socket;
753 
754     if (old_sockfd != INVALID_FD)
755         return PyLong_FromSocket_t(old_sockfd);
756     else
757         return PyLong_FromLong(-1);
758 #else
759     if (fd != -1) {
760         int blocking;
761 
762         if (_Py_fstat(fd, &status) != 0)
763             return NULL;
764 
765         blocking = _Py_get_blocking(fd);
766         if (blocking < 0)
767             return NULL;
768         if (blocking) {
769             _PyErr_Format(tstate, PyExc_ValueError,
770                           "the fd %i must be in non-blocking mode",
771                           fd);
772             return NULL;
773         }
774     }
775 
776     old_fd = wakeup.fd;
777     wakeup.fd = fd;
778     wakeup.warn_on_full_buffer = warn_on_full_buffer;
779 
780     return PyLong_FromLong(old_fd);
781 #endif
782 }
783 
784 PyDoc_STRVAR(set_wakeup_fd_doc,
785 "set_wakeup_fd(fd, *, warn_on_full_buffer=True) -> fd\n\
786 \n\
787 Sets the fd to be written to (with the signal number) when a signal\n\
788 comes in.  A library can use this to wakeup select or poll.\n\
789 The previous fd or -1 is returned.\n\
790 \n\
791 The fd must be non-blocking.");
792 
793 /* C API for the same, without all the error checking */
794 int
PySignal_SetWakeupFd(int fd)795 PySignal_SetWakeupFd(int fd)
796 {
797     int old_fd;
798     if (fd < 0)
799         fd = -1;
800 
801 #ifdef MS_WINDOWS
802     old_fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
803 #else
804     old_fd = wakeup.fd;
805 #endif
806     wakeup.fd = fd;
807     wakeup.warn_on_full_buffer = 1;
808     return old_fd;
809 }
810 
811 
812 #ifdef HAVE_SETITIMER
813 
814 /*[clinic input]
815 signal.setitimer
816 
817     which:    int
818     seconds:  object
819     interval: object(c_default="NULL") = 0.0
820     /
821 
822 Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF).
823 
824 The timer will fire after value seconds and after that every interval seconds.
825 The itimer can be cleared by setting seconds to zero.
826 
827 Returns old values as a tuple: (delay, interval).
828 [clinic start generated code]*/
829 
830 static PyObject *
signal_setitimer_impl(PyObject * module,int which,PyObject * seconds,PyObject * interval)831 signal_setitimer_impl(PyObject *module, int which, PyObject *seconds,
832                       PyObject *interval)
833 /*[clinic end generated code: output=65f9dcbddc35527b input=de43daf194e6f66f]*/
834 {
835     struct itimerval new, old;
836 
837     if (timeval_from_double(seconds, &new.it_value) < 0) {
838         return NULL;
839     }
840     if (timeval_from_double(interval, &new.it_interval) < 0) {
841         return NULL;
842     }
843 
844     /* Let OS check "which" value */
845     if (setitimer(which, &new, &old) != 0) {
846         PyErr_SetFromErrno(ItimerError);
847         return NULL;
848     }
849 
850     return itimer_retval(&old);
851 }
852 
853 #endif
854 
855 
856 #ifdef HAVE_GETITIMER
857 
858 /*[clinic input]
859 signal.getitimer
860 
861     which:    int
862     /
863 
864 Returns current value of given itimer.
865 [clinic start generated code]*/
866 
867 static PyObject *
signal_getitimer_impl(PyObject * module,int which)868 signal_getitimer_impl(PyObject *module, int which)
869 /*[clinic end generated code: output=9e053175d517db40 input=f7d21d38f3490627]*/
870 {
871     struct itimerval old;
872 
873     if (getitimer(which, &old) != 0) {
874         PyErr_SetFromErrno(ItimerError);
875         return NULL;
876     }
877 
878     return itimer_retval(&old);
879 }
880 
881 #endif
882 
883 #if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGPENDING)
884 static PyObject*
sigset_to_set(sigset_t mask)885 sigset_to_set(sigset_t mask)
886 {
887     PyObject *signum, *result;
888     int sig;
889 
890     result = PySet_New(0);
891     if (result == NULL)
892         return NULL;
893 
894     for (sig = 1; sig < NSIG; sig++) {
895         if (sigismember(&mask, sig) != 1)
896             continue;
897 
898         /* Handle the case where it is a member by adding the signal to
899            the result list.  Ignore the other cases because they mean the
900            signal isn't a member of the mask or the signal was invalid,
901            and an invalid signal must have been our fault in constructing
902            the loop boundaries. */
903         signum = PyLong_FromLong(sig);
904         if (signum == NULL) {
905             Py_DECREF(result);
906             return NULL;
907         }
908         if (PySet_Add(result, signum) == -1) {
909             Py_DECREF(signum);
910             Py_DECREF(result);
911             return NULL;
912         }
913         Py_DECREF(signum);
914     }
915     return result;
916 }
917 #endif
918 
919 #ifdef PYPTHREAD_SIGMASK
920 
921 /*[clinic input]
922 signal.pthread_sigmask
923 
924     how:  int
925     mask: sigset_t
926     /
927 
928 Fetch and/or change the signal mask of the calling thread.
929 [clinic start generated code]*/
930 
931 static PyObject *
signal_pthread_sigmask_impl(PyObject * module,int how,sigset_t mask)932 signal_pthread_sigmask_impl(PyObject *module, int how, sigset_t mask)
933 /*[clinic end generated code: output=0562c0fb192981a8 input=85bcebda442fa77f]*/
934 {
935     sigset_t previous;
936     int err;
937 
938     err = pthread_sigmask(how, &mask, &previous);
939     if (err != 0) {
940         errno = err;
941         PyErr_SetFromErrno(PyExc_OSError);
942         return NULL;
943     }
944 
945     /* if signals was unblocked, signal handlers have been called */
946     if (PyErr_CheckSignals())
947         return NULL;
948 
949     return sigset_to_set(previous);
950 }
951 
952 #endif   /* #ifdef PYPTHREAD_SIGMASK */
953 
954 
955 #ifdef HAVE_SIGPENDING
956 
957 /*[clinic input]
958 signal.sigpending
959 
960 Examine pending signals.
961 
962 Returns a set of signal numbers that are pending for delivery to
963 the calling thread.
964 [clinic start generated code]*/
965 
966 static PyObject *
signal_sigpending_impl(PyObject * module)967 signal_sigpending_impl(PyObject *module)
968 /*[clinic end generated code: output=53375ffe89325022 input=e0036c016f874e29]*/
969 {
970     int err;
971     sigset_t mask;
972     err = sigpending(&mask);
973     if (err)
974         return PyErr_SetFromErrno(PyExc_OSError);
975     return sigset_to_set(mask);
976 }
977 
978 #endif   /* #ifdef HAVE_SIGPENDING */
979 
980 
981 #ifdef HAVE_SIGWAIT
982 
983 /*[clinic input]
984 signal.sigwait
985 
986     sigset: sigset_t
987     /
988 
989 Wait for a signal.
990 
991 Suspend execution of the calling thread until the delivery of one of the
992 signals specified in the signal set sigset.  The function accepts the signal
993 and returns the signal number.
994 [clinic start generated code]*/
995 
996 static PyObject *
signal_sigwait_impl(PyObject * module,sigset_t sigset)997 signal_sigwait_impl(PyObject *module, sigset_t sigset)
998 /*[clinic end generated code: output=f43770699d682f96 input=a6fbd47b1086d119]*/
999 {
1000     int err, signum;
1001 
1002     Py_BEGIN_ALLOW_THREADS
1003     err = sigwait(&sigset, &signum);
1004     Py_END_ALLOW_THREADS
1005     if (err) {
1006         errno = err;
1007         return PyErr_SetFromErrno(PyExc_OSError);
1008     }
1009 
1010     return PyLong_FromLong(signum);
1011 }
1012 
1013 #endif   /* #ifdef HAVE_SIGWAIT */
1014 
1015 
1016 #if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)
1017 
1018 /*[clinic input]
1019 signal.valid_signals
1020 
1021 Return a set of valid signal numbers on this platform.
1022 
1023 The signal numbers returned by this function can be safely passed to
1024 functions like `pthread_sigmask`.
1025 [clinic start generated code]*/
1026 
1027 static PyObject *
signal_valid_signals_impl(PyObject * module)1028 signal_valid_signals_impl(PyObject *module)
1029 /*[clinic end generated code: output=1609cffbcfcf1314 input=86a3717ff25288f2]*/
1030 {
1031 #ifdef MS_WINDOWS
1032 #ifdef SIGBREAK
1033     PyObject *tup = Py_BuildValue("(iiiiiii)", SIGABRT, SIGBREAK, SIGFPE,
1034                                   SIGILL, SIGINT, SIGSEGV, SIGTERM);
1035 #else
1036     PyObject *tup = Py_BuildValue("(iiiiii)", SIGABRT, SIGFPE, SIGILL,
1037                                   SIGINT, SIGSEGV, SIGTERM);
1038 #endif
1039     if (tup == NULL) {
1040         return NULL;
1041     }
1042     PyObject *set = PySet_New(tup);
1043     Py_DECREF(tup);
1044     return set;
1045 #else
1046     sigset_t mask;
1047     if (sigemptyset(&mask) || sigfillset(&mask)) {
1048         return PyErr_SetFromErrno(PyExc_OSError);
1049     }
1050     return sigset_to_set(mask);
1051 #endif
1052 }
1053 
1054 #endif   /* #if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS) */
1055 
1056 
1057 #if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
1058 static int initialized;
1059 static PyStructSequence_Field struct_siginfo_fields[] = {
1060     {"si_signo",        "signal number"},
1061     {"si_code",         "signal code"},
1062     {"si_errno",        "errno associated with this signal"},
1063     {"si_pid",          "sending process ID"},
1064     {"si_uid",          "real user ID of sending process"},
1065     {"si_status",       "exit value or signal"},
1066     {"si_band",         "band event for SIGPOLL"},
1067     {0}
1068 };
1069 
1070 PyDoc_STRVAR(struct_siginfo__doc__,
1071 "struct_siginfo: Result from sigwaitinfo or sigtimedwait.\n\n\
1072 This object may be accessed either as a tuple of\n\
1073 (si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band),\n\
1074 or via the attributes si_signo, si_code, and so on.");
1075 
1076 static PyStructSequence_Desc struct_siginfo_desc = {
1077     "signal.struct_siginfo",           /* name */
1078     struct_siginfo__doc__,       /* doc */
1079     struct_siginfo_fields,       /* fields */
1080     7          /* n_in_sequence */
1081 };
1082 
1083 static PyTypeObject SiginfoType;
1084 
1085 static PyObject *
fill_siginfo(siginfo_t * si)1086 fill_siginfo(siginfo_t *si)
1087 {
1088     PyObject *result = PyStructSequence_New(&SiginfoType);
1089     if (!result)
1090         return NULL;
1091 
1092     PyStructSequence_SET_ITEM(result, 0, PyLong_FromLong((long)(si->si_signo)));
1093     PyStructSequence_SET_ITEM(result, 1, PyLong_FromLong((long)(si->si_code)));
1094 #ifdef __VXWORKS__
1095     PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(0L));
1096     PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(0L));
1097     PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(0L));
1098     PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(0L));
1099 #else
1100     PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si->si_errno)));
1101     PyStructSequence_SET_ITEM(result, 3, PyLong_FromPid(si->si_pid));
1102     PyStructSequence_SET_ITEM(result, 4, _PyLong_FromUid(si->si_uid));
1103     PyStructSequence_SET_ITEM(result, 5,
1104                                 PyLong_FromLong((long)(si->si_status)));
1105 #endif
1106 #ifdef HAVE_SIGINFO_T_SI_BAND
1107     PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(si->si_band));
1108 #else
1109     PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(0L));
1110 #endif
1111     if (PyErr_Occurred()) {
1112         Py_DECREF(result);
1113         return NULL;
1114     }
1115 
1116     return result;
1117 }
1118 #endif
1119 
1120 #ifdef HAVE_SIGWAITINFO
1121 
1122 /*[clinic input]
1123 signal.sigwaitinfo
1124 
1125     sigset: sigset_t
1126     /
1127 
1128 Wait synchronously until one of the signals in *sigset* is delivered.
1129 
1130 Returns a struct_siginfo containing information about the signal.
1131 [clinic start generated code]*/
1132 
1133 static PyObject *
signal_sigwaitinfo_impl(PyObject * module,sigset_t sigset)1134 signal_sigwaitinfo_impl(PyObject *module, sigset_t sigset)
1135 /*[clinic end generated code: output=1eb2f1fa236fdbca input=3d1a7e1f27fc664c]*/
1136 {
1137     siginfo_t si;
1138     int err;
1139     int async_err = 0;
1140 
1141     do {
1142         Py_BEGIN_ALLOW_THREADS
1143         err = sigwaitinfo(&sigset, &si);
1144         Py_END_ALLOW_THREADS
1145     } while (err == -1
1146              && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1147     if (err == -1)
1148         return (!async_err) ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
1149 
1150     return fill_siginfo(&si);
1151 }
1152 
1153 #endif   /* #ifdef HAVE_SIGWAITINFO */
1154 
1155 #ifdef HAVE_SIGTIMEDWAIT
1156 
1157 /*[clinic input]
1158 signal.sigtimedwait
1159 
1160     sigset: sigset_t
1161     timeout as timeout_obj: object
1162     /
1163 
1164 Like sigwaitinfo(), but with a timeout.
1165 
1166 The timeout is specified in seconds, with floating point numbers allowed.
1167 [clinic start generated code]*/
1168 
1169 static PyObject *
signal_sigtimedwait_impl(PyObject * module,sigset_t sigset,PyObject * timeout_obj)1170 signal_sigtimedwait_impl(PyObject *module, sigset_t sigset,
1171                          PyObject *timeout_obj)
1172 /*[clinic end generated code: output=59c8971e8ae18a64 input=87fd39237cf0b7ba]*/
1173 {
1174     struct timespec ts;
1175     siginfo_t si;
1176     int res;
1177     _PyTime_t timeout, deadline, monotonic;
1178 
1179     if (_PyTime_FromSecondsObject(&timeout,
1180                                   timeout_obj, _PyTime_ROUND_CEILING) < 0)
1181         return NULL;
1182 
1183     if (timeout < 0) {
1184         PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
1185         return NULL;
1186     }
1187 
1188     deadline = _PyTime_GetMonotonicClock() + timeout;
1189 
1190     do {
1191         if (_PyTime_AsTimespec(timeout, &ts) < 0)
1192             return NULL;
1193 
1194         Py_BEGIN_ALLOW_THREADS
1195         res = sigtimedwait(&sigset, &si, &ts);
1196         Py_END_ALLOW_THREADS
1197 
1198         if (res != -1)
1199             break;
1200 
1201         if (errno != EINTR) {
1202             if (errno == EAGAIN)
1203                 Py_RETURN_NONE;
1204             else
1205                 return PyErr_SetFromErrno(PyExc_OSError);
1206         }
1207 
1208         /* sigtimedwait() was interrupted by a signal (EINTR) */
1209         if (PyErr_CheckSignals())
1210             return NULL;
1211 
1212         monotonic = _PyTime_GetMonotonicClock();
1213         timeout = deadline - monotonic;
1214         if (timeout < 0)
1215             break;
1216     } while (1);
1217 
1218     return fill_siginfo(&si);
1219 }
1220 
1221 #endif   /* #ifdef HAVE_SIGTIMEDWAIT */
1222 
1223 
1224 #if defined(HAVE_PTHREAD_KILL)
1225 
1226 /*[clinic input]
1227 signal.pthread_kill
1228 
1229     thread_id:  unsigned_long(bitwise=True)
1230     signalnum:  int
1231     /
1232 
1233 Send a signal to a thread.
1234 [clinic start generated code]*/
1235 
1236 static PyObject *
signal_pthread_kill_impl(PyObject * module,unsigned long thread_id,int signalnum)1237 signal_pthread_kill_impl(PyObject *module, unsigned long thread_id,
1238                          int signalnum)
1239 /*[clinic end generated code: output=7629919b791bc27f input=1d901f2c7bb544ff]*/
1240 {
1241     int err;
1242 
1243     if (PySys_Audit("signal.pthread_kill", "ki", thread_id, signalnum) < 0) {
1244         return NULL;
1245     }
1246 
1247     err = pthread_kill((pthread_t)thread_id, signalnum);
1248     if (err != 0) {
1249         errno = err;
1250         PyErr_SetFromErrno(PyExc_OSError);
1251         return NULL;
1252     }
1253 
1254     /* the signal may have been send to the current thread */
1255     if (PyErr_CheckSignals())
1256         return NULL;
1257 
1258     Py_RETURN_NONE;
1259 }
1260 
1261 #endif   /* #if defined(HAVE_PTHREAD_KILL) */
1262 
1263 
1264 #if defined(__linux__) && defined(__NR_pidfd_send_signal)
1265 /*[clinic input]
1266 signal.pidfd_send_signal
1267 
1268     pidfd: int
1269     signalnum: int
1270     siginfo: object = None
1271     flags: int = 0
1272     /
1273 
1274 Send a signal to a process referred to by a pid file descriptor.
1275 [clinic start generated code]*/
1276 
1277 static PyObject *
signal_pidfd_send_signal_impl(PyObject * module,int pidfd,int signalnum,PyObject * siginfo,int flags)1278 signal_pidfd_send_signal_impl(PyObject *module, int pidfd, int signalnum,
1279                               PyObject *siginfo, int flags)
1280 /*[clinic end generated code: output=2d59f04a75d9cbdf input=2a6543a1f4ac2000]*/
1281 
1282 {
1283     if (siginfo != Py_None) {
1284         PyErr_SetString(PyExc_TypeError, "siginfo must be None");
1285         return NULL;
1286     }
1287     if (syscall(__NR_pidfd_send_signal, pidfd, signalnum, NULL, flags) < 0) {
1288         PyErr_SetFromErrno(PyExc_OSError);
1289         return NULL;
1290     }
1291     Py_RETURN_NONE;
1292 }
1293 #endif
1294 
1295 
1296 
1297 /* List of functions defined in the module -- some of the methoddefs are
1298    defined to nothing if the corresponding C function is not available. */
1299 static PyMethodDef signal_methods[] = {
1300     {"default_int_handler", signal_default_int_handler, METH_VARARGS, default_int_handler_doc},
1301     SIGNAL_ALARM_METHODDEF
1302     SIGNAL_SETITIMER_METHODDEF
1303     SIGNAL_GETITIMER_METHODDEF
1304     SIGNAL_SIGNAL_METHODDEF
1305     SIGNAL_RAISE_SIGNAL_METHODDEF
1306     SIGNAL_STRSIGNAL_METHODDEF
1307     SIGNAL_GETSIGNAL_METHODDEF
1308     {"set_wakeup_fd", (PyCFunction)(void(*)(void))signal_set_wakeup_fd, METH_VARARGS | METH_KEYWORDS, set_wakeup_fd_doc},
1309     SIGNAL_SIGINTERRUPT_METHODDEF
1310     SIGNAL_PAUSE_METHODDEF
1311     SIGNAL_PIDFD_SEND_SIGNAL_METHODDEF
1312     SIGNAL_PTHREAD_KILL_METHODDEF
1313     SIGNAL_PTHREAD_SIGMASK_METHODDEF
1314     SIGNAL_SIGPENDING_METHODDEF
1315     SIGNAL_SIGWAIT_METHODDEF
1316     SIGNAL_SIGWAITINFO_METHODDEF
1317     SIGNAL_SIGTIMEDWAIT_METHODDEF
1318 #if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)
1319     SIGNAL_VALID_SIGNALS_METHODDEF
1320 #endif
1321     {NULL, NULL}           /* sentinel */
1322 };
1323 
1324 
1325 PyDoc_STRVAR(module_doc,
1326 "This module provides mechanisms to use signal handlers in Python.\n\
1327 \n\
1328 Functions:\n\
1329 \n\
1330 alarm() -- cause SIGALRM after a specified time [Unix only]\n\
1331 setitimer() -- cause a signal (described below) after a specified\n\
1332                float time and the timer may restart then [Unix only]\n\
1333 getitimer() -- get current value of timer [Unix only]\n\
1334 signal() -- set the action for a given signal\n\
1335 getsignal() -- get the signal action for a given signal\n\
1336 pause() -- wait until a signal arrives [Unix only]\n\
1337 default_int_handler() -- default SIGINT handler\n\
1338 \n\
1339 signal constants:\n\
1340 SIG_DFL -- used to refer to the system default handler\n\
1341 SIG_IGN -- used to ignore the signal\n\
1342 NSIG -- number of defined signals\n\
1343 SIGINT, SIGTERM, etc. -- signal numbers\n\
1344 \n\
1345 itimer constants:\n\
1346 ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\
1347                expiration\n\
1348 ITIMER_VIRTUAL -- decrements only when the process is executing,\n\
1349                and delivers SIGVTALRM upon expiration\n\
1350 ITIMER_PROF -- decrements both when the process is executing and\n\
1351                when the system is executing on behalf of the process.\n\
1352                Coupled with ITIMER_VIRTUAL, this timer is usually\n\
1353                used to profile the time spent by the application\n\
1354                in user and kernel space. SIGPROF is delivered upon\n\
1355                expiration.\n\
1356 \n\n\
1357 *** IMPORTANT NOTICE ***\n\
1358 A signal handler function is called with two arguments:\n\
1359 the first is the signal number, the second is the interrupted stack frame.");
1360 
1361 static struct PyModuleDef signalmodule = {
1362     PyModuleDef_HEAD_INIT,
1363     "_signal",
1364     module_doc,
1365     -1,
1366     signal_methods,
1367     NULL,
1368     NULL,
1369     NULL,
1370     NULL
1371 };
1372 
1373 PyMODINIT_FUNC
PyInit__signal(void)1374 PyInit__signal(void)
1375 {
1376     PyObject *m, *d;
1377     int i;
1378 
1379     /* Create the module and add the functions */
1380     m = PyModule_Create(&signalmodule);
1381     if (m == NULL)
1382         return NULL;
1383 
1384 #if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
1385     if (!initialized) {
1386         if (PyStructSequence_InitType2(&SiginfoType, &struct_siginfo_desc) < 0)
1387             return NULL;
1388     }
1389     Py_INCREF((PyObject*) &SiginfoType);
1390     PyModule_AddObject(m, "struct_siginfo", (PyObject*) &SiginfoType);
1391     initialized = 1;
1392 #endif
1393 
1394     /* Add some symbolic constants to the module */
1395     d = PyModule_GetDict(m);
1396 
1397     DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL);
1398     if (!DefaultHandler ||
1399         PyDict_SetItemString(d, "SIG_DFL", DefaultHandler) < 0) {
1400         goto finally;
1401     }
1402 
1403     IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN);
1404     if (!IgnoreHandler ||
1405         PyDict_SetItemString(d, "SIG_IGN", IgnoreHandler) < 0) {
1406         goto finally;
1407     }
1408 
1409     if (PyModule_AddIntMacro(m, NSIG))
1410         goto finally;
1411 
1412 #ifdef SIG_BLOCK
1413     if (PyModule_AddIntMacro(m, SIG_BLOCK))
1414          goto finally;
1415 #endif
1416 #ifdef SIG_UNBLOCK
1417     if (PyModule_AddIntMacro(m, SIG_UNBLOCK))
1418          goto finally;
1419 #endif
1420 #ifdef SIG_SETMASK
1421     if (PyModule_AddIntMacro(m, SIG_SETMASK))
1422          goto finally;
1423 #endif
1424 
1425     IntHandler = PyDict_GetItemString(d, "default_int_handler");
1426     if (!IntHandler)
1427         goto finally;
1428     Py_INCREF(IntHandler);
1429 
1430     _Py_atomic_store_relaxed(&Handlers[0].tripped, 0);
1431     for (i = 1; i < NSIG; i++) {
1432         void (*t)(int);
1433         t = PyOS_getsig(i);
1434         _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1435         if (t == SIG_DFL)
1436             Handlers[i].func = DefaultHandler;
1437         else if (t == SIG_IGN)
1438             Handlers[i].func = IgnoreHandler;
1439         else
1440             Handlers[i].func = Py_None; /* None of our business */
1441         Py_INCREF(Handlers[i].func);
1442     }
1443     if (Handlers[SIGINT].func == DefaultHandler) {
1444         /* Install default int handler */
1445         Py_INCREF(IntHandler);
1446         Py_SETREF(Handlers[SIGINT].func, IntHandler);
1447         PyOS_setsig(SIGINT, signal_handler);
1448     }
1449 
1450 #ifdef SIGHUP
1451     if (PyModule_AddIntMacro(m, SIGHUP))
1452          goto finally;
1453 #endif
1454 #ifdef SIGINT
1455     if (PyModule_AddIntMacro(m, SIGINT))
1456          goto finally;
1457 #endif
1458 #ifdef SIGBREAK
1459     if (PyModule_AddIntMacro(m, SIGBREAK))
1460          goto finally;
1461 #endif
1462 #ifdef SIGQUIT
1463     if (PyModule_AddIntMacro(m, SIGQUIT))
1464          goto finally;
1465 #endif
1466 #ifdef SIGILL
1467     if (PyModule_AddIntMacro(m, SIGILL))
1468          goto finally;
1469 #endif
1470 #ifdef SIGTRAP
1471     if (PyModule_AddIntMacro(m, SIGTRAP))
1472          goto finally;
1473 #endif
1474 #ifdef SIGIOT
1475     if (PyModule_AddIntMacro(m, SIGIOT))
1476          goto finally;
1477 #endif
1478 #ifdef SIGABRT
1479     if (PyModule_AddIntMacro(m, SIGABRT))
1480          goto finally;
1481 #endif
1482 #ifdef SIGEMT
1483     if (PyModule_AddIntMacro(m, SIGEMT))
1484          goto finally;
1485 #endif
1486 #ifdef SIGFPE
1487     if (PyModule_AddIntMacro(m, SIGFPE))
1488          goto finally;
1489 #endif
1490 #ifdef SIGKILL
1491     if (PyModule_AddIntMacro(m, SIGKILL))
1492          goto finally;
1493 #endif
1494 #ifdef SIGBUS
1495     if (PyModule_AddIntMacro(m, SIGBUS))
1496          goto finally;
1497 #endif
1498 #ifdef SIGSEGV
1499     if (PyModule_AddIntMacro(m, SIGSEGV))
1500          goto finally;
1501 #endif
1502 #ifdef SIGSYS
1503     if (PyModule_AddIntMacro(m, SIGSYS))
1504          goto finally;
1505 #endif
1506 #ifdef SIGPIPE
1507     if (PyModule_AddIntMacro(m, SIGPIPE))
1508          goto finally;
1509 #endif
1510 #ifdef SIGALRM
1511     if (PyModule_AddIntMacro(m, SIGALRM))
1512          goto finally;
1513 #endif
1514 #ifdef SIGTERM
1515     if (PyModule_AddIntMacro(m, SIGTERM))
1516          goto finally;
1517 #endif
1518 #ifdef SIGUSR1
1519     if (PyModule_AddIntMacro(m, SIGUSR1))
1520          goto finally;
1521 #endif
1522 #ifdef SIGUSR2
1523     if (PyModule_AddIntMacro(m, SIGUSR2))
1524          goto finally;
1525 #endif
1526 #ifdef SIGCLD
1527     if (PyModule_AddIntMacro(m, SIGCLD))
1528          goto finally;
1529 #endif
1530 #ifdef SIGCHLD
1531     if (PyModule_AddIntMacro(m, SIGCHLD))
1532          goto finally;
1533 #endif
1534 #ifdef SIGPWR
1535     if (PyModule_AddIntMacro(m, SIGPWR))
1536          goto finally;
1537 #endif
1538 #ifdef SIGIO
1539     if (PyModule_AddIntMacro(m, SIGIO))
1540          goto finally;
1541 #endif
1542 #ifdef SIGURG
1543     if (PyModule_AddIntMacro(m, SIGURG))
1544          goto finally;
1545 #endif
1546 #ifdef SIGWINCH
1547     if (PyModule_AddIntMacro(m, SIGWINCH))
1548          goto finally;
1549 #endif
1550 #ifdef SIGPOLL
1551     if (PyModule_AddIntMacro(m, SIGPOLL))
1552          goto finally;
1553 #endif
1554 #ifdef SIGSTOP
1555     if (PyModule_AddIntMacro(m, SIGSTOP))
1556          goto finally;
1557 #endif
1558 #ifdef SIGTSTP
1559     if (PyModule_AddIntMacro(m, SIGTSTP))
1560          goto finally;
1561 #endif
1562 #ifdef SIGCONT
1563     if (PyModule_AddIntMacro(m, SIGCONT))
1564          goto finally;
1565 #endif
1566 #ifdef SIGTTIN
1567     if (PyModule_AddIntMacro(m, SIGTTIN))
1568          goto finally;
1569 #endif
1570 #ifdef SIGTTOU
1571     if (PyModule_AddIntMacro(m, SIGTTOU))
1572          goto finally;
1573 #endif
1574 #ifdef SIGVTALRM
1575     if (PyModule_AddIntMacro(m, SIGVTALRM))
1576          goto finally;
1577 #endif
1578 #ifdef SIGPROF
1579     if (PyModule_AddIntMacro(m, SIGPROF))
1580          goto finally;
1581 #endif
1582 #ifdef SIGXCPU
1583     if (PyModule_AddIntMacro(m, SIGXCPU))
1584          goto finally;
1585 #endif
1586 #ifdef SIGXFSZ
1587     if (PyModule_AddIntMacro(m, SIGXFSZ))
1588          goto finally;
1589 #endif
1590 #ifdef SIGRTMIN
1591     if (PyModule_AddIntMacro(m, SIGRTMIN))
1592          goto finally;
1593 #endif
1594 #ifdef SIGRTMAX
1595     if (PyModule_AddIntMacro(m, SIGRTMAX))
1596          goto finally;
1597 #endif
1598 #ifdef SIGINFO
1599     if (PyModule_AddIntMacro(m, SIGINFO))
1600          goto finally;
1601 #endif
1602 
1603 #ifdef ITIMER_REAL
1604     if (PyModule_AddIntMacro(m, ITIMER_REAL))
1605          goto finally;
1606 #endif
1607 #ifdef ITIMER_VIRTUAL
1608     if (PyModule_AddIntMacro(m, ITIMER_VIRTUAL))
1609          goto finally;
1610 #endif
1611 #ifdef ITIMER_PROF
1612     if (PyModule_AddIntMacro(m, ITIMER_PROF))
1613          goto finally;
1614 #endif
1615 
1616 #if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER)
1617     ItimerError = PyErr_NewException("signal.ItimerError",
1618             PyExc_OSError, NULL);
1619     if (!ItimerError ||
1620         PyDict_SetItemString(d, "ItimerError", ItimerError) < 0) {
1621         goto finally;
1622     }
1623 #endif
1624 
1625 #ifdef CTRL_C_EVENT
1626     if (PyModule_AddIntMacro(m, CTRL_C_EVENT))
1627          goto finally;
1628 #endif
1629 
1630 #ifdef CTRL_BREAK_EVENT
1631     if (PyModule_AddIntMacro(m, CTRL_BREAK_EVENT))
1632          goto finally;
1633 #endif
1634 
1635     if (PyErr_Occurred()) {
1636         Py_DECREF(m);
1637         m = NULL;
1638     }
1639 
1640   finally:
1641     return m;
1642 }
1643 
1644 static void
finisignal(void)1645 finisignal(void)
1646 {
1647     int i;
1648     PyObject *func;
1649 
1650     for (i = 1; i < NSIG; i++) {
1651         func = Handlers[i].func;
1652         _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1653         Handlers[i].func = NULL;
1654         if (func != NULL && func != Py_None &&
1655             func != DefaultHandler && func != IgnoreHandler)
1656             PyOS_setsig(i, SIG_DFL);
1657         Py_XDECREF(func);
1658     }
1659 
1660     Py_CLEAR(IntHandler);
1661     Py_CLEAR(DefaultHandler);
1662     Py_CLEAR(IgnoreHandler);
1663 #ifdef HAVE_GETITIMER
1664     Py_CLEAR(ItimerError);
1665 #endif
1666 }
1667 
1668 
1669 /* Declared in pyerrors.h */
1670 int
PyErr_CheckSignals(void)1671 PyErr_CheckSignals(void)
1672 {
1673     PyThreadState *tstate = _PyThreadState_GET();
1674     if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
1675         return 0;
1676     }
1677 
1678     return _PyErr_CheckSignalsTstate(tstate);
1679 }
1680 
1681 
1682 /* Declared in cpython/pyerrors.h */
1683 int
_PyErr_CheckSignalsTstate(PyThreadState * tstate)1684 _PyErr_CheckSignalsTstate(PyThreadState *tstate)
1685 {
1686     if (!_Py_atomic_load(&is_tripped)) {
1687         return 0;
1688     }
1689 
1690     /*
1691      * The is_tripped variable is meant to speed up the calls to
1692      * PyErr_CheckSignals (both directly or via pending calls) when no
1693      * signal has arrived. This variable is set to 1 when a signal arrives
1694      * and it is set to 0 here, when we know some signals arrived. This way
1695      * we can run the registered handlers with no signals blocked.
1696      *
1697      * NOTE: with this approach we can have a situation where is_tripped is
1698      *       1 but we have no more signals to handle (Handlers[i].tripped
1699      *       is 0 for every signal i). This won't do us any harm (except
1700      *       we're gonna spent some cycles for nothing). This happens when
1701      *       we receive a signal i after we zero is_tripped and before we
1702      *       check Handlers[i].tripped.
1703      */
1704     _Py_atomic_store(&is_tripped, 0);
1705 
1706     PyObject *frame = (PyObject *)tstate->frame;
1707     if (!frame) {
1708         frame = Py_None;
1709     }
1710 
1711     for (int i = 1; i < NSIG; i++) {
1712         if (!_Py_atomic_load_relaxed(&Handlers[i].tripped)) {
1713             continue;
1714         }
1715         _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1716 
1717         PyObject *arglist = Py_BuildValue("(iO)", i, frame);
1718         PyObject *result;
1719         if (arglist) {
1720             result = _PyObject_Call(tstate, Handlers[i].func, arglist, NULL);
1721             Py_DECREF(arglist);
1722         }
1723         else {
1724             result = NULL;
1725         }
1726         if (!result) {
1727             /* On error, re-schedule a call to _PyErr_CheckSignalsTstate() */
1728             _Py_atomic_store(&is_tripped, 1);
1729             return -1;
1730         }
1731 
1732         Py_DECREF(result);
1733     }
1734 
1735     return 0;
1736 }
1737 
1738 
1739 
1740 int
_PyErr_CheckSignals(void)1741 _PyErr_CheckSignals(void)
1742 {
1743     PyThreadState *tstate = _PyThreadState_GET();
1744     return _PyErr_CheckSignalsTstate(tstate);
1745 }
1746 
1747 
1748 /* Simulate the effect of a signal.SIGINT signal arriving. The next time
1749    PyErr_CheckSignals is called,  the Python SIGINT signal handler will be
1750    raised.
1751 
1752    Missing signal handler for the SIGINT signal is silently ignored. */
1753 void
PyErr_SetInterrupt(void)1754 PyErr_SetInterrupt(void)
1755 {
1756     if ((Handlers[SIGINT].func != IgnoreHandler) &&
1757         (Handlers[SIGINT].func != DefaultHandler)) {
1758         trip_signal(SIGINT);
1759     }
1760 }
1761 
1762 void
PyOS_InitInterrupts(void)1763 PyOS_InitInterrupts(void)
1764 {
1765     PyObject *m = PyImport_ImportModule("_signal");
1766     if (m) {
1767         Py_DECREF(m);
1768     }
1769 }
1770 
1771 
1772 static int
signal_install_handlers(void)1773 signal_install_handlers(void)
1774 {
1775 #ifdef SIGPIPE
1776     PyOS_setsig(SIGPIPE, SIG_IGN);
1777 #endif
1778 #ifdef SIGXFZ
1779     PyOS_setsig(SIGXFZ, SIG_IGN);
1780 #endif
1781 #ifdef SIGXFSZ
1782     PyOS_setsig(SIGXFSZ, SIG_IGN);
1783 #endif
1784 
1785     // Import _signal to install the Python SIGINT handler
1786     PyObject *module = PyImport_ImportModule("_signal");
1787     if (!module) {
1788         return -1;
1789     }
1790     Py_DECREF(module);
1791 
1792     return 0;
1793 }
1794 
1795 
1796 int
_PySignal_Init(int install_signal_handlers)1797 _PySignal_Init(int install_signal_handlers)
1798 {
1799 #ifdef MS_WINDOWS
1800     /* Create manual-reset event, initially unset */
1801     sigint_event = CreateEvent(NULL, TRUE, FALSE, FALSE);
1802     if (sigint_event == NULL) {
1803         PyErr_SetFromWindowsErr(0);
1804         return -1;
1805     }
1806 #endif
1807 
1808     if (install_signal_handlers) {
1809         if (signal_install_handlers() < 0) {
1810             return -1;
1811         }
1812     }
1813 
1814     return 0;
1815 }
1816 
1817 
1818 void
PyOS_FiniInterrupts(void)1819 PyOS_FiniInterrupts(void)
1820 {
1821     finisignal();
1822 }
1823 
1824 
1825 // The caller doesn't have to hold the GIL
1826 int
_PyOS_InterruptOccurred(PyThreadState * tstate)1827 _PyOS_InterruptOccurred(PyThreadState *tstate)
1828 {
1829     _Py_EnsureTstateNotNULL(tstate);
1830     if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
1831         return 0;
1832     }
1833 
1834     if (!_Py_atomic_load_relaxed(&Handlers[SIGINT].tripped)) {
1835         return 0;
1836     }
1837 
1838     _Py_atomic_store_relaxed(&Handlers[SIGINT].tripped, 0);
1839     return 1;
1840 }
1841 
1842 
1843 // The caller must to hold the GIL
1844 int
PyOS_InterruptOccurred(void)1845 PyOS_InterruptOccurred(void)
1846 {
1847     PyThreadState *tstate = _PyThreadState_GET();
1848     return _PyOS_InterruptOccurred(tstate);
1849 }
1850 
1851 
1852 static void
_clear_pending_signals(void)1853 _clear_pending_signals(void)
1854 {
1855     int i;
1856     if (!_Py_atomic_load(&is_tripped))
1857         return;
1858     _Py_atomic_store(&is_tripped, 0);
1859     for (i = 1; i < NSIG; ++i) {
1860         _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1861     }
1862 }
1863 
1864 void
_PySignal_AfterFork(void)1865 _PySignal_AfterFork(void)
1866 {
1867     /* Clear the signal flags after forking so that they aren't handled
1868      * in both processes if they came in just before the fork() but before
1869      * the interpreter had an opportunity to call the handlers.  issue9535. */
1870     _clear_pending_signals();
1871 }
1872 
1873 int
_PyOS_IsMainThread(void)1874 _PyOS_IsMainThread(void)
1875 {
1876     PyInterpreterState *interp = _PyInterpreterState_GET();
1877     return _Py_ThreadCanHandleSignals(interp);
1878 }
1879 
1880 #ifdef MS_WINDOWS
_PyOS_SigintEvent(void)1881 void *_PyOS_SigintEvent(void)
1882 {
1883     /* Returns a manual-reset event which gets tripped whenever
1884        SIGINT is received.
1885 
1886        Python.h does not include windows.h so we do cannot use HANDLE
1887        as the return type of this function.  We use void* instead. */
1888     return sigint_event;
1889 }
1890 #endif
1891