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