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