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