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