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