blob: 98a938f19767357840fce0fad5c0060b4bc8fc6e [file] [log] [blame]
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001
Guido van Rossum3bbc62e1995-01-02 19:30:30 +00002/* Signal module -- many thanks to Lance Ellinghaus */
Guido van Rossum398d9fe1994-05-11 08:59:13 +00003
Guido van Rossum644a12b1997-04-09 19:24:53 +00004/* XXX Signals should be recorded per thread, now we have thread state. */
5
Guido van Rossum602099a1994-09-14 13:32:22 +00006#include "Python.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01007#include "pycore_atomic.h"
Victor Stinner72818982020-03-26 22:28:11 +01008#include "pycore_call.h"
Victor Stinner09532fe2019-05-10 23:39:09 +02009#include "pycore_ceval.h"
Victor Stinner72818982020-03-26 22:28:11 +010010#include "pycore_pyerrors.h"
Antoine Pitrouba251c22021-03-11 23:35:45 +010011#include "pycore_pylifecycle.h"
Victor Stinnere5014be2020-04-14 17:52:15 +020012#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner31368a42018-10-30 15:14:25 +010013
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020014#ifndef MS_WINDOWS
15#include "posixmodule.h"
16#endif
Victor Stinner11517102014-07-29 23:31:34 +020017#ifdef MS_WINDOWS
18#include "socketmodule.h" /* needed for SOCKET_T */
19#endif
Guido van Rossum398d9fe1994-05-11 08:59:13 +000020
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000021#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +020022#include <windows.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000023#ifdef HAVE_PROCESS_H
Guido van Rossum644a12b1997-04-09 19:24:53 +000024#include <process.h>
25#endif
Benjamin Peterson2614cda2010-03-21 22:36:19 +000026#endif
Guido van Rossum644a12b1997-04-09 19:24:53 +000027
Benjamin Peterson2614cda2010-03-21 22:36:19 +000028#ifdef HAVE_SIGNAL_H
Guido van Rossum398d9fe1994-05-11 08:59:13 +000029#include <signal.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000030#endif
Benjamin Peterson74834512019-11-19 20:39:14 -080031#ifdef HAVE_SYS_SYSCALL_H
32#include <sys/syscall.h>
33#endif
Benjamin Peterson2614cda2010-03-21 22:36:19 +000034#ifdef HAVE_SYS_STAT_H
Christian Heimes5fb7c2a2007-12-24 08:52:31 +000035#include <sys/stat.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000036#endif
Martin v. Löwis3bf3cc02008-03-24 14:05:07 +000037#ifdef HAVE_SYS_TIME_H
Martin v. Löwis823725e2008-03-24 13:39:54 +000038#include <sys/time.h>
Martin v. Löwis3bf3cc02008-03-24 14:05:07 +000039#endif
Christian Heimes5fb7c2a2007-12-24 08:52:31 +000040
Victor Stinnera9293352011-04-30 15:21:58 +020041#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
42# define PYPTHREAD_SIGMASK
43#endif
44
45#if defined(PYPTHREAD_SIGMASK) && defined(HAVE_PTHREAD_H)
46# include <pthread.h>
47#endif
48
Guido van Rossumbb4ba121994-06-23 11:25:45 +000049#ifndef SIG_ERR
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +000050#define SIG_ERR ((PyOS_sighandler_t)(-1))
Guido van Rossumbb4ba121994-06-23 11:25:45 +000051#endif
52
Tal Einatc7027b72015-05-16 14:14:49 +030053#include "clinic/signalmodule.c.h"
54
55/*[clinic input]
56module signal
57[clinic start generated code]*/
58/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b0301a3bde5fe9d3]*/
59
Serhiy Storchakad54cfb12018-05-08 07:48:50 +030060/*[python input]
61
62class sigset_t_converter(CConverter):
63 type = 'sigset_t'
64 converter = '_Py_Sigset_Converter'
65
66[python start generated code]*/
67/*[python end generated code: output=da39a3ee5e6b4b0d input=b5689d14466b6823]*/
Guido van Rossum3bbc62e1995-01-02 19:30:30 +000068
Guido van Rossumbb4ba121994-06-23 11:25:45 +000069/*
70 NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS
71
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +020072 We want the following semantics:
Guido van Rossumbb4ba121994-06-23 11:25:45 +000073
74 - only the main thread can set a signal handler
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +020075 - only the main thread runs the signal handler
76 - signals can be delivered to any thread
Guido van Rossumbb4ba121994-06-23 11:25:45 +000077 - any thread can get a signal handler
Guido van Rossumbb4ba121994-06-23 11:25:45 +000078
79 I.e. we don't support "synchronous signals" like SIGFPE (catching
80 this doesn't make much sense in Python anyway) nor do we support
81 signals as a means of inter-thread communication, since not all
82 thread implementations support that (at least our thread library
83 doesn't).
84
85 We still have the problem that in some implementations signals
86 generated by the keyboard (e.g. SIGINT) are delivered to all
87 threads (e.g. SGI), while in others (e.g. Solaris) such signals are
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +020088 delivered to one random thread. On Linux, signals are delivered to
89 the main thread (unless the main thread is blocking the signal, for
90 example because it's already handling the same signal). Since we
91 allow signals to be delivered to any thread, this works fine. The
92 only oddity is that the thread executing the Python signal handler
93 may not be the thread that received the signal.
Guido van Rossumbb4ba121994-06-23 11:25:45 +000094*/
95
Victor Stinner2ec6b172011-05-15 10:21:59 +020096static volatile struct {
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +020097 _Py_atomic_int tripped;
Antoine Pitrouba251c22021-03-11 23:35:45 +010098 /* func is atomic to ensure that PyErr_SetInterrupt is async-signal-safe
99 * (even though it would probably be otherwise, anyway).
100 */
101 _Py_atomic_address func;
Barry Warsaw92971171997-01-03 00:14:25 +0000102} Handlers[NSIG];
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000103
Victor Stinner11517102014-07-29 23:31:34 +0200104#ifdef MS_WINDOWS
105#define INVALID_FD ((SOCKET_T)-1)
106
107static volatile struct {
108 SOCKET_T fd;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800109 int warn_on_full_buffer;
Victor Stinner11517102014-07-29 23:31:34 +0200110 int use_send;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800111} wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1, .use_send = 0};
Victor Stinner11517102014-07-29 23:31:34 +0200112#else
113#define INVALID_FD (-1)
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800114static volatile struct {
pxinwr1244c812020-12-01 05:48:33 +0800115#ifdef __VXWORKS__
116 int fd;
117#else
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800118 sig_atomic_t fd;
pxinwr1244c812020-12-01 05:48:33 +0800119#endif
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800120 int warn_on_full_buffer;
121} wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1};
Victor Stinner11517102014-07-29 23:31:34 +0200122#endif
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000123
Christian Heimesb76922a2007-12-11 01:06:40 +0000124/* Speed up sigcheck() when none tripped */
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200125static _Py_atomic_int is_tripped;
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000126
Barry Warsaw92971171997-01-03 00:14:25 +0000127static PyObject *DefaultHandler;
128static PyObject *IgnoreHandler;
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000129
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100130#ifdef MS_WINDOWS
131static HANDLE sigint_event = NULL;
132#endif
133
Victor Stinner0ae323b2020-11-17 18:15:20 +0100134#if defined(HAVE_GETITIMER) || defined(HAVE_SETITIMER)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000135static PyObject *ItimerError;
Victor Stinner0ae323b2020-11-17 18:15:20 +0100136#endif
Martin v. Löwis823725e2008-03-24 13:39:54 +0000137
Antoine Pitrouba251c22021-03-11 23:35:45 +0100138Py_LOCAL_INLINE(PyObject *)
139get_handler(int i) {
140 return (PyObject *)_Py_atomic_load(&Handlers[i].func);
141}
142
143Py_LOCAL_INLINE(void)
144SetHandler(int i, PyObject* func) {
145 _Py_atomic_store(&Handlers[i].func, (uintptr_t)func);
146}
147
Victor Stinner0ae323b2020-11-17 18:15:20 +0100148#ifdef HAVE_GETITIMER
Victor Stinneref611c92017-10-13 13:49:43 -0700149/* auxiliary functions for setitimer */
150static int
151timeval_from_double(PyObject *obj, struct timeval *tv)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000152{
Victor Stinneref611c92017-10-13 13:49:43 -0700153 if (obj == NULL) {
154 tv->tv_sec = 0;
155 tv->tv_usec = 0;
156 return 0;
Antoine Pitrou729780a2017-06-30 10:01:05 +0200157 }
Victor Stinneref611c92017-10-13 13:49:43 -0700158
159 _PyTime_t t;
160 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_CEILING) < 0) {
161 return -1;
162 }
163 return _PyTime_AsTimeval(t, tv, _PyTime_ROUND_CEILING);
Martin v. Löwis823725e2008-03-24 13:39:54 +0000164}
165
Christian Heimes1a8501c2008-10-02 19:56:01 +0000166Py_LOCAL_INLINE(double)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000167double_from_timeval(struct timeval *tv)
168{
169 return tv->tv_sec + (double)(tv->tv_usec / 1000000.0);
170}
171
172static PyObject *
173itimer_retval(struct itimerval *iv)
174{
175 PyObject *r, *v;
176
177 r = PyTuple_New(2);
178 if (r == NULL)
Martin Panter6d57fe12016-09-17 03:26:16 +0000179 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000180
181 if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
Martin Panter6d57fe12016-09-17 03:26:16 +0000182 Py_DECREF(r);
183 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000184 }
185
186 PyTuple_SET_ITEM(r, 0, v);
187
188 if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) {
Martin Panter6d57fe12016-09-17 03:26:16 +0000189 Py_DECREF(r);
190 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000191 }
192
193 PyTuple_SET_ITEM(r, 1, v);
194
195 return r;
196}
197#endif
Barry Warsaw92971171997-01-03 00:14:25 +0000198
Serhiy Storchakab0689ae2020-07-12 19:15:20 +0300199/*[clinic input]
200signal.default_int_handler
201 signalnum: int
202 frame: object
203 /
204
205The default handler for SIGINT installed by Python.
206
207It raises KeyboardInterrupt.
208[clinic start generated code]*/
209
Guido van Rossume4485b01994-09-07 14:32:49 +0000210static PyObject *
Serhiy Storchakab0689ae2020-07-12 19:15:20 +0300211signal_default_int_handler_impl(PyObject *module, int signalnum,
212 PyObject *frame)
213/*[clinic end generated code: output=bb11c2eb115ace4e input=efcd4a56a207acfd]*/
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 PyErr_SetNone(PyExc_KeyboardInterrupt);
216 return NULL;
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000217}
218
Thomas Wouters0796b002000-07-22 23:49:30 +0000219
220static int
Victor Stinner11517102014-07-29 23:31:34 +0200221report_wakeup_write_error(void *data)
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200222{
Eric Snowfdf282d2019-01-11 14:26:55 -0700223 PyObject *exc, *val, *tb;
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200224 int save_errno = errno;
Benjamin Petersonca470632016-09-06 13:47:26 -0700225 errno = (int) (intptr_t) data;
Eric Snowfdf282d2019-01-11 14:26:55 -0700226 PyErr_Fetch(&exc, &val, &tb);
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200227 PyErr_SetFromErrno(PyExc_OSError);
228 PySys_WriteStderr("Exception ignored when trying to write to the "
229 "signal wakeup fd:\n");
230 PyErr_WriteUnraisable(NULL);
Eric Snowfdf282d2019-01-11 14:26:55 -0700231 PyErr_Restore(exc, val, tb);
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200232 errno = save_errno;
233 return 0;
234}
235
Victor Stinner11517102014-07-29 23:31:34 +0200236#ifdef MS_WINDOWS
237static int
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800238report_wakeup_send_error(void* data)
Victor Stinner11517102014-07-29 23:31:34 +0200239{
Eric Snowfdf282d2019-01-11 14:26:55 -0700240 PyObject *exc, *val, *tb;
241 PyErr_Fetch(&exc, &val, &tb);
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800242 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
243 recognizes the error codes used by both GetLastError() and
244 WSAGetLastError */
245 PyErr_SetExcFromWindowsErr(PyExc_OSError, (int) (intptr_t) data);
Victor Stinner11517102014-07-29 23:31:34 +0200246 PySys_WriteStderr("Exception ignored when trying to send to the "
247 "signal wakeup fd:\n");
248 PyErr_WriteUnraisable(NULL);
Eric Snowfdf282d2019-01-11 14:26:55 -0700249 PyErr_Restore(exc, val, tb);
Victor Stinner11517102014-07-29 23:31:34 +0200250 return 0;
251}
252#endif /* MS_WINDOWS */
253
Tim Peters4f1b2082000-07-23 21:18:09 +0000254static void
Victor Stinner6c9b35b2011-04-18 16:25:56 +0200255trip_signal(int sig_num)
256{
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200257 _Py_atomic_store_relaxed(&Handlers[sig_num].tripped, 1);
Victor Stinner11517102014-07-29 23:31:34 +0200258
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200259 /* Set is_tripped after setting .tripped, as it gets
260 cleared in PyErr_CheckSignals() before .tripped. */
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200261 _Py_atomic_store(&is_tripped, 1);
262
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200263 /* Signals are always handled by the main interpreter */
264 PyInterpreterState *interp = _PyRuntime.interpreters.main;
Victor Stinner8849e592020-03-18 19:28:53 +0100265
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200266 /* Notify ceval.c */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200267 _PyEval_SignalReceived(interp);
Nathaniel J. Smith4ae01492017-05-16 14:12:11 -0700268
269 /* And then write to the wakeup fd *after* setting all the globals and
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200270 doing the _PyEval_SignalReceived. We used to write to the wakeup fd
271 and then set the flag, but this allowed the following sequence of events
272 (especially on windows, where trip_signal may run in a new thread):
Nathaniel J. Smith4ae01492017-05-16 14:12:11 -0700273
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800274 - main thread blocks on select([wakeup.fd], ...)
Nathaniel J. Smith4ae01492017-05-16 14:12:11 -0700275 - signal arrives
276 - trip_signal writes to the wakeup fd
277 - the main thread wakes up
278 - the main thread checks the signal flags, sees that they're unset
279 - the main thread empties the wakeup fd
280 - the main thread goes back to sleep
281 - trip_signal sets the flags to request the Python-level signal handler
282 be run
283 - the main thread doesn't notice, because it's asleep
284
285 See bpo-30038 for more details.
286 */
287
Victor Stinnercda23be2020-11-17 18:57:32 +0100288 int fd;
Victor Stinner11517102014-07-29 23:31:34 +0200289#ifdef MS_WINDOWS
290 fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
291#else
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800292 fd = wakeup.fd;
Victor Stinner11517102014-07-29 23:31:34 +0200293#endif
294
295 if (fd != INVALID_FD) {
Victor Stinnercda23be2020-11-17 18:57:32 +0100296 unsigned char byte = (unsigned char)sig_num;
Victor Stinner11517102014-07-29 23:31:34 +0200297#ifdef MS_WINDOWS
298 if (wakeup.use_send) {
Victor Stinnercda23be2020-11-17 18:57:32 +0100299 Py_ssize_t rc = send(fd, &byte, 1, 0);
Victor Stinner11517102014-07-29 23:31:34 +0200300
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800301 if (rc < 0) {
302 int last_error = GetLastError();
303 if (wakeup.warn_on_full_buffer ||
304 last_error != WSAEWOULDBLOCK)
305 {
Victor Stinner50e6e992020-03-19 02:41:21 +0100306 /* _PyEval_AddPendingCall() isn't signal-safe, but we
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800307 still use it for this exceptional case. */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200308 _PyEval_AddPendingCall(interp,
Victor Stinner09532fe2019-05-10 23:39:09 +0200309 report_wakeup_send_error,
310 (void *)(intptr_t) last_error);
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800311 }
Victor Stinner11517102014-07-29 23:31:34 +0200312 }
313 }
314 else
315#endif
316 {
Victor Stinnere72fe392015-04-01 18:35:22 +0200317 /* _Py_write_noraise() retries write() if write() is interrupted by
318 a signal (fails with EINTR). */
Victor Stinnercda23be2020-11-17 18:57:32 +0100319 Py_ssize_t rc = _Py_write_noraise(fd, &byte, 1);
Victor Stinner11517102014-07-29 23:31:34 +0200320
321 if (rc < 0) {
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800322 if (wakeup.warn_on_full_buffer ||
323 (errno != EWOULDBLOCK && errno != EAGAIN))
324 {
Victor Stinner50e6e992020-03-19 02:41:21 +0100325 /* _PyEval_AddPendingCall() isn't signal-safe, but we
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800326 still use it for this exceptional case. */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200327 _PyEval_AddPendingCall(interp,
Victor Stinner09532fe2019-05-10 23:39:09 +0200328 report_wakeup_write_error,
329 (void *)(intptr_t)errno);
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800330 }
Victor Stinner11517102014-07-29 23:31:34 +0200331 }
332 }
Victor Stinnerc13ef662011-05-25 02:35:58 +0200333 }
Victor Stinner6c9b35b2011-04-18 16:25:56 +0200334}
335
336static void
Peter Schneider-Kampe89b1562000-07-10 12:04:18 +0000337signal_handler(int sig_num)
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000338{
Antoine Pitrou39a65912010-11-05 19:47:27 +0000339 int save_errno = errno;
340
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +0200341 trip_signal(sig_num);
Antoine Pitrou39a65912010-11-05 19:47:27 +0000342
Jean-Paul Calderone6f137ca2010-05-09 03:18:57 +0000343#ifndef HAVE_SIGACTION
Antoine Pitrou39a65912010-11-05 19:47:27 +0000344#ifdef SIGCHLD
345 /* To avoid infinite recursion, this signal remains
346 reset until explicit re-instated.
347 Don't clear the 'func' field as it is our pointer
348 to the Python handler... */
349 if (sig_num != SIGCHLD)
350#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* If the handler was not set up with sigaction, reinstall it. See
Nick Coghland6009512014-11-20 21:39:37 +1000352 * Python/pylifecycle.c for the implementation of PyOS_setsig which
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 * makes this true. See also issue8354. */
354 PyOS_setsig(sig_num, signal_handler);
Jean-Paul Calderone6f137ca2010-05-09 03:18:57 +0000355#endif
Antoine Pitrou39a65912010-11-05 19:47:27 +0000356
357 /* Issue #10311: asynchronously executing signal handlers should not
358 mutate errno under the feet of unsuspecting C code. */
359 errno = save_errno;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100360
361#ifdef MS_WINDOWS
362 if (sig_num == SIGINT)
363 SetEvent(sigint_event);
364#endif
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000365}
Guido van Rossume4485b01994-09-07 14:32:49 +0000366
Guido van Rossum06d511d1995-03-10 15:13:48 +0000367
Guido van Rossum1171ee61997-08-22 20:42:00 +0000368#ifdef HAVE_ALARM
Tal Einatc7027b72015-05-16 14:14:49 +0300369
370/*[clinic input]
371signal.alarm -> long
372
373 seconds: int
374 /
375
376Arrange for SIGALRM to arrive after the given number of seconds.
377[clinic start generated code]*/
378
379static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300380signal_alarm_impl(PyObject *module, int seconds)
381/*[clinic end generated code: output=144232290814c298 input=0d5e97e0e6f39e86]*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 /* alarm() returns the number of seconds remaining */
Tal Einatc7027b72015-05-16 14:14:49 +0300384 return (long)alarm(seconds);
Guido van Rossumaa0f4c71994-08-23 13:49:37 +0000385}
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +0000386
Guido van Rossum06d511d1995-03-10 15:13:48 +0000387#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000388
Guido van Rossum1171ee61997-08-22 20:42:00 +0000389#ifdef HAVE_PAUSE
Tal Einatc7027b72015-05-16 14:14:49 +0300390
391/*[clinic input]
392signal.pause
393
394Wait until a signal arrives.
395[clinic start generated code]*/
396
Guido van Rossuma597dde1995-01-10 20:56:29 +0000397static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300398signal_pause_impl(PyObject *module)
399/*[clinic end generated code: output=391656788b3c3929 input=f03de0f875752062]*/
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_BEGIN_ALLOW_THREADS
402 (void)pause();
403 Py_END_ALLOW_THREADS
404 /* make sure that any exceptions that got raised are propagated
405 * back into Python
406 */
407 if (PyErr_CheckSignals())
408 return NULL;
Barry Warsaw92971171997-01-03 00:14:25 +0000409
Tal Einatc7027b72015-05-16 14:14:49 +0300410 Py_RETURN_NONE;
Guido van Rossume4485b01994-09-07 14:32:49 +0000411}
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +0000412
Guido van Rossum06d511d1995-03-10 15:13:48 +0000413#endif
Guido van Rossume4485b01994-09-07 14:32:49 +0000414
Vladimir Matveevc24c6c22019-01-08 01:58:25 -0800415/*[clinic input]
416signal.raise_signal
417
418 signalnum: int
419 /
420
421Send a signal to the executing process.
422[clinic start generated code]*/
423
424static PyObject *
425signal_raise_signal_impl(PyObject *module, int signalnum)
426/*[clinic end generated code: output=e2b014220aa6111d input=e90c0f9a42358de6]*/
427{
428 int err;
429 Py_BEGIN_ALLOW_THREADS
430 _Py_BEGIN_SUPPRESS_IPH
431 err = raise(signalnum);
432 _Py_END_SUPPRESS_IPH
433 Py_END_ALLOW_THREADS
Victor Stinner09532fe2019-05-10 23:39:09 +0200434
Vladimir Matveevc24c6c22019-01-08 01:58:25 -0800435 if (err) {
436 return PyErr_SetFromErrno(PyExc_OSError);
437 }
438 Py_RETURN_NONE;
439}
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +0000440
Tal Einatc7027b72015-05-16 14:14:49 +0300441/*[clinic input]
442signal.signal
443
444 signalnum: int
445 handler: object
446 /
447
448Set the action for the given signal.
449
450The action can be SIG_DFL, SIG_IGN, or a callable Python object.
451The previous action is returned. See getsignal() for possible return values.
452
453*** IMPORTANT NOTICE ***
454A signal handler function is called with two arguments:
455the first is the signal number, the second is the interrupted stack frame.
456[clinic start generated code]*/
457
Guido van Rossume4485b01994-09-07 14:32:49 +0000458static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300459signal_signal_impl(PyObject *module, int signalnum, PyObject *handler)
460/*[clinic end generated code: output=b44cfda43780f3a1 input=deee84af5fa0432c]*/
Guido van Rossume4485b01994-09-07 14:32:49 +0000461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PyObject *old_handler;
463 void (*func)(int);
Brian Curtinef9efbd2010-08-06 19:27:32 +0000464#ifdef MS_WINDOWS
Tal Einatc7027b72015-05-16 14:14:49 +0300465 /* Validate that signalnum is one of the allowable signals */
466 switch (signalnum) {
Brian Curtinc734b312010-09-06 16:04:10 +0000467 case SIGABRT: break;
Brian Curtin9e88b5a2010-10-01 14:49:24 +0000468#ifdef SIGBREAK
469 /* Issue #10003: SIGBREAK is not documented as permitted, but works
470 and corresponds to CTRL_BREAK_EVENT. */
471 case SIGBREAK: break;
472#endif
Brian Curtinc734b312010-09-06 16:04:10 +0000473 case SIGFPE: break;
474 case SIGILL: break;
475 case SIGINT: break;
476 case SIGSEGV: break;
477 case SIGTERM: break;
478 default:
479 PyErr_SetString(PyExc_ValueError, "invalid signal value");
480 return NULL;
Brian Curtinef9efbd2010-08-06 19:27:32 +0000481 }
482#endif
Victor Stinnerd8613dc2019-05-24 13:43:55 +0200483
Victor Stinner72818982020-03-26 22:28:11 +0100484 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200485 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Victor Stinner72818982020-03-26 22:28:11 +0100486 _PyErr_SetString(tstate, PyExc_ValueError,
487 "signal only works in main thread "
488 "of the main interpreter");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 return NULL;
490 }
Tal Einatc7027b72015-05-16 14:14:49 +0300491 if (signalnum < 1 || signalnum >= NSIG) {
Victor Stinner72818982020-03-26 22:28:11 +0100492 _PyErr_SetString(tstate, PyExc_ValueError,
493 "signal number out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return NULL;
495 }
Victor Stinner72818982020-03-26 22:28:11 +0100496 if (handler == IgnoreHandler) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 func = SIG_IGN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 }
Victor Stinner72818982020-03-26 22:28:11 +0100499 else if (handler == DefaultHandler) {
500 func = SIG_DFL;
501 }
502 else if (!PyCallable_Check(handler)) {
503 _PyErr_SetString(tstate, PyExc_TypeError,
504 "signal handler must be signal.SIG_IGN, "
505 "signal.SIG_DFL, or a callable object");
506 return NULL;
507 }
508 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 func = signal_handler;
Victor Stinner72818982020-03-26 22:28:11 +0100510 }
511
Antoine Pitrouf6f90ff2017-11-03 19:58:46 +0100512 /* Check for pending signals before changing signal handler */
Victor Stinner72818982020-03-26 22:28:11 +0100513 if (_PyErr_CheckSignalsTstate(tstate)) {
Antoine Pitrouf6f90ff2017-11-03 19:58:46 +0100514 return NULL;
515 }
Tal Einatc7027b72015-05-16 14:14:49 +0300516 if (PyOS_setsig(signalnum, func) == SIG_ERR) {
Victor Stinner388196e2011-05-10 17:13:00 +0200517 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return NULL;
519 }
Victor Stinner72818982020-03-26 22:28:11 +0100520
Antoine Pitrouba251c22021-03-11 23:35:45 +0100521 old_handler = get_handler(signalnum);
522 SetHandler(signalnum, Py_NewRef(handler));
Victor Stinner72818982020-03-26 22:28:11 +0100523
524 if (old_handler != NULL) {
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200525 return old_handler;
Victor Stinner72818982020-03-26 22:28:11 +0100526 }
527 else {
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200528 Py_RETURN_NONE;
Victor Stinner72818982020-03-26 22:28:11 +0100529 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000530}
531
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +0000532
Tal Einatc7027b72015-05-16 14:14:49 +0300533/*[clinic input]
534signal.getsignal
535
536 signalnum: int
537 /
538
539Return the current action for the given signal.
540
541The return value can be:
542 SIG_IGN -- if the signal is being ignored
543 SIG_DFL -- if the default action for the signal is in effect
544 None -- if an unknown handler is in effect
545 anything else -- the callable Python object used as a handler
546[clinic start generated code]*/
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +0000547
Guido van Rossume4485b01994-09-07 14:32:49 +0000548static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300549signal_getsignal_impl(PyObject *module, int signalnum)
550/*[clinic end generated code: output=35b3e0e796fd555e input=ac23a00f19dfa509]*/
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyObject *old_handler;
Tal Einatc7027b72015-05-16 14:14:49 +0300553 if (signalnum < 1 || signalnum >= NSIG) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 PyErr_SetString(PyExc_ValueError,
555 "signal number out of range");
556 return NULL;
557 }
Antoine Pitrouba251c22021-03-11 23:35:45 +0100558 old_handler = get_handler(signalnum);
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200559 if (old_handler != NULL) {
Victor Stinnercda23be2020-11-17 18:57:32 +0100560 return Py_NewRef(old_handler);
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200561 }
562 else {
563 Py_RETURN_NONE;
564 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000565}
566
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100567
568/*[clinic input]
569signal.strsignal
570
571 signalnum: int
572 /
573
574Return the system description of the given signal.
575
576The return values can be such as "Interrupt", "Segmentation fault", etc.
577Returns None if the signal is not recognized.
578[clinic start generated code]*/
579
580static PyObject *
581signal_strsignal_impl(PyObject *module, int signalnum)
582/*[clinic end generated code: output=44e12e1e3b666261 input=b77914b03f856c74]*/
583{
584 char *res;
585
586 if (signalnum < 1 || signalnum >= NSIG) {
587 PyErr_SetString(PyExc_ValueError,
588 "signal number out of range");
589 return NULL;
590 }
591
Michael Osipov48ce4892018-08-23 15:27:19 +0200592#ifndef HAVE_STRSIGNAL
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100593 switch (signalnum) {
Michael Osipov48ce4892018-08-23 15:27:19 +0200594 /* Though being a UNIX, HP-UX does not provide strsignal(3). */
595#ifndef MS_WINDOWS
596 case SIGHUP:
597 res = "Hangup";
598 break;
599 case SIGALRM:
600 res = "Alarm clock";
601 break;
602 case SIGPIPE:
603 res = "Broken pipe";
604 break;
605 case SIGQUIT:
606 res = "Quit";
607 break;
608 case SIGCHLD:
609 res = "Child exited";
610 break;
611#endif
612 /* Custom redefinition of POSIX signals allowed on Windows. */
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100613 case SIGINT:
614 res = "Interrupt";
615 break;
616 case SIGILL:
617 res = "Illegal instruction";
618 break;
619 case SIGABRT:
620 res = "Aborted";
621 break;
622 case SIGFPE:
623 res = "Floating point exception";
624 break;
625 case SIGSEGV:
626 res = "Segmentation fault";
627 break;
628 case SIGTERM:
629 res = "Terminated";
630 break;
631 default:
632 Py_RETURN_NONE;
633 }
634#else
635 errno = 0;
636 res = strsignal(signalnum);
637
638 if (errno || res == NULL || strstr(res, "Unknown signal") != NULL)
639 Py_RETURN_NONE;
640#endif
641
642 return Py_BuildValue("s", res);
643}
644
Christian Heimes8640e742008-02-23 16:23:06 +0000645#ifdef HAVE_SIGINTERRUPT
Tal Einatc7027b72015-05-16 14:14:49 +0300646
647/*[clinic input]
648signal.siginterrupt
649
650 signalnum: int
651 flag: int
652 /
653
654Change system call restart behaviour.
655
656If flag is False, system calls will be restarted when interrupted by
657signal sig, else system calls will be interrupted.
658[clinic start generated code]*/
Christian Heimes8640e742008-02-23 16:23:06 +0000659
660static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300661signal_siginterrupt_impl(PyObject *module, int signalnum, int flag)
662/*[clinic end generated code: output=063816243d85dd19 input=4160acacca3e2099]*/
Christian Heimes8640e742008-02-23 16:23:06 +0000663{
Tal Einatc7027b72015-05-16 14:14:49 +0300664 if (signalnum < 1 || signalnum >= NSIG) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 PyErr_SetString(PyExc_ValueError,
666 "signal number out of range");
667 return NULL;
668 }
Pablo Galindof9c5e3f2020-09-02 15:29:12 +0100669#ifdef HAVE_SIGACTION
670 struct sigaction act;
671 (void) sigaction(signalnum, NULL, &act);
672 if (flag) {
673 act.sa_flags &= ~SA_RESTART;
674 }
675 else {
676 act.sa_flags |= SA_RESTART;
677 }
678 if (sigaction(signalnum, &act, NULL) < 0) {
679#else
680 if (siginterrupt(signalnum, flag) < 0) {
681#endif
Victor Stinner388196e2011-05-10 17:13:00 +0200682 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 return NULL;
684 }
Tal Einatc7027b72015-05-16 14:14:49 +0300685 Py_RETURN_NONE;
Christian Heimes8640e742008-02-23 16:23:06 +0000686}
687
688#endif
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +0000689
Tal Einatc7027b72015-05-16 14:14:49 +0300690
691static PyObject*
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800692signal_set_wakeup_fd(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000693{
Victor Stinnere134a7f2015-03-30 10:09:31 +0200694 struct _Py_stat_struct status;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800695 static char *kwlist[] = {
696 "", "warn_on_full_buffer", NULL,
697 };
698 int warn_on_full_buffer = 1;
Victor Stinner11517102014-07-29 23:31:34 +0200699#ifdef MS_WINDOWS
700 PyObject *fdobj;
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100701 SOCKET_T sockfd, old_sockfd;
Victor Stinner11517102014-07-29 23:31:34 +0200702 int res;
703 int res_size = sizeof res;
704 PyObject *mod;
Victor Stinner11517102014-07-29 23:31:34 +0200705 int is_socket;
706
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800707 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|$p:set_wakeup_fd", kwlist,
708 &fdobj, &warn_on_full_buffer))
Victor Stinner11517102014-07-29 23:31:34 +0200709 return NULL;
710
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100711 sockfd = PyLong_AsSocket_t(fdobj);
712 if (sockfd == (SOCKET_T)(-1) && PyErr_Occurred())
Victor Stinner11517102014-07-29 23:31:34 +0200713 return NULL;
714#else
Victor Stinnercda23be2020-11-17 18:57:32 +0100715 int fd;
Victor Stinner11517102014-07-29 23:31:34 +0200716
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800717 if (!PyArg_ParseTupleAndKeywords(args, kwds, "i|$p:set_wakeup_fd", kwlist,
718 &fd, &warn_on_full_buffer))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 return NULL;
Victor Stinner11517102014-07-29 23:31:34 +0200720#endif
721
Victor Stinner72818982020-03-26 22:28:11 +0100722 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200723 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Victor Stinner72818982020-03-26 22:28:11 +0100724 _PyErr_SetString(tstate, PyExc_ValueError,
725 "set_wakeup_fd only works in main thread "
726 "of the main interpreter");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 return NULL;
728 }
Victor Stinner0bffc942014-07-21 16:28:54 +0200729
Victor Stinner11517102014-07-29 23:31:34 +0200730#ifdef MS_WINDOWS
731 is_socket = 0;
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100732 if (sockfd != INVALID_FD) {
Victor Stinner11517102014-07-29 23:31:34 +0200733 /* Import the _socket module to call WSAStartup() */
734 mod = PyImport_ImportModuleNoBlock("_socket");
735 if (mod == NULL)
736 return NULL;
737 Py_DECREF(mod);
738
739 /* test the socket */
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100740 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
Victor Stinner11517102014-07-29 23:31:34 +0200741 (char *)&res, &res_size) != 0) {
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100742 int fd, err;
743
744 err = WSAGetLastError();
Victor Stinner11517102014-07-29 23:31:34 +0200745 if (err != WSAENOTSOCK) {
746 PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
747 return NULL;
748 }
749
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100750 fd = (int)sockfd;
Steve Dower940f33a2016-09-08 11:21:54 -0700751 if ((SOCKET_T)fd != sockfd) {
Victor Stinner72818982020-03-26 22:28:11 +0100752 _PyErr_SetString(tstate, PyExc_ValueError, "invalid fd");
Victor Stinner11517102014-07-29 23:31:34 +0200753 return NULL;
754 }
755
Victor Stinner72818982020-03-26 22:28:11 +0100756 if (_Py_fstat(fd, &status) != 0) {
Victor Stinner11517102014-07-29 23:31:34 +0200757 return NULL;
Victor Stinner72818982020-03-26 22:28:11 +0100758 }
Victor Stinner38227602014-08-27 12:59:44 +0200759
760 /* on Windows, a file cannot be set to non-blocking mode */
Victor Stinner11517102014-07-29 23:31:34 +0200761 }
Victor Stinner38227602014-08-27 12:59:44 +0200762 else {
Victor Stinner11517102014-07-29 23:31:34 +0200763 is_socket = 1;
Victor Stinner38227602014-08-27 12:59:44 +0200764
765 /* Windows does not provide a function to test if a socket
766 is in non-blocking mode */
767 }
Victor Stinner11517102014-07-29 23:31:34 +0200768 }
769
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100770 old_sockfd = wakeup.fd;
771 wakeup.fd = sockfd;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800772 wakeup.warn_on_full_buffer = warn_on_full_buffer;
Victor Stinner11517102014-07-29 23:31:34 +0200773 wakeup.use_send = is_socket;
774
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100775 if (old_sockfd != INVALID_FD)
776 return PyLong_FromSocket_t(old_sockfd);
Victor Stinner11517102014-07-29 23:31:34 +0200777 else
778 return PyLong_FromLong(-1);
779#else
Victor Stinnerd18ccd12014-07-24 21:58:53 +0200780 if (fd != -1) {
Victor Stinner38227602014-08-27 12:59:44 +0200781 int blocking;
782
Victor Stinnere134a7f2015-03-30 10:09:31 +0200783 if (_Py_fstat(fd, &status) != 0)
Victor Stinner11517102014-07-29 23:31:34 +0200784 return NULL;
Victor Stinner38227602014-08-27 12:59:44 +0200785
786 blocking = _Py_get_blocking(fd);
787 if (blocking < 0)
788 return NULL;
789 if (blocking) {
Victor Stinner72818982020-03-26 22:28:11 +0100790 _PyErr_Format(tstate, PyExc_ValueError,
791 "the fd %i must be in non-blocking mode",
792 fd);
Victor Stinner38227602014-08-27 12:59:44 +0200793 return NULL;
794 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 }
Victor Stinner0bffc942014-07-21 16:28:54 +0200796
Victor Stinnercda23be2020-11-17 18:57:32 +0100797 int old_fd = wakeup.fd;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800798 wakeup.fd = fd;
799 wakeup.warn_on_full_buffer = warn_on_full_buffer;
Victor Stinner0bffc942014-07-21 16:28:54 +0200800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 return PyLong_FromLong(old_fd);
Victor Stinner11517102014-07-29 23:31:34 +0200802#endif
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000803}
804
805PyDoc_STRVAR(set_wakeup_fd_doc,
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800806"set_wakeup_fd(fd, *, warn_on_full_buffer=True) -> fd\n\
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000807\n\
Victor Stinner11517102014-07-29 23:31:34 +0200808Sets the fd to be written to (with the signal number) when a signal\n\
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000809comes in. A library can use this to wakeup select or poll.\n\
Victor Stinner11517102014-07-29 23:31:34 +0200810The previous fd or -1 is returned.\n\
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000811\n\
812The fd must be non-blocking.");
813
814/* C API for the same, without all the error checking */
815int
816PySignal_SetWakeupFd(int fd)
817{
Victor Stinnercda23be2020-11-17 18:57:32 +0100818 if (fd < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 fd = -1;
Victor Stinnercda23be2020-11-17 18:57:32 +0100820 }
Victor Stinner11517102014-07-29 23:31:34 +0200821
822#ifdef MS_WINDOWS
Victor Stinnercda23be2020-11-17 18:57:32 +0100823 int old_fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
Victor Stinner11517102014-07-29 23:31:34 +0200824#else
Victor Stinnercda23be2020-11-17 18:57:32 +0100825 int old_fd = wakeup.fd;
Victor Stinner11517102014-07-29 23:31:34 +0200826#endif
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800827 wakeup.fd = fd;
828 wakeup.warn_on_full_buffer = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 return old_fd;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000830}
831
832
Martin v. Löwis823725e2008-03-24 13:39:54 +0000833#ifdef HAVE_SETITIMER
Tal Einatc7027b72015-05-16 14:14:49 +0300834
835/*[clinic input]
836signal.setitimer
837
838 which: int
Victor Stinneref611c92017-10-13 13:49:43 -0700839 seconds: object
840 interval: object(c_default="NULL") = 0.0
Tal Einatc7027b72015-05-16 14:14:49 +0300841 /
842
843Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF).
844
845The timer will fire after value seconds and after that every interval seconds.
846The itimer can be cleared by setting seconds to zero.
847
848Returns old values as a tuple: (delay, interval).
849[clinic start generated code]*/
850
Martin v. Löwis823725e2008-03-24 13:39:54 +0000851static PyObject *
Victor Stinneref611c92017-10-13 13:49:43 -0700852signal_setitimer_impl(PyObject *module, int which, PyObject *seconds,
853 PyObject *interval)
854/*[clinic end generated code: output=65f9dcbddc35527b input=de43daf194e6f66f]*/
Martin v. Löwis823725e2008-03-24 13:39:54 +0000855{
Victor Stinnercda23be2020-11-17 18:57:32 +0100856 struct itimerval new;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000857
Victor Stinneref611c92017-10-13 13:49:43 -0700858 if (timeval_from_double(seconds, &new.it_value) < 0) {
859 return NULL;
860 }
861 if (timeval_from_double(interval, &new.it_interval) < 0) {
862 return NULL;
863 }
864
Martin v. Löwis823725e2008-03-24 13:39:54 +0000865 /* Let OS check "which" value */
Victor Stinnercda23be2020-11-17 18:57:32 +0100866 struct itimerval old;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000867 if (setitimer(which, &new, &old) != 0) {
Tal Einatc7027b72015-05-16 14:14:49 +0300868 PyErr_SetFromErrno(ItimerError);
869 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000870 }
871
872 return itimer_retval(&old);
873}
874
Martin v. Löwis823725e2008-03-24 13:39:54 +0000875#endif
876
877
878#ifdef HAVE_GETITIMER
Tal Einatc7027b72015-05-16 14:14:49 +0300879
880/*[clinic input]
881signal.getitimer
882
883 which: int
884 /
885
886Returns current value of given itimer.
887[clinic start generated code]*/
888
Martin v. Löwis823725e2008-03-24 13:39:54 +0000889static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300890signal_getitimer_impl(PyObject *module, int which)
891/*[clinic end generated code: output=9e053175d517db40 input=f7d21d38f3490627]*/
Martin v. Löwis823725e2008-03-24 13:39:54 +0000892{
Martin v. Löwis823725e2008-03-24 13:39:54 +0000893 struct itimerval old;
894
Martin v. Löwis823725e2008-03-24 13:39:54 +0000895 if (getitimer(which, &old) != 0) {
Tal Einatc7027b72015-05-16 14:14:49 +0300896 PyErr_SetFromErrno(ItimerError);
897 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000898 }
899
900 return itimer_retval(&old);
901}
902
Martin v. Löwis823725e2008-03-24 13:39:54 +0000903#endif
904
Victor Stinnerb3e72192011-05-08 01:46:11 +0200905#if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGPENDING)
Victor Stinner35b300c2011-05-04 13:20:35 +0200906static PyObject*
907sigset_to_set(sigset_t mask)
908{
909 PyObject *signum, *result;
910 int sig;
911
912 result = PySet_New(0);
913 if (result == NULL)
914 return NULL;
915
916 for (sig = 1; sig < NSIG; sig++) {
917 if (sigismember(&mask, sig) != 1)
918 continue;
919
920 /* Handle the case where it is a member by adding the signal to
921 the result list. Ignore the other cases because they mean the
922 signal isn't a member of the mask or the signal was invalid,
923 and an invalid signal must have been our fault in constructing
924 the loop boundaries. */
925 signum = PyLong_FromLong(sig);
926 if (signum == NULL) {
927 Py_DECREF(result);
928 return NULL;
929 }
930 if (PySet_Add(result, signum) == -1) {
931 Py_DECREF(signum);
932 Py_DECREF(result);
933 return NULL;
934 }
935 Py_DECREF(signum);
936 }
937 return result;
938}
Victor Stinnerb3e72192011-05-08 01:46:11 +0200939#endif
Victor Stinner35b300c2011-05-04 13:20:35 +0200940
Victor Stinnerb3e72192011-05-08 01:46:11 +0200941#ifdef PYPTHREAD_SIGMASK
Tal Einatc7027b72015-05-16 14:14:49 +0300942
943/*[clinic input]
944signal.pthread_sigmask
945
946 how: int
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300947 mask: sigset_t
Tal Einatc7027b72015-05-16 14:14:49 +0300948 /
949
950Fetch and/or change the signal mask of the calling thread.
951[clinic start generated code]*/
952
Victor Stinnera9293352011-04-30 15:21:58 +0200953static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300954signal_pthread_sigmask_impl(PyObject *module, int how, sigset_t mask)
955/*[clinic end generated code: output=0562c0fb192981a8 input=85bcebda442fa77f]*/
Victor Stinnera9293352011-04-30 15:21:58 +0200956{
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300957 sigset_t previous;
Victor Stinnera9293352011-04-30 15:21:58 +0200958 int err;
959
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300960 err = pthread_sigmask(how, &mask, &previous);
Victor Stinnera9293352011-04-30 15:21:58 +0200961 if (err != 0) {
962 errno = err;
Victor Stinnerb3e72192011-05-08 01:46:11 +0200963 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnera9293352011-04-30 15:21:58 +0200964 return NULL;
965 }
966
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200967 /* if signals was unblocked, signal handlers have been called */
968 if (PyErr_CheckSignals())
969 return NULL;
970
Victor Stinner35b300c2011-05-04 13:20:35 +0200971 return sigset_to_set(previous);
Victor Stinnera9293352011-04-30 15:21:58 +0200972}
973
Victor Stinnera9293352011-04-30 15:21:58 +0200974#endif /* #ifdef PYPTHREAD_SIGMASK */
975
Martin v. Löwis823725e2008-03-24 13:39:54 +0000976
Victor Stinnerb3e72192011-05-08 01:46:11 +0200977#ifdef HAVE_SIGPENDING
Tal Einatc7027b72015-05-16 14:14:49 +0300978
979/*[clinic input]
980signal.sigpending
981
982Examine pending signals.
983
984Returns a set of signal numbers that are pending for delivery to
985the calling thread.
986[clinic start generated code]*/
987
Victor Stinnerb3e72192011-05-08 01:46:11 +0200988static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300989signal_sigpending_impl(PyObject *module)
990/*[clinic end generated code: output=53375ffe89325022 input=e0036c016f874e29]*/
Victor Stinnerb3e72192011-05-08 01:46:11 +0200991{
992 int err;
993 sigset_t mask;
994 err = sigpending(&mask);
995 if (err)
996 return PyErr_SetFromErrno(PyExc_OSError);
997 return sigset_to_set(mask);
998}
999
Victor Stinnerb3e72192011-05-08 01:46:11 +02001000#endif /* #ifdef HAVE_SIGPENDING */
1001
1002
1003#ifdef HAVE_SIGWAIT
Tal Einatc7027b72015-05-16 14:14:49 +03001004
1005/*[clinic input]
1006signal.sigwait
1007
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001008 sigset: sigset_t
Tal Einatc7027b72015-05-16 14:14:49 +03001009 /
1010
1011Wait for a signal.
1012
1013Suspend execution of the calling thread until the delivery of one of the
1014signals specified in the signal set sigset. The function accepts the signal
1015and returns the signal number.
1016[clinic start generated code]*/
1017
Victor Stinnerb3e72192011-05-08 01:46:11 +02001018static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001019signal_sigwait_impl(PyObject *module, sigset_t sigset)
1020/*[clinic end generated code: output=f43770699d682f96 input=a6fbd47b1086d119]*/
Victor Stinnerb3e72192011-05-08 01:46:11 +02001021{
Victor Stinnerb3e72192011-05-08 01:46:11 +02001022 int err, signum;
1023
Victor Stinner10c30d62011-06-10 01:39:53 +02001024 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001025 err = sigwait(&sigset, &signum);
Victor Stinner10c30d62011-06-10 01:39:53 +02001026 Py_END_ALLOW_THREADS
Victor Stinnerb3e72192011-05-08 01:46:11 +02001027 if (err) {
1028 errno = err;
1029 return PyErr_SetFromErrno(PyExc_OSError);
1030 }
1031
1032 return PyLong_FromLong(signum);
1033}
1034
Tal Einatc7027b72015-05-16 14:14:49 +03001035#endif /* #ifdef HAVE_SIGWAIT */
1036
Victor Stinnerb3e72192011-05-08 01:46:11 +02001037
Antoine Pitrou9d3627e2018-05-04 13:00:50 +02001038#if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)
1039
1040/*[clinic input]
1041signal.valid_signals
1042
1043Return a set of valid signal numbers on this platform.
1044
1045The signal numbers returned by this function can be safely passed to
1046functions like `pthread_sigmask`.
1047[clinic start generated code]*/
1048
1049static PyObject *
1050signal_valid_signals_impl(PyObject *module)
1051/*[clinic end generated code: output=1609cffbcfcf1314 input=86a3717ff25288f2]*/
1052{
1053#ifdef MS_WINDOWS
1054#ifdef SIGBREAK
1055 PyObject *tup = Py_BuildValue("(iiiiiii)", SIGABRT, SIGBREAK, SIGFPE,
1056 SIGILL, SIGINT, SIGSEGV, SIGTERM);
1057#else
1058 PyObject *tup = Py_BuildValue("(iiiiii)", SIGABRT, SIGFPE, SIGILL,
1059 SIGINT, SIGSEGV, SIGTERM);
1060#endif
1061 if (tup == NULL) {
1062 return NULL;
1063 }
1064 PyObject *set = PySet_New(tup);
1065 Py_DECREF(tup);
1066 return set;
1067#else
1068 sigset_t mask;
1069 if (sigemptyset(&mask) || sigfillset(&mask)) {
1070 return PyErr_SetFromErrno(PyExc_OSError);
1071 }
1072 return sigset_to_set(mask);
1073#endif
1074}
1075
1076#endif /* #if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS) */
1077
1078
Ross Lagerwallbc808222011-06-25 12:13:40 +02001079#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
Ross Lagerwallbc808222011-06-25 12:13:40 +02001080static PyStructSequence_Field struct_siginfo_fields[] = {
1081 {"si_signo", "signal number"},
1082 {"si_code", "signal code"},
1083 {"si_errno", "errno associated with this signal"},
1084 {"si_pid", "sending process ID"},
1085 {"si_uid", "real user ID of sending process"},
1086 {"si_status", "exit value or signal"},
1087 {"si_band", "band event for SIGPOLL"},
1088 {0}
1089};
1090
1091PyDoc_STRVAR(struct_siginfo__doc__,
1092"struct_siginfo: Result from sigwaitinfo or sigtimedwait.\n\n\
1093This object may be accessed either as a tuple of\n\
1094(si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band),\n\
1095or via the attributes si_signo, si_code, and so on.");
1096
1097static PyStructSequence_Desc struct_siginfo_desc = {
1098 "signal.struct_siginfo", /* name */
1099 struct_siginfo__doc__, /* doc */
1100 struct_siginfo_fields, /* fields */
1101 7 /* n_in_sequence */
1102};
1103
1104static PyTypeObject SiginfoType;
1105
1106static PyObject *
1107fill_siginfo(siginfo_t *si)
1108{
1109 PyObject *result = PyStructSequence_New(&SiginfoType);
1110 if (!result)
1111 return NULL;
1112
1113 PyStructSequence_SET_ITEM(result, 0, PyLong_FromLong((long)(si->si_signo)));
1114 PyStructSequence_SET_ITEM(result, 1, PyLong_FromLong((long)(si->si_code)));
Victor Stinner09532fe2019-05-10 23:39:09 +02001115#ifdef __VXWORKS__
pxinwr8b5bdda2019-03-14 01:18:25 +08001116 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(0L));
1117 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(0L));
1118 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(0L));
1119 PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(0L));
Victor Stinner09532fe2019-05-10 23:39:09 +02001120#else
Ross Lagerwallbc808222011-06-25 12:13:40 +02001121 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si->si_errno)));
1122 PyStructSequence_SET_ITEM(result, 3, PyLong_FromPid(si->si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02001123 PyStructSequence_SET_ITEM(result, 4, _PyLong_FromUid(si->si_uid));
Ross Lagerwallbc808222011-06-25 12:13:40 +02001124 PyStructSequence_SET_ITEM(result, 5,
1125 PyLong_FromLong((long)(si->si_status)));
Victor Stinner09532fe2019-05-10 23:39:09 +02001126#endif
Zachary Ware6a6967e2016-10-01 00:47:27 -05001127#ifdef HAVE_SIGINFO_T_SI_BAND
Ross Lagerwallbc808222011-06-25 12:13:40 +02001128 PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(si->si_band));
Zachary Ware6a6967e2016-10-01 00:47:27 -05001129#else
1130 PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(0L));
1131#endif
Ross Lagerwallbc808222011-06-25 12:13:40 +02001132 if (PyErr_Occurred()) {
1133 Py_DECREF(result);
1134 return NULL;
1135 }
1136
1137 return result;
1138}
1139#endif
1140
1141#ifdef HAVE_SIGWAITINFO
Tal Einatc7027b72015-05-16 14:14:49 +03001142
1143/*[clinic input]
1144signal.sigwaitinfo
1145
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001146 sigset: sigset_t
Tal Einatc7027b72015-05-16 14:14:49 +03001147 /
1148
1149Wait synchronously until one of the signals in *sigset* is delivered.
1150
1151Returns a struct_siginfo containing information about the signal.
1152[clinic start generated code]*/
1153
Ross Lagerwallbc808222011-06-25 12:13:40 +02001154static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001155signal_sigwaitinfo_impl(PyObject *module, sigset_t sigset)
1156/*[clinic end generated code: output=1eb2f1fa236fdbca input=3d1a7e1f27fc664c]*/
Ross Lagerwallbc808222011-06-25 12:13:40 +02001157{
Ross Lagerwallbc808222011-06-25 12:13:40 +02001158 siginfo_t si;
1159 int err;
Victor Stinnera453cd82015-03-20 12:54:28 +01001160 int async_err = 0;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001161
Victor Stinnera453cd82015-03-20 12:54:28 +01001162 do {
1163 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001164 err = sigwaitinfo(&sigset, &si);
Victor Stinnera453cd82015-03-20 12:54:28 +01001165 Py_END_ALLOW_THREADS
1166 } while (err == -1
1167 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwallbc808222011-06-25 12:13:40 +02001168 if (err == -1)
Victor Stinnera453cd82015-03-20 12:54:28 +01001169 return (!async_err) ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001170
1171 return fill_siginfo(&si);
1172}
1173
Ross Lagerwallbc808222011-06-25 12:13:40 +02001174#endif /* #ifdef HAVE_SIGWAITINFO */
1175
1176#ifdef HAVE_SIGTIMEDWAIT
Tal Einatc7027b72015-05-16 14:14:49 +03001177
1178/*[clinic input]
1179signal.sigtimedwait
1180
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001181 sigset: sigset_t
Serhiy Storchaka6b680cd2015-05-16 15:57:56 +03001182 timeout as timeout_obj: object
Tal Einatc7027b72015-05-16 14:14:49 +03001183 /
1184
1185Like sigwaitinfo(), but with a timeout.
1186
1187The timeout is specified in seconds, with floating point numbers allowed.
1188[clinic start generated code]*/
1189
Ross Lagerwallbc808222011-06-25 12:13:40 +02001190static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001191signal_sigtimedwait_impl(PyObject *module, sigset_t sigset,
Serhiy Storchaka6b680cd2015-05-16 15:57:56 +03001192 PyObject *timeout_obj)
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001193/*[clinic end generated code: output=59c8971e8ae18a64 input=87fd39237cf0b7ba]*/
Ross Lagerwallbc808222011-06-25 12:13:40 +02001194{
Victor Stinnera453cd82015-03-20 12:54:28 +01001195 struct timespec ts;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001196 siginfo_t si;
Victor Stinnera453cd82015-03-20 12:54:28 +01001197 int res;
Victor Stinner34dc0f42015-03-27 18:19:03 +01001198 _PyTime_t timeout, deadline, monotonic;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001199
Victor Stinner869e1772015-03-30 03:49:14 +02001200 if (_PyTime_FromSecondsObject(&timeout,
1201 timeout_obj, _PyTime_ROUND_CEILING) < 0)
Ross Lagerwallbc808222011-06-25 12:13:40 +02001202 return NULL;
1203
Victor Stinnera453cd82015-03-20 12:54:28 +01001204 if (timeout < 0) {
Ross Lagerwallbc808222011-06-25 12:13:40 +02001205 PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
1206 return NULL;
1207 }
1208
Victor Stinner34dc0f42015-03-27 18:19:03 +01001209 deadline = _PyTime_GetMonotonicClock() + timeout;
Victor Stinnera453cd82015-03-20 12:54:28 +01001210
1211 do {
Victor Stinner34dc0f42015-03-27 18:19:03 +01001212 if (_PyTime_AsTimespec(timeout, &ts) < 0)
1213 return NULL;
Victor Stinnera453cd82015-03-20 12:54:28 +01001214
1215 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001216 res = sigtimedwait(&sigset, &si, &ts);
Victor Stinnera453cd82015-03-20 12:54:28 +01001217 Py_END_ALLOW_THREADS
1218
1219 if (res != -1)
1220 break;
1221
1222 if (errno != EINTR) {
1223 if (errno == EAGAIN)
1224 Py_RETURN_NONE;
1225 else
1226 return PyErr_SetFromErrno(PyExc_OSError);
1227 }
1228
1229 /* sigtimedwait() was interrupted by a signal (EINTR) */
1230 if (PyErr_CheckSignals())
1231 return NULL;
1232
Victor Stinner34dc0f42015-03-27 18:19:03 +01001233 monotonic = _PyTime_GetMonotonicClock();
1234 timeout = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001235 if (timeout < 0)
Victor Stinnera453cd82015-03-20 12:54:28 +01001236 break;
1237 } while (1);
Ross Lagerwallbc808222011-06-25 12:13:40 +02001238
1239 return fill_siginfo(&si);
1240}
1241
Ross Lagerwallbc808222011-06-25 12:13:40 +02001242#endif /* #ifdef HAVE_SIGTIMEDWAIT */
1243
Victor Stinnerb3e72192011-05-08 01:46:11 +02001244
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001245#if defined(HAVE_PTHREAD_KILL)
Tal Einatc7027b72015-05-16 14:14:49 +03001246
1247/*[clinic input]
1248signal.pthread_kill
1249
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001250 thread_id: unsigned_long(bitwise=True)
Tal Einatc7027b72015-05-16 14:14:49 +03001251 signalnum: int
1252 /
1253
1254Send a signal to a thread.
1255[clinic start generated code]*/
1256
Victor Stinnerb3e72192011-05-08 01:46:11 +02001257static PyObject *
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001258signal_pthread_kill_impl(PyObject *module, unsigned long thread_id,
1259 int signalnum)
1260/*[clinic end generated code: output=7629919b791bc27f input=1d901f2c7bb544ff]*/
Victor Stinnerb3e72192011-05-08 01:46:11 +02001261{
Victor Stinnerb3e72192011-05-08 01:46:11 +02001262 int err;
1263
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001264 if (PySys_Audit("signal.pthread_kill", "ki", thread_id, signalnum) < 0) {
1265 return NULL;
1266 }
1267
Tal Einatc7027b72015-05-16 14:14:49 +03001268 err = pthread_kill((pthread_t)thread_id, signalnum);
Victor Stinnerb3e72192011-05-08 01:46:11 +02001269 if (err != 0) {
1270 errno = err;
1271 PyErr_SetFromErrno(PyExc_OSError);
1272 return NULL;
1273 }
1274
1275 /* the signal may have been send to the current thread */
1276 if (PyErr_CheckSignals())
1277 return NULL;
1278
1279 Py_RETURN_NONE;
1280}
1281
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001282#endif /* #if defined(HAVE_PTHREAD_KILL) */
Victor Stinnerb3e72192011-05-08 01:46:11 +02001283
1284
Benjamin Peterson74834512019-11-19 20:39:14 -08001285#if defined(__linux__) && defined(__NR_pidfd_send_signal)
1286/*[clinic input]
1287signal.pidfd_send_signal
1288
1289 pidfd: int
1290 signalnum: int
1291 siginfo: object = None
1292 flags: int = 0
1293 /
1294
1295Send a signal to a process referred to by a pid file descriptor.
1296[clinic start generated code]*/
1297
1298static PyObject *
1299signal_pidfd_send_signal_impl(PyObject *module, int pidfd, int signalnum,
1300 PyObject *siginfo, int flags)
1301/*[clinic end generated code: output=2d59f04a75d9cbdf input=2a6543a1f4ac2000]*/
1302
1303{
1304 if (siginfo != Py_None) {
1305 PyErr_SetString(PyExc_TypeError, "siginfo must be None");
1306 return NULL;
1307 }
1308 if (syscall(__NR_pidfd_send_signal, pidfd, signalnum, NULL, flags) < 0) {
1309 PyErr_SetFromErrno(PyExc_OSError);
1310 return NULL;
1311 }
1312 Py_RETURN_NONE;
1313}
1314#endif
1315
1316
Victor Stinnerb3e72192011-05-08 01:46:11 +02001317
Tal Einatc7027b72015-05-16 14:14:49 +03001318/* List of functions defined in the module -- some of the methoddefs are
1319 defined to nothing if the corresponding C function is not available. */
Barry Warsaw92971171997-01-03 00:14:25 +00001320static PyMethodDef signal_methods[] = {
Serhiy Storchakab0689ae2020-07-12 19:15:20 +03001321 SIGNAL_DEFAULT_INT_HANDLER_METHODDEF
Tal Einatc7027b72015-05-16 14:14:49 +03001322 SIGNAL_ALARM_METHODDEF
1323 SIGNAL_SETITIMER_METHODDEF
1324 SIGNAL_GETITIMER_METHODDEF
1325 SIGNAL_SIGNAL_METHODDEF
Vladimir Matveevc24c6c22019-01-08 01:58:25 -08001326 SIGNAL_RAISE_SIGNAL_METHODDEF
Antoine Pietri5d2a27d2018-03-12 14:42:34 +01001327 SIGNAL_STRSIGNAL_METHODDEF
Tal Einatc7027b72015-05-16 14:14:49 +03001328 SIGNAL_GETSIGNAL_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001329 {"set_wakeup_fd", (PyCFunction)(void(*)(void))signal_set_wakeup_fd, METH_VARARGS | METH_KEYWORDS, set_wakeup_fd_doc},
Tal Einatc7027b72015-05-16 14:14:49 +03001330 SIGNAL_SIGINTERRUPT_METHODDEF
1331 SIGNAL_PAUSE_METHODDEF
Benjamin Peterson74834512019-11-19 20:39:14 -08001332 SIGNAL_PIDFD_SEND_SIGNAL_METHODDEF
Tal Einatc7027b72015-05-16 14:14:49 +03001333 SIGNAL_PTHREAD_KILL_METHODDEF
1334 SIGNAL_PTHREAD_SIGMASK_METHODDEF
1335 SIGNAL_SIGPENDING_METHODDEF
1336 SIGNAL_SIGWAIT_METHODDEF
1337 SIGNAL_SIGWAITINFO_METHODDEF
1338 SIGNAL_SIGTIMEDWAIT_METHODDEF
Antoine Pitrou9d3627e2018-05-04 13:00:50 +02001339#if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)
1340 SIGNAL_VALID_SIGNALS_METHODDEF
1341#endif
Tal Einatc7027b72015-05-16 14:14:49 +03001342 {NULL, NULL} /* sentinel */
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001343};
1344
Barry Warsaw92971171997-01-03 00:14:25 +00001345
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001346PyDoc_STRVAR(module_doc,
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001347"This module provides mechanisms to use signal handlers in Python.\n\
1348\n\
1349Functions:\n\
1350\n\
1351alarm() -- cause SIGALRM after a specified time [Unix only]\n\
Martin v. Löwis823725e2008-03-24 13:39:54 +00001352setitimer() -- cause a signal (described below) after a specified\n\
1353 float time and the timer may restart then [Unix only]\n\
1354getitimer() -- get current value of timer [Unix only]\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001355signal() -- set the action for a given signal\n\
1356getsignal() -- get the signal action for a given signal\n\
1357pause() -- wait until a signal arrives [Unix only]\n\
1358default_int_handler() -- default SIGINT handler\n\
1359\n\
Martin v. Löwis823725e2008-03-24 13:39:54 +00001360signal constants:\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001361SIG_DFL -- used to refer to the system default handler\n\
1362SIG_IGN -- used to ignore the signal\n\
1363NSIG -- number of defined signals\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001364SIGINT, SIGTERM, etc. -- signal numbers\n\
1365\n\
Martin v. Löwis823725e2008-03-24 13:39:54 +00001366itimer constants:\n\
1367ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\
1368 expiration\n\
1369ITIMER_VIRTUAL -- decrements only when the process is executing,\n\
1370 and delivers SIGVTALRM upon expiration\n\
1371ITIMER_PROF -- decrements both when the process is executing and\n\
1372 when the system is executing on behalf of the process.\n\
1373 Coupled with ITIMER_VIRTUAL, this timer is usually\n\
1374 used to profile the time spent by the application\n\
1375 in user and kernel space. SIGPROF is delivered upon\n\
1376 expiration.\n\
1377\n\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001378*** IMPORTANT NOTICE ***\n\
1379A signal handler function is called with two arguments:\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001380the first is the signal number, the second is the interrupted stack frame.");
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001381
Martin v. Löwis1a214512008-06-11 05:26:20 +00001382
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001383
1384static int
Victor Stinnercda23be2020-11-17 18:57:32 +01001385signal_add_constants(PyObject *module)
1386{
1387#define ADD_INT_MACRO(macro) \
1388 if (PyModule_AddIntConstant(module, #macro, macro) < 0) { \
1389 return -1; \
1390 }
1391
1392 ADD_INT_MACRO(NSIG);
1393
1394 // SIG_xxx pthread_sigmask() constants
1395#ifdef SIG_BLOCK
1396 ADD_INT_MACRO(SIG_BLOCK);
1397#endif
1398#ifdef SIG_UNBLOCK
1399 ADD_INT_MACRO(SIG_UNBLOCK);
1400#endif
1401#ifdef SIG_SETMASK
1402 ADD_INT_MACRO(SIG_SETMASK);
1403#endif
1404
1405 // SIGxxx signal number constants
1406#ifdef SIGHUP
1407 ADD_INT_MACRO(SIGHUP);
1408#endif
1409#ifdef SIGINT
1410 ADD_INT_MACRO(SIGINT);
1411#endif
1412#ifdef SIGBREAK
1413 ADD_INT_MACRO(SIGBREAK);
1414#endif
1415#ifdef SIGQUIT
1416 ADD_INT_MACRO(SIGQUIT);
1417#endif
1418#ifdef SIGILL
1419 ADD_INT_MACRO(SIGILL);
1420#endif
1421#ifdef SIGTRAP
1422 ADD_INT_MACRO(SIGTRAP);
1423#endif
1424#ifdef SIGIOT
1425 ADD_INT_MACRO(SIGIOT);
1426#endif
1427#ifdef SIGABRT
1428 ADD_INT_MACRO(SIGABRT);
1429#endif
1430#ifdef SIGEMT
1431 ADD_INT_MACRO(SIGEMT);
1432#endif
1433#ifdef SIGFPE
1434 ADD_INT_MACRO(SIGFPE);
1435#endif
1436#ifdef SIGKILL
1437 ADD_INT_MACRO(SIGKILL);
1438#endif
1439#ifdef SIGBUS
1440 ADD_INT_MACRO(SIGBUS);
1441#endif
1442#ifdef SIGSEGV
1443 ADD_INT_MACRO(SIGSEGV);
1444#endif
1445#ifdef SIGSYS
1446 ADD_INT_MACRO(SIGSYS);
1447#endif
1448#ifdef SIGPIPE
1449 ADD_INT_MACRO(SIGPIPE);
1450#endif
1451#ifdef SIGALRM
1452 ADD_INT_MACRO(SIGALRM);
1453#endif
1454#ifdef SIGTERM
1455 ADD_INT_MACRO(SIGTERM);
1456#endif
1457#ifdef SIGUSR1
1458 ADD_INT_MACRO(SIGUSR1);
1459#endif
1460#ifdef SIGUSR2
1461 ADD_INT_MACRO(SIGUSR2);
1462#endif
1463#ifdef SIGCLD
1464 ADD_INT_MACRO(SIGCLD);
1465#endif
1466#ifdef SIGCHLD
1467 ADD_INT_MACRO(SIGCHLD);
1468#endif
1469#ifdef SIGPWR
1470 ADD_INT_MACRO(SIGPWR);
1471#endif
1472#ifdef SIGIO
1473 ADD_INT_MACRO(SIGIO);
1474#endif
1475#ifdef SIGURG
1476 ADD_INT_MACRO(SIGURG);
1477#endif
1478#ifdef SIGWINCH
1479 ADD_INT_MACRO(SIGWINCH);
1480#endif
1481#ifdef SIGPOLL
1482 ADD_INT_MACRO(SIGPOLL);
1483#endif
1484#ifdef SIGSTOP
1485 ADD_INT_MACRO(SIGSTOP);
1486#endif
1487#ifdef SIGTSTP
1488 ADD_INT_MACRO(SIGTSTP);
1489#endif
1490#ifdef SIGCONT
1491 ADD_INT_MACRO(SIGCONT);
1492#endif
1493#ifdef SIGTTIN
1494 ADD_INT_MACRO(SIGTTIN);
1495#endif
1496#ifdef SIGTTOU
1497 ADD_INT_MACRO(SIGTTOU);
1498#endif
1499#ifdef SIGVTALRM
1500 ADD_INT_MACRO(SIGVTALRM);
1501#endif
1502#ifdef SIGPROF
1503 ADD_INT_MACRO(SIGPROF);
1504#endif
1505#ifdef SIGXCPU
1506 ADD_INT_MACRO(SIGXCPU);
1507#endif
1508#ifdef SIGXFSZ
1509 ADD_INT_MACRO(SIGXFSZ);
1510#endif
1511#ifdef SIGRTMIN
1512 ADD_INT_MACRO(SIGRTMIN);
1513#endif
1514#ifdef SIGRTMAX
1515 ADD_INT_MACRO(SIGRTMAX);
1516#endif
1517#ifdef SIGINFO
1518 ADD_INT_MACRO(SIGINFO);
1519#endif
1520
1521 // ITIMER_xxx constants
1522#ifdef ITIMER_REAL
1523 ADD_INT_MACRO(ITIMER_REAL);
1524#endif
1525#ifdef ITIMER_VIRTUAL
1526 ADD_INT_MACRO(ITIMER_VIRTUAL);
1527#endif
1528#ifdef ITIMER_PROF
1529 ADD_INT_MACRO(ITIMER_PROF);
1530#endif
1531
1532 // CTRL_xxx Windows signals
1533#ifdef CTRL_C_EVENT
1534 ADD_INT_MACRO(CTRL_C_EVENT);
1535#endif
1536#ifdef CTRL_BREAK_EVENT
1537 ADD_INT_MACRO(CTRL_BREAK_EVENT);
1538#endif
1539
1540 return 0;
1541
1542#undef ADD_INT_MACRO
1543}
1544
1545
1546static int
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001547signal_module_exec(PyObject *m)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001548{
Victor Stinnercda23be2020-11-17 18:57:32 +01001549 assert(!PyErr_Occurred());
1550
1551 if (signal_add_constants(m) < 0) {
1552 return -1;
1553 }
1554
1555 /* Add some symbolic constants to the module */
1556 PyObject *d = PyModule_GetDict(m);
1557 if (PyDict_SetItemString(d, "SIG_DFL", DefaultHandler) < 0) {
1558 return -1;
1559 }
1560 if (PyDict_SetItemString(d, "SIG_IGN", IgnoreHandler) < 0) {
1561 return -1;
1562 }
1563#if defined(HAVE_GETITIMER) || defined(HAVE_SETITIMER)
1564 if (PyDict_SetItemString(d, "ItimerError", ItimerError) < 0) {
1565 return -1;
1566 }
1567#endif
Ross Lagerwallbc808222011-06-25 12:13:40 +02001568#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001569 if (PyModule_AddType(m, &SiginfoType) < 0) {
1570 return -1;
1571 }
Ross Lagerwallbc808222011-06-25 12:13:40 +02001572#endif
1573
Victor Stinnercda23be2020-11-17 18:57:32 +01001574 // Get signal handlers
1575 for (int signum = 1; signum < NSIG; signum++) {
1576 void (*c_handler)(int) = PyOS_getsig(signum);
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001577 PyObject *func;
Victor Stinnercda23be2020-11-17 18:57:32 +01001578 if (c_handler == SIG_DFL) {
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001579 func = DefaultHandler;
Victor Stinnercda23be2020-11-17 18:57:32 +01001580 }
1581 else if (c_handler == SIG_IGN) {
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001582 func = IgnoreHandler;
Victor Stinnercda23be2020-11-17 18:57:32 +01001583 }
1584 else {
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001585 func = Py_None; // None of our business
Victor Stinnercda23be2020-11-17 18:57:32 +01001586 }
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001587 // If signal_module_exec() is called more than one, we must
1588 // clear the strong reference to the previous function.
Antoine Pitrouba251c22021-03-11 23:35:45 +01001589 PyObject* old_func = get_handler(signum);
1590 SetHandler(signum, Py_NewRef(func));
1591 Py_XDECREF(old_func);
animalize77643c42019-09-09 21:46:26 +08001592 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001593
Victor Stinnercda23be2020-11-17 18:57:32 +01001594 // Instal Python SIGINT handler which raises KeyboardInterrupt
Antoine Pitrouba251c22021-03-11 23:35:45 +01001595 PyObject* sigint_func = get_handler(SIGINT);
1596 if (sigint_func == DefaultHandler) {
Victor Stinner0ae323b2020-11-17 18:15:20 +01001597 PyObject *int_handler = PyMapping_GetItemString(d, "default_int_handler");
1598 if (!int_handler) {
1599 return -1;
1600 }
1601
Antoine Pitrouba251c22021-03-11 23:35:45 +01001602 SetHandler(SIGINT, int_handler);
1603 Py_DECREF(sigint_func);
pkerlinge905c842018-06-01 09:47:18 +00001604 PyOS_setsig(SIGINT, signal_handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001606
Victor Stinnercda23be2020-11-17 18:57:32 +01001607 assert(!PyErr_Occurred());
1608 return 0;
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001609}
1610
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001611
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001612static PyModuleDef_Slot signal_slots[] = {
1613 {Py_mod_exec, signal_module_exec},
1614 {0, NULL}
1615};
1616
1617static struct PyModuleDef signal_module = {
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001618 PyModuleDef_HEAD_INIT,
1619 "_signal",
1620 .m_doc = module_doc,
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001621 .m_size = 0,
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001622 .m_methods = signal_methods,
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001623 .m_slots = signal_slots,
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001624};
1625
Victor Stinner4b8032e2020-09-04 14:51:05 +02001626
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001627PyMODINIT_FUNC
1628PyInit__signal(void)
1629{
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001630 return PyModuleDef_Init(&signal_module);
Guido van Rossum08c16611997-08-02 03:01:42 +00001631}
1632
Victor Stinner4b8032e2020-09-04 14:51:05 +02001633
Victor Stinner296a7962020-11-17 16:22:23 +01001634void
1635_PySignal_Fini(void)
Guido van Rossum08c16611997-08-02 03:01:42 +00001636{
Victor Stinner0ae323b2020-11-17 18:15:20 +01001637 // Restore default signals and clear handlers
1638 for (int signum = 1; signum < NSIG; signum++) {
Antoine Pitrouba251c22021-03-11 23:35:45 +01001639 PyObject *func = get_handler(signum);
Victor Stinner0ae323b2020-11-17 18:15:20 +01001640 _Py_atomic_store_relaxed(&Handlers[signum].tripped, 0);
Antoine Pitrouba251c22021-03-11 23:35:45 +01001641 SetHandler(signum, NULL);
Victor Stinner0ae323b2020-11-17 18:15:20 +01001642 if (func != NULL
1643 && func != Py_None
1644 && func != DefaultHandler
1645 && func != IgnoreHandler)
1646 {
1647 PyOS_setsig(signum, SIG_DFL);
1648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 Py_XDECREF(func);
1650 }
Guido van Rossum08c16611997-08-02 03:01:42 +00001651
Victor Stinner0ae323b2020-11-17 18:15:20 +01001652#ifdef MS_WINDOWS
1653 if (sigint_event != NULL) {
1654 CloseHandle(sigint_event);
1655 sigint_event = NULL;
1656 }
1657#endif
1658
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001659 Py_CLEAR(DefaultHandler);
1660 Py_CLEAR(IgnoreHandler);
Victor Stinner0ae323b2020-11-17 18:15:20 +01001661#if defined(HAVE_GETITIMER) || defined(HAVE_SETITIMER)
animalize77643c42019-09-09 21:46:26 +08001662 Py_CLEAR(ItimerError);
1663#endif
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001664}
1665
Barry Warsaw92971171997-01-03 00:14:25 +00001666
Barry Warsaw92971171997-01-03 00:14:25 +00001667/* Declared in pyerrors.h */
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001668int
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001669PyErr_CheckSignals(void)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001670{
Victor Stinner72818982020-03-26 22:28:11 +01001671 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001672 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Eric Snow64d6cc82019-02-23 15:40:43 -07001673 return 0;
1674 }
1675
Victor Stinner72818982020-03-26 22:28:11 +01001676 return _PyErr_CheckSignalsTstate(tstate);
Eric Snow64d6cc82019-02-23 15:40:43 -07001677}
1678
1679
1680/* Declared in cpython/pyerrors.h */
1681int
Victor Stinner72818982020-03-26 22:28:11 +01001682_PyErr_CheckSignalsTstate(PyThreadState *tstate)
Eric Snow64d6cc82019-02-23 15:40:43 -07001683{
Victor Stinner72818982020-03-26 22:28:11 +01001684 if (!_Py_atomic_load(&is_tripped)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 return 0;
Victor Stinner72818982020-03-26 22:28:11 +01001686 }
Christian Heimesb76922a2007-12-11 01:06:40 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /*
1689 * The is_tripped variable is meant to speed up the calls to
1690 * PyErr_CheckSignals (both directly or via pending calls) when no
1691 * signal has arrived. This variable is set to 1 when a signal arrives
1692 * and it is set to 0 here, when we know some signals arrived. This way
1693 * we can run the registered handlers with no signals blocked.
1694 *
1695 * NOTE: with this approach we can have a situation where is_tripped is
1696 * 1 but we have no more signals to handle (Handlers[i].tripped
1697 * is 0 for every signal i). This won't do us any harm (except
1698 * we're gonna spent some cycles for nothing). This happens when
1699 * we receive a signal i after we zero is_tripped and before we
1700 * check Handlers[i].tripped.
1701 */
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +02001702 _Py_atomic_store(&is_tripped, 0);
Christian Heimesb76922a2007-12-11 01:06:40 +00001703
Victor Stinner72818982020-03-26 22:28:11 +01001704 PyObject *frame = (PyObject *)tstate->frame;
1705 if (!frame) {
1706 frame = Py_None;
1707 }
Christian Heimesb76922a2007-12-11 01:06:40 +00001708
Victor Stinner72818982020-03-26 22:28:11 +01001709 for (int i = 1; i < NSIG; i++) {
1710 if (!_Py_atomic_load_relaxed(&Handlers[i].tripped)) {
1711 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 }
Victor Stinner72818982020-03-26 22:28:11 +01001713 _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1714
Antoine Pitrou68245b72021-03-05 10:32:50 +01001715 /* Signal handlers can be modified while a signal is received,
1716 * and therefore the fact that trip_signal() or PyErr_SetInterrupt()
1717 * was called doesn't guarantee that there is still a Python
1718 * signal handler for it by the time PyErr_CheckSignals() is called
1719 * (see bpo-43406).
1720 */
Antoine Pitrouba251c22021-03-11 23:35:45 +01001721 PyObject *func = get_handler(i);
Antoine Pitrou68245b72021-03-05 10:32:50 +01001722 if (func == NULL || func == Py_None || func == IgnoreHandler ||
1723 func == DefaultHandler) {
1724 /* No Python signal handler due to aforementioned race condition.
1725 * We can't call raise() as it would break the assumption
1726 * that PyErr_SetInterrupt() only *simulates* an incoming
1727 * signal (i.e. it will never kill the process).
1728 * We also don't want to interrupt user code with a cryptic
1729 * asynchronous exception, so instead just write out an
1730 * unraisable error.
1731 */
1732 PyErr_Format(PyExc_OSError,
1733 "Signal %i ignored due to race condition",
1734 i);
1735 PyErr_WriteUnraisable(Py_None);
1736 continue;
1737 }
1738
Victor Stinner72818982020-03-26 22:28:11 +01001739 PyObject *arglist = Py_BuildValue("(iO)", i, frame);
1740 PyObject *result;
1741 if (arglist) {
Antoine Pitrou68245b72021-03-05 10:32:50 +01001742 result = _PyObject_Call(tstate, func, arglist, NULL);
Victor Stinner72818982020-03-26 22:28:11 +01001743 Py_DECREF(arglist);
1744 }
1745 else {
1746 result = NULL;
1747 }
1748 if (!result) {
1749 /* On error, re-schedule a call to _PyErr_CheckSignalsTstate() */
1750 _Py_atomic_store(&is_tripped, 1);
1751 return -1;
1752 }
1753
1754 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 }
Christian Heimesb76922a2007-12-11 01:06:40 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 return 0;
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001758}
1759
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +00001760
Victor Stinner72818982020-03-26 22:28:11 +01001761
1762int
1763_PyErr_CheckSignals(void)
1764{
1765 PyThreadState *tstate = _PyThreadState_GET();
1766 return _PyErr_CheckSignalsTstate(tstate);
1767}
1768
1769
Antoine Pitrouba251c22021-03-11 23:35:45 +01001770/* Simulate the effect of a signal arriving. The next time PyErr_CheckSignals
1771 is called, the corresponding Python signal handler will be raised.
Matěj Cepl608876b2019-05-23 22:30:00 +02001772
Antoine Pitrouba251c22021-03-11 23:35:45 +01001773 Missing signal handler for the given signal number is silently ignored. */
1774int
1775PyErr_SetInterruptEx(int signum)
1776{
1777 if (signum < 1 || signum >= NSIG) {
1778 return -1;
1779 }
1780 PyObject* func = get_handler(signum);
1781 if (func != IgnoreHandler && func != DefaultHandler) {
1782 trip_signal(signum);
1783 }
1784 return 0;
1785}
1786
Barry Warsaw92971171997-01-03 00:14:25 +00001787void
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001788PyErr_SetInterrupt(void)
Barry Warsaw92971171997-01-03 00:14:25 +00001789{
Antoine Pitrouba251c22021-03-11 23:35:45 +01001790 (void) PyErr_SetInterruptEx(SIGINT);
Barry Warsaw92971171997-01-03 00:14:25 +00001791}
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001792
Victor Stinner0ae323b2020-11-17 18:15:20 +01001793static int
1794signal_install_handlers(void)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001795{
Victor Stinner296a7962020-11-17 16:22:23 +01001796#ifdef SIGPIPE
1797 PyOS_setsig(SIGPIPE, SIG_IGN);
1798#endif
1799#ifdef SIGXFZ
1800 PyOS_setsig(SIGXFZ, SIG_IGN);
1801#endif
1802#ifdef SIGXFSZ
1803 PyOS_setsig(SIGXFSZ, SIG_IGN);
1804#endif
1805
1806 // Import _signal to install the Python SIGINT handler
1807 PyObject *module = PyImport_ImportModule("_signal");
1808 if (!module) {
1809 return -1;
1810 }
1811 Py_DECREF(module);
1812
1813 return 0;
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001814}
1815
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001816
Victor Stinner29aa6242020-11-17 22:55:30 +01001817/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1818 *
1819 * All of the code in this function must only use async-signal-safe functions,
1820 * listed at `man 7 signal` or
1821 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1822 *
1823 * If this function is updated, update also _posix_spawn() of subprocess.py.
1824 */
1825void
1826_Py_RestoreSignals(void)
1827{
1828#ifdef SIGPIPE
1829 PyOS_setsig(SIGPIPE, SIG_DFL);
1830#endif
1831#ifdef SIGXFZ
1832 PyOS_setsig(SIGXFZ, SIG_DFL);
1833#endif
1834#ifdef SIGXFSZ
1835 PyOS_setsig(SIGXFSZ, SIG_DFL);
1836#endif
1837}
1838
1839
Victor Stinner0ae323b2020-11-17 18:15:20 +01001840int
1841_PySignal_Init(int install_signal_handlers)
1842{
1843 DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL);
1844 if (!DefaultHandler) {
1845 return -1;
1846 }
1847
1848 IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN);
1849 if (!IgnoreHandler) {
1850 return -1;
1851 }
1852
1853#if defined(HAVE_GETITIMER) || defined(HAVE_SETITIMER)
1854 ItimerError = PyErr_NewException("signal.ItimerError",
1855 PyExc_OSError, NULL);
1856 if (!ItimerError) {
1857 return -1;
1858 }
1859#endif
1860
1861#ifdef MS_WINDOWS
1862 /* Create manual-reset event, initially unset */
1863 sigint_event = CreateEvent(NULL, TRUE, FALSE, FALSE);
1864 if (sigint_event == NULL) {
1865 PyErr_SetFromWindowsErr(0);
1866 return -1;
1867 }
1868#endif
1869
1870#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
1871 if (SiginfoType.tp_name == NULL) {
1872 if (PyStructSequence_InitType2(&SiginfoType, &struct_siginfo_desc) < 0) {
1873 return -1;
1874 }
1875 }
1876#endif
1877
1878 for (int signum = 1; signum < NSIG; signum++) {
1879 _Py_atomic_store_relaxed(&Handlers[signum].tripped, 0);
1880 }
1881
1882 if (install_signal_handlers) {
1883 if (signal_install_handlers() < 0) {
1884 return -1;
1885 }
1886 }
1887
1888 return 0;
1889}
1890
1891
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001892// The caller doesn't have to hold the GIL
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001893int
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001894_PyOS_InterruptOccurred(PyThreadState *tstate)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001895{
Victor Stinnercbe12962020-06-01 20:34:15 +02001896 _Py_EnsureTstateNotNULL(tstate);
1897 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Victor Stinner72818982020-03-26 22:28:11 +01001898 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 }
Victor Stinner72818982020-03-26 22:28:11 +01001900
1901 if (!_Py_atomic_load_relaxed(&Handlers[SIGINT].tripped)) {
1902 return 0;
1903 }
1904
1905 _Py_atomic_store_relaxed(&Handlers[SIGINT].tripped, 0);
1906 return 1;
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001907}
Guido van Rossum359bcaa1997-11-14 22:24:28 +00001908
Victor Stinner26881c82020-06-02 15:51:37 +02001909
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001910// The caller must to hold the GIL
1911int
1912PyOS_InterruptOccurred(void)
1913{
1914 PyThreadState *tstate = _PyThreadState_GET();
1915 return _PyOS_InterruptOccurred(tstate);
1916}
1917
1918
Victor Stinner26881c82020-06-02 15:51:37 +02001919#ifdef HAVE_FORK
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08001920static void
1921_clear_pending_signals(void)
1922{
Victor Stinner26881c82020-06-02 15:51:37 +02001923 if (!_Py_atomic_load(&is_tripped)) {
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08001924 return;
Victor Stinner26881c82020-06-02 15:51:37 +02001925 }
1926
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +02001927 _Py_atomic_store(&is_tripped, 0);
Victor Stinner26881c82020-06-02 15:51:37 +02001928 for (int i = 1; i < NSIG; ++i) {
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +02001929 _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08001930 }
1931}
1932
Guido van Rossum359bcaa1997-11-14 22:24:28 +00001933void
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001934_PySignal_AfterFork(void)
Guido van Rossum359bcaa1997-11-14 22:24:28 +00001935{
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08001936 /* Clear the signal flags after forking so that they aren't handled
1937 * in both processes if they came in just before the fork() but before
1938 * the interpreter had an opportunity to call the handlers. issue9535. */
1939 _clear_pending_signals();
Guido van Rossum359bcaa1997-11-14 22:24:28 +00001940}
Victor Stinner26881c82020-06-02 15:51:37 +02001941#endif /* HAVE_FORK */
1942
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001943
1944int
1945_PyOS_IsMainThread(void)
1946{
Victor Stinner81a7be32020-04-14 15:14:01 +02001947 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001948 return _Py_ThreadCanHandleSignals(interp);
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01001949}
1950
1951#ifdef MS_WINDOWS
1952void *_PyOS_SigintEvent(void)
1953{
1954 /* Returns a manual-reset event which gets tripped whenever
1955 SIGINT is received.
1956
1957 Python.h does not include windows.h so we do cannot use HANDLE
1958 as the return type of this function. We use void* instead. */
1959 return sigint_event;
1960}
1961#endif