blob: 96881d4a49f105c3885de66acdfa0ca36a35686a [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 Stinnera5e64442021-04-28 03:02:55 +02007#include "pycore_atomic.h" // _Py_atomic_int
8#include "pycore_call.h" // _PyObject_Call()
9#include "pycore_ceval.h" // _PyEval_SignalReceived()
10#include "pycore_moduleobject.h" // _PyModule_GetState()
11#include "pycore_pyerrors.h" // _PyErr_SetString()
12#include "pycore_pylifecycle.h" // NSIG
13#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner31368a42018-10-30 15:14:25 +010014
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020015#ifndef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +020016# include "posixmodule.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020017#endif
Victor Stinner11517102014-07-29 23:31:34 +020018#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +020019# include "socketmodule.h" /* needed for SOCKET_T */
Victor Stinner11517102014-07-29 23:31:34 +020020#endif
Guido van Rossum398d9fe1994-05-11 08:59:13 +000021
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000022#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +020023# include <windows.h>
24# ifdef HAVE_PROCESS_H
25# include <process.h>
26# endif
Benjamin Peterson2614cda2010-03-21 22:36:19 +000027#endif
Guido van Rossum644a12b1997-04-09 19:24:53 +000028
Benjamin Peterson2614cda2010-03-21 22:36:19 +000029#ifdef HAVE_SIGNAL_H
Victor Stinnera5e64442021-04-28 03:02:55 +020030# include <signal.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000031#endif
Benjamin Peterson74834512019-11-19 20:39:14 -080032#ifdef HAVE_SYS_SYSCALL_H
Victor Stinnera5e64442021-04-28 03:02:55 +020033# include <sys/syscall.h>
Benjamin Peterson74834512019-11-19 20:39:14 -080034#endif
Benjamin Peterson2614cda2010-03-21 22:36:19 +000035#ifdef HAVE_SYS_STAT_H
Victor Stinnera5e64442021-04-28 03:02:55 +020036# include <sys/stat.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000037#endif
Martin v. Löwis3bf3cc02008-03-24 14:05:07 +000038#ifdef HAVE_SYS_TIME_H
Victor Stinnera5e64442021-04-28 03:02:55 +020039# include <sys/time.h>
Martin v. Löwis3bf3cc02008-03-24 14:05:07 +000040#endif
Christian Heimes5fb7c2a2007-12-24 08:52:31 +000041
Victor Stinnera9293352011-04-30 15:21:58 +020042#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
43# define PYPTHREAD_SIGMASK
44#endif
45
46#if defined(PYPTHREAD_SIGMASK) && defined(HAVE_PTHREAD_H)
47# include <pthread.h>
48#endif
49
Guido van Rossumbb4ba121994-06-23 11:25:45 +000050#ifndef SIG_ERR
Victor Stinnera5e64442021-04-28 03:02:55 +020051# define SIG_ERR ((PyOS_sighandler_t)(-1))
Guido van Rossumbb4ba121994-06-23 11:25:45 +000052#endif
53
Tal Einatc7027b72015-05-16 14:14:49 +030054#include "clinic/signalmodule.c.h"
55
56/*[clinic input]
57module signal
58[clinic start generated code]*/
59/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b0301a3bde5fe9d3]*/
60
Miss Islington (bot)632d5892021-11-25 03:53:07 -080061#ifdef HAVE_SETSIG_T
62
Serhiy Storchakad54cfb12018-05-08 07:48:50 +030063/*[python input]
64
65class sigset_t_converter(CConverter):
66 type = 'sigset_t'
67 converter = '_Py_Sigset_Converter'
68
69[python start generated code]*/
70/*[python end generated code: output=da39a3ee5e6b4b0d input=b5689d14466b6823]*/
Miss Islington (bot)632d5892021-11-25 03:53:07 -080071#endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +000072
Guido van Rossumbb4ba121994-06-23 11:25:45 +000073/*
74 NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS
75
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +020076 We want the following semantics:
Guido van Rossumbb4ba121994-06-23 11:25:45 +000077
78 - only the main thread can set a signal handler
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +020079 - only the main thread runs the signal handler
80 - signals can be delivered to any thread
Guido van Rossumbb4ba121994-06-23 11:25:45 +000081 - any thread can get a signal handler
Guido van Rossumbb4ba121994-06-23 11:25:45 +000082
83 I.e. we don't support "synchronous signals" like SIGFPE (catching
84 this doesn't make much sense in Python anyway) nor do we support
85 signals as a means of inter-thread communication, since not all
86 thread implementations support that (at least our thread library
87 doesn't).
88
89 We still have the problem that in some implementations signals
90 generated by the keyboard (e.g. SIGINT) are delivered to all
91 threads (e.g. SGI), while in others (e.g. Solaris) such signals are
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +020092 delivered to one random thread. On Linux, signals are delivered to
93 the main thread (unless the main thread is blocking the signal, for
94 example because it's already handling the same signal). Since we
95 allow signals to be delivered to any thread, this works fine. The
96 only oddity is that the thread executing the Python signal handler
97 may not be the thread that received the signal.
Guido van Rossumbb4ba121994-06-23 11:25:45 +000098*/
99
Victor Stinner2ec6b172011-05-15 10:21:59 +0200100static volatile struct {
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200101 _Py_atomic_int tripped;
Antoine Pitrouba251c22021-03-11 23:35:45 +0100102 /* func is atomic to ensure that PyErr_SetInterrupt is async-signal-safe
103 * (even though it would probably be otherwise, anyway).
104 */
105 _Py_atomic_address func;
Barry Warsaw92971171997-01-03 00:14:25 +0000106} Handlers[NSIG];
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000107
Victor Stinner11517102014-07-29 23:31:34 +0200108#ifdef MS_WINDOWS
109#define INVALID_FD ((SOCKET_T)-1)
110
111static volatile struct {
112 SOCKET_T fd;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800113 int warn_on_full_buffer;
Victor Stinner11517102014-07-29 23:31:34 +0200114 int use_send;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800115} wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1, .use_send = 0};
Victor Stinner11517102014-07-29 23:31:34 +0200116#else
117#define INVALID_FD (-1)
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800118static volatile struct {
pxinwr1244c812020-12-01 05:48:33 +0800119#ifdef __VXWORKS__
120 int fd;
121#else
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800122 sig_atomic_t fd;
pxinwr1244c812020-12-01 05:48:33 +0800123#endif
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800124 int warn_on_full_buffer;
125} wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1};
Victor Stinner11517102014-07-29 23:31:34 +0200126#endif
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000127
Christian Heimesb76922a2007-12-11 01:06:40 +0000128/* Speed up sigcheck() when none tripped */
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200129static _Py_atomic_int is_tripped;
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000130
Victor Stinnera5e64442021-04-28 03:02:55 +0200131typedef struct {
132 PyObject *default_handler;
133 PyObject *ignore_handler;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100134#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +0200135 HANDLE sigint_event;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100136#endif
Victor Stinnera5e64442021-04-28 03:02:55 +0200137} signal_state_t;
138
139// State shared by all Python interpreters
140static signal_state_t signal_global_state = {0};
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100141
Victor Stinner0ae323b2020-11-17 18:15:20 +0100142#if defined(HAVE_GETITIMER) || defined(HAVE_SETITIMER)
Victor Stinnera5e64442021-04-28 03:02:55 +0200143# define PYHAVE_ITIMER_ERROR
Victor Stinner0ae323b2020-11-17 18:15:20 +0100144#endif
Martin v. Löwis823725e2008-03-24 13:39:54 +0000145
Victor Stinnera5e64442021-04-28 03:02:55 +0200146typedef struct {
147 PyObject *default_handler; // borrowed ref (signal_global_state)
148 PyObject *ignore_handler; // borrowed ref (signal_global_state)
149#ifdef PYHAVE_ITIMER_ERROR
150 PyObject *itimer_error;
151#endif
152} _signal_module_state;
153
154
Antoine Pitrouba251c22021-03-11 23:35:45 +0100155Py_LOCAL_INLINE(PyObject *)
Victor Stinnera5e64442021-04-28 03:02:55 +0200156get_handler(int i)
157{
Antoine Pitrouba251c22021-03-11 23:35:45 +0100158 return (PyObject *)_Py_atomic_load(&Handlers[i].func);
159}
160
161Py_LOCAL_INLINE(void)
Victor Stinnera5e64442021-04-28 03:02:55 +0200162set_handler(int i, PyObject* func)
163{
Antoine Pitrouba251c22021-03-11 23:35:45 +0100164 _Py_atomic_store(&Handlers[i].func, (uintptr_t)func);
165}
166
Victor Stinnera5e64442021-04-28 03:02:55 +0200167
168static inline _signal_module_state*
169get_signal_state(PyObject *module)
170{
171 void *state = _PyModule_GetState(module);
172 assert(state != NULL);
173 return (_signal_module_state *)state;
174}
175
176
Victor Stinner0ae323b2020-11-17 18:15:20 +0100177#ifdef HAVE_GETITIMER
Victor Stinneref611c92017-10-13 13:49:43 -0700178/* auxiliary functions for setitimer */
179static int
180timeval_from_double(PyObject *obj, struct timeval *tv)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000181{
Victor Stinneref611c92017-10-13 13:49:43 -0700182 if (obj == NULL) {
183 tv->tv_sec = 0;
184 tv->tv_usec = 0;
185 return 0;
Antoine Pitrou729780a2017-06-30 10:01:05 +0200186 }
Victor Stinneref611c92017-10-13 13:49:43 -0700187
188 _PyTime_t t;
189 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_CEILING) < 0) {
190 return -1;
191 }
192 return _PyTime_AsTimeval(t, tv, _PyTime_ROUND_CEILING);
Martin v. Löwis823725e2008-03-24 13:39:54 +0000193}
194
Christian Heimes1a8501c2008-10-02 19:56:01 +0000195Py_LOCAL_INLINE(double)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000196double_from_timeval(struct timeval *tv)
197{
198 return tv->tv_sec + (double)(tv->tv_usec / 1000000.0);
199}
200
201static PyObject *
202itimer_retval(struct itimerval *iv)
203{
204 PyObject *r, *v;
205
206 r = PyTuple_New(2);
207 if (r == NULL)
Martin Panter6d57fe12016-09-17 03:26:16 +0000208 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000209
210 if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
Martin Panter6d57fe12016-09-17 03:26:16 +0000211 Py_DECREF(r);
212 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000213 }
214
215 PyTuple_SET_ITEM(r, 0, v);
216
217 if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) {
Martin Panter6d57fe12016-09-17 03:26:16 +0000218 Py_DECREF(r);
219 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000220 }
221
222 PyTuple_SET_ITEM(r, 1, v);
223
224 return r;
225}
226#endif
Barry Warsaw92971171997-01-03 00:14:25 +0000227
Serhiy Storchakab0689ae2020-07-12 19:15:20 +0300228/*[clinic input]
229signal.default_int_handler
230 signalnum: int
231 frame: object
232 /
233
234The default handler for SIGINT installed by Python.
235
236It raises KeyboardInterrupt.
237[clinic start generated code]*/
238
Guido van Rossume4485b01994-09-07 14:32:49 +0000239static PyObject *
Serhiy Storchakab0689ae2020-07-12 19:15:20 +0300240signal_default_int_handler_impl(PyObject *module, int signalnum,
241 PyObject *frame)
242/*[clinic end generated code: output=bb11c2eb115ace4e input=efcd4a56a207acfd]*/
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 PyErr_SetNone(PyExc_KeyboardInterrupt);
245 return NULL;
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000246}
247
Thomas Wouters0796b002000-07-22 23:49:30 +0000248
249static int
Victor Stinner11517102014-07-29 23:31:34 +0200250report_wakeup_write_error(void *data)
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200251{
Eric Snowfdf282d2019-01-11 14:26:55 -0700252 PyObject *exc, *val, *tb;
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200253 int save_errno = errno;
Benjamin Petersonca470632016-09-06 13:47:26 -0700254 errno = (int) (intptr_t) data;
Eric Snowfdf282d2019-01-11 14:26:55 -0700255 PyErr_Fetch(&exc, &val, &tb);
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200256 PyErr_SetFromErrno(PyExc_OSError);
257 PySys_WriteStderr("Exception ignored when trying to write to the "
258 "signal wakeup fd:\n");
259 PyErr_WriteUnraisable(NULL);
Eric Snowfdf282d2019-01-11 14:26:55 -0700260 PyErr_Restore(exc, val, tb);
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200261 errno = save_errno;
262 return 0;
263}
264
Victor Stinner11517102014-07-29 23:31:34 +0200265#ifdef MS_WINDOWS
266static int
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800267report_wakeup_send_error(void* data)
Victor Stinner11517102014-07-29 23:31:34 +0200268{
Eric Snowfdf282d2019-01-11 14:26:55 -0700269 PyObject *exc, *val, *tb;
270 PyErr_Fetch(&exc, &val, &tb);
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800271 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
272 recognizes the error codes used by both GetLastError() and
273 WSAGetLastError */
274 PyErr_SetExcFromWindowsErr(PyExc_OSError, (int) (intptr_t) data);
Victor Stinner11517102014-07-29 23:31:34 +0200275 PySys_WriteStderr("Exception ignored when trying to send to the "
276 "signal wakeup fd:\n");
277 PyErr_WriteUnraisable(NULL);
Eric Snowfdf282d2019-01-11 14:26:55 -0700278 PyErr_Restore(exc, val, tb);
Victor Stinner11517102014-07-29 23:31:34 +0200279 return 0;
280}
281#endif /* MS_WINDOWS */
282
Tim Peters4f1b2082000-07-23 21:18:09 +0000283static void
Victor Stinner6c9b35b2011-04-18 16:25:56 +0200284trip_signal(int sig_num)
285{
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200286 _Py_atomic_store_relaxed(&Handlers[sig_num].tripped, 1);
Victor Stinner11517102014-07-29 23:31:34 +0200287
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200288 /* Set is_tripped after setting .tripped, as it gets
289 cleared in PyErr_CheckSignals() before .tripped. */
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200290 _Py_atomic_store(&is_tripped, 1);
291
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200292 /* Signals are always handled by the main interpreter */
293 PyInterpreterState *interp = _PyRuntime.interpreters.main;
Victor Stinner8849e592020-03-18 19:28:53 +0100294
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200295 /* Notify ceval.c */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200296 _PyEval_SignalReceived(interp);
Nathaniel J. Smith4ae01492017-05-16 14:12:11 -0700297
298 /* And then write to the wakeup fd *after* setting all the globals and
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200299 doing the _PyEval_SignalReceived. We used to write to the wakeup fd
300 and then set the flag, but this allowed the following sequence of events
301 (especially on windows, where trip_signal may run in a new thread):
Nathaniel J. Smith4ae01492017-05-16 14:12:11 -0700302
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800303 - main thread blocks on select([wakeup.fd], ...)
Nathaniel J. Smith4ae01492017-05-16 14:12:11 -0700304 - signal arrives
305 - trip_signal writes to the wakeup fd
306 - the main thread wakes up
307 - the main thread checks the signal flags, sees that they're unset
308 - the main thread empties the wakeup fd
309 - the main thread goes back to sleep
310 - trip_signal sets the flags to request the Python-level signal handler
311 be run
312 - the main thread doesn't notice, because it's asleep
313
314 See bpo-30038 for more details.
315 */
316
Victor Stinnercda23be2020-11-17 18:57:32 +0100317 int fd;
Victor Stinner11517102014-07-29 23:31:34 +0200318#ifdef MS_WINDOWS
319 fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
320#else
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800321 fd = wakeup.fd;
Victor Stinner11517102014-07-29 23:31:34 +0200322#endif
323
324 if (fd != INVALID_FD) {
Victor Stinnercda23be2020-11-17 18:57:32 +0100325 unsigned char byte = (unsigned char)sig_num;
Victor Stinner11517102014-07-29 23:31:34 +0200326#ifdef MS_WINDOWS
327 if (wakeup.use_send) {
Victor Stinnercda23be2020-11-17 18:57:32 +0100328 Py_ssize_t rc = send(fd, &byte, 1, 0);
Victor Stinner11517102014-07-29 23:31:34 +0200329
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800330 if (rc < 0) {
331 int last_error = GetLastError();
332 if (wakeup.warn_on_full_buffer ||
333 last_error != WSAEWOULDBLOCK)
334 {
Victor Stinner50e6e992020-03-19 02:41:21 +0100335 /* _PyEval_AddPendingCall() isn't signal-safe, but we
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800336 still use it for this exceptional case. */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200337 _PyEval_AddPendingCall(interp,
Victor Stinner09532fe2019-05-10 23:39:09 +0200338 report_wakeup_send_error,
339 (void *)(intptr_t) last_error);
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800340 }
Victor Stinner11517102014-07-29 23:31:34 +0200341 }
342 }
343 else
344#endif
345 {
Victor Stinnere72fe392015-04-01 18:35:22 +0200346 /* _Py_write_noraise() retries write() if write() is interrupted by
347 a signal (fails with EINTR). */
Victor Stinnercda23be2020-11-17 18:57:32 +0100348 Py_ssize_t rc = _Py_write_noraise(fd, &byte, 1);
Victor Stinner11517102014-07-29 23:31:34 +0200349
350 if (rc < 0) {
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800351 if (wakeup.warn_on_full_buffer ||
352 (errno != EWOULDBLOCK && errno != EAGAIN))
353 {
Victor Stinner50e6e992020-03-19 02:41:21 +0100354 /* _PyEval_AddPendingCall() isn't signal-safe, but we
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800355 still use it for this exceptional case. */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200356 _PyEval_AddPendingCall(interp,
Victor Stinner09532fe2019-05-10 23:39:09 +0200357 report_wakeup_write_error,
358 (void *)(intptr_t)errno);
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800359 }
Victor Stinner11517102014-07-29 23:31:34 +0200360 }
361 }
Victor Stinnerc13ef662011-05-25 02:35:58 +0200362 }
Victor Stinner6c9b35b2011-04-18 16:25:56 +0200363}
364
365static void
Peter Schneider-Kampe89b1562000-07-10 12:04:18 +0000366signal_handler(int sig_num)
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000367{
Antoine Pitrou39a65912010-11-05 19:47:27 +0000368 int save_errno = errno;
369
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +0200370 trip_signal(sig_num);
Antoine Pitrou39a65912010-11-05 19:47:27 +0000371
Jean-Paul Calderone6f137ca2010-05-09 03:18:57 +0000372#ifndef HAVE_SIGACTION
Antoine Pitrou39a65912010-11-05 19:47:27 +0000373#ifdef SIGCHLD
374 /* To avoid infinite recursion, this signal remains
375 reset until explicit re-instated.
376 Don't clear the 'func' field as it is our pointer
377 to the Python handler... */
378 if (sig_num != SIGCHLD)
379#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* If the handler was not set up with sigaction, reinstall it. See
Nick Coghland6009512014-11-20 21:39:37 +1000381 * Python/pylifecycle.c for the implementation of PyOS_setsig which
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 * makes this true. See also issue8354. */
383 PyOS_setsig(sig_num, signal_handler);
Jean-Paul Calderone6f137ca2010-05-09 03:18:57 +0000384#endif
Antoine Pitrou39a65912010-11-05 19:47:27 +0000385
386 /* Issue #10311: asynchronously executing signal handlers should not
387 mutate errno under the feet of unsuspecting C code. */
388 errno = save_errno;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100389
390#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +0200391 if (sig_num == SIGINT) {
392 signal_state_t *state = &signal_global_state;
393 SetEvent(state->sigint_event);
394 }
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100395#endif
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000396}
Guido van Rossume4485b01994-09-07 14:32:49 +0000397
Guido van Rossum06d511d1995-03-10 15:13:48 +0000398
Guido van Rossum1171ee61997-08-22 20:42:00 +0000399#ifdef HAVE_ALARM
Tal Einatc7027b72015-05-16 14:14:49 +0300400
401/*[clinic input]
402signal.alarm -> long
403
404 seconds: int
405 /
406
407Arrange for SIGALRM to arrive after the given number of seconds.
408[clinic start generated code]*/
409
410static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300411signal_alarm_impl(PyObject *module, int seconds)
412/*[clinic end generated code: output=144232290814c298 input=0d5e97e0e6f39e86]*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 /* alarm() returns the number of seconds remaining */
Tal Einatc7027b72015-05-16 14:14:49 +0300415 return (long)alarm(seconds);
Guido van Rossumaa0f4c71994-08-23 13:49:37 +0000416}
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +0000417
Guido van Rossum06d511d1995-03-10 15:13:48 +0000418#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000419
Guido van Rossum1171ee61997-08-22 20:42:00 +0000420#ifdef HAVE_PAUSE
Tal Einatc7027b72015-05-16 14:14:49 +0300421
422/*[clinic input]
423signal.pause
424
425Wait until a signal arrives.
426[clinic start generated code]*/
427
Guido van Rossuma597dde1995-01-10 20:56:29 +0000428static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300429signal_pause_impl(PyObject *module)
430/*[clinic end generated code: output=391656788b3c3929 input=f03de0f875752062]*/
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_BEGIN_ALLOW_THREADS
433 (void)pause();
434 Py_END_ALLOW_THREADS
435 /* make sure that any exceptions that got raised are propagated
436 * back into Python
437 */
438 if (PyErr_CheckSignals())
439 return NULL;
Barry Warsaw92971171997-01-03 00:14:25 +0000440
Tal Einatc7027b72015-05-16 14:14:49 +0300441 Py_RETURN_NONE;
Guido van Rossume4485b01994-09-07 14:32:49 +0000442}
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +0000443
Guido van Rossum06d511d1995-03-10 15:13:48 +0000444#endif
Guido van Rossume4485b01994-09-07 14:32:49 +0000445
Vladimir Matveevc24c6c22019-01-08 01:58:25 -0800446/*[clinic input]
447signal.raise_signal
448
449 signalnum: int
450 /
451
452Send a signal to the executing process.
453[clinic start generated code]*/
454
455static PyObject *
456signal_raise_signal_impl(PyObject *module, int signalnum)
457/*[clinic end generated code: output=e2b014220aa6111d input=e90c0f9a42358de6]*/
458{
459 int err;
460 Py_BEGIN_ALLOW_THREADS
461 _Py_BEGIN_SUPPRESS_IPH
462 err = raise(signalnum);
463 _Py_END_SUPPRESS_IPH
464 Py_END_ALLOW_THREADS
Victor Stinner09532fe2019-05-10 23:39:09 +0200465
Vladimir Matveevc24c6c22019-01-08 01:58:25 -0800466 if (err) {
467 return PyErr_SetFromErrno(PyExc_OSError);
468 }
469 Py_RETURN_NONE;
470}
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +0000471
Tal Einatc7027b72015-05-16 14:14:49 +0300472/*[clinic input]
473signal.signal
474
475 signalnum: int
476 handler: object
477 /
478
479Set the action for the given signal.
480
481The action can be SIG_DFL, SIG_IGN, or a callable Python object.
482The previous action is returned. See getsignal() for possible return values.
483
484*** IMPORTANT NOTICE ***
485A signal handler function is called with two arguments:
486the first is the signal number, the second is the interrupted stack frame.
487[clinic start generated code]*/
488
Guido van Rossume4485b01994-09-07 14:32:49 +0000489static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300490signal_signal_impl(PyObject *module, int signalnum, PyObject *handler)
491/*[clinic end generated code: output=b44cfda43780f3a1 input=deee84af5fa0432c]*/
Guido van Rossume4485b01994-09-07 14:32:49 +0000492{
Victor Stinnera5e64442021-04-28 03:02:55 +0200493 _signal_module_state *modstate = get_signal_state(module);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 PyObject *old_handler;
495 void (*func)(int);
Brian Curtinef9efbd2010-08-06 19:27:32 +0000496#ifdef MS_WINDOWS
Tal Einatc7027b72015-05-16 14:14:49 +0300497 /* Validate that signalnum is one of the allowable signals */
498 switch (signalnum) {
Brian Curtinc734b312010-09-06 16:04:10 +0000499 case SIGABRT: break;
Brian Curtin9e88b5a2010-10-01 14:49:24 +0000500#ifdef SIGBREAK
501 /* Issue #10003: SIGBREAK is not documented as permitted, but works
502 and corresponds to CTRL_BREAK_EVENT. */
503 case SIGBREAK: break;
504#endif
Brian Curtinc734b312010-09-06 16:04:10 +0000505 case SIGFPE: break;
506 case SIGILL: break;
507 case SIGINT: break;
508 case SIGSEGV: break;
509 case SIGTERM: break;
510 default:
511 PyErr_SetString(PyExc_ValueError, "invalid signal value");
512 return NULL;
Brian Curtinef9efbd2010-08-06 19:27:32 +0000513 }
514#endif
Victor Stinnerd8613dc2019-05-24 13:43:55 +0200515
Victor Stinner72818982020-03-26 22:28:11 +0100516 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200517 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Victor Stinner72818982020-03-26 22:28:11 +0100518 _PyErr_SetString(tstate, PyExc_ValueError,
519 "signal only works in main thread "
520 "of the main interpreter");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return NULL;
522 }
Tal Einatc7027b72015-05-16 14:14:49 +0300523 if (signalnum < 1 || signalnum >= NSIG) {
Victor Stinner72818982020-03-26 22:28:11 +0100524 _PyErr_SetString(tstate, PyExc_ValueError,
525 "signal number out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return NULL;
527 }
Victor Stinnera5e64442021-04-28 03:02:55 +0200528 if (handler == modstate->ignore_handler) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 func = SIG_IGN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 }
Victor Stinnera5e64442021-04-28 03:02:55 +0200531 else if (handler == modstate->default_handler) {
Victor Stinner72818982020-03-26 22:28:11 +0100532 func = SIG_DFL;
533 }
534 else if (!PyCallable_Check(handler)) {
535 _PyErr_SetString(tstate, PyExc_TypeError,
536 "signal handler must be signal.SIG_IGN, "
537 "signal.SIG_DFL, or a callable object");
538 return NULL;
539 }
540 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 func = signal_handler;
Victor Stinner72818982020-03-26 22:28:11 +0100542 }
543
Antoine Pitrouf6f90ff2017-11-03 19:58:46 +0100544 /* Check for pending signals before changing signal handler */
Victor Stinner72818982020-03-26 22:28:11 +0100545 if (_PyErr_CheckSignalsTstate(tstate)) {
Antoine Pitrouf6f90ff2017-11-03 19:58:46 +0100546 return NULL;
547 }
Tal Einatc7027b72015-05-16 14:14:49 +0300548 if (PyOS_setsig(signalnum, func) == SIG_ERR) {
Victor Stinner388196e2011-05-10 17:13:00 +0200549 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return NULL;
551 }
Victor Stinner72818982020-03-26 22:28:11 +0100552
Antoine Pitrouba251c22021-03-11 23:35:45 +0100553 old_handler = get_handler(signalnum);
Victor Stinnera5e64442021-04-28 03:02:55 +0200554 set_handler(signalnum, Py_NewRef(handler));
Victor Stinner72818982020-03-26 22:28:11 +0100555
556 if (old_handler != NULL) {
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200557 return old_handler;
Victor Stinner72818982020-03-26 22:28:11 +0100558 }
559 else {
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200560 Py_RETURN_NONE;
Victor Stinner72818982020-03-26 22:28:11 +0100561 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000562}
563
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +0000564
Tal Einatc7027b72015-05-16 14:14:49 +0300565/*[clinic input]
566signal.getsignal
567
568 signalnum: int
569 /
570
571Return the current action for the given signal.
572
573The return value can be:
574 SIG_IGN -- if the signal is being ignored
575 SIG_DFL -- if the default action for the signal is in effect
576 None -- if an unknown handler is in effect
577 anything else -- the callable Python object used as a handler
578[clinic start generated code]*/
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +0000579
Guido van Rossume4485b01994-09-07 14:32:49 +0000580static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300581signal_getsignal_impl(PyObject *module, int signalnum)
582/*[clinic end generated code: output=35b3e0e796fd555e input=ac23a00f19dfa509]*/
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 PyObject *old_handler;
Tal Einatc7027b72015-05-16 14:14:49 +0300585 if (signalnum < 1 || signalnum >= NSIG) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 PyErr_SetString(PyExc_ValueError,
587 "signal number out of range");
588 return NULL;
589 }
Antoine Pitrouba251c22021-03-11 23:35:45 +0100590 old_handler = get_handler(signalnum);
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200591 if (old_handler != NULL) {
Victor Stinnercda23be2020-11-17 18:57:32 +0100592 return Py_NewRef(old_handler);
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200593 }
594 else {
595 Py_RETURN_NONE;
596 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000597}
598
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100599
600/*[clinic input]
601signal.strsignal
602
603 signalnum: int
604 /
605
606Return the system description of the given signal.
607
608The return values can be such as "Interrupt", "Segmentation fault", etc.
609Returns None if the signal is not recognized.
610[clinic start generated code]*/
611
612static PyObject *
613signal_strsignal_impl(PyObject *module, int signalnum)
614/*[clinic end generated code: output=44e12e1e3b666261 input=b77914b03f856c74]*/
615{
616 char *res;
617
618 if (signalnum < 1 || signalnum >= NSIG) {
619 PyErr_SetString(PyExc_ValueError,
620 "signal number out of range");
621 return NULL;
622 }
623
Michael Osipov48ce4892018-08-23 15:27:19 +0200624#ifndef HAVE_STRSIGNAL
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100625 switch (signalnum) {
Michael Osipov48ce4892018-08-23 15:27:19 +0200626 /* Though being a UNIX, HP-UX does not provide strsignal(3). */
627#ifndef MS_WINDOWS
628 case SIGHUP:
629 res = "Hangup";
630 break;
631 case SIGALRM:
632 res = "Alarm clock";
633 break;
634 case SIGPIPE:
635 res = "Broken pipe";
636 break;
637 case SIGQUIT:
638 res = "Quit";
639 break;
640 case SIGCHLD:
641 res = "Child exited";
642 break;
643#endif
644 /* Custom redefinition of POSIX signals allowed on Windows. */
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100645 case SIGINT:
646 res = "Interrupt";
647 break;
648 case SIGILL:
649 res = "Illegal instruction";
650 break;
651 case SIGABRT:
652 res = "Aborted";
653 break;
654 case SIGFPE:
655 res = "Floating point exception";
656 break;
657 case SIGSEGV:
658 res = "Segmentation fault";
659 break;
660 case SIGTERM:
661 res = "Terminated";
662 break;
663 default:
664 Py_RETURN_NONE;
665 }
666#else
667 errno = 0;
668 res = strsignal(signalnum);
669
670 if (errno || res == NULL || strstr(res, "Unknown signal") != NULL)
671 Py_RETURN_NONE;
672#endif
673
674 return Py_BuildValue("s", res);
675}
676
Christian Heimes8640e742008-02-23 16:23:06 +0000677#ifdef HAVE_SIGINTERRUPT
Tal Einatc7027b72015-05-16 14:14:49 +0300678
679/*[clinic input]
680signal.siginterrupt
681
682 signalnum: int
683 flag: int
684 /
685
686Change system call restart behaviour.
687
688If flag is False, system calls will be restarted when interrupted by
689signal sig, else system calls will be interrupted.
690[clinic start generated code]*/
Christian Heimes8640e742008-02-23 16:23:06 +0000691
692static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300693signal_siginterrupt_impl(PyObject *module, int signalnum, int flag)
694/*[clinic end generated code: output=063816243d85dd19 input=4160acacca3e2099]*/
Christian Heimes8640e742008-02-23 16:23:06 +0000695{
Tal Einatc7027b72015-05-16 14:14:49 +0300696 if (signalnum < 1 || signalnum >= NSIG) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 PyErr_SetString(PyExc_ValueError,
698 "signal number out of range");
699 return NULL;
700 }
Pablo Galindof9c5e3f2020-09-02 15:29:12 +0100701#ifdef HAVE_SIGACTION
702 struct sigaction act;
703 (void) sigaction(signalnum, NULL, &act);
704 if (flag) {
705 act.sa_flags &= ~SA_RESTART;
706 }
707 else {
708 act.sa_flags |= SA_RESTART;
709 }
710 if (sigaction(signalnum, &act, NULL) < 0) {
711#else
712 if (siginterrupt(signalnum, flag) < 0) {
713#endif
Victor Stinner388196e2011-05-10 17:13:00 +0200714 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return NULL;
716 }
Tal Einatc7027b72015-05-16 14:14:49 +0300717 Py_RETURN_NONE;
Christian Heimes8640e742008-02-23 16:23:06 +0000718}
719
720#endif
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +0000721
Tal Einatc7027b72015-05-16 14:14:49 +0300722
723static PyObject*
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800724signal_set_wakeup_fd(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000725{
Victor Stinnere134a7f2015-03-30 10:09:31 +0200726 struct _Py_stat_struct status;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800727 static char *kwlist[] = {
728 "", "warn_on_full_buffer", NULL,
729 };
730 int warn_on_full_buffer = 1;
Victor Stinner11517102014-07-29 23:31:34 +0200731#ifdef MS_WINDOWS
732 PyObject *fdobj;
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100733 SOCKET_T sockfd, old_sockfd;
Victor Stinner11517102014-07-29 23:31:34 +0200734 int res;
735 int res_size = sizeof res;
736 PyObject *mod;
Victor Stinner11517102014-07-29 23:31:34 +0200737 int is_socket;
738
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800739 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|$p:set_wakeup_fd", kwlist,
740 &fdobj, &warn_on_full_buffer))
Victor Stinner11517102014-07-29 23:31:34 +0200741 return NULL;
742
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100743 sockfd = PyLong_AsSocket_t(fdobj);
744 if (sockfd == (SOCKET_T)(-1) && PyErr_Occurred())
Victor Stinner11517102014-07-29 23:31:34 +0200745 return NULL;
746#else
Victor Stinnercda23be2020-11-17 18:57:32 +0100747 int fd;
Victor Stinner11517102014-07-29 23:31:34 +0200748
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800749 if (!PyArg_ParseTupleAndKeywords(args, kwds, "i|$p:set_wakeup_fd", kwlist,
750 &fd, &warn_on_full_buffer))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 return NULL;
Victor Stinner11517102014-07-29 23:31:34 +0200752#endif
753
Victor Stinner72818982020-03-26 22:28:11 +0100754 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200755 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Victor Stinner72818982020-03-26 22:28:11 +0100756 _PyErr_SetString(tstate, PyExc_ValueError,
757 "set_wakeup_fd only works in main thread "
758 "of the main interpreter");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 return NULL;
760 }
Victor Stinner0bffc942014-07-21 16:28:54 +0200761
Victor Stinner11517102014-07-29 23:31:34 +0200762#ifdef MS_WINDOWS
763 is_socket = 0;
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100764 if (sockfd != INVALID_FD) {
Victor Stinner11517102014-07-29 23:31:34 +0200765 /* Import the _socket module to call WSAStartup() */
766 mod = PyImport_ImportModuleNoBlock("_socket");
767 if (mod == NULL)
768 return NULL;
769 Py_DECREF(mod);
770
771 /* test the socket */
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100772 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
Victor Stinner11517102014-07-29 23:31:34 +0200773 (char *)&res, &res_size) != 0) {
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100774 int fd, err;
775
776 err = WSAGetLastError();
Victor Stinner11517102014-07-29 23:31:34 +0200777 if (err != WSAENOTSOCK) {
778 PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
779 return NULL;
780 }
781
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100782 fd = (int)sockfd;
Steve Dower940f33a2016-09-08 11:21:54 -0700783 if ((SOCKET_T)fd != sockfd) {
Victor Stinner72818982020-03-26 22:28:11 +0100784 _PyErr_SetString(tstate, PyExc_ValueError, "invalid fd");
Victor Stinner11517102014-07-29 23:31:34 +0200785 return NULL;
786 }
787
Victor Stinner72818982020-03-26 22:28:11 +0100788 if (_Py_fstat(fd, &status) != 0) {
Victor Stinner11517102014-07-29 23:31:34 +0200789 return NULL;
Victor Stinner72818982020-03-26 22:28:11 +0100790 }
Victor Stinner38227602014-08-27 12:59:44 +0200791
792 /* on Windows, a file cannot be set to non-blocking mode */
Victor Stinner11517102014-07-29 23:31:34 +0200793 }
Victor Stinner38227602014-08-27 12:59:44 +0200794 else {
Victor Stinner11517102014-07-29 23:31:34 +0200795 is_socket = 1;
Victor Stinner38227602014-08-27 12:59:44 +0200796
797 /* Windows does not provide a function to test if a socket
798 is in non-blocking mode */
799 }
Victor Stinner11517102014-07-29 23:31:34 +0200800 }
801
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100802 old_sockfd = wakeup.fd;
803 wakeup.fd = sockfd;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800804 wakeup.warn_on_full_buffer = warn_on_full_buffer;
Victor Stinner11517102014-07-29 23:31:34 +0200805 wakeup.use_send = is_socket;
806
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100807 if (old_sockfd != INVALID_FD)
808 return PyLong_FromSocket_t(old_sockfd);
Victor Stinner11517102014-07-29 23:31:34 +0200809 else
810 return PyLong_FromLong(-1);
811#else
Victor Stinnerd18ccd12014-07-24 21:58:53 +0200812 if (fd != -1) {
Victor Stinner38227602014-08-27 12:59:44 +0200813 int blocking;
814
Victor Stinnere134a7f2015-03-30 10:09:31 +0200815 if (_Py_fstat(fd, &status) != 0)
Victor Stinner11517102014-07-29 23:31:34 +0200816 return NULL;
Victor Stinner38227602014-08-27 12:59:44 +0200817
818 blocking = _Py_get_blocking(fd);
819 if (blocking < 0)
820 return NULL;
821 if (blocking) {
Victor Stinner72818982020-03-26 22:28:11 +0100822 _PyErr_Format(tstate, PyExc_ValueError,
823 "the fd %i must be in non-blocking mode",
824 fd);
Victor Stinner38227602014-08-27 12:59:44 +0200825 return NULL;
826 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 }
Victor Stinner0bffc942014-07-21 16:28:54 +0200828
Victor Stinnercda23be2020-11-17 18:57:32 +0100829 int old_fd = wakeup.fd;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800830 wakeup.fd = fd;
831 wakeup.warn_on_full_buffer = warn_on_full_buffer;
Victor Stinner0bffc942014-07-21 16:28:54 +0200832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 return PyLong_FromLong(old_fd);
Victor Stinner11517102014-07-29 23:31:34 +0200834#endif
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000835}
836
837PyDoc_STRVAR(set_wakeup_fd_doc,
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800838"set_wakeup_fd(fd, *, warn_on_full_buffer=True) -> fd\n\
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000839\n\
Victor Stinner11517102014-07-29 23:31:34 +0200840Sets the fd to be written to (with the signal number) when a signal\n\
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000841comes in. A library can use this to wakeup select or poll.\n\
Victor Stinner11517102014-07-29 23:31:34 +0200842The previous fd or -1 is returned.\n\
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000843\n\
844The fd must be non-blocking.");
845
846/* C API for the same, without all the error checking */
847int
848PySignal_SetWakeupFd(int fd)
849{
Victor Stinnercda23be2020-11-17 18:57:32 +0100850 if (fd < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 fd = -1;
Victor Stinnercda23be2020-11-17 18:57:32 +0100852 }
Victor Stinner11517102014-07-29 23:31:34 +0200853
854#ifdef MS_WINDOWS
Victor Stinnercda23be2020-11-17 18:57:32 +0100855 int old_fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
Victor Stinner11517102014-07-29 23:31:34 +0200856#else
Victor Stinnercda23be2020-11-17 18:57:32 +0100857 int old_fd = wakeup.fd;
Victor Stinner11517102014-07-29 23:31:34 +0200858#endif
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800859 wakeup.fd = fd;
860 wakeup.warn_on_full_buffer = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 return old_fd;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000862}
863
864
Martin v. Löwis823725e2008-03-24 13:39:54 +0000865#ifdef HAVE_SETITIMER
Tal Einatc7027b72015-05-16 14:14:49 +0300866/*[clinic input]
867signal.setitimer
868
869 which: int
Victor Stinneref611c92017-10-13 13:49:43 -0700870 seconds: object
871 interval: object(c_default="NULL") = 0.0
Tal Einatc7027b72015-05-16 14:14:49 +0300872 /
873
874Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF).
875
876The timer will fire after value seconds and after that every interval seconds.
877The itimer can be cleared by setting seconds to zero.
878
879Returns old values as a tuple: (delay, interval).
880[clinic start generated code]*/
881
Martin v. Löwis823725e2008-03-24 13:39:54 +0000882static PyObject *
Victor Stinneref611c92017-10-13 13:49:43 -0700883signal_setitimer_impl(PyObject *module, int which, PyObject *seconds,
884 PyObject *interval)
885/*[clinic end generated code: output=65f9dcbddc35527b input=de43daf194e6f66f]*/
Martin v. Löwis823725e2008-03-24 13:39:54 +0000886{
Victor Stinnera5e64442021-04-28 03:02:55 +0200887 _signal_module_state *modstate = get_signal_state(module);
Martin v. Löwis823725e2008-03-24 13:39:54 +0000888
Victor Stinnera5e64442021-04-28 03:02:55 +0200889 struct itimerval new;
Victor Stinneref611c92017-10-13 13:49:43 -0700890 if (timeval_from_double(seconds, &new.it_value) < 0) {
891 return NULL;
892 }
893 if (timeval_from_double(interval, &new.it_interval) < 0) {
894 return NULL;
895 }
896
Martin v. Löwis823725e2008-03-24 13:39:54 +0000897 /* Let OS check "which" value */
Victor Stinnercda23be2020-11-17 18:57:32 +0100898 struct itimerval old;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000899 if (setitimer(which, &new, &old) != 0) {
Victor Stinnera5e64442021-04-28 03:02:55 +0200900 PyErr_SetFromErrno(modstate->itimer_error);
Tal Einatc7027b72015-05-16 14:14:49 +0300901 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000902 }
903
904 return itimer_retval(&old);
905}
Victor Stinnera5e64442021-04-28 03:02:55 +0200906#endif // HAVE_SETITIMER
Martin v. Löwis823725e2008-03-24 13:39:54 +0000907
908
909#ifdef HAVE_GETITIMER
Tal Einatc7027b72015-05-16 14:14:49 +0300910/*[clinic input]
911signal.getitimer
912
913 which: int
914 /
915
916Returns current value of given itimer.
917[clinic start generated code]*/
918
Martin v. Löwis823725e2008-03-24 13:39:54 +0000919static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300920signal_getitimer_impl(PyObject *module, int which)
921/*[clinic end generated code: output=9e053175d517db40 input=f7d21d38f3490627]*/
Martin v. Löwis823725e2008-03-24 13:39:54 +0000922{
Victor Stinnera5e64442021-04-28 03:02:55 +0200923 _signal_module_state *modstate = get_signal_state(module);
Martin v. Löwis823725e2008-03-24 13:39:54 +0000924
Victor Stinnera5e64442021-04-28 03:02:55 +0200925 struct itimerval old;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000926 if (getitimer(which, &old) != 0) {
Victor Stinnera5e64442021-04-28 03:02:55 +0200927 PyErr_SetFromErrno(modstate->itimer_error);
Tal Einatc7027b72015-05-16 14:14:49 +0300928 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000929 }
930
931 return itimer_retval(&old);
932}
Victor Stinnera5e64442021-04-28 03:02:55 +0200933#endif // HAVE_GETITIMER
Martin v. Löwis823725e2008-03-24 13:39:54 +0000934
Martin v. Löwis823725e2008-03-24 13:39:54 +0000935
Miss Islington (bot)632d5892021-11-25 03:53:07 -0800936#ifdef HAVE_SIGSET_T
Victor Stinnerb3e72192011-05-08 01:46:11 +0200937#if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGPENDING)
Victor Stinner35b300c2011-05-04 13:20:35 +0200938static PyObject*
939sigset_to_set(sigset_t mask)
940{
941 PyObject *signum, *result;
942 int sig;
943
944 result = PySet_New(0);
945 if (result == NULL)
946 return NULL;
947
948 for (sig = 1; sig < NSIG; sig++) {
949 if (sigismember(&mask, sig) != 1)
950 continue;
951
952 /* Handle the case where it is a member by adding the signal to
953 the result list. Ignore the other cases because they mean the
954 signal isn't a member of the mask or the signal was invalid,
955 and an invalid signal must have been our fault in constructing
956 the loop boundaries. */
957 signum = PyLong_FromLong(sig);
958 if (signum == NULL) {
959 Py_DECREF(result);
960 return NULL;
961 }
962 if (PySet_Add(result, signum) == -1) {
963 Py_DECREF(signum);
964 Py_DECREF(result);
965 return NULL;
966 }
967 Py_DECREF(signum);
968 }
969 return result;
970}
Victor Stinnerb3e72192011-05-08 01:46:11 +0200971#endif
Victor Stinner35b300c2011-05-04 13:20:35 +0200972
Victor Stinnerb3e72192011-05-08 01:46:11 +0200973#ifdef PYPTHREAD_SIGMASK
Tal Einatc7027b72015-05-16 14:14:49 +0300974
975/*[clinic input]
976signal.pthread_sigmask
977
978 how: int
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300979 mask: sigset_t
Tal Einatc7027b72015-05-16 14:14:49 +0300980 /
981
982Fetch and/or change the signal mask of the calling thread.
983[clinic start generated code]*/
984
Victor Stinnera9293352011-04-30 15:21:58 +0200985static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300986signal_pthread_sigmask_impl(PyObject *module, int how, sigset_t mask)
987/*[clinic end generated code: output=0562c0fb192981a8 input=85bcebda442fa77f]*/
Victor Stinnera9293352011-04-30 15:21:58 +0200988{
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300989 sigset_t previous;
Victor Stinnera9293352011-04-30 15:21:58 +0200990 int err;
991
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300992 err = pthread_sigmask(how, &mask, &previous);
Victor Stinnera9293352011-04-30 15:21:58 +0200993 if (err != 0) {
994 errno = err;
Victor Stinnerb3e72192011-05-08 01:46:11 +0200995 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnera9293352011-04-30 15:21:58 +0200996 return NULL;
997 }
998
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200999 /* if signals was unblocked, signal handlers have been called */
1000 if (PyErr_CheckSignals())
1001 return NULL;
1002
Victor Stinner35b300c2011-05-04 13:20:35 +02001003 return sigset_to_set(previous);
Victor Stinnera9293352011-04-30 15:21:58 +02001004}
1005
Victor Stinnera9293352011-04-30 15:21:58 +02001006#endif /* #ifdef PYPTHREAD_SIGMASK */
1007
Martin v. Löwis823725e2008-03-24 13:39:54 +00001008
Victor Stinnerb3e72192011-05-08 01:46:11 +02001009#ifdef HAVE_SIGPENDING
Tal Einatc7027b72015-05-16 14:14:49 +03001010
1011/*[clinic input]
1012signal.sigpending
1013
1014Examine pending signals.
1015
1016Returns a set of signal numbers that are pending for delivery to
1017the calling thread.
1018[clinic start generated code]*/
1019
Victor Stinnerb3e72192011-05-08 01:46:11 +02001020static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001021signal_sigpending_impl(PyObject *module)
1022/*[clinic end generated code: output=53375ffe89325022 input=e0036c016f874e29]*/
Victor Stinnerb3e72192011-05-08 01:46:11 +02001023{
1024 int err;
1025 sigset_t mask;
1026 err = sigpending(&mask);
1027 if (err)
1028 return PyErr_SetFromErrno(PyExc_OSError);
1029 return sigset_to_set(mask);
1030}
1031
Victor Stinnerb3e72192011-05-08 01:46:11 +02001032#endif /* #ifdef HAVE_SIGPENDING */
1033
1034
1035#ifdef HAVE_SIGWAIT
Tal Einatc7027b72015-05-16 14:14:49 +03001036
1037/*[clinic input]
1038signal.sigwait
1039
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001040 sigset: sigset_t
Tal Einatc7027b72015-05-16 14:14:49 +03001041 /
1042
1043Wait for a signal.
1044
1045Suspend execution of the calling thread until the delivery of one of the
1046signals specified in the signal set sigset. The function accepts the signal
1047and returns the signal number.
1048[clinic start generated code]*/
1049
Victor Stinnerb3e72192011-05-08 01:46:11 +02001050static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001051signal_sigwait_impl(PyObject *module, sigset_t sigset)
1052/*[clinic end generated code: output=f43770699d682f96 input=a6fbd47b1086d119]*/
Victor Stinnerb3e72192011-05-08 01:46:11 +02001053{
Victor Stinnerb3e72192011-05-08 01:46:11 +02001054 int err, signum;
1055
Victor Stinner10c30d62011-06-10 01:39:53 +02001056 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001057 err = sigwait(&sigset, &signum);
Victor Stinner10c30d62011-06-10 01:39:53 +02001058 Py_END_ALLOW_THREADS
Victor Stinnerb3e72192011-05-08 01:46:11 +02001059 if (err) {
1060 errno = err;
1061 return PyErr_SetFromErrno(PyExc_OSError);
1062 }
1063
1064 return PyLong_FromLong(signum);
1065}
1066
Tal Einatc7027b72015-05-16 14:14:49 +03001067#endif /* #ifdef HAVE_SIGWAIT */
Miss Islington (bot)632d5892021-11-25 03:53:07 -08001068#endif /* #ifdef HAVE_SIGSET_T */
Tal Einatc7027b72015-05-16 14:14:49 +03001069
Miss Islington (bot)632d5892021-11-25 03:53:07 -08001070#if (defined(HAVE_SIGFILLSET) && defined(HAVE_SIGSET_T)) || defined(MS_WINDOWS)
Antoine Pitrou9d3627e2018-05-04 13:00:50 +02001071
1072/*[clinic input]
1073signal.valid_signals
1074
1075Return a set of valid signal numbers on this platform.
1076
1077The signal numbers returned by this function can be safely passed to
1078functions like `pthread_sigmask`.
1079[clinic start generated code]*/
1080
1081static PyObject *
1082signal_valid_signals_impl(PyObject *module)
1083/*[clinic end generated code: output=1609cffbcfcf1314 input=86a3717ff25288f2]*/
1084{
1085#ifdef MS_WINDOWS
1086#ifdef SIGBREAK
1087 PyObject *tup = Py_BuildValue("(iiiiiii)", SIGABRT, SIGBREAK, SIGFPE,
1088 SIGILL, SIGINT, SIGSEGV, SIGTERM);
1089#else
1090 PyObject *tup = Py_BuildValue("(iiiiii)", SIGABRT, SIGFPE, SIGILL,
1091 SIGINT, SIGSEGV, SIGTERM);
1092#endif
1093 if (tup == NULL) {
1094 return NULL;
1095 }
1096 PyObject *set = PySet_New(tup);
1097 Py_DECREF(tup);
1098 return set;
1099#else
1100 sigset_t mask;
1101 if (sigemptyset(&mask) || sigfillset(&mask)) {
1102 return PyErr_SetFromErrno(PyExc_OSError);
1103 }
1104 return sigset_to_set(mask);
1105#endif
1106}
1107
Miss Islington (bot)632d5892021-11-25 03:53:07 -08001108#endif /* #if (defined(HAVE_SIGFILLSET) && defined(HAVE_SIGSET_T)) || defined(MS_WINDOWS) */
1109
Antoine Pitrou9d3627e2018-05-04 13:00:50 +02001110
1111
Ross Lagerwallbc808222011-06-25 12:13:40 +02001112#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
Ross Lagerwallbc808222011-06-25 12:13:40 +02001113static PyStructSequence_Field struct_siginfo_fields[] = {
1114 {"si_signo", "signal number"},
1115 {"si_code", "signal code"},
1116 {"si_errno", "errno associated with this signal"},
1117 {"si_pid", "sending process ID"},
1118 {"si_uid", "real user ID of sending process"},
1119 {"si_status", "exit value or signal"},
1120 {"si_band", "band event for SIGPOLL"},
1121 {0}
1122};
1123
1124PyDoc_STRVAR(struct_siginfo__doc__,
1125"struct_siginfo: Result from sigwaitinfo or sigtimedwait.\n\n\
1126This object may be accessed either as a tuple of\n\
1127(si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band),\n\
1128or via the attributes si_signo, si_code, and so on.");
1129
1130static PyStructSequence_Desc struct_siginfo_desc = {
1131 "signal.struct_siginfo", /* name */
1132 struct_siginfo__doc__, /* doc */
1133 struct_siginfo_fields, /* fields */
1134 7 /* n_in_sequence */
1135};
1136
1137static PyTypeObject SiginfoType;
1138
1139static PyObject *
1140fill_siginfo(siginfo_t *si)
1141{
1142 PyObject *result = PyStructSequence_New(&SiginfoType);
1143 if (!result)
1144 return NULL;
1145
1146 PyStructSequence_SET_ITEM(result, 0, PyLong_FromLong((long)(si->si_signo)));
1147 PyStructSequence_SET_ITEM(result, 1, PyLong_FromLong((long)(si->si_code)));
Victor Stinner09532fe2019-05-10 23:39:09 +02001148#ifdef __VXWORKS__
pxinwr8b5bdda2019-03-14 01:18:25 +08001149 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(0L));
1150 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(0L));
1151 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(0L));
1152 PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(0L));
Victor Stinner09532fe2019-05-10 23:39:09 +02001153#else
Ross Lagerwallbc808222011-06-25 12:13:40 +02001154 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si->si_errno)));
1155 PyStructSequence_SET_ITEM(result, 3, PyLong_FromPid(si->si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02001156 PyStructSequence_SET_ITEM(result, 4, _PyLong_FromUid(si->si_uid));
Ross Lagerwallbc808222011-06-25 12:13:40 +02001157 PyStructSequence_SET_ITEM(result, 5,
1158 PyLong_FromLong((long)(si->si_status)));
Victor Stinner09532fe2019-05-10 23:39:09 +02001159#endif
Zachary Ware6a6967e2016-10-01 00:47:27 -05001160#ifdef HAVE_SIGINFO_T_SI_BAND
Ross Lagerwallbc808222011-06-25 12:13:40 +02001161 PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(si->si_band));
Zachary Ware6a6967e2016-10-01 00:47:27 -05001162#else
1163 PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(0L));
1164#endif
Ross Lagerwallbc808222011-06-25 12:13:40 +02001165 if (PyErr_Occurred()) {
1166 Py_DECREF(result);
1167 return NULL;
1168 }
1169
1170 return result;
1171}
1172#endif
1173
Miss Islington (bot)632d5892021-11-25 03:53:07 -08001174#ifdef HAVE_SIGSET_T
Ross Lagerwallbc808222011-06-25 12:13:40 +02001175#ifdef HAVE_SIGWAITINFO
Tal Einatc7027b72015-05-16 14:14:49 +03001176
1177/*[clinic input]
1178signal.sigwaitinfo
1179
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001180 sigset: sigset_t
Tal Einatc7027b72015-05-16 14:14:49 +03001181 /
1182
1183Wait synchronously until one of the signals in *sigset* is delivered.
1184
1185Returns a struct_siginfo containing information about the signal.
1186[clinic start generated code]*/
1187
Ross Lagerwallbc808222011-06-25 12:13:40 +02001188static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001189signal_sigwaitinfo_impl(PyObject *module, sigset_t sigset)
1190/*[clinic end generated code: output=1eb2f1fa236fdbca input=3d1a7e1f27fc664c]*/
Ross Lagerwallbc808222011-06-25 12:13:40 +02001191{
Ross Lagerwallbc808222011-06-25 12:13:40 +02001192 siginfo_t si;
1193 int err;
Victor Stinnera453cd82015-03-20 12:54:28 +01001194 int async_err = 0;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001195
Victor Stinnera453cd82015-03-20 12:54:28 +01001196 do {
1197 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001198 err = sigwaitinfo(&sigset, &si);
Victor Stinnera453cd82015-03-20 12:54:28 +01001199 Py_END_ALLOW_THREADS
1200 } while (err == -1
1201 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwallbc808222011-06-25 12:13:40 +02001202 if (err == -1)
Victor Stinnera453cd82015-03-20 12:54:28 +01001203 return (!async_err) ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001204
1205 return fill_siginfo(&si);
1206}
1207
Ross Lagerwallbc808222011-06-25 12:13:40 +02001208#endif /* #ifdef HAVE_SIGWAITINFO */
1209
1210#ifdef HAVE_SIGTIMEDWAIT
Tal Einatc7027b72015-05-16 14:14:49 +03001211
1212/*[clinic input]
1213signal.sigtimedwait
1214
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001215 sigset: sigset_t
Serhiy Storchaka6b680cd2015-05-16 15:57:56 +03001216 timeout as timeout_obj: object
Tal Einatc7027b72015-05-16 14:14:49 +03001217 /
1218
1219Like sigwaitinfo(), but with a timeout.
1220
1221The timeout is specified in seconds, with floating point numbers allowed.
1222[clinic start generated code]*/
1223
Ross Lagerwallbc808222011-06-25 12:13:40 +02001224static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001225signal_sigtimedwait_impl(PyObject *module, sigset_t sigset,
Serhiy Storchaka6b680cd2015-05-16 15:57:56 +03001226 PyObject *timeout_obj)
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001227/*[clinic end generated code: output=59c8971e8ae18a64 input=87fd39237cf0b7ba]*/
Ross Lagerwallbc808222011-06-25 12:13:40 +02001228{
Victor Stinnera453cd82015-03-20 12:54:28 +01001229 struct timespec ts;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001230 siginfo_t si;
Victor Stinnera453cd82015-03-20 12:54:28 +01001231 int res;
Victor Stinner34dc0f42015-03-27 18:19:03 +01001232 _PyTime_t timeout, deadline, monotonic;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001233
Victor Stinner869e1772015-03-30 03:49:14 +02001234 if (_PyTime_FromSecondsObject(&timeout,
1235 timeout_obj, _PyTime_ROUND_CEILING) < 0)
Ross Lagerwallbc808222011-06-25 12:13:40 +02001236 return NULL;
1237
Victor Stinnera453cd82015-03-20 12:54:28 +01001238 if (timeout < 0) {
Ross Lagerwallbc808222011-06-25 12:13:40 +02001239 PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
1240 return NULL;
1241 }
1242
Victor Stinner34dc0f42015-03-27 18:19:03 +01001243 deadline = _PyTime_GetMonotonicClock() + timeout;
Victor Stinnera453cd82015-03-20 12:54:28 +01001244
1245 do {
Victor Stinner34dc0f42015-03-27 18:19:03 +01001246 if (_PyTime_AsTimespec(timeout, &ts) < 0)
1247 return NULL;
Victor Stinnera453cd82015-03-20 12:54:28 +01001248
1249 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001250 res = sigtimedwait(&sigset, &si, &ts);
Victor Stinnera453cd82015-03-20 12:54:28 +01001251 Py_END_ALLOW_THREADS
1252
1253 if (res != -1)
1254 break;
1255
1256 if (errno != EINTR) {
1257 if (errno == EAGAIN)
1258 Py_RETURN_NONE;
1259 else
1260 return PyErr_SetFromErrno(PyExc_OSError);
1261 }
1262
1263 /* sigtimedwait() was interrupted by a signal (EINTR) */
1264 if (PyErr_CheckSignals())
1265 return NULL;
1266
Victor Stinner34dc0f42015-03-27 18:19:03 +01001267 monotonic = _PyTime_GetMonotonicClock();
1268 timeout = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001269 if (timeout < 0)
Victor Stinnera453cd82015-03-20 12:54:28 +01001270 break;
1271 } while (1);
Ross Lagerwallbc808222011-06-25 12:13:40 +02001272
1273 return fill_siginfo(&si);
1274}
1275
Ross Lagerwallbc808222011-06-25 12:13:40 +02001276#endif /* #ifdef HAVE_SIGTIMEDWAIT */
Miss Islington (bot)632d5892021-11-25 03:53:07 -08001277#endif /* #ifdef HAVE_SIGSET_T */
Ross Lagerwallbc808222011-06-25 12:13:40 +02001278
Victor Stinnerb3e72192011-05-08 01:46:11 +02001279
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001280#if defined(HAVE_PTHREAD_KILL)
Tal Einatc7027b72015-05-16 14:14:49 +03001281
1282/*[clinic input]
1283signal.pthread_kill
1284
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001285 thread_id: unsigned_long(bitwise=True)
Tal Einatc7027b72015-05-16 14:14:49 +03001286 signalnum: int
1287 /
1288
1289Send a signal to a thread.
1290[clinic start generated code]*/
1291
Victor Stinnerb3e72192011-05-08 01:46:11 +02001292static PyObject *
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001293signal_pthread_kill_impl(PyObject *module, unsigned long thread_id,
1294 int signalnum)
1295/*[clinic end generated code: output=7629919b791bc27f input=1d901f2c7bb544ff]*/
Victor Stinnerb3e72192011-05-08 01:46:11 +02001296{
Victor Stinnerb3e72192011-05-08 01:46:11 +02001297 int err;
1298
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001299 if (PySys_Audit("signal.pthread_kill", "ki", thread_id, signalnum) < 0) {
1300 return NULL;
1301 }
1302
Tal Einatc7027b72015-05-16 14:14:49 +03001303 err = pthread_kill((pthread_t)thread_id, signalnum);
Victor Stinnerb3e72192011-05-08 01:46:11 +02001304 if (err != 0) {
1305 errno = err;
1306 PyErr_SetFromErrno(PyExc_OSError);
1307 return NULL;
1308 }
1309
1310 /* the signal may have been send to the current thread */
1311 if (PyErr_CheckSignals())
1312 return NULL;
1313
1314 Py_RETURN_NONE;
1315}
1316
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001317#endif /* #if defined(HAVE_PTHREAD_KILL) */
Victor Stinnerb3e72192011-05-08 01:46:11 +02001318
1319
Benjamin Peterson74834512019-11-19 20:39:14 -08001320#if defined(__linux__) && defined(__NR_pidfd_send_signal)
1321/*[clinic input]
1322signal.pidfd_send_signal
1323
1324 pidfd: int
1325 signalnum: int
1326 siginfo: object = None
1327 flags: int = 0
1328 /
1329
1330Send a signal to a process referred to by a pid file descriptor.
1331[clinic start generated code]*/
1332
1333static PyObject *
1334signal_pidfd_send_signal_impl(PyObject *module, int pidfd, int signalnum,
1335 PyObject *siginfo, int flags)
1336/*[clinic end generated code: output=2d59f04a75d9cbdf input=2a6543a1f4ac2000]*/
1337
1338{
1339 if (siginfo != Py_None) {
1340 PyErr_SetString(PyExc_TypeError, "siginfo must be None");
1341 return NULL;
1342 }
1343 if (syscall(__NR_pidfd_send_signal, pidfd, signalnum, NULL, flags) < 0) {
1344 PyErr_SetFromErrno(PyExc_OSError);
1345 return NULL;
1346 }
1347 Py_RETURN_NONE;
1348}
1349#endif
1350
1351
Victor Stinnerb3e72192011-05-08 01:46:11 +02001352
Tal Einatc7027b72015-05-16 14:14:49 +03001353/* List of functions defined in the module -- some of the methoddefs are
1354 defined to nothing if the corresponding C function is not available. */
Barry Warsaw92971171997-01-03 00:14:25 +00001355static PyMethodDef signal_methods[] = {
Serhiy Storchakab0689ae2020-07-12 19:15:20 +03001356 SIGNAL_DEFAULT_INT_HANDLER_METHODDEF
Tal Einatc7027b72015-05-16 14:14:49 +03001357 SIGNAL_ALARM_METHODDEF
1358 SIGNAL_SETITIMER_METHODDEF
1359 SIGNAL_GETITIMER_METHODDEF
1360 SIGNAL_SIGNAL_METHODDEF
Vladimir Matveevc24c6c22019-01-08 01:58:25 -08001361 SIGNAL_RAISE_SIGNAL_METHODDEF
Antoine Pietri5d2a27d2018-03-12 14:42:34 +01001362 SIGNAL_STRSIGNAL_METHODDEF
Tal Einatc7027b72015-05-16 14:14:49 +03001363 SIGNAL_GETSIGNAL_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001364 {"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 +03001365 SIGNAL_SIGINTERRUPT_METHODDEF
1366 SIGNAL_PAUSE_METHODDEF
Benjamin Peterson74834512019-11-19 20:39:14 -08001367 SIGNAL_PIDFD_SEND_SIGNAL_METHODDEF
Tal Einatc7027b72015-05-16 14:14:49 +03001368 SIGNAL_PTHREAD_KILL_METHODDEF
1369 SIGNAL_PTHREAD_SIGMASK_METHODDEF
1370 SIGNAL_SIGPENDING_METHODDEF
1371 SIGNAL_SIGWAIT_METHODDEF
1372 SIGNAL_SIGWAITINFO_METHODDEF
1373 SIGNAL_SIGTIMEDWAIT_METHODDEF
Antoine Pitrou9d3627e2018-05-04 13:00:50 +02001374#if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)
1375 SIGNAL_VALID_SIGNALS_METHODDEF
1376#endif
Tal Einatc7027b72015-05-16 14:14:49 +03001377 {NULL, NULL} /* sentinel */
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001378};
1379
Barry Warsaw92971171997-01-03 00:14:25 +00001380
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001381PyDoc_STRVAR(module_doc,
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001382"This module provides mechanisms to use signal handlers in Python.\n\
1383\n\
1384Functions:\n\
1385\n\
1386alarm() -- cause SIGALRM after a specified time [Unix only]\n\
Martin v. Löwis823725e2008-03-24 13:39:54 +00001387setitimer() -- cause a signal (described below) after a specified\n\
1388 float time and the timer may restart then [Unix only]\n\
1389getitimer() -- get current value of timer [Unix only]\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001390signal() -- set the action for a given signal\n\
1391getsignal() -- get the signal action for a given signal\n\
1392pause() -- wait until a signal arrives [Unix only]\n\
1393default_int_handler() -- default SIGINT handler\n\
1394\n\
Martin v. Löwis823725e2008-03-24 13:39:54 +00001395signal constants:\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001396SIG_DFL -- used to refer to the system default handler\n\
1397SIG_IGN -- used to ignore the signal\n\
1398NSIG -- number of defined signals\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001399SIGINT, SIGTERM, etc. -- signal numbers\n\
1400\n\
Martin v. Löwis823725e2008-03-24 13:39:54 +00001401itimer constants:\n\
1402ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\
1403 expiration\n\
1404ITIMER_VIRTUAL -- decrements only when the process is executing,\n\
1405 and delivers SIGVTALRM upon expiration\n\
1406ITIMER_PROF -- decrements both when the process is executing and\n\
1407 when the system is executing on behalf of the process.\n\
1408 Coupled with ITIMER_VIRTUAL, this timer is usually\n\
1409 used to profile the time spent by the application\n\
1410 in user and kernel space. SIGPROF is delivered upon\n\
1411 expiration.\n\
1412\n\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001413*** IMPORTANT NOTICE ***\n\
1414A signal handler function is called with two arguments:\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001415the first is the signal number, the second is the interrupted stack frame.");
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001416
Martin v. Löwis1a214512008-06-11 05:26:20 +00001417
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001418
1419static int
Victor Stinnercda23be2020-11-17 18:57:32 +01001420signal_add_constants(PyObject *module)
1421{
1422#define ADD_INT_MACRO(macro) \
1423 if (PyModule_AddIntConstant(module, #macro, macro) < 0) { \
1424 return -1; \
1425 }
1426
1427 ADD_INT_MACRO(NSIG);
1428
1429 // SIG_xxx pthread_sigmask() constants
1430#ifdef SIG_BLOCK
1431 ADD_INT_MACRO(SIG_BLOCK);
1432#endif
1433#ifdef SIG_UNBLOCK
1434 ADD_INT_MACRO(SIG_UNBLOCK);
1435#endif
1436#ifdef SIG_SETMASK
1437 ADD_INT_MACRO(SIG_SETMASK);
1438#endif
1439
1440 // SIGxxx signal number constants
1441#ifdef SIGHUP
1442 ADD_INT_MACRO(SIGHUP);
1443#endif
1444#ifdef SIGINT
1445 ADD_INT_MACRO(SIGINT);
1446#endif
1447#ifdef SIGBREAK
1448 ADD_INT_MACRO(SIGBREAK);
1449#endif
1450#ifdef SIGQUIT
1451 ADD_INT_MACRO(SIGQUIT);
1452#endif
1453#ifdef SIGILL
1454 ADD_INT_MACRO(SIGILL);
1455#endif
1456#ifdef SIGTRAP
1457 ADD_INT_MACRO(SIGTRAP);
1458#endif
1459#ifdef SIGIOT
1460 ADD_INT_MACRO(SIGIOT);
1461#endif
1462#ifdef SIGABRT
1463 ADD_INT_MACRO(SIGABRT);
1464#endif
1465#ifdef SIGEMT
1466 ADD_INT_MACRO(SIGEMT);
1467#endif
1468#ifdef SIGFPE
1469 ADD_INT_MACRO(SIGFPE);
1470#endif
1471#ifdef SIGKILL
1472 ADD_INT_MACRO(SIGKILL);
1473#endif
1474#ifdef SIGBUS
1475 ADD_INT_MACRO(SIGBUS);
1476#endif
1477#ifdef SIGSEGV
1478 ADD_INT_MACRO(SIGSEGV);
1479#endif
1480#ifdef SIGSYS
1481 ADD_INT_MACRO(SIGSYS);
1482#endif
1483#ifdef SIGPIPE
1484 ADD_INT_MACRO(SIGPIPE);
1485#endif
1486#ifdef SIGALRM
1487 ADD_INT_MACRO(SIGALRM);
1488#endif
1489#ifdef SIGTERM
1490 ADD_INT_MACRO(SIGTERM);
1491#endif
1492#ifdef SIGUSR1
1493 ADD_INT_MACRO(SIGUSR1);
1494#endif
1495#ifdef SIGUSR2
1496 ADD_INT_MACRO(SIGUSR2);
1497#endif
1498#ifdef SIGCLD
1499 ADD_INT_MACRO(SIGCLD);
1500#endif
1501#ifdef SIGCHLD
1502 ADD_INT_MACRO(SIGCHLD);
1503#endif
1504#ifdef SIGPWR
1505 ADD_INT_MACRO(SIGPWR);
1506#endif
1507#ifdef SIGIO
1508 ADD_INT_MACRO(SIGIO);
1509#endif
1510#ifdef SIGURG
1511 ADD_INT_MACRO(SIGURG);
1512#endif
1513#ifdef SIGWINCH
1514 ADD_INT_MACRO(SIGWINCH);
1515#endif
1516#ifdef SIGPOLL
1517 ADD_INT_MACRO(SIGPOLL);
1518#endif
1519#ifdef SIGSTOP
1520 ADD_INT_MACRO(SIGSTOP);
1521#endif
1522#ifdef SIGTSTP
1523 ADD_INT_MACRO(SIGTSTP);
1524#endif
1525#ifdef SIGCONT
1526 ADD_INT_MACRO(SIGCONT);
1527#endif
1528#ifdef SIGTTIN
1529 ADD_INT_MACRO(SIGTTIN);
1530#endif
1531#ifdef SIGTTOU
1532 ADD_INT_MACRO(SIGTTOU);
1533#endif
1534#ifdef SIGVTALRM
1535 ADD_INT_MACRO(SIGVTALRM);
1536#endif
1537#ifdef SIGPROF
1538 ADD_INT_MACRO(SIGPROF);
1539#endif
1540#ifdef SIGXCPU
1541 ADD_INT_MACRO(SIGXCPU);
1542#endif
1543#ifdef SIGXFSZ
1544 ADD_INT_MACRO(SIGXFSZ);
1545#endif
1546#ifdef SIGRTMIN
1547 ADD_INT_MACRO(SIGRTMIN);
1548#endif
1549#ifdef SIGRTMAX
1550 ADD_INT_MACRO(SIGRTMAX);
1551#endif
1552#ifdef SIGINFO
1553 ADD_INT_MACRO(SIGINFO);
1554#endif
1555
1556 // ITIMER_xxx constants
1557#ifdef ITIMER_REAL
1558 ADD_INT_MACRO(ITIMER_REAL);
1559#endif
1560#ifdef ITIMER_VIRTUAL
1561 ADD_INT_MACRO(ITIMER_VIRTUAL);
1562#endif
1563#ifdef ITIMER_PROF
1564 ADD_INT_MACRO(ITIMER_PROF);
1565#endif
1566
1567 // CTRL_xxx Windows signals
1568#ifdef CTRL_C_EVENT
1569 ADD_INT_MACRO(CTRL_C_EVENT);
1570#endif
1571#ifdef CTRL_BREAK_EVENT
1572 ADD_INT_MACRO(CTRL_BREAK_EVENT);
1573#endif
1574
1575 return 0;
1576
1577#undef ADD_INT_MACRO
1578}
1579
1580
1581static int
Victor Stinnera5e64442021-04-28 03:02:55 +02001582signal_get_set_handlers(signal_state_t *state, PyObject *mod_dict)
Victor Stinnera09766d2021-04-28 01:50:04 +02001583{
1584 // Get signal handlers
1585 for (int signum = 1; signum < NSIG; signum++) {
1586 void (*c_handler)(int) = PyOS_getsig(signum);
1587 PyObject *func;
1588 if (c_handler == SIG_DFL) {
Victor Stinnera5e64442021-04-28 03:02:55 +02001589 func = state->default_handler;
Victor Stinnera09766d2021-04-28 01:50:04 +02001590 }
1591 else if (c_handler == SIG_IGN) {
Victor Stinnera5e64442021-04-28 03:02:55 +02001592 func = state->ignore_handler;
Victor Stinnera09766d2021-04-28 01:50:04 +02001593 }
1594 else {
1595 func = Py_None; // None of our business
1596 }
1597 // If signal_module_exec() is called more than one, we must
1598 // clear the strong reference to the previous function.
1599 PyObject* old_func = get_handler(signum);
Victor Stinnera5e64442021-04-28 03:02:55 +02001600 set_handler(signum, Py_NewRef(func));
Victor Stinnera09766d2021-04-28 01:50:04 +02001601 Py_XDECREF(old_func);
1602 }
1603
Miss Islington (bot)5afc5bb2021-10-07 01:55:18 -07001604 // Install Python SIGINT handler which raises KeyboardInterrupt
Victor Stinnera09766d2021-04-28 01:50:04 +02001605 PyObject* sigint_func = get_handler(SIGINT);
Victor Stinnera5e64442021-04-28 03:02:55 +02001606 if (sigint_func == state->default_handler) {
Victor Stinnera09766d2021-04-28 01:50:04 +02001607 PyObject *int_handler = PyMapping_GetItemString(mod_dict,
1608 "default_int_handler");
1609 if (!int_handler) {
1610 return -1;
1611 }
1612
Victor Stinnera5e64442021-04-28 03:02:55 +02001613 set_handler(SIGINT, int_handler);
Victor Stinnera09766d2021-04-28 01:50:04 +02001614 Py_DECREF(sigint_func);
1615 PyOS_setsig(SIGINT, signal_handler);
1616 }
1617 return 0;
1618}
1619
1620
1621static int
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001622signal_module_exec(PyObject *m)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001623{
Victor Stinnercda23be2020-11-17 18:57:32 +01001624 assert(!PyErr_Occurred());
1625
Victor Stinnera5e64442021-04-28 03:02:55 +02001626 signal_state_t *state = &signal_global_state;
1627 _signal_module_state *modstate = get_signal_state(m);
1628
1629 modstate->default_handler = state->default_handler; // borrowed ref
1630 modstate->ignore_handler = state->ignore_handler; // borrowed ref
1631
1632#ifdef PYHAVE_ITIMER_ERROR
1633 modstate->itimer_error = PyErr_NewException("signal.itimer_error",
1634 PyExc_OSError, NULL);
1635 if (modstate->itimer_error == NULL) {
1636 return -1;
1637 }
1638#endif
1639
Victor Stinnercda23be2020-11-17 18:57:32 +01001640 if (signal_add_constants(m) < 0) {
1641 return -1;
1642 }
1643
1644 /* Add some symbolic constants to the module */
1645 PyObject *d = PyModule_GetDict(m);
Victor Stinnera5e64442021-04-28 03:02:55 +02001646 if (PyDict_SetItemString(d, "SIG_DFL", state->default_handler) < 0) {
Victor Stinnercda23be2020-11-17 18:57:32 +01001647 return -1;
1648 }
Victor Stinnera5e64442021-04-28 03:02:55 +02001649 if (PyDict_SetItemString(d, "SIG_IGN", state->ignore_handler) < 0) {
Victor Stinnercda23be2020-11-17 18:57:32 +01001650 return -1;
1651 }
Victor Stinnera5e64442021-04-28 03:02:55 +02001652#ifdef PYHAVE_ITIMER_ERROR
1653 if (PyDict_SetItemString(d, "ItimerError", modstate->itimer_error) < 0) {
Victor Stinnercda23be2020-11-17 18:57:32 +01001654 return -1;
1655 }
1656#endif
Ross Lagerwallbc808222011-06-25 12:13:40 +02001657#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001658 if (PyModule_AddType(m, &SiginfoType) < 0) {
1659 return -1;
1660 }
Ross Lagerwallbc808222011-06-25 12:13:40 +02001661#endif
1662
Victor Stinnera09766d2021-04-28 01:50:04 +02001663 PyThreadState *tstate = _PyThreadState_GET();
1664 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinnera5e64442021-04-28 03:02:55 +02001665 if (signal_get_set_handlers(state, d) < 0) {
Victor Stinner0ae323b2020-11-17 18:15:20 +01001666 return -1;
1667 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001669
Victor Stinnercda23be2020-11-17 18:57:32 +01001670 assert(!PyErr_Occurred());
1671 return 0;
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001672}
1673
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001674
Victor Stinnera5e64442021-04-28 03:02:55 +02001675#ifdef PYHAVE_ITIMER_ERROR
1676static int
1677_signal_module_traverse(PyObject *module, visitproc visit, void *arg)
1678{
1679 _signal_module_state *modstate = get_signal_state(module);
1680 Py_VISIT(modstate->itimer_error);
1681 return 0;
1682}
1683
1684static int
1685_signal_module_clear(PyObject *module)
1686{
1687 _signal_module_state *modstate = get_signal_state(module);
1688 Py_CLEAR(modstate->itimer_error);
1689 return 0;
1690}
1691
1692static void
1693_signal_module_free(void *module)
1694{
1695 _signal_module_clear((PyObject *)module);
1696}
1697#endif // PYHAVE_ITIMER_ERROR
1698
1699
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001700static PyModuleDef_Slot signal_slots[] = {
1701 {Py_mod_exec, signal_module_exec},
1702 {0, NULL}
1703};
1704
1705static struct PyModuleDef signal_module = {
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001706 PyModuleDef_HEAD_INIT,
1707 "_signal",
1708 .m_doc = module_doc,
Victor Stinnera5e64442021-04-28 03:02:55 +02001709 .m_size = sizeof(_signal_module_state),
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001710 .m_methods = signal_methods,
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001711 .m_slots = signal_slots,
Victor Stinnera5e64442021-04-28 03:02:55 +02001712#ifdef PYHAVE_ITIMER_ERROR
1713 .m_traverse = _signal_module_traverse,
1714 .m_clear = _signal_module_clear,
1715 .m_free = _signal_module_free,
1716#endif
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001717};
1718
Victor Stinner4b8032e2020-09-04 14:51:05 +02001719
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001720PyMODINIT_FUNC
1721PyInit__signal(void)
1722{
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001723 return PyModuleDef_Init(&signal_module);
Guido van Rossum08c16611997-08-02 03:01:42 +00001724}
1725
Victor Stinner4b8032e2020-09-04 14:51:05 +02001726
Victor Stinner296a7962020-11-17 16:22:23 +01001727void
1728_PySignal_Fini(void)
Guido van Rossum08c16611997-08-02 03:01:42 +00001729{
Victor Stinnera5e64442021-04-28 03:02:55 +02001730 signal_state_t *state = &signal_global_state;
1731
Victor Stinner0ae323b2020-11-17 18:15:20 +01001732 // Restore default signals and clear handlers
1733 for (int signum = 1; signum < NSIG; signum++) {
Antoine Pitrouba251c22021-03-11 23:35:45 +01001734 PyObject *func = get_handler(signum);
Victor Stinner0ae323b2020-11-17 18:15:20 +01001735 _Py_atomic_store_relaxed(&Handlers[signum].tripped, 0);
Victor Stinnera5e64442021-04-28 03:02:55 +02001736 set_handler(signum, NULL);
Victor Stinner0ae323b2020-11-17 18:15:20 +01001737 if (func != NULL
1738 && func != Py_None
Victor Stinnera5e64442021-04-28 03:02:55 +02001739 && func != state->default_handler
1740 && func != state->ignore_handler)
Victor Stinner0ae323b2020-11-17 18:15:20 +01001741 {
1742 PyOS_setsig(signum, SIG_DFL);
1743 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 Py_XDECREF(func);
1745 }
Guido van Rossum08c16611997-08-02 03:01:42 +00001746
Victor Stinner0ae323b2020-11-17 18:15:20 +01001747#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +02001748 if (state->sigint_event != NULL) {
1749 CloseHandle(state->sigint_event);
1750 state->sigint_event = NULL;
Victor Stinner0ae323b2020-11-17 18:15:20 +01001751 }
1752#endif
1753
Victor Stinnera5e64442021-04-28 03:02:55 +02001754 Py_CLEAR(state->default_handler);
1755 Py_CLEAR(state->ignore_handler);
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001756}
1757
Barry Warsaw92971171997-01-03 00:14:25 +00001758
Barry Warsaw92971171997-01-03 00:14:25 +00001759/* Declared in pyerrors.h */
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001760int
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001761PyErr_CheckSignals(void)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001762{
Victor Stinner72818982020-03-26 22:28:11 +01001763 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001764 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Eric Snow64d6cc82019-02-23 15:40:43 -07001765 return 0;
1766 }
1767
Victor Stinner72818982020-03-26 22:28:11 +01001768 return _PyErr_CheckSignalsTstate(tstate);
Eric Snow64d6cc82019-02-23 15:40:43 -07001769}
1770
1771
1772/* Declared in cpython/pyerrors.h */
1773int
Victor Stinner72818982020-03-26 22:28:11 +01001774_PyErr_CheckSignalsTstate(PyThreadState *tstate)
Eric Snow64d6cc82019-02-23 15:40:43 -07001775{
Victor Stinner72818982020-03-26 22:28:11 +01001776 if (!_Py_atomic_load(&is_tripped)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 return 0;
Victor Stinner72818982020-03-26 22:28:11 +01001778 }
Christian Heimesb76922a2007-12-11 01:06:40 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /*
1781 * The is_tripped variable is meant to speed up the calls to
1782 * PyErr_CheckSignals (both directly or via pending calls) when no
1783 * signal has arrived. This variable is set to 1 when a signal arrives
1784 * and it is set to 0 here, when we know some signals arrived. This way
1785 * we can run the registered handlers with no signals blocked.
1786 *
1787 * NOTE: with this approach we can have a situation where is_tripped is
1788 * 1 but we have no more signals to handle (Handlers[i].tripped
1789 * is 0 for every signal i). This won't do us any harm (except
1790 * we're gonna spent some cycles for nothing). This happens when
1791 * we receive a signal i after we zero is_tripped and before we
1792 * check Handlers[i].tripped.
1793 */
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +02001794 _Py_atomic_store(&is_tripped, 0);
Christian Heimesb76922a2007-12-11 01:06:40 +00001795
Victor Stinner72818982020-03-26 22:28:11 +01001796 PyObject *frame = (PyObject *)tstate->frame;
1797 if (!frame) {
1798 frame = Py_None;
1799 }
Christian Heimesb76922a2007-12-11 01:06:40 +00001800
Victor Stinnera5e64442021-04-28 03:02:55 +02001801 signal_state_t *state = &signal_global_state;
Victor Stinner72818982020-03-26 22:28:11 +01001802 for (int i = 1; i < NSIG; i++) {
1803 if (!_Py_atomic_load_relaxed(&Handlers[i].tripped)) {
1804 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 }
Victor Stinner72818982020-03-26 22:28:11 +01001806 _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1807
Antoine Pitrou68245b72021-03-05 10:32:50 +01001808 /* Signal handlers can be modified while a signal is received,
1809 * and therefore the fact that trip_signal() or PyErr_SetInterrupt()
1810 * was called doesn't guarantee that there is still a Python
1811 * signal handler for it by the time PyErr_CheckSignals() is called
1812 * (see bpo-43406).
1813 */
Antoine Pitrouba251c22021-03-11 23:35:45 +01001814 PyObject *func = get_handler(i);
Victor Stinnera5e64442021-04-28 03:02:55 +02001815 if (func == NULL || func == Py_None || func == state->ignore_handler ||
1816 func == state->default_handler) {
Antoine Pitrou68245b72021-03-05 10:32:50 +01001817 /* No Python signal handler due to aforementioned race condition.
1818 * We can't call raise() as it would break the assumption
1819 * that PyErr_SetInterrupt() only *simulates* an incoming
1820 * signal (i.e. it will never kill the process).
1821 * We also don't want to interrupt user code with a cryptic
1822 * asynchronous exception, so instead just write out an
1823 * unraisable error.
1824 */
1825 PyErr_Format(PyExc_OSError,
1826 "Signal %i ignored due to race condition",
1827 i);
1828 PyErr_WriteUnraisable(Py_None);
1829 continue;
1830 }
1831
Victor Stinner72818982020-03-26 22:28:11 +01001832 PyObject *arglist = Py_BuildValue("(iO)", i, frame);
1833 PyObject *result;
1834 if (arglist) {
Antoine Pitrou68245b72021-03-05 10:32:50 +01001835 result = _PyObject_Call(tstate, func, arglist, NULL);
Victor Stinner72818982020-03-26 22:28:11 +01001836 Py_DECREF(arglist);
1837 }
1838 else {
1839 result = NULL;
1840 }
1841 if (!result) {
1842 /* On error, re-schedule a call to _PyErr_CheckSignalsTstate() */
1843 _Py_atomic_store(&is_tripped, 1);
1844 return -1;
1845 }
1846
1847 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 }
Christian Heimesb76922a2007-12-11 01:06:40 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 return 0;
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001851}
1852
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +00001853
Victor Stinner72818982020-03-26 22:28:11 +01001854
1855int
1856_PyErr_CheckSignals(void)
1857{
1858 PyThreadState *tstate = _PyThreadState_GET();
1859 return _PyErr_CheckSignalsTstate(tstate);
1860}
1861
1862
Antoine Pitrouba251c22021-03-11 23:35:45 +01001863/* Simulate the effect of a signal arriving. The next time PyErr_CheckSignals
1864 is called, the corresponding Python signal handler will be raised.
Matěj Cepl608876b2019-05-23 22:30:00 +02001865
Antoine Pitrouba251c22021-03-11 23:35:45 +01001866 Missing signal handler for the given signal number is silently ignored. */
1867int
1868PyErr_SetInterruptEx(int signum)
1869{
1870 if (signum < 1 || signum >= NSIG) {
1871 return -1;
1872 }
Victor Stinnera5e64442021-04-28 03:02:55 +02001873
1874 signal_state_t *state = &signal_global_state;
1875 PyObject *func = get_handler(signum);
1876 if (func != state->ignore_handler && func != state->default_handler) {
Antoine Pitrouba251c22021-03-11 23:35:45 +01001877 trip_signal(signum);
1878 }
1879 return 0;
1880}
1881
Barry Warsaw92971171997-01-03 00:14:25 +00001882void
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001883PyErr_SetInterrupt(void)
Barry Warsaw92971171997-01-03 00:14:25 +00001884{
Antoine Pitrouba251c22021-03-11 23:35:45 +01001885 (void) PyErr_SetInterruptEx(SIGINT);
Barry Warsaw92971171997-01-03 00:14:25 +00001886}
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001887
Victor Stinner0ae323b2020-11-17 18:15:20 +01001888static int
1889signal_install_handlers(void)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001890{
Victor Stinner296a7962020-11-17 16:22:23 +01001891#ifdef SIGPIPE
1892 PyOS_setsig(SIGPIPE, SIG_IGN);
1893#endif
1894#ifdef SIGXFZ
1895 PyOS_setsig(SIGXFZ, SIG_IGN);
1896#endif
1897#ifdef SIGXFSZ
1898 PyOS_setsig(SIGXFSZ, SIG_IGN);
1899#endif
1900
1901 // Import _signal to install the Python SIGINT handler
1902 PyObject *module = PyImport_ImportModule("_signal");
1903 if (!module) {
1904 return -1;
1905 }
1906 Py_DECREF(module);
1907
1908 return 0;
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001909}
1910
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001911
Victor Stinner29aa6242020-11-17 22:55:30 +01001912/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1913 *
1914 * All of the code in this function must only use async-signal-safe functions,
1915 * listed at `man 7 signal` or
1916 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1917 *
1918 * If this function is updated, update also _posix_spawn() of subprocess.py.
1919 */
1920void
1921_Py_RestoreSignals(void)
1922{
1923#ifdef SIGPIPE
1924 PyOS_setsig(SIGPIPE, SIG_DFL);
1925#endif
1926#ifdef SIGXFZ
1927 PyOS_setsig(SIGXFZ, SIG_DFL);
1928#endif
1929#ifdef SIGXFSZ
1930 PyOS_setsig(SIGXFSZ, SIG_DFL);
1931#endif
1932}
1933
1934
Victor Stinner0ae323b2020-11-17 18:15:20 +01001935int
1936_PySignal_Init(int install_signal_handlers)
1937{
Victor Stinnera5e64442021-04-28 03:02:55 +02001938 signal_state_t *state = &signal_global_state;
1939
1940 state->default_handler = PyLong_FromVoidPtr((void *)SIG_DFL);
1941 if (state->default_handler == NULL) {
Victor Stinner0ae323b2020-11-17 18:15:20 +01001942 return -1;
1943 }
1944
Victor Stinnera5e64442021-04-28 03:02:55 +02001945 state->ignore_handler = PyLong_FromVoidPtr((void *)SIG_IGN);
1946 if (state->ignore_handler == NULL) {
Victor Stinner0ae323b2020-11-17 18:15:20 +01001947 return -1;
1948 }
1949
Victor Stinner0ae323b2020-11-17 18:15:20 +01001950#ifdef MS_WINDOWS
1951 /* Create manual-reset event, initially unset */
Victor Stinnera5e64442021-04-28 03:02:55 +02001952 state->sigint_event = CreateEvent(NULL, TRUE, FALSE, FALSE);
1953 if (state->sigint_event == NULL) {
Victor Stinner0ae323b2020-11-17 18:15:20 +01001954 PyErr_SetFromWindowsErr(0);
1955 return -1;
1956 }
1957#endif
1958
1959#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
1960 if (SiginfoType.tp_name == NULL) {
1961 if (PyStructSequence_InitType2(&SiginfoType, &struct_siginfo_desc) < 0) {
1962 return -1;
1963 }
1964 }
1965#endif
1966
1967 for (int signum = 1; signum < NSIG; signum++) {
1968 _Py_atomic_store_relaxed(&Handlers[signum].tripped, 0);
1969 }
1970
1971 if (install_signal_handlers) {
1972 if (signal_install_handlers() < 0) {
1973 return -1;
1974 }
1975 }
1976
1977 return 0;
1978}
1979
1980
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001981// The caller doesn't have to hold the GIL
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001982int
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001983_PyOS_InterruptOccurred(PyThreadState *tstate)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001984{
Victor Stinnercbe12962020-06-01 20:34:15 +02001985 _Py_EnsureTstateNotNULL(tstate);
1986 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Victor Stinner72818982020-03-26 22:28:11 +01001987 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 }
Victor Stinner72818982020-03-26 22:28:11 +01001989
1990 if (!_Py_atomic_load_relaxed(&Handlers[SIGINT].tripped)) {
1991 return 0;
1992 }
1993
1994 _Py_atomic_store_relaxed(&Handlers[SIGINT].tripped, 0);
1995 return 1;
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001996}
Guido van Rossum359bcaa1997-11-14 22:24:28 +00001997
Victor Stinner26881c82020-06-02 15:51:37 +02001998
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001999// The caller must to hold the GIL
2000int
2001PyOS_InterruptOccurred(void)
2002{
2003 PyThreadState *tstate = _PyThreadState_GET();
2004 return _PyOS_InterruptOccurred(tstate);
2005}
2006
2007
Victor Stinner26881c82020-06-02 15:51:37 +02002008#ifdef HAVE_FORK
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08002009static void
2010_clear_pending_signals(void)
2011{
Victor Stinner26881c82020-06-02 15:51:37 +02002012 if (!_Py_atomic_load(&is_tripped)) {
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08002013 return;
Victor Stinner26881c82020-06-02 15:51:37 +02002014 }
2015
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +02002016 _Py_atomic_store(&is_tripped, 0);
Victor Stinner26881c82020-06-02 15:51:37 +02002017 for (int i = 1; i < NSIG; ++i) {
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +02002018 _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08002019 }
2020}
2021
Guido van Rossum359bcaa1997-11-14 22:24:28 +00002022void
Antoine Pitrou346cbd32017-05-27 17:50:54 +02002023_PySignal_AfterFork(void)
Guido van Rossum359bcaa1997-11-14 22:24:28 +00002024{
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08002025 /* Clear the signal flags after forking so that they aren't handled
2026 * in both processes if they came in just before the fork() but before
2027 * the interpreter had an opportunity to call the handlers. issue9535. */
2028 _clear_pending_signals();
Guido van Rossum359bcaa1997-11-14 22:24:28 +00002029}
Victor Stinner26881c82020-06-02 15:51:37 +02002030#endif /* HAVE_FORK */
2031
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01002032
2033int
2034_PyOS_IsMainThread(void)
2035{
Victor Stinner81a7be32020-04-14 15:14:01 +02002036 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +02002037 return _Py_ThreadCanHandleSignals(interp);
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01002038}
2039
2040#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +02002041/* Returns a manual-reset event which gets tripped whenever
2042 SIGINT is received.
2043
2044 Python.h does not include windows.h so we do cannot use HANDLE
2045 as the return type of this function. We use void* instead. */
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01002046void *_PyOS_SigintEvent(void)
2047{
Victor Stinnera5e64442021-04-28 03:02:55 +02002048 signal_state_t *state = &signal_global_state;
2049 return state->sigint_event;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01002050}
2051#endif