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