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