blob: a4eeec9807c919525c0a1b20a31dfcf39f92ef6b [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
Serhiy Storchakad54cfb12018-05-08 07:48:50 +030061/*[python input]
62
63class sigset_t_converter(CConverter):
64 type = 'sigset_t'
65 converter = '_Py_Sigset_Converter'
66
67[python start generated code]*/
68/*[python end generated code: output=da39a3ee5e6b4b0d input=b5689d14466b6823]*/
Guido van Rossum3bbc62e1995-01-02 19:30:30 +000069
Guido van Rossumbb4ba121994-06-23 11:25:45 +000070/*
71 NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS
72
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +020073 We want the following semantics:
Guido van Rossumbb4ba121994-06-23 11:25:45 +000074
75 - only the main thread can set a signal handler
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +020076 - only the main thread runs the signal handler
77 - signals can be delivered to any thread
Guido van Rossumbb4ba121994-06-23 11:25:45 +000078 - any thread can get a signal handler
Guido van Rossumbb4ba121994-06-23 11:25:45 +000079
80 I.e. we don't support "synchronous signals" like SIGFPE (catching
81 this doesn't make much sense in Python anyway) nor do we support
82 signals as a means of inter-thread communication, since not all
83 thread implementations support that (at least our thread library
84 doesn't).
85
86 We still have the problem that in some implementations signals
87 generated by the keyboard (e.g. SIGINT) are delivered to all
88 threads (e.g. SGI), while in others (e.g. Solaris) such signals are
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +020089 delivered to one random thread. On Linux, signals are delivered to
90 the main thread (unless the main thread is blocking the signal, for
91 example because it's already handling the same signal). Since we
92 allow signals to be delivered to any thread, this works fine. The
93 only oddity is that the thread executing the Python signal handler
94 may not be the thread that received the signal.
Guido van Rossumbb4ba121994-06-23 11:25:45 +000095*/
96
Victor Stinner2ec6b172011-05-15 10:21:59 +020097static volatile struct {
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +020098 _Py_atomic_int tripped;
Antoine Pitrouba251c22021-03-11 23:35:45 +010099 /* func is atomic to ensure that PyErr_SetInterrupt is async-signal-safe
100 * (even though it would probably be otherwise, anyway).
101 */
102 _Py_atomic_address func;
Barry Warsaw92971171997-01-03 00:14:25 +0000103} Handlers[NSIG];
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000104
Victor Stinner11517102014-07-29 23:31:34 +0200105#ifdef MS_WINDOWS
106#define INVALID_FD ((SOCKET_T)-1)
107
108static volatile struct {
109 SOCKET_T fd;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800110 int warn_on_full_buffer;
Victor Stinner11517102014-07-29 23:31:34 +0200111 int use_send;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800112} wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1, .use_send = 0};
Victor Stinner11517102014-07-29 23:31:34 +0200113#else
114#define INVALID_FD (-1)
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800115static volatile struct {
pxinwr1244c812020-12-01 05:48:33 +0800116#ifdef __VXWORKS__
117 int fd;
118#else
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800119 sig_atomic_t fd;
pxinwr1244c812020-12-01 05:48:33 +0800120#endif
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800121 int warn_on_full_buffer;
122} wakeup = {.fd = INVALID_FD, .warn_on_full_buffer = 1};
Victor Stinner11517102014-07-29 23:31:34 +0200123#endif
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000124
Christian Heimesb76922a2007-12-11 01:06:40 +0000125/* Speed up sigcheck() when none tripped */
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200126static _Py_atomic_int is_tripped;
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000127
Victor Stinnera5e64442021-04-28 03:02:55 +0200128typedef struct {
129 PyObject *default_handler;
130 PyObject *ignore_handler;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100131#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +0200132 HANDLE sigint_event;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100133#endif
Victor Stinnera5e64442021-04-28 03:02:55 +0200134} signal_state_t;
135
136// State shared by all Python interpreters
137static signal_state_t signal_global_state = {0};
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100138
Victor Stinner0ae323b2020-11-17 18:15:20 +0100139#if defined(HAVE_GETITIMER) || defined(HAVE_SETITIMER)
Victor Stinnera5e64442021-04-28 03:02:55 +0200140# define PYHAVE_ITIMER_ERROR
Victor Stinner0ae323b2020-11-17 18:15:20 +0100141#endif
Martin v. Löwis823725e2008-03-24 13:39:54 +0000142
Victor Stinnera5e64442021-04-28 03:02:55 +0200143typedef struct {
144 PyObject *default_handler; // borrowed ref (signal_global_state)
145 PyObject *ignore_handler; // borrowed ref (signal_global_state)
146#ifdef PYHAVE_ITIMER_ERROR
147 PyObject *itimer_error;
148#endif
149} _signal_module_state;
150
151
Antoine Pitrouba251c22021-03-11 23:35:45 +0100152Py_LOCAL_INLINE(PyObject *)
Victor Stinnera5e64442021-04-28 03:02:55 +0200153get_handler(int i)
154{
Antoine Pitrouba251c22021-03-11 23:35:45 +0100155 return (PyObject *)_Py_atomic_load(&Handlers[i].func);
156}
157
158Py_LOCAL_INLINE(void)
Victor Stinnera5e64442021-04-28 03:02:55 +0200159set_handler(int i, PyObject* func)
160{
Antoine Pitrouba251c22021-03-11 23:35:45 +0100161 _Py_atomic_store(&Handlers[i].func, (uintptr_t)func);
162}
163
Victor Stinnera5e64442021-04-28 03:02:55 +0200164
165static inline _signal_module_state*
166get_signal_state(PyObject *module)
167{
168 void *state = _PyModule_GetState(module);
169 assert(state != NULL);
170 return (_signal_module_state *)state;
171}
172
173
Victor Stinner0ae323b2020-11-17 18:15:20 +0100174#ifdef HAVE_GETITIMER
Victor Stinneref611c92017-10-13 13:49:43 -0700175/* auxiliary functions for setitimer */
176static int
177timeval_from_double(PyObject *obj, struct timeval *tv)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000178{
Victor Stinneref611c92017-10-13 13:49:43 -0700179 if (obj == NULL) {
180 tv->tv_sec = 0;
181 tv->tv_usec = 0;
182 return 0;
Antoine Pitrou729780a2017-06-30 10:01:05 +0200183 }
Victor Stinneref611c92017-10-13 13:49:43 -0700184
185 _PyTime_t t;
186 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_CEILING) < 0) {
187 return -1;
188 }
189 return _PyTime_AsTimeval(t, tv, _PyTime_ROUND_CEILING);
Martin v. Löwis823725e2008-03-24 13:39:54 +0000190}
191
Christian Heimes1a8501c2008-10-02 19:56:01 +0000192Py_LOCAL_INLINE(double)
Martin v. Löwis823725e2008-03-24 13:39:54 +0000193double_from_timeval(struct timeval *tv)
194{
195 return tv->tv_sec + (double)(tv->tv_usec / 1000000.0);
196}
197
198static PyObject *
199itimer_retval(struct itimerval *iv)
200{
201 PyObject *r, *v;
202
203 r = PyTuple_New(2);
204 if (r == NULL)
Martin Panter6d57fe12016-09-17 03:26:16 +0000205 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000206
207 if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
Martin Panter6d57fe12016-09-17 03:26:16 +0000208 Py_DECREF(r);
209 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000210 }
211
212 PyTuple_SET_ITEM(r, 0, v);
213
214 if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) {
Martin Panter6d57fe12016-09-17 03:26:16 +0000215 Py_DECREF(r);
216 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000217 }
218
219 PyTuple_SET_ITEM(r, 1, v);
220
221 return r;
222}
223#endif
Barry Warsaw92971171997-01-03 00:14:25 +0000224
Serhiy Storchakab0689ae2020-07-12 19:15:20 +0300225/*[clinic input]
226signal.default_int_handler
227 signalnum: int
228 frame: object
229 /
230
231The default handler for SIGINT installed by Python.
232
233It raises KeyboardInterrupt.
234[clinic start generated code]*/
235
Guido van Rossume4485b01994-09-07 14:32:49 +0000236static PyObject *
Serhiy Storchakab0689ae2020-07-12 19:15:20 +0300237signal_default_int_handler_impl(PyObject *module, int signalnum,
238 PyObject *frame)
239/*[clinic end generated code: output=bb11c2eb115ace4e input=efcd4a56a207acfd]*/
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyErr_SetNone(PyExc_KeyboardInterrupt);
242 return NULL;
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000243}
244
Thomas Wouters0796b002000-07-22 23:49:30 +0000245
246static int
Victor Stinner11517102014-07-29 23:31:34 +0200247report_wakeup_write_error(void *data)
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200248{
Eric Snowfdf282d2019-01-11 14:26:55 -0700249 PyObject *exc, *val, *tb;
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200250 int save_errno = errno;
Benjamin Petersonca470632016-09-06 13:47:26 -0700251 errno = (int) (intptr_t) data;
Eric Snowfdf282d2019-01-11 14:26:55 -0700252 PyErr_Fetch(&exc, &val, &tb);
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200253 PyErr_SetFromErrno(PyExc_OSError);
254 PySys_WriteStderr("Exception ignored when trying to write to the "
255 "signal wakeup fd:\n");
256 PyErr_WriteUnraisable(NULL);
Eric Snowfdf282d2019-01-11 14:26:55 -0700257 PyErr_Restore(exc, val, tb);
Antoine Pitrou6f6ec372013-08-17 20:27:56 +0200258 errno = save_errno;
259 return 0;
260}
261
Victor Stinner11517102014-07-29 23:31:34 +0200262#ifdef MS_WINDOWS
263static int
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800264report_wakeup_send_error(void* data)
Victor Stinner11517102014-07-29 23:31:34 +0200265{
Eric Snowfdf282d2019-01-11 14:26:55 -0700266 PyObject *exc, *val, *tb;
267 PyErr_Fetch(&exc, &val, &tb);
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800268 /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
269 recognizes the error codes used by both GetLastError() and
270 WSAGetLastError */
271 PyErr_SetExcFromWindowsErr(PyExc_OSError, (int) (intptr_t) data);
Victor Stinner11517102014-07-29 23:31:34 +0200272 PySys_WriteStderr("Exception ignored when trying to send to the "
273 "signal wakeup fd:\n");
274 PyErr_WriteUnraisable(NULL);
Eric Snowfdf282d2019-01-11 14:26:55 -0700275 PyErr_Restore(exc, val, tb);
Victor Stinner11517102014-07-29 23:31:34 +0200276 return 0;
277}
278#endif /* MS_WINDOWS */
279
Tim Peters4f1b2082000-07-23 21:18:09 +0000280static void
Victor Stinner6c9b35b2011-04-18 16:25:56 +0200281trip_signal(int sig_num)
282{
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200283 _Py_atomic_store_relaxed(&Handlers[sig_num].tripped, 1);
Victor Stinner11517102014-07-29 23:31:34 +0200284
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200285 /* Set is_tripped after setting .tripped, as it gets
286 cleared in PyErr_CheckSignals() before .tripped. */
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200287 _Py_atomic_store(&is_tripped, 1);
288
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200289 /* Signals are always handled by the main interpreter */
290 PyInterpreterState *interp = _PyRuntime.interpreters.main;
Victor Stinner8849e592020-03-18 19:28:53 +0100291
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +0200292 /* Notify ceval.c */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200293 _PyEval_SignalReceived(interp);
Nathaniel J. Smith4ae01492017-05-16 14:12:11 -0700294
295 /* And then write to the wakeup fd *after* setting all the globals and
Antoine Pitrouc08177a2017-06-28 23:29:29 +0200296 doing the _PyEval_SignalReceived. We used to write to the wakeup fd
297 and then set the flag, but this allowed the following sequence of events
298 (especially on windows, where trip_signal may run in a new thread):
Nathaniel J. Smith4ae01492017-05-16 14:12:11 -0700299
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800300 - main thread blocks on select([wakeup.fd], ...)
Nathaniel J. Smith4ae01492017-05-16 14:12:11 -0700301 - signal arrives
302 - trip_signal writes to the wakeup fd
303 - the main thread wakes up
304 - the main thread checks the signal flags, sees that they're unset
305 - the main thread empties the wakeup fd
306 - the main thread goes back to sleep
307 - trip_signal sets the flags to request the Python-level signal handler
308 be run
309 - the main thread doesn't notice, because it's asleep
310
311 See bpo-30038 for more details.
312 */
313
Victor Stinnercda23be2020-11-17 18:57:32 +0100314 int fd;
Victor Stinner11517102014-07-29 23:31:34 +0200315#ifdef MS_WINDOWS
316 fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
317#else
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800318 fd = wakeup.fd;
Victor Stinner11517102014-07-29 23:31:34 +0200319#endif
320
321 if (fd != INVALID_FD) {
Victor Stinnercda23be2020-11-17 18:57:32 +0100322 unsigned char byte = (unsigned char)sig_num;
Victor Stinner11517102014-07-29 23:31:34 +0200323#ifdef MS_WINDOWS
324 if (wakeup.use_send) {
Victor Stinnercda23be2020-11-17 18:57:32 +0100325 Py_ssize_t rc = send(fd, &byte, 1, 0);
Victor Stinner11517102014-07-29 23:31:34 +0200326
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800327 if (rc < 0) {
328 int last_error = GetLastError();
329 if (wakeup.warn_on_full_buffer ||
330 last_error != WSAEWOULDBLOCK)
331 {
Victor Stinner50e6e992020-03-19 02:41:21 +0100332 /* _PyEval_AddPendingCall() isn't signal-safe, but we
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800333 still use it for this exceptional case. */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200334 _PyEval_AddPendingCall(interp,
Victor Stinner09532fe2019-05-10 23:39:09 +0200335 report_wakeup_send_error,
336 (void *)(intptr_t) last_error);
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800337 }
Victor Stinner11517102014-07-29 23:31:34 +0200338 }
339 }
340 else
341#endif
342 {
Victor Stinnere72fe392015-04-01 18:35:22 +0200343 /* _Py_write_noraise() retries write() if write() is interrupted by
344 a signal (fails with EINTR). */
Victor Stinnercda23be2020-11-17 18:57:32 +0100345 Py_ssize_t rc = _Py_write_noraise(fd, &byte, 1);
Victor Stinner11517102014-07-29 23:31:34 +0200346
347 if (rc < 0) {
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800348 if (wakeup.warn_on_full_buffer ||
349 (errno != EWOULDBLOCK && errno != EAGAIN))
350 {
Victor Stinner50e6e992020-03-19 02:41:21 +0100351 /* _PyEval_AddPendingCall() isn't signal-safe, but we
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800352 still use it for this exceptional case. */
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200353 _PyEval_AddPendingCall(interp,
Victor Stinner09532fe2019-05-10 23:39:09 +0200354 report_wakeup_write_error,
355 (void *)(intptr_t)errno);
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800356 }
Victor Stinner11517102014-07-29 23:31:34 +0200357 }
358 }
Victor Stinnerc13ef662011-05-25 02:35:58 +0200359 }
Victor Stinner6c9b35b2011-04-18 16:25:56 +0200360}
361
362static void
Peter Schneider-Kampe89b1562000-07-10 12:04:18 +0000363signal_handler(int sig_num)
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000364{
Antoine Pitrou39a65912010-11-05 19:47:27 +0000365 int save_errno = errno;
366
Jeroen Demeyerd237b3f2019-05-10 03:28:57 +0200367 trip_signal(sig_num);
Antoine Pitrou39a65912010-11-05 19:47:27 +0000368
Jean-Paul Calderone6f137ca2010-05-09 03:18:57 +0000369#ifndef HAVE_SIGACTION
Antoine Pitrou39a65912010-11-05 19:47:27 +0000370#ifdef SIGCHLD
371 /* To avoid infinite recursion, this signal remains
372 reset until explicit re-instated.
373 Don't clear the 'func' field as it is our pointer
374 to the Python handler... */
375 if (sig_num != SIGCHLD)
376#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* If the handler was not set up with sigaction, reinstall it. See
Nick Coghland6009512014-11-20 21:39:37 +1000378 * Python/pylifecycle.c for the implementation of PyOS_setsig which
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 * makes this true. See also issue8354. */
380 PyOS_setsig(sig_num, signal_handler);
Jean-Paul Calderone6f137ca2010-05-09 03:18:57 +0000381#endif
Antoine Pitrou39a65912010-11-05 19:47:27 +0000382
383 /* Issue #10311: asynchronously executing signal handlers should not
384 mutate errno under the feet of unsuspecting C code. */
385 errno = save_errno;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100386
387#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +0200388 if (sig_num == SIGINT) {
389 signal_state_t *state = &signal_global_state;
390 SetEvent(state->sigint_event);
391 }
Antoine Pitrou6dd381e2011-11-21 21:26:56 +0100392#endif
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000393}
Guido van Rossume4485b01994-09-07 14:32:49 +0000394
Guido van Rossum06d511d1995-03-10 15:13:48 +0000395
Guido van Rossum1171ee61997-08-22 20:42:00 +0000396#ifdef HAVE_ALARM
Tal Einatc7027b72015-05-16 14:14:49 +0300397
398/*[clinic input]
399signal.alarm -> long
400
401 seconds: int
402 /
403
404Arrange for SIGALRM to arrive after the given number of seconds.
405[clinic start generated code]*/
406
407static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300408signal_alarm_impl(PyObject *module, int seconds)
409/*[clinic end generated code: output=144232290814c298 input=0d5e97e0e6f39e86]*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 /* alarm() returns the number of seconds remaining */
Tal Einatc7027b72015-05-16 14:14:49 +0300412 return (long)alarm(seconds);
Guido van Rossumaa0f4c71994-08-23 13:49:37 +0000413}
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +0000414
Guido van Rossum06d511d1995-03-10 15:13:48 +0000415#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000416
Guido van Rossum1171ee61997-08-22 20:42:00 +0000417#ifdef HAVE_PAUSE
Tal Einatc7027b72015-05-16 14:14:49 +0300418
419/*[clinic input]
420signal.pause
421
422Wait until a signal arrives.
423[clinic start generated code]*/
424
Guido van Rossuma597dde1995-01-10 20:56:29 +0000425static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300426signal_pause_impl(PyObject *module)
427/*[clinic end generated code: output=391656788b3c3929 input=f03de0f875752062]*/
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 Py_BEGIN_ALLOW_THREADS
430 (void)pause();
431 Py_END_ALLOW_THREADS
432 /* make sure that any exceptions that got raised are propagated
433 * back into Python
434 */
435 if (PyErr_CheckSignals())
436 return NULL;
Barry Warsaw92971171997-01-03 00:14:25 +0000437
Tal Einatc7027b72015-05-16 14:14:49 +0300438 Py_RETURN_NONE;
Guido van Rossume4485b01994-09-07 14:32:49 +0000439}
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +0000440
Guido van Rossum06d511d1995-03-10 15:13:48 +0000441#endif
Guido van Rossume4485b01994-09-07 14:32:49 +0000442
Vladimir Matveevc24c6c22019-01-08 01:58:25 -0800443/*[clinic input]
444signal.raise_signal
445
446 signalnum: int
447 /
448
449Send a signal to the executing process.
450[clinic start generated code]*/
451
452static PyObject *
453signal_raise_signal_impl(PyObject *module, int signalnum)
454/*[clinic end generated code: output=e2b014220aa6111d input=e90c0f9a42358de6]*/
455{
456 int err;
457 Py_BEGIN_ALLOW_THREADS
458 _Py_BEGIN_SUPPRESS_IPH
459 err = raise(signalnum);
460 _Py_END_SUPPRESS_IPH
461 Py_END_ALLOW_THREADS
Victor Stinner09532fe2019-05-10 23:39:09 +0200462
Vladimir Matveevc24c6c22019-01-08 01:58:25 -0800463 if (err) {
464 return PyErr_SetFromErrno(PyExc_OSError);
465 }
466 Py_RETURN_NONE;
467}
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +0000468
Tal Einatc7027b72015-05-16 14:14:49 +0300469/*[clinic input]
470signal.signal
471
472 signalnum: int
473 handler: object
474 /
475
476Set the action for the given signal.
477
478The action can be SIG_DFL, SIG_IGN, or a callable Python object.
479The previous action is returned. See getsignal() for possible return values.
480
481*** IMPORTANT NOTICE ***
482A signal handler function is called with two arguments:
483the first is the signal number, the second is the interrupted stack frame.
484[clinic start generated code]*/
485
Guido van Rossume4485b01994-09-07 14:32:49 +0000486static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300487signal_signal_impl(PyObject *module, int signalnum, PyObject *handler)
488/*[clinic end generated code: output=b44cfda43780f3a1 input=deee84af5fa0432c]*/
Guido van Rossume4485b01994-09-07 14:32:49 +0000489{
Victor Stinnera5e64442021-04-28 03:02:55 +0200490 _signal_module_state *modstate = get_signal_state(module);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 PyObject *old_handler;
492 void (*func)(int);
Brian Curtinef9efbd2010-08-06 19:27:32 +0000493#ifdef MS_WINDOWS
Tal Einatc7027b72015-05-16 14:14:49 +0300494 /* Validate that signalnum is one of the allowable signals */
495 switch (signalnum) {
Brian Curtinc734b312010-09-06 16:04:10 +0000496 case SIGABRT: break;
Brian Curtin9e88b5a2010-10-01 14:49:24 +0000497#ifdef SIGBREAK
498 /* Issue #10003: SIGBREAK is not documented as permitted, but works
499 and corresponds to CTRL_BREAK_EVENT. */
500 case SIGBREAK: break;
501#endif
Brian Curtinc734b312010-09-06 16:04:10 +0000502 case SIGFPE: break;
503 case SIGILL: break;
504 case SIGINT: break;
505 case SIGSEGV: break;
506 case SIGTERM: break;
507 default:
508 PyErr_SetString(PyExc_ValueError, "invalid signal value");
509 return NULL;
Brian Curtinef9efbd2010-08-06 19:27:32 +0000510 }
511#endif
Victor Stinnerd8613dc2019-05-24 13:43:55 +0200512
Victor Stinner72818982020-03-26 22:28:11 +0100513 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200514 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Victor Stinner72818982020-03-26 22:28:11 +0100515 _PyErr_SetString(tstate, PyExc_ValueError,
516 "signal only works in main thread "
517 "of the main interpreter");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return NULL;
519 }
Tal Einatc7027b72015-05-16 14:14:49 +0300520 if (signalnum < 1 || signalnum >= NSIG) {
Victor Stinner72818982020-03-26 22:28:11 +0100521 _PyErr_SetString(tstate, PyExc_ValueError,
522 "signal number out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 return NULL;
524 }
Victor Stinnera5e64442021-04-28 03:02:55 +0200525 if (handler == modstate->ignore_handler) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 func = SIG_IGN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 }
Victor Stinnera5e64442021-04-28 03:02:55 +0200528 else if (handler == modstate->default_handler) {
Victor Stinner72818982020-03-26 22:28:11 +0100529 func = SIG_DFL;
530 }
531 else if (!PyCallable_Check(handler)) {
532 _PyErr_SetString(tstate, PyExc_TypeError,
533 "signal handler must be signal.SIG_IGN, "
534 "signal.SIG_DFL, or a callable object");
535 return NULL;
536 }
537 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 func = signal_handler;
Victor Stinner72818982020-03-26 22:28:11 +0100539 }
540
Antoine Pitrouf6f90ff2017-11-03 19:58:46 +0100541 /* Check for pending signals before changing signal handler */
Victor Stinner72818982020-03-26 22:28:11 +0100542 if (_PyErr_CheckSignalsTstate(tstate)) {
Antoine Pitrouf6f90ff2017-11-03 19:58:46 +0100543 return NULL;
544 }
Tal Einatc7027b72015-05-16 14:14:49 +0300545 if (PyOS_setsig(signalnum, func) == SIG_ERR) {
Victor Stinner388196e2011-05-10 17:13:00 +0200546 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 return NULL;
548 }
Victor Stinner72818982020-03-26 22:28:11 +0100549
Antoine Pitrouba251c22021-03-11 23:35:45 +0100550 old_handler = get_handler(signalnum);
Victor Stinnera5e64442021-04-28 03:02:55 +0200551 set_handler(signalnum, Py_NewRef(handler));
Victor Stinner72818982020-03-26 22:28:11 +0100552
553 if (old_handler != NULL) {
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200554 return old_handler;
Victor Stinner72818982020-03-26 22:28:11 +0100555 }
556 else {
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200557 Py_RETURN_NONE;
Victor Stinner72818982020-03-26 22:28:11 +0100558 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000559}
560
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +0000561
Tal Einatc7027b72015-05-16 14:14:49 +0300562/*[clinic input]
563signal.getsignal
564
565 signalnum: int
566 /
567
568Return the current action for the given signal.
569
570The return value can be:
571 SIG_IGN -- if the signal is being ignored
572 SIG_DFL -- if the default action for the signal is in effect
573 None -- if an unknown handler is in effect
574 anything else -- the callable Python object used as a handler
575[clinic start generated code]*/
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +0000576
Guido van Rossume4485b01994-09-07 14:32:49 +0000577static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300578signal_getsignal_impl(PyObject *module, int signalnum)
579/*[clinic end generated code: output=35b3e0e796fd555e input=ac23a00f19dfa509]*/
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 PyObject *old_handler;
Tal Einatc7027b72015-05-16 14:14:49 +0300582 if (signalnum < 1 || signalnum >= NSIG) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyErr_SetString(PyExc_ValueError,
584 "signal number out of range");
585 return NULL;
586 }
Antoine Pitrouba251c22021-03-11 23:35:45 +0100587 old_handler = get_handler(signalnum);
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200588 if (old_handler != NULL) {
Victor Stinnercda23be2020-11-17 18:57:32 +0100589 return Py_NewRef(old_handler);
Antoine Pitrouc8c952c2013-05-04 23:16:59 +0200590 }
591 else {
592 Py_RETURN_NONE;
593 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +0000594}
595
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100596
597/*[clinic input]
598signal.strsignal
599
600 signalnum: int
601 /
602
603Return the system description of the given signal.
604
605The return values can be such as "Interrupt", "Segmentation fault", etc.
606Returns None if the signal is not recognized.
607[clinic start generated code]*/
608
609static PyObject *
610signal_strsignal_impl(PyObject *module, int signalnum)
611/*[clinic end generated code: output=44e12e1e3b666261 input=b77914b03f856c74]*/
612{
613 char *res;
614
615 if (signalnum < 1 || signalnum >= NSIG) {
616 PyErr_SetString(PyExc_ValueError,
617 "signal number out of range");
618 return NULL;
619 }
620
Michael Osipov48ce4892018-08-23 15:27:19 +0200621#ifndef HAVE_STRSIGNAL
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100622 switch (signalnum) {
Michael Osipov48ce4892018-08-23 15:27:19 +0200623 /* Though being a UNIX, HP-UX does not provide strsignal(3). */
624#ifndef MS_WINDOWS
625 case SIGHUP:
626 res = "Hangup";
627 break;
628 case SIGALRM:
629 res = "Alarm clock";
630 break;
631 case SIGPIPE:
632 res = "Broken pipe";
633 break;
634 case SIGQUIT:
635 res = "Quit";
636 break;
637 case SIGCHLD:
638 res = "Child exited";
639 break;
640#endif
641 /* Custom redefinition of POSIX signals allowed on Windows. */
Antoine Pietri5d2a27d2018-03-12 14:42:34 +0100642 case SIGINT:
643 res = "Interrupt";
644 break;
645 case SIGILL:
646 res = "Illegal instruction";
647 break;
648 case SIGABRT:
649 res = "Aborted";
650 break;
651 case SIGFPE:
652 res = "Floating point exception";
653 break;
654 case SIGSEGV:
655 res = "Segmentation fault";
656 break;
657 case SIGTERM:
658 res = "Terminated";
659 break;
660 default:
661 Py_RETURN_NONE;
662 }
663#else
664 errno = 0;
665 res = strsignal(signalnum);
666
667 if (errno || res == NULL || strstr(res, "Unknown signal") != NULL)
668 Py_RETURN_NONE;
669#endif
670
671 return Py_BuildValue("s", res);
672}
673
Christian Heimes8640e742008-02-23 16:23:06 +0000674#ifdef HAVE_SIGINTERRUPT
Tal Einatc7027b72015-05-16 14:14:49 +0300675
676/*[clinic input]
677signal.siginterrupt
678
679 signalnum: int
680 flag: int
681 /
682
683Change system call restart behaviour.
684
685If flag is False, system calls will be restarted when interrupted by
686signal sig, else system calls will be interrupted.
687[clinic start generated code]*/
Christian Heimes8640e742008-02-23 16:23:06 +0000688
689static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300690signal_siginterrupt_impl(PyObject *module, int signalnum, int flag)
691/*[clinic end generated code: output=063816243d85dd19 input=4160acacca3e2099]*/
Christian Heimes8640e742008-02-23 16:23:06 +0000692{
Tal Einatc7027b72015-05-16 14:14:49 +0300693 if (signalnum < 1 || signalnum >= NSIG) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyErr_SetString(PyExc_ValueError,
695 "signal number out of range");
696 return NULL;
697 }
Pablo Galindof9c5e3f2020-09-02 15:29:12 +0100698#ifdef HAVE_SIGACTION
699 struct sigaction act;
700 (void) sigaction(signalnum, NULL, &act);
701 if (flag) {
702 act.sa_flags &= ~SA_RESTART;
703 }
704 else {
705 act.sa_flags |= SA_RESTART;
706 }
707 if (sigaction(signalnum, &act, NULL) < 0) {
708#else
709 if (siginterrupt(signalnum, flag) < 0) {
710#endif
Victor Stinner388196e2011-05-10 17:13:00 +0200711 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 return NULL;
713 }
Tal Einatc7027b72015-05-16 14:14:49 +0300714 Py_RETURN_NONE;
Christian Heimes8640e742008-02-23 16:23:06 +0000715}
716
717#endif
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +0000718
Tal Einatc7027b72015-05-16 14:14:49 +0300719
720static PyObject*
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800721signal_set_wakeup_fd(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000722{
Victor Stinnere134a7f2015-03-30 10:09:31 +0200723 struct _Py_stat_struct status;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800724 static char *kwlist[] = {
725 "", "warn_on_full_buffer", NULL,
726 };
727 int warn_on_full_buffer = 1;
Victor Stinner11517102014-07-29 23:31:34 +0200728#ifdef MS_WINDOWS
729 PyObject *fdobj;
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100730 SOCKET_T sockfd, old_sockfd;
Victor Stinner11517102014-07-29 23:31:34 +0200731 int res;
732 int res_size = sizeof res;
733 PyObject *mod;
Victor Stinner11517102014-07-29 23:31:34 +0200734 int is_socket;
735
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800736 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|$p:set_wakeup_fd", kwlist,
737 &fdobj, &warn_on_full_buffer))
Victor Stinner11517102014-07-29 23:31:34 +0200738 return NULL;
739
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100740 sockfd = PyLong_AsSocket_t(fdobj);
741 if (sockfd == (SOCKET_T)(-1) && PyErr_Occurred())
Victor Stinner11517102014-07-29 23:31:34 +0200742 return NULL;
743#else
Victor Stinnercda23be2020-11-17 18:57:32 +0100744 int fd;
Victor Stinner11517102014-07-29 23:31:34 +0200745
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800746 if (!PyArg_ParseTupleAndKeywords(args, kwds, "i|$p:set_wakeup_fd", kwlist,
747 &fd, &warn_on_full_buffer))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 return NULL;
Victor Stinner11517102014-07-29 23:31:34 +0200749#endif
750
Victor Stinner72818982020-03-26 22:28:11 +0100751 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +0200752 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Victor Stinner72818982020-03-26 22:28:11 +0100753 _PyErr_SetString(tstate, PyExc_ValueError,
754 "set_wakeup_fd only works in main thread "
755 "of the main interpreter");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return NULL;
757 }
Victor Stinner0bffc942014-07-21 16:28:54 +0200758
Victor Stinner11517102014-07-29 23:31:34 +0200759#ifdef MS_WINDOWS
760 is_socket = 0;
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100761 if (sockfd != INVALID_FD) {
Victor Stinner11517102014-07-29 23:31:34 +0200762 /* Import the _socket module to call WSAStartup() */
763 mod = PyImport_ImportModuleNoBlock("_socket");
764 if (mod == NULL)
765 return NULL;
766 Py_DECREF(mod);
767
768 /* test the socket */
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100769 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
Victor Stinner11517102014-07-29 23:31:34 +0200770 (char *)&res, &res_size) != 0) {
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100771 int fd, err;
772
773 err = WSAGetLastError();
Victor Stinner11517102014-07-29 23:31:34 +0200774 if (err != WSAENOTSOCK) {
775 PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
776 return NULL;
777 }
778
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100779 fd = (int)sockfd;
Steve Dower940f33a2016-09-08 11:21:54 -0700780 if ((SOCKET_T)fd != sockfd) {
Victor Stinner72818982020-03-26 22:28:11 +0100781 _PyErr_SetString(tstate, PyExc_ValueError, "invalid fd");
Victor Stinner11517102014-07-29 23:31:34 +0200782 return NULL;
783 }
784
Victor Stinner72818982020-03-26 22:28:11 +0100785 if (_Py_fstat(fd, &status) != 0) {
Victor Stinner11517102014-07-29 23:31:34 +0200786 return NULL;
Victor Stinner72818982020-03-26 22:28:11 +0100787 }
Victor Stinner38227602014-08-27 12:59:44 +0200788
789 /* on Windows, a file cannot be set to non-blocking mode */
Victor Stinner11517102014-07-29 23:31:34 +0200790 }
Victor Stinner38227602014-08-27 12:59:44 +0200791 else {
Victor Stinner11517102014-07-29 23:31:34 +0200792 is_socket = 1;
Victor Stinner38227602014-08-27 12:59:44 +0200793
794 /* Windows does not provide a function to test if a socket
795 is in non-blocking mode */
796 }
Victor Stinner11517102014-07-29 23:31:34 +0200797 }
798
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100799 old_sockfd = wakeup.fd;
800 wakeup.fd = sockfd;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800801 wakeup.warn_on_full_buffer = warn_on_full_buffer;
Victor Stinner11517102014-07-29 23:31:34 +0200802 wakeup.use_send = is_socket;
803
Victor Stinnercf40a9e2015-02-12 16:34:54 +0100804 if (old_sockfd != INVALID_FD)
805 return PyLong_FromSocket_t(old_sockfd);
Victor Stinner11517102014-07-29 23:31:34 +0200806 else
807 return PyLong_FromLong(-1);
808#else
Victor Stinnerd18ccd12014-07-24 21:58:53 +0200809 if (fd != -1) {
Victor Stinner38227602014-08-27 12:59:44 +0200810 int blocking;
811
Victor Stinnere134a7f2015-03-30 10:09:31 +0200812 if (_Py_fstat(fd, &status) != 0)
Victor Stinner11517102014-07-29 23:31:34 +0200813 return NULL;
Victor Stinner38227602014-08-27 12:59:44 +0200814
815 blocking = _Py_get_blocking(fd);
816 if (blocking < 0)
817 return NULL;
818 if (blocking) {
Victor Stinner72818982020-03-26 22:28:11 +0100819 _PyErr_Format(tstate, PyExc_ValueError,
820 "the fd %i must be in non-blocking mode",
821 fd);
Victor Stinner38227602014-08-27 12:59:44 +0200822 return NULL;
823 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 }
Victor Stinner0bffc942014-07-21 16:28:54 +0200825
Victor Stinnercda23be2020-11-17 18:57:32 +0100826 int old_fd = wakeup.fd;
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800827 wakeup.fd = fd;
828 wakeup.warn_on_full_buffer = warn_on_full_buffer;
Victor Stinner0bffc942014-07-21 16:28:54 +0200829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 return PyLong_FromLong(old_fd);
Victor Stinner11517102014-07-29 23:31:34 +0200831#endif
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000832}
833
834PyDoc_STRVAR(set_wakeup_fd_doc,
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800835"set_wakeup_fd(fd, *, warn_on_full_buffer=True) -> fd\n\
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000836\n\
Victor Stinner11517102014-07-29 23:31:34 +0200837Sets the fd to be written to (with the signal number) when a signal\n\
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000838comes in. A library can use this to wakeup select or poll.\n\
Victor Stinner11517102014-07-29 23:31:34 +0200839The previous fd or -1 is returned.\n\
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000840\n\
841The fd must be non-blocking.");
842
843/* C API for the same, without all the error checking */
844int
845PySignal_SetWakeupFd(int fd)
846{
Victor Stinnercda23be2020-11-17 18:57:32 +0100847 if (fd < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 fd = -1;
Victor Stinnercda23be2020-11-17 18:57:32 +0100849 }
Victor Stinner11517102014-07-29 23:31:34 +0200850
851#ifdef MS_WINDOWS
Victor Stinnercda23be2020-11-17 18:57:32 +0100852 int old_fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
Victor Stinner11517102014-07-29 23:31:34 +0200853#else
Victor Stinnercda23be2020-11-17 18:57:32 +0100854 int old_fd = wakeup.fd;
Victor Stinner11517102014-07-29 23:31:34 +0200855#endif
Nathaniel J. Smith902ab802017-12-17 20:10:18 -0800856 wakeup.fd = fd;
857 wakeup.warn_on_full_buffer = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 return old_fd;
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000859}
860
861
Martin v. Löwis823725e2008-03-24 13:39:54 +0000862#ifdef HAVE_SETITIMER
Tal Einatc7027b72015-05-16 14:14:49 +0300863/*[clinic input]
864signal.setitimer
865
866 which: int
Victor Stinneref611c92017-10-13 13:49:43 -0700867 seconds: object
868 interval: object(c_default="NULL") = 0.0
Tal Einatc7027b72015-05-16 14:14:49 +0300869 /
870
871Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF).
872
873The timer will fire after value seconds and after that every interval seconds.
874The itimer can be cleared by setting seconds to zero.
875
876Returns old values as a tuple: (delay, interval).
877[clinic start generated code]*/
878
Martin v. Löwis823725e2008-03-24 13:39:54 +0000879static PyObject *
Victor Stinneref611c92017-10-13 13:49:43 -0700880signal_setitimer_impl(PyObject *module, int which, PyObject *seconds,
881 PyObject *interval)
882/*[clinic end generated code: output=65f9dcbddc35527b input=de43daf194e6f66f]*/
Martin v. Löwis823725e2008-03-24 13:39:54 +0000883{
Victor Stinnera5e64442021-04-28 03:02:55 +0200884 _signal_module_state *modstate = get_signal_state(module);
Martin v. Löwis823725e2008-03-24 13:39:54 +0000885
Victor Stinnera5e64442021-04-28 03:02:55 +0200886 struct itimerval new;
Victor Stinneref611c92017-10-13 13:49:43 -0700887 if (timeval_from_double(seconds, &new.it_value) < 0) {
888 return NULL;
889 }
890 if (timeval_from_double(interval, &new.it_interval) < 0) {
891 return NULL;
892 }
893
Martin v. Löwis823725e2008-03-24 13:39:54 +0000894 /* Let OS check "which" value */
Victor Stinnercda23be2020-11-17 18:57:32 +0100895 struct itimerval old;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000896 if (setitimer(which, &new, &old) != 0) {
Victor Stinnera5e64442021-04-28 03:02:55 +0200897 PyErr_SetFromErrno(modstate->itimer_error);
Tal Einatc7027b72015-05-16 14:14:49 +0300898 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000899 }
900
901 return itimer_retval(&old);
902}
Victor Stinnera5e64442021-04-28 03:02:55 +0200903#endif // HAVE_SETITIMER
Martin v. Löwis823725e2008-03-24 13:39:54 +0000904
905
906#ifdef HAVE_GETITIMER
Tal Einatc7027b72015-05-16 14:14:49 +0300907/*[clinic input]
908signal.getitimer
909
910 which: int
911 /
912
913Returns current value of given itimer.
914[clinic start generated code]*/
915
Martin v. Löwis823725e2008-03-24 13:39:54 +0000916static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300917signal_getitimer_impl(PyObject *module, int which)
918/*[clinic end generated code: output=9e053175d517db40 input=f7d21d38f3490627]*/
Martin v. Löwis823725e2008-03-24 13:39:54 +0000919{
Victor Stinnera5e64442021-04-28 03:02:55 +0200920 _signal_module_state *modstate = get_signal_state(module);
Martin v. Löwis823725e2008-03-24 13:39:54 +0000921
Victor Stinnera5e64442021-04-28 03:02:55 +0200922 struct itimerval old;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000923 if (getitimer(which, &old) != 0) {
Victor Stinnera5e64442021-04-28 03:02:55 +0200924 PyErr_SetFromErrno(modstate->itimer_error);
Tal Einatc7027b72015-05-16 14:14:49 +0300925 return NULL;
Martin v. Löwis823725e2008-03-24 13:39:54 +0000926 }
927
928 return itimer_retval(&old);
929}
Victor Stinnera5e64442021-04-28 03:02:55 +0200930#endif // HAVE_GETITIMER
Martin v. Löwis823725e2008-03-24 13:39:54 +0000931
Martin v. Löwis823725e2008-03-24 13:39:54 +0000932
Victor Stinnerb3e72192011-05-08 01:46:11 +0200933#if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGPENDING)
Victor Stinner35b300c2011-05-04 13:20:35 +0200934static PyObject*
935sigset_to_set(sigset_t mask)
936{
937 PyObject *signum, *result;
938 int sig;
939
940 result = PySet_New(0);
941 if (result == NULL)
942 return NULL;
943
944 for (sig = 1; sig < NSIG; sig++) {
945 if (sigismember(&mask, sig) != 1)
946 continue;
947
948 /* Handle the case where it is a member by adding the signal to
949 the result list. Ignore the other cases because they mean the
950 signal isn't a member of the mask or the signal was invalid,
951 and an invalid signal must have been our fault in constructing
952 the loop boundaries. */
953 signum = PyLong_FromLong(sig);
954 if (signum == NULL) {
955 Py_DECREF(result);
956 return NULL;
957 }
958 if (PySet_Add(result, signum) == -1) {
959 Py_DECREF(signum);
960 Py_DECREF(result);
961 return NULL;
962 }
963 Py_DECREF(signum);
964 }
965 return result;
966}
Victor Stinnerb3e72192011-05-08 01:46:11 +0200967#endif
Victor Stinner35b300c2011-05-04 13:20:35 +0200968
Victor Stinnerb3e72192011-05-08 01:46:11 +0200969#ifdef PYPTHREAD_SIGMASK
Tal Einatc7027b72015-05-16 14:14:49 +0300970
971/*[clinic input]
972signal.pthread_sigmask
973
974 how: int
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300975 mask: sigset_t
Tal Einatc7027b72015-05-16 14:14:49 +0300976 /
977
978Fetch and/or change the signal mask of the calling thread.
979[clinic start generated code]*/
980
Victor Stinnera9293352011-04-30 15:21:58 +0200981static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300982signal_pthread_sigmask_impl(PyObject *module, int how, sigset_t mask)
983/*[clinic end generated code: output=0562c0fb192981a8 input=85bcebda442fa77f]*/
Victor Stinnera9293352011-04-30 15:21:58 +0200984{
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300985 sigset_t previous;
Victor Stinnera9293352011-04-30 15:21:58 +0200986 int err;
987
Serhiy Storchakad54cfb12018-05-08 07:48:50 +0300988 err = pthread_sigmask(how, &mask, &previous);
Victor Stinnera9293352011-04-30 15:21:58 +0200989 if (err != 0) {
990 errno = err;
Victor Stinnerb3e72192011-05-08 01:46:11 +0200991 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnera9293352011-04-30 15:21:58 +0200992 return NULL;
993 }
994
Victor Stinnerd0e516d2011-05-03 14:57:12 +0200995 /* if signals was unblocked, signal handlers have been called */
996 if (PyErr_CheckSignals())
997 return NULL;
998
Victor Stinner35b300c2011-05-04 13:20:35 +0200999 return sigset_to_set(previous);
Victor Stinnera9293352011-04-30 15:21:58 +02001000}
1001
Victor Stinnera9293352011-04-30 15:21:58 +02001002#endif /* #ifdef PYPTHREAD_SIGMASK */
1003
Martin v. Löwis823725e2008-03-24 13:39:54 +00001004
Victor Stinnerb3e72192011-05-08 01:46:11 +02001005#ifdef HAVE_SIGPENDING
Tal Einatc7027b72015-05-16 14:14:49 +03001006
1007/*[clinic input]
1008signal.sigpending
1009
1010Examine pending signals.
1011
1012Returns a set of signal numbers that are pending for delivery to
1013the calling thread.
1014[clinic start generated code]*/
1015
Victor Stinnerb3e72192011-05-08 01:46:11 +02001016static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001017signal_sigpending_impl(PyObject *module)
1018/*[clinic end generated code: output=53375ffe89325022 input=e0036c016f874e29]*/
Victor Stinnerb3e72192011-05-08 01:46:11 +02001019{
1020 int err;
1021 sigset_t mask;
1022 err = sigpending(&mask);
1023 if (err)
1024 return PyErr_SetFromErrno(PyExc_OSError);
1025 return sigset_to_set(mask);
1026}
1027
Victor Stinnerb3e72192011-05-08 01:46:11 +02001028#endif /* #ifdef HAVE_SIGPENDING */
1029
1030
1031#ifdef HAVE_SIGWAIT
Tal Einatc7027b72015-05-16 14:14:49 +03001032
1033/*[clinic input]
1034signal.sigwait
1035
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001036 sigset: sigset_t
Tal Einatc7027b72015-05-16 14:14:49 +03001037 /
1038
1039Wait for a signal.
1040
1041Suspend execution of the calling thread until the delivery of one of the
1042signals specified in the signal set sigset. The function accepts the signal
1043and returns the signal number.
1044[clinic start generated code]*/
1045
Victor Stinnerb3e72192011-05-08 01:46:11 +02001046static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001047signal_sigwait_impl(PyObject *module, sigset_t sigset)
1048/*[clinic end generated code: output=f43770699d682f96 input=a6fbd47b1086d119]*/
Victor Stinnerb3e72192011-05-08 01:46:11 +02001049{
Victor Stinnerb3e72192011-05-08 01:46:11 +02001050 int err, signum;
1051
Victor Stinner10c30d62011-06-10 01:39:53 +02001052 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001053 err = sigwait(&sigset, &signum);
Victor Stinner10c30d62011-06-10 01:39:53 +02001054 Py_END_ALLOW_THREADS
Victor Stinnerb3e72192011-05-08 01:46:11 +02001055 if (err) {
1056 errno = err;
1057 return PyErr_SetFromErrno(PyExc_OSError);
1058 }
1059
1060 return PyLong_FromLong(signum);
1061}
1062
Tal Einatc7027b72015-05-16 14:14:49 +03001063#endif /* #ifdef HAVE_SIGWAIT */
1064
Victor Stinnerb3e72192011-05-08 01:46:11 +02001065
Antoine Pitrou9d3627e2018-05-04 13:00:50 +02001066#if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)
1067
1068/*[clinic input]
1069signal.valid_signals
1070
1071Return a set of valid signal numbers on this platform.
1072
1073The signal numbers returned by this function can be safely passed to
1074functions like `pthread_sigmask`.
1075[clinic start generated code]*/
1076
1077static PyObject *
1078signal_valid_signals_impl(PyObject *module)
1079/*[clinic end generated code: output=1609cffbcfcf1314 input=86a3717ff25288f2]*/
1080{
1081#ifdef MS_WINDOWS
1082#ifdef SIGBREAK
1083 PyObject *tup = Py_BuildValue("(iiiiiii)", SIGABRT, SIGBREAK, SIGFPE,
1084 SIGILL, SIGINT, SIGSEGV, SIGTERM);
1085#else
1086 PyObject *tup = Py_BuildValue("(iiiiii)", SIGABRT, SIGFPE, SIGILL,
1087 SIGINT, SIGSEGV, SIGTERM);
1088#endif
1089 if (tup == NULL) {
1090 return NULL;
1091 }
1092 PyObject *set = PySet_New(tup);
1093 Py_DECREF(tup);
1094 return set;
1095#else
1096 sigset_t mask;
1097 if (sigemptyset(&mask) || sigfillset(&mask)) {
1098 return PyErr_SetFromErrno(PyExc_OSError);
1099 }
1100 return sigset_to_set(mask);
1101#endif
1102}
1103
1104#endif /* #if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS) */
1105
1106
Ross Lagerwallbc808222011-06-25 12:13:40 +02001107#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
Ross Lagerwallbc808222011-06-25 12:13:40 +02001108static PyStructSequence_Field struct_siginfo_fields[] = {
1109 {"si_signo", "signal number"},
1110 {"si_code", "signal code"},
1111 {"si_errno", "errno associated with this signal"},
1112 {"si_pid", "sending process ID"},
1113 {"si_uid", "real user ID of sending process"},
1114 {"si_status", "exit value or signal"},
1115 {"si_band", "band event for SIGPOLL"},
1116 {0}
1117};
1118
1119PyDoc_STRVAR(struct_siginfo__doc__,
1120"struct_siginfo: Result from sigwaitinfo or sigtimedwait.\n\n\
1121This object may be accessed either as a tuple of\n\
1122(si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band),\n\
1123or via the attributes si_signo, si_code, and so on.");
1124
1125static PyStructSequence_Desc struct_siginfo_desc = {
1126 "signal.struct_siginfo", /* name */
1127 struct_siginfo__doc__, /* doc */
1128 struct_siginfo_fields, /* fields */
1129 7 /* n_in_sequence */
1130};
1131
1132static PyTypeObject SiginfoType;
1133
1134static PyObject *
1135fill_siginfo(siginfo_t *si)
1136{
1137 PyObject *result = PyStructSequence_New(&SiginfoType);
1138 if (!result)
1139 return NULL;
1140
1141 PyStructSequence_SET_ITEM(result, 0, PyLong_FromLong((long)(si->si_signo)));
1142 PyStructSequence_SET_ITEM(result, 1, PyLong_FromLong((long)(si->si_code)));
Victor Stinner09532fe2019-05-10 23:39:09 +02001143#ifdef __VXWORKS__
pxinwr8b5bdda2019-03-14 01:18:25 +08001144 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(0L));
1145 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(0L));
1146 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(0L));
1147 PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(0L));
Victor Stinner09532fe2019-05-10 23:39:09 +02001148#else
Ross Lagerwallbc808222011-06-25 12:13:40 +02001149 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si->si_errno)));
1150 PyStructSequence_SET_ITEM(result, 3, PyLong_FromPid(si->si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02001151 PyStructSequence_SET_ITEM(result, 4, _PyLong_FromUid(si->si_uid));
Ross Lagerwallbc808222011-06-25 12:13:40 +02001152 PyStructSequence_SET_ITEM(result, 5,
1153 PyLong_FromLong((long)(si->si_status)));
Victor Stinner09532fe2019-05-10 23:39:09 +02001154#endif
Zachary Ware6a6967e2016-10-01 00:47:27 -05001155#ifdef HAVE_SIGINFO_T_SI_BAND
Ross Lagerwallbc808222011-06-25 12:13:40 +02001156 PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(si->si_band));
Zachary Ware6a6967e2016-10-01 00:47:27 -05001157#else
1158 PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(0L));
1159#endif
Ross Lagerwallbc808222011-06-25 12:13:40 +02001160 if (PyErr_Occurred()) {
1161 Py_DECREF(result);
1162 return NULL;
1163 }
1164
1165 return result;
1166}
1167#endif
1168
1169#ifdef HAVE_SIGWAITINFO
Tal Einatc7027b72015-05-16 14:14:49 +03001170
1171/*[clinic input]
1172signal.sigwaitinfo
1173
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001174 sigset: sigset_t
Tal Einatc7027b72015-05-16 14:14:49 +03001175 /
1176
1177Wait synchronously until one of the signals in *sigset* is delivered.
1178
1179Returns a struct_siginfo containing information about the signal.
1180[clinic start generated code]*/
1181
Ross Lagerwallbc808222011-06-25 12:13:40 +02001182static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001183signal_sigwaitinfo_impl(PyObject *module, sigset_t sigset)
1184/*[clinic end generated code: output=1eb2f1fa236fdbca input=3d1a7e1f27fc664c]*/
Ross Lagerwallbc808222011-06-25 12:13:40 +02001185{
Ross Lagerwallbc808222011-06-25 12:13:40 +02001186 siginfo_t si;
1187 int err;
Victor Stinnera453cd82015-03-20 12:54:28 +01001188 int async_err = 0;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001189
Victor Stinnera453cd82015-03-20 12:54:28 +01001190 do {
1191 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001192 err = sigwaitinfo(&sigset, &si);
Victor Stinnera453cd82015-03-20 12:54:28 +01001193 Py_END_ALLOW_THREADS
1194 } while (err == -1
1195 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwallbc808222011-06-25 12:13:40 +02001196 if (err == -1)
Victor Stinnera453cd82015-03-20 12:54:28 +01001197 return (!async_err) ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001198
1199 return fill_siginfo(&si);
1200}
1201
Ross Lagerwallbc808222011-06-25 12:13:40 +02001202#endif /* #ifdef HAVE_SIGWAITINFO */
1203
1204#ifdef HAVE_SIGTIMEDWAIT
Tal Einatc7027b72015-05-16 14:14:49 +03001205
1206/*[clinic input]
1207signal.sigtimedwait
1208
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001209 sigset: sigset_t
Serhiy Storchaka6b680cd2015-05-16 15:57:56 +03001210 timeout as timeout_obj: object
Tal Einatc7027b72015-05-16 14:14:49 +03001211 /
1212
1213Like sigwaitinfo(), but with a timeout.
1214
1215The timeout is specified in seconds, with floating point numbers allowed.
1216[clinic start generated code]*/
1217
Ross Lagerwallbc808222011-06-25 12:13:40 +02001218static PyObject *
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001219signal_sigtimedwait_impl(PyObject *module, sigset_t sigset,
Serhiy Storchaka6b680cd2015-05-16 15:57:56 +03001220 PyObject *timeout_obj)
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001221/*[clinic end generated code: output=59c8971e8ae18a64 input=87fd39237cf0b7ba]*/
Ross Lagerwallbc808222011-06-25 12:13:40 +02001222{
Victor Stinnera453cd82015-03-20 12:54:28 +01001223 struct timespec ts;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001224 siginfo_t si;
Victor Stinnera453cd82015-03-20 12:54:28 +01001225 int res;
Victor Stinner34dc0f42015-03-27 18:19:03 +01001226 _PyTime_t timeout, deadline, monotonic;
Ross Lagerwallbc808222011-06-25 12:13:40 +02001227
Victor Stinner869e1772015-03-30 03:49:14 +02001228 if (_PyTime_FromSecondsObject(&timeout,
1229 timeout_obj, _PyTime_ROUND_CEILING) < 0)
Ross Lagerwallbc808222011-06-25 12:13:40 +02001230 return NULL;
1231
Victor Stinnera453cd82015-03-20 12:54:28 +01001232 if (timeout < 0) {
Ross Lagerwallbc808222011-06-25 12:13:40 +02001233 PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
1234 return NULL;
1235 }
1236
Victor Stinner34dc0f42015-03-27 18:19:03 +01001237 deadline = _PyTime_GetMonotonicClock() + timeout;
Victor Stinnera453cd82015-03-20 12:54:28 +01001238
1239 do {
Victor Stinner34dc0f42015-03-27 18:19:03 +01001240 if (_PyTime_AsTimespec(timeout, &ts) < 0)
1241 return NULL;
Victor Stinnera453cd82015-03-20 12:54:28 +01001242
1243 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001244 res = sigtimedwait(&sigset, &si, &ts);
Victor Stinnera453cd82015-03-20 12:54:28 +01001245 Py_END_ALLOW_THREADS
1246
1247 if (res != -1)
1248 break;
1249
1250 if (errno != EINTR) {
1251 if (errno == EAGAIN)
1252 Py_RETURN_NONE;
1253 else
1254 return PyErr_SetFromErrno(PyExc_OSError);
1255 }
1256
1257 /* sigtimedwait() was interrupted by a signal (EINTR) */
1258 if (PyErr_CheckSignals())
1259 return NULL;
1260
Victor Stinner34dc0f42015-03-27 18:19:03 +01001261 monotonic = _PyTime_GetMonotonicClock();
1262 timeout = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02001263 if (timeout < 0)
Victor Stinnera453cd82015-03-20 12:54:28 +01001264 break;
1265 } while (1);
Ross Lagerwallbc808222011-06-25 12:13:40 +02001266
1267 return fill_siginfo(&si);
1268}
1269
Ross Lagerwallbc808222011-06-25 12:13:40 +02001270#endif /* #ifdef HAVE_SIGTIMEDWAIT */
1271
Victor Stinnerb3e72192011-05-08 01:46:11 +02001272
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001273#if defined(HAVE_PTHREAD_KILL)
Tal Einatc7027b72015-05-16 14:14:49 +03001274
1275/*[clinic input]
1276signal.pthread_kill
1277
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001278 thread_id: unsigned_long(bitwise=True)
Tal Einatc7027b72015-05-16 14:14:49 +03001279 signalnum: int
1280 /
1281
1282Send a signal to a thread.
1283[clinic start generated code]*/
1284
Victor Stinnerb3e72192011-05-08 01:46:11 +02001285static PyObject *
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001286signal_pthread_kill_impl(PyObject *module, unsigned long thread_id,
1287 int signalnum)
1288/*[clinic end generated code: output=7629919b791bc27f input=1d901f2c7bb544ff]*/
Victor Stinnerb3e72192011-05-08 01:46:11 +02001289{
Victor Stinnerb3e72192011-05-08 01:46:11 +02001290 int err;
1291
Saiyang Gou7514f4f2020-02-12 23:47:42 -08001292 if (PySys_Audit("signal.pthread_kill", "ki", thread_id, signalnum) < 0) {
1293 return NULL;
1294 }
1295
Tal Einatc7027b72015-05-16 14:14:49 +03001296 err = pthread_kill((pthread_t)thread_id, signalnum);
Victor Stinnerb3e72192011-05-08 01:46:11 +02001297 if (err != 0) {
1298 errno = err;
1299 PyErr_SetFromErrno(PyExc_OSError);
1300 return NULL;
1301 }
1302
1303 /* the signal may have been send to the current thread */
1304 if (PyErr_CheckSignals())
1305 return NULL;
1306
1307 Py_RETURN_NONE;
1308}
1309
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001310#endif /* #if defined(HAVE_PTHREAD_KILL) */
Victor Stinnerb3e72192011-05-08 01:46:11 +02001311
1312
Benjamin Peterson74834512019-11-19 20:39:14 -08001313#if defined(__linux__) && defined(__NR_pidfd_send_signal)
1314/*[clinic input]
1315signal.pidfd_send_signal
1316
1317 pidfd: int
1318 signalnum: int
1319 siginfo: object = None
1320 flags: int = 0
1321 /
1322
1323Send a signal to a process referred to by a pid file descriptor.
1324[clinic start generated code]*/
1325
1326static PyObject *
1327signal_pidfd_send_signal_impl(PyObject *module, int pidfd, int signalnum,
1328 PyObject *siginfo, int flags)
1329/*[clinic end generated code: output=2d59f04a75d9cbdf input=2a6543a1f4ac2000]*/
1330
1331{
1332 if (siginfo != Py_None) {
1333 PyErr_SetString(PyExc_TypeError, "siginfo must be None");
1334 return NULL;
1335 }
1336 if (syscall(__NR_pidfd_send_signal, pidfd, signalnum, NULL, flags) < 0) {
1337 PyErr_SetFromErrno(PyExc_OSError);
1338 return NULL;
1339 }
1340 Py_RETURN_NONE;
1341}
1342#endif
1343
1344
Victor Stinnerb3e72192011-05-08 01:46:11 +02001345
Tal Einatc7027b72015-05-16 14:14:49 +03001346/* List of functions defined in the module -- some of the methoddefs are
1347 defined to nothing if the corresponding C function is not available. */
Barry Warsaw92971171997-01-03 00:14:25 +00001348static PyMethodDef signal_methods[] = {
Serhiy Storchakab0689ae2020-07-12 19:15:20 +03001349 SIGNAL_DEFAULT_INT_HANDLER_METHODDEF
Tal Einatc7027b72015-05-16 14:14:49 +03001350 SIGNAL_ALARM_METHODDEF
1351 SIGNAL_SETITIMER_METHODDEF
1352 SIGNAL_GETITIMER_METHODDEF
1353 SIGNAL_SIGNAL_METHODDEF
Vladimir Matveevc24c6c22019-01-08 01:58:25 -08001354 SIGNAL_RAISE_SIGNAL_METHODDEF
Antoine Pietri5d2a27d2018-03-12 14:42:34 +01001355 SIGNAL_STRSIGNAL_METHODDEF
Tal Einatc7027b72015-05-16 14:14:49 +03001356 SIGNAL_GETSIGNAL_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001357 {"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 +03001358 SIGNAL_SIGINTERRUPT_METHODDEF
1359 SIGNAL_PAUSE_METHODDEF
Benjamin Peterson74834512019-11-19 20:39:14 -08001360 SIGNAL_PIDFD_SEND_SIGNAL_METHODDEF
Tal Einatc7027b72015-05-16 14:14:49 +03001361 SIGNAL_PTHREAD_KILL_METHODDEF
1362 SIGNAL_PTHREAD_SIGMASK_METHODDEF
1363 SIGNAL_SIGPENDING_METHODDEF
1364 SIGNAL_SIGWAIT_METHODDEF
1365 SIGNAL_SIGWAITINFO_METHODDEF
1366 SIGNAL_SIGTIMEDWAIT_METHODDEF
Antoine Pitrou9d3627e2018-05-04 13:00:50 +02001367#if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)
1368 SIGNAL_VALID_SIGNALS_METHODDEF
1369#endif
Tal Einatc7027b72015-05-16 14:14:49 +03001370 {NULL, NULL} /* sentinel */
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001371};
1372
Barry Warsaw92971171997-01-03 00:14:25 +00001373
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001374PyDoc_STRVAR(module_doc,
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001375"This module provides mechanisms to use signal handlers in Python.\n\
1376\n\
1377Functions:\n\
1378\n\
1379alarm() -- cause SIGALRM after a specified time [Unix only]\n\
Martin v. Löwis823725e2008-03-24 13:39:54 +00001380setitimer() -- cause a signal (described below) after a specified\n\
1381 float time and the timer may restart then [Unix only]\n\
1382getitimer() -- get current value of timer [Unix only]\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001383signal() -- set the action for a given signal\n\
1384getsignal() -- get the signal action for a given signal\n\
1385pause() -- wait until a signal arrives [Unix only]\n\
1386default_int_handler() -- default SIGINT handler\n\
1387\n\
Martin v. Löwis823725e2008-03-24 13:39:54 +00001388signal constants:\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001389SIG_DFL -- used to refer to the system default handler\n\
1390SIG_IGN -- used to ignore the signal\n\
1391NSIG -- number of defined signals\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001392SIGINT, SIGTERM, etc. -- signal numbers\n\
1393\n\
Martin v. Löwis823725e2008-03-24 13:39:54 +00001394itimer constants:\n\
1395ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\
1396 expiration\n\
1397ITIMER_VIRTUAL -- decrements only when the process is executing,\n\
1398 and delivers SIGVTALRM upon expiration\n\
1399ITIMER_PROF -- decrements both when the process is executing and\n\
1400 when the system is executing on behalf of the process.\n\
1401 Coupled with ITIMER_VIRTUAL, this timer is usually\n\
1402 used to profile the time spent by the application\n\
1403 in user and kernel space. SIGPROF is delivered upon\n\
1404 expiration.\n\
1405\n\n\
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001406*** IMPORTANT NOTICE ***\n\
1407A signal handler function is called with two arguments:\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001408the first is the signal number, the second is the interrupted stack frame.");
Guido van Rossum1d8fb2d1998-06-28 16:54:49 +00001409
Martin v. Löwis1a214512008-06-11 05:26:20 +00001410
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001411
1412static int
Victor Stinnercda23be2020-11-17 18:57:32 +01001413signal_add_constants(PyObject *module)
1414{
1415#define ADD_INT_MACRO(macro) \
1416 if (PyModule_AddIntConstant(module, #macro, macro) < 0) { \
1417 return -1; \
1418 }
1419
1420 ADD_INT_MACRO(NSIG);
1421
1422 // SIG_xxx pthread_sigmask() constants
1423#ifdef SIG_BLOCK
1424 ADD_INT_MACRO(SIG_BLOCK);
1425#endif
1426#ifdef SIG_UNBLOCK
1427 ADD_INT_MACRO(SIG_UNBLOCK);
1428#endif
1429#ifdef SIG_SETMASK
1430 ADD_INT_MACRO(SIG_SETMASK);
1431#endif
1432
1433 // SIGxxx signal number constants
1434#ifdef SIGHUP
1435 ADD_INT_MACRO(SIGHUP);
1436#endif
1437#ifdef SIGINT
1438 ADD_INT_MACRO(SIGINT);
1439#endif
1440#ifdef SIGBREAK
1441 ADD_INT_MACRO(SIGBREAK);
1442#endif
1443#ifdef SIGQUIT
1444 ADD_INT_MACRO(SIGQUIT);
1445#endif
1446#ifdef SIGILL
1447 ADD_INT_MACRO(SIGILL);
1448#endif
1449#ifdef SIGTRAP
1450 ADD_INT_MACRO(SIGTRAP);
1451#endif
1452#ifdef SIGIOT
1453 ADD_INT_MACRO(SIGIOT);
1454#endif
1455#ifdef SIGABRT
1456 ADD_INT_MACRO(SIGABRT);
1457#endif
1458#ifdef SIGEMT
1459 ADD_INT_MACRO(SIGEMT);
1460#endif
1461#ifdef SIGFPE
1462 ADD_INT_MACRO(SIGFPE);
1463#endif
1464#ifdef SIGKILL
1465 ADD_INT_MACRO(SIGKILL);
1466#endif
1467#ifdef SIGBUS
1468 ADD_INT_MACRO(SIGBUS);
1469#endif
1470#ifdef SIGSEGV
1471 ADD_INT_MACRO(SIGSEGV);
1472#endif
1473#ifdef SIGSYS
1474 ADD_INT_MACRO(SIGSYS);
1475#endif
1476#ifdef SIGPIPE
1477 ADD_INT_MACRO(SIGPIPE);
1478#endif
1479#ifdef SIGALRM
1480 ADD_INT_MACRO(SIGALRM);
1481#endif
1482#ifdef SIGTERM
1483 ADD_INT_MACRO(SIGTERM);
1484#endif
1485#ifdef SIGUSR1
1486 ADD_INT_MACRO(SIGUSR1);
1487#endif
1488#ifdef SIGUSR2
1489 ADD_INT_MACRO(SIGUSR2);
1490#endif
1491#ifdef SIGCLD
1492 ADD_INT_MACRO(SIGCLD);
1493#endif
1494#ifdef SIGCHLD
1495 ADD_INT_MACRO(SIGCHLD);
1496#endif
1497#ifdef SIGPWR
1498 ADD_INT_MACRO(SIGPWR);
1499#endif
1500#ifdef SIGIO
1501 ADD_INT_MACRO(SIGIO);
1502#endif
1503#ifdef SIGURG
1504 ADD_INT_MACRO(SIGURG);
1505#endif
1506#ifdef SIGWINCH
1507 ADD_INT_MACRO(SIGWINCH);
1508#endif
1509#ifdef SIGPOLL
1510 ADD_INT_MACRO(SIGPOLL);
1511#endif
1512#ifdef SIGSTOP
1513 ADD_INT_MACRO(SIGSTOP);
1514#endif
1515#ifdef SIGTSTP
1516 ADD_INT_MACRO(SIGTSTP);
1517#endif
1518#ifdef SIGCONT
1519 ADD_INT_MACRO(SIGCONT);
1520#endif
1521#ifdef SIGTTIN
1522 ADD_INT_MACRO(SIGTTIN);
1523#endif
1524#ifdef SIGTTOU
1525 ADD_INT_MACRO(SIGTTOU);
1526#endif
1527#ifdef SIGVTALRM
1528 ADD_INT_MACRO(SIGVTALRM);
1529#endif
1530#ifdef SIGPROF
1531 ADD_INT_MACRO(SIGPROF);
1532#endif
1533#ifdef SIGXCPU
1534 ADD_INT_MACRO(SIGXCPU);
1535#endif
1536#ifdef SIGXFSZ
1537 ADD_INT_MACRO(SIGXFSZ);
1538#endif
1539#ifdef SIGRTMIN
1540 ADD_INT_MACRO(SIGRTMIN);
1541#endif
1542#ifdef SIGRTMAX
1543 ADD_INT_MACRO(SIGRTMAX);
1544#endif
1545#ifdef SIGINFO
1546 ADD_INT_MACRO(SIGINFO);
1547#endif
1548
1549 // ITIMER_xxx constants
1550#ifdef ITIMER_REAL
1551 ADD_INT_MACRO(ITIMER_REAL);
1552#endif
1553#ifdef ITIMER_VIRTUAL
1554 ADD_INT_MACRO(ITIMER_VIRTUAL);
1555#endif
1556#ifdef ITIMER_PROF
1557 ADD_INT_MACRO(ITIMER_PROF);
1558#endif
1559
1560 // CTRL_xxx Windows signals
1561#ifdef CTRL_C_EVENT
1562 ADD_INT_MACRO(CTRL_C_EVENT);
1563#endif
1564#ifdef CTRL_BREAK_EVENT
1565 ADD_INT_MACRO(CTRL_BREAK_EVENT);
1566#endif
1567
1568 return 0;
1569
1570#undef ADD_INT_MACRO
1571}
1572
1573
1574static int
Victor Stinnera5e64442021-04-28 03:02:55 +02001575signal_get_set_handlers(signal_state_t *state, PyObject *mod_dict)
Victor Stinnera09766d2021-04-28 01:50:04 +02001576{
1577 // Get signal handlers
1578 for (int signum = 1; signum < NSIG; signum++) {
1579 void (*c_handler)(int) = PyOS_getsig(signum);
1580 PyObject *func;
1581 if (c_handler == SIG_DFL) {
Victor Stinnera5e64442021-04-28 03:02:55 +02001582 func = state->default_handler;
Victor Stinnera09766d2021-04-28 01:50:04 +02001583 }
1584 else if (c_handler == SIG_IGN) {
Victor Stinnera5e64442021-04-28 03:02:55 +02001585 func = state->ignore_handler;
Victor Stinnera09766d2021-04-28 01:50:04 +02001586 }
1587 else {
1588 func = Py_None; // None of our business
1589 }
1590 // If signal_module_exec() is called more than one, we must
1591 // clear the strong reference to the previous function.
1592 PyObject* old_func = get_handler(signum);
Victor Stinnera5e64442021-04-28 03:02:55 +02001593 set_handler(signum, Py_NewRef(func));
Victor Stinnera09766d2021-04-28 01:50:04 +02001594 Py_XDECREF(old_func);
1595 }
1596
1597 // Instal Python SIGINT handler which raises KeyboardInterrupt
1598 PyObject* sigint_func = get_handler(SIGINT);
Victor Stinnera5e64442021-04-28 03:02:55 +02001599 if (sigint_func == state->default_handler) {
Victor Stinnera09766d2021-04-28 01:50:04 +02001600 PyObject *int_handler = PyMapping_GetItemString(mod_dict,
1601 "default_int_handler");
1602 if (!int_handler) {
1603 return -1;
1604 }
1605
Victor Stinnera5e64442021-04-28 03:02:55 +02001606 set_handler(SIGINT, int_handler);
Victor Stinnera09766d2021-04-28 01:50:04 +02001607 Py_DECREF(sigint_func);
1608 PyOS_setsig(SIGINT, signal_handler);
1609 }
1610 return 0;
1611}
1612
1613
1614static int
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001615signal_module_exec(PyObject *m)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001616{
Victor Stinnercda23be2020-11-17 18:57:32 +01001617 assert(!PyErr_Occurred());
1618
Victor Stinnera5e64442021-04-28 03:02:55 +02001619 signal_state_t *state = &signal_global_state;
1620 _signal_module_state *modstate = get_signal_state(m);
1621
1622 modstate->default_handler = state->default_handler; // borrowed ref
1623 modstate->ignore_handler = state->ignore_handler; // borrowed ref
1624
1625#ifdef PYHAVE_ITIMER_ERROR
1626 modstate->itimer_error = PyErr_NewException("signal.itimer_error",
1627 PyExc_OSError, NULL);
1628 if (modstate->itimer_error == NULL) {
1629 return -1;
1630 }
1631#endif
1632
Victor Stinnercda23be2020-11-17 18:57:32 +01001633 if (signal_add_constants(m) < 0) {
1634 return -1;
1635 }
1636
1637 /* Add some symbolic constants to the module */
1638 PyObject *d = PyModule_GetDict(m);
Victor Stinnera5e64442021-04-28 03:02:55 +02001639 if (PyDict_SetItemString(d, "SIG_DFL", state->default_handler) < 0) {
Victor Stinnercda23be2020-11-17 18:57:32 +01001640 return -1;
1641 }
Victor Stinnera5e64442021-04-28 03:02:55 +02001642 if (PyDict_SetItemString(d, "SIG_IGN", state->ignore_handler) < 0) {
Victor Stinnercda23be2020-11-17 18:57:32 +01001643 return -1;
1644 }
Victor Stinnera5e64442021-04-28 03:02:55 +02001645#ifdef PYHAVE_ITIMER_ERROR
1646 if (PyDict_SetItemString(d, "ItimerError", modstate->itimer_error) < 0) {
Victor Stinnercda23be2020-11-17 18:57:32 +01001647 return -1;
1648 }
1649#endif
Ross Lagerwallbc808222011-06-25 12:13:40 +02001650#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001651 if (PyModule_AddType(m, &SiginfoType) < 0) {
1652 return -1;
1653 }
Ross Lagerwallbc808222011-06-25 12:13:40 +02001654#endif
1655
Victor Stinnera09766d2021-04-28 01:50:04 +02001656 PyThreadState *tstate = _PyThreadState_GET();
1657 if (_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinnera5e64442021-04-28 03:02:55 +02001658 if (signal_get_set_handlers(state, d) < 0) {
Victor Stinner0ae323b2020-11-17 18:15:20 +01001659 return -1;
1660 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 }
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001662
Victor Stinnercda23be2020-11-17 18:57:32 +01001663 assert(!PyErr_Occurred());
1664 return 0;
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001665}
1666
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001667
Victor Stinnera5e64442021-04-28 03:02:55 +02001668#ifdef PYHAVE_ITIMER_ERROR
1669static int
1670_signal_module_traverse(PyObject *module, visitproc visit, void *arg)
1671{
1672 _signal_module_state *modstate = get_signal_state(module);
1673 Py_VISIT(modstate->itimer_error);
1674 return 0;
1675}
1676
1677static int
1678_signal_module_clear(PyObject *module)
1679{
1680 _signal_module_state *modstate = get_signal_state(module);
1681 Py_CLEAR(modstate->itimer_error);
1682 return 0;
1683}
1684
1685static void
1686_signal_module_free(void *module)
1687{
1688 _signal_module_clear((PyObject *)module);
1689}
1690#endif // PYHAVE_ITIMER_ERROR
1691
1692
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001693static PyModuleDef_Slot signal_slots[] = {
1694 {Py_mod_exec, signal_module_exec},
1695 {0, NULL}
1696};
1697
1698static struct PyModuleDef signal_module = {
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001699 PyModuleDef_HEAD_INIT,
1700 "_signal",
1701 .m_doc = module_doc,
Victor Stinnera5e64442021-04-28 03:02:55 +02001702 .m_size = sizeof(_signal_module_state),
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001703 .m_methods = signal_methods,
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001704 .m_slots = signal_slots,
Victor Stinnera5e64442021-04-28 03:02:55 +02001705#ifdef PYHAVE_ITIMER_ERROR
1706 .m_traverse = _signal_module_traverse,
1707 .m_clear = _signal_module_clear,
1708 .m_free = _signal_module_free,
1709#endif
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001710};
1711
Victor Stinner4b8032e2020-09-04 14:51:05 +02001712
Mohamed Koubaa71d1bd92020-09-03 03:21:06 -05001713PyMODINIT_FUNC
1714PyInit__signal(void)
1715{
Victor Stinner7f9b25a2020-11-17 23:28:25 +01001716 return PyModuleDef_Init(&signal_module);
Guido van Rossum08c16611997-08-02 03:01:42 +00001717}
1718
Victor Stinner4b8032e2020-09-04 14:51:05 +02001719
Victor Stinner296a7962020-11-17 16:22:23 +01001720void
1721_PySignal_Fini(void)
Guido van Rossum08c16611997-08-02 03:01:42 +00001722{
Victor Stinnera5e64442021-04-28 03:02:55 +02001723 signal_state_t *state = &signal_global_state;
1724
Victor Stinner0ae323b2020-11-17 18:15:20 +01001725 // Restore default signals and clear handlers
1726 for (int signum = 1; signum < NSIG; signum++) {
Antoine Pitrouba251c22021-03-11 23:35:45 +01001727 PyObject *func = get_handler(signum);
Victor Stinner0ae323b2020-11-17 18:15:20 +01001728 _Py_atomic_store_relaxed(&Handlers[signum].tripped, 0);
Victor Stinnera5e64442021-04-28 03:02:55 +02001729 set_handler(signum, NULL);
Victor Stinner0ae323b2020-11-17 18:15:20 +01001730 if (func != NULL
1731 && func != Py_None
Victor Stinnera5e64442021-04-28 03:02:55 +02001732 && func != state->default_handler
1733 && func != state->ignore_handler)
Victor Stinner0ae323b2020-11-17 18:15:20 +01001734 {
1735 PyOS_setsig(signum, SIG_DFL);
1736 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 Py_XDECREF(func);
1738 }
Guido van Rossum08c16611997-08-02 03:01:42 +00001739
Victor Stinner0ae323b2020-11-17 18:15:20 +01001740#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +02001741 if (state->sigint_event != NULL) {
1742 CloseHandle(state->sigint_event);
1743 state->sigint_event = NULL;
Victor Stinner0ae323b2020-11-17 18:15:20 +01001744 }
1745#endif
1746
Victor Stinnera5e64442021-04-28 03:02:55 +02001747 Py_CLEAR(state->default_handler);
1748 Py_CLEAR(state->ignore_handler);
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001749}
1750
Barry Warsaw92971171997-01-03 00:14:25 +00001751
Barry Warsaw92971171997-01-03 00:14:25 +00001752/* Declared in pyerrors.h */
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001753int
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001754PyErr_CheckSignals(void)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001755{
Victor Stinner72818982020-03-26 22:28:11 +01001756 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +02001757 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Eric Snow64d6cc82019-02-23 15:40:43 -07001758 return 0;
1759 }
1760
Victor Stinner72818982020-03-26 22:28:11 +01001761 return _PyErr_CheckSignalsTstate(tstate);
Eric Snow64d6cc82019-02-23 15:40:43 -07001762}
1763
1764
1765/* Declared in cpython/pyerrors.h */
1766int
Victor Stinner72818982020-03-26 22:28:11 +01001767_PyErr_CheckSignalsTstate(PyThreadState *tstate)
Eric Snow64d6cc82019-02-23 15:40:43 -07001768{
Victor Stinner72818982020-03-26 22:28:11 +01001769 if (!_Py_atomic_load(&is_tripped)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 return 0;
Victor Stinner72818982020-03-26 22:28:11 +01001771 }
Christian Heimesb76922a2007-12-11 01:06:40 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 /*
1774 * The is_tripped variable is meant to speed up the calls to
1775 * PyErr_CheckSignals (both directly or via pending calls) when no
1776 * signal has arrived. This variable is set to 1 when a signal arrives
1777 * and it is set to 0 here, when we know some signals arrived. This way
1778 * we can run the registered handlers with no signals blocked.
1779 *
1780 * NOTE: with this approach we can have a situation where is_tripped is
1781 * 1 but we have no more signals to handle (Handlers[i].tripped
1782 * is 0 for every signal i). This won't do us any harm (except
1783 * we're gonna spent some cycles for nothing). This happens when
1784 * we receive a signal i after we zero is_tripped and before we
1785 * check Handlers[i].tripped.
1786 */
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +02001787 _Py_atomic_store(&is_tripped, 0);
Christian Heimesb76922a2007-12-11 01:06:40 +00001788
Victor Stinner72818982020-03-26 22:28:11 +01001789 PyObject *frame = (PyObject *)tstate->frame;
1790 if (!frame) {
1791 frame = Py_None;
1792 }
Christian Heimesb76922a2007-12-11 01:06:40 +00001793
Victor Stinnera5e64442021-04-28 03:02:55 +02001794 signal_state_t *state = &signal_global_state;
Victor Stinner72818982020-03-26 22:28:11 +01001795 for (int i = 1; i < NSIG; i++) {
1796 if (!_Py_atomic_load_relaxed(&Handlers[i].tripped)) {
1797 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 }
Victor Stinner72818982020-03-26 22:28:11 +01001799 _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
1800
Antoine Pitrou68245b72021-03-05 10:32:50 +01001801 /* Signal handlers can be modified while a signal is received,
1802 * and therefore the fact that trip_signal() or PyErr_SetInterrupt()
1803 * was called doesn't guarantee that there is still a Python
1804 * signal handler for it by the time PyErr_CheckSignals() is called
1805 * (see bpo-43406).
1806 */
Antoine Pitrouba251c22021-03-11 23:35:45 +01001807 PyObject *func = get_handler(i);
Victor Stinnera5e64442021-04-28 03:02:55 +02001808 if (func == NULL || func == Py_None || func == state->ignore_handler ||
1809 func == state->default_handler) {
Antoine Pitrou68245b72021-03-05 10:32:50 +01001810 /* No Python signal handler due to aforementioned race condition.
1811 * We can't call raise() as it would break the assumption
1812 * that PyErr_SetInterrupt() only *simulates* an incoming
1813 * signal (i.e. it will never kill the process).
1814 * We also don't want to interrupt user code with a cryptic
1815 * asynchronous exception, so instead just write out an
1816 * unraisable error.
1817 */
1818 PyErr_Format(PyExc_OSError,
1819 "Signal %i ignored due to race condition",
1820 i);
1821 PyErr_WriteUnraisable(Py_None);
1822 continue;
1823 }
1824
Victor Stinner72818982020-03-26 22:28:11 +01001825 PyObject *arglist = Py_BuildValue("(iO)", i, frame);
1826 PyObject *result;
1827 if (arglist) {
Antoine Pitrou68245b72021-03-05 10:32:50 +01001828 result = _PyObject_Call(tstate, func, arglist, NULL);
Victor Stinner72818982020-03-26 22:28:11 +01001829 Py_DECREF(arglist);
1830 }
1831 else {
1832 result = NULL;
1833 }
1834 if (!result) {
1835 /* On error, re-schedule a call to _PyErr_CheckSignalsTstate() */
1836 _Py_atomic_store(&is_tripped, 1);
1837 return -1;
1838 }
1839
1840 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 }
Christian Heimesb76922a2007-12-11 01:06:40 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 return 0;
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001844}
1845
Guido van Rossumd2cd7ad2000-09-16 16:35:28 +00001846
Victor Stinner72818982020-03-26 22:28:11 +01001847
1848int
1849_PyErr_CheckSignals(void)
1850{
1851 PyThreadState *tstate = _PyThreadState_GET();
1852 return _PyErr_CheckSignalsTstate(tstate);
1853}
1854
1855
Antoine Pitrouba251c22021-03-11 23:35:45 +01001856/* Simulate the effect of a signal arriving. The next time PyErr_CheckSignals
1857 is called, the corresponding Python signal handler will be raised.
Matěj Cepl608876b2019-05-23 22:30:00 +02001858
Antoine Pitrouba251c22021-03-11 23:35:45 +01001859 Missing signal handler for the given signal number is silently ignored. */
1860int
1861PyErr_SetInterruptEx(int signum)
1862{
1863 if (signum < 1 || signum >= NSIG) {
1864 return -1;
1865 }
Victor Stinnera5e64442021-04-28 03:02:55 +02001866
1867 signal_state_t *state = &signal_global_state;
1868 PyObject *func = get_handler(signum);
1869 if (func != state->ignore_handler && func != state->default_handler) {
Antoine Pitrouba251c22021-03-11 23:35:45 +01001870 trip_signal(signum);
1871 }
1872 return 0;
1873}
1874
Barry Warsaw92971171997-01-03 00:14:25 +00001875void
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001876PyErr_SetInterrupt(void)
Barry Warsaw92971171997-01-03 00:14:25 +00001877{
Antoine Pitrouba251c22021-03-11 23:35:45 +01001878 (void) PyErr_SetInterruptEx(SIGINT);
Barry Warsaw92971171997-01-03 00:14:25 +00001879}
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001880
Victor Stinner0ae323b2020-11-17 18:15:20 +01001881static int
1882signal_install_handlers(void)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001883{
Victor Stinner296a7962020-11-17 16:22:23 +01001884#ifdef SIGPIPE
1885 PyOS_setsig(SIGPIPE, SIG_IGN);
1886#endif
1887#ifdef SIGXFZ
1888 PyOS_setsig(SIGXFZ, SIG_IGN);
1889#endif
1890#ifdef SIGXFSZ
1891 PyOS_setsig(SIGXFSZ, SIG_IGN);
1892#endif
1893
1894 // Import _signal to install the Python SIGINT handler
1895 PyObject *module = PyImport_ImportModule("_signal");
1896 if (!module) {
1897 return -1;
1898 }
1899 Py_DECREF(module);
1900
1901 return 0;
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001902}
1903
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001904
Victor Stinner29aa6242020-11-17 22:55:30 +01001905/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1906 *
1907 * All of the code in this function must only use async-signal-safe functions,
1908 * listed at `man 7 signal` or
1909 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1910 *
1911 * If this function is updated, update also _posix_spawn() of subprocess.py.
1912 */
1913void
1914_Py_RestoreSignals(void)
1915{
1916#ifdef SIGPIPE
1917 PyOS_setsig(SIGPIPE, SIG_DFL);
1918#endif
1919#ifdef SIGXFZ
1920 PyOS_setsig(SIGXFZ, SIG_DFL);
1921#endif
1922#ifdef SIGXFSZ
1923 PyOS_setsig(SIGXFSZ, SIG_DFL);
1924#endif
1925}
1926
1927
Victor Stinner0ae323b2020-11-17 18:15:20 +01001928int
1929_PySignal_Init(int install_signal_handlers)
1930{
Victor Stinnera5e64442021-04-28 03:02:55 +02001931 signal_state_t *state = &signal_global_state;
1932
1933 state->default_handler = PyLong_FromVoidPtr((void *)SIG_DFL);
1934 if (state->default_handler == NULL) {
Victor Stinner0ae323b2020-11-17 18:15:20 +01001935 return -1;
1936 }
1937
Victor Stinnera5e64442021-04-28 03:02:55 +02001938 state->ignore_handler = PyLong_FromVoidPtr((void *)SIG_IGN);
1939 if (state->ignore_handler == NULL) {
Victor Stinner0ae323b2020-11-17 18:15:20 +01001940 return -1;
1941 }
1942
Victor Stinner0ae323b2020-11-17 18:15:20 +01001943#ifdef MS_WINDOWS
1944 /* Create manual-reset event, initially unset */
Victor Stinnera5e64442021-04-28 03:02:55 +02001945 state->sigint_event = CreateEvent(NULL, TRUE, FALSE, FALSE);
1946 if (state->sigint_event == NULL) {
Victor Stinner0ae323b2020-11-17 18:15:20 +01001947 PyErr_SetFromWindowsErr(0);
1948 return -1;
1949 }
1950#endif
1951
1952#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
1953 if (SiginfoType.tp_name == NULL) {
1954 if (PyStructSequence_InitType2(&SiginfoType, &struct_siginfo_desc) < 0) {
1955 return -1;
1956 }
1957 }
1958#endif
1959
1960 for (int signum = 1; signum < NSIG; signum++) {
1961 _Py_atomic_store_relaxed(&Handlers[signum].tripped, 0);
1962 }
1963
1964 if (install_signal_handlers) {
1965 if (signal_install_handlers() < 0) {
1966 return -1;
1967 }
1968 }
1969
1970 return 0;
1971}
1972
1973
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001974// The caller doesn't have to hold the GIL
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001975int
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001976_PyOS_InterruptOccurred(PyThreadState *tstate)
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001977{
Victor Stinnercbe12962020-06-01 20:34:15 +02001978 _Py_EnsureTstateNotNULL(tstate);
1979 if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
Victor Stinner72818982020-03-26 22:28:11 +01001980 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 }
Victor Stinner72818982020-03-26 22:28:11 +01001982
1983 if (!_Py_atomic_load_relaxed(&Handlers[SIGINT].tripped)) {
1984 return 0;
1985 }
1986
1987 _Py_atomic_store_relaxed(&Handlers[SIGINT].tripped, 0);
1988 return 1;
Guido van Rossum398d9fe1994-05-11 08:59:13 +00001989}
Guido van Rossum359bcaa1997-11-14 22:24:28 +00001990
Victor Stinner26881c82020-06-02 15:51:37 +02001991
Victor Stinnerfa7ab6a2020-06-03 14:39:59 +02001992// The caller must to hold the GIL
1993int
1994PyOS_InterruptOccurred(void)
1995{
1996 PyThreadState *tstate = _PyThreadState_GET();
1997 return _PyOS_InterruptOccurred(tstate);
1998}
1999
2000
Victor Stinner26881c82020-06-02 15:51:37 +02002001#ifdef HAVE_FORK
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08002002static void
2003_clear_pending_signals(void)
2004{
Victor Stinner26881c82020-06-02 15:51:37 +02002005 if (!_Py_atomic_load(&is_tripped)) {
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08002006 return;
Victor Stinner26881c82020-06-02 15:51:37 +02002007 }
2008
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +02002009 _Py_atomic_store(&is_tripped, 0);
Victor Stinner26881c82020-06-02 15:51:37 +02002010 for (int i = 1; i < NSIG; ++i) {
Antoine Pitrou2c8a5e42017-07-17 12:25:19 +02002011 _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08002012 }
2013}
2014
Guido van Rossum359bcaa1997-11-14 22:24:28 +00002015void
Antoine Pitrou346cbd32017-05-27 17:50:54 +02002016_PySignal_AfterFork(void)
Guido van Rossum359bcaa1997-11-14 22:24:28 +00002017{
Gregory P. Smith9463e3a2012-11-10 20:33:07 -08002018 /* Clear the signal flags after forking so that they aren't handled
2019 * in both processes if they came in just before the fork() but before
2020 * the interpreter had an opportunity to call the handlers. issue9535. */
2021 _clear_pending_signals();
Guido van Rossum359bcaa1997-11-14 22:24:28 +00002022}
Victor Stinner26881c82020-06-02 15:51:37 +02002023#endif /* HAVE_FORK */
2024
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01002025
2026int
2027_PyOS_IsMainThread(void)
2028{
Victor Stinner81a7be32020-04-14 15:14:01 +02002029 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerb54a99d2020-04-08 23:35:05 +02002030 return _Py_ThreadCanHandleSignals(interp);
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01002031}
2032
2033#ifdef MS_WINDOWS
Victor Stinnera5e64442021-04-28 03:02:55 +02002034/* Returns a manual-reset event which gets tripped whenever
2035 SIGINT is received.
2036
2037 Python.h does not include windows.h so we do cannot use HANDLE
2038 as the return type of this function. We use void* instead. */
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01002039void *_PyOS_SigintEvent(void)
2040{
Victor Stinnera5e64442021-04-28 03:02:55 +02002041 signal_state_t *state = &signal_global_state;
2042 return state->sigint_event;
Antoine Pitrou6dd381e2011-11-21 21:26:56 +01002043}
2044#endif