Debian Codegraph @

src/sources/signals.rs

raw
1 //! Event source for tracking Unix signals
2 //!
3 //! Only available on Linux.
4 //!
5 //! This allows you to track and receive Unix signals through the event loop
6 //! rather than by registering signal handlers. It uses `signalfd` under the hood.
7 //!
8 //! The source will take care of masking and unmasking signals for the thread it runs on,
9 //! but you are responsible for masking them on other threads if you run them. The simplest
10 //! way to ensure that is to setup the signal event source before spawning any thread, as
11 //! they'll inherit their parent signal mask.
12
13 use std::convert::TryFrom;
14 use std::fmt;
15 use std::io::Error as IoError;
16 use std::os::raw::c_int;
17
18 use nix::sys::signal::SigSet;
19 use nix::sys::signalfd::{siginfo, SfdFlags, SignalFd};
20 use tracing::warn;
21
22 use super::generic::{FdWrapper, Generic};
23 use crate::{EventSource, Interest, Mode, Poll, PostAction, Readiness, Token, TokenFactory};
24
25 // Code taken from async-signal
26 macro_rules! define_signal_enum {
27 (
28 $(#[$outer:meta])*
29 pub enum Signal {
30 $(
31 $(#[$inner:meta])*
32 $value:ident,
33 )*
34 }
35 ) => {
36 $(#[$outer])*
37 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
38 #[repr(i32)]
39 pub enum Signal {
40 $(
41 $(#[$inner])*
42 $value = nix::sys::signal::Signal::$value as i32,
43 )*
44 }
45
46 impl Signal {
47 /// Returns the signal number.
48 fn as_nix(self) -> nix::sys::signal::Signal {
49 match self {
50 $(
51 Signal::$value => nix::sys::signal::Signal::$value,
52 )*
53 }
54 }
55
56 /// Generate from a signal number.
57 fn from_num(id: i32) -> Self {
58 match nix::sys::signal::Signal::try_from(id) {
59 $(
60 Ok(nix::sys::signal::Signal::$value) => Self::$value,
61 )*
62
63 Ok(sig) => panic!("unknown signal: {:?}", sig),
64 Err(_) => panic!("unknown signal: {}", id)
65 }
66 }
67 }
68 }
69 }
70
71 define_signal_enum! {
72 // Copied from https://github.com/bytecodealliance/rustix/blob/main/src/backend/linux_raw/process/types.rs#L81-L161
73
74 /// The signal types that we are able to listen for.
75 pub enum Signal {
76 /// `SIGHUP`
77 SIGHUP,
78 /// `SIGINT`
79 SIGINT,
80 /// `SIGQUIT`
81 SIGQUIT,
82 /// `SIGILL`
83 SIGILL,
84 /// `SIGTRAP`
85 SIGTRAP,
86 /// `SIGABRT`, aka `SIGIOT`
87 #[doc(alias = "Iot")]
88 #[doc(alias = "Abrt")]
89 SIGABRT,
90 /// `SIGBUS`
91 SIGBUS,
92 /// `SIGFPE`
93 SIGFPE,
94 /// `SIGKILL`
95 SIGKILL,
96 /// `SIGUSR1`
97 SIGUSR1,
98 /// `SIGSEGV`
99 SIGSEGV,
100 /// `SIGUSR2`
101 SIGUSR2,
102 /// `SIGPIPE`
103 SIGPIPE,
104 /// `SIGALRM`
105 #[doc(alias = "Alrm")]
106 SIGALRM,
107 /// `SIGTERM`
108 SIGTERM,
109 /// `SIGCHLD`
110 #[doc(alias = "Chld")]
111 SIGCHLD,
112 /// `SIGCONT`
113 SIGCONT,
114 /// `SIGSTOP`
115 SIGSTOP,
116 /// `SIGTSTP`
117 SIGTSTP,
118 /// `SIGTTIN`
119 SIGTTIN,
120 /// `SIGTTOU`
121 SIGTTOU,
122 /// `SIGURG`
123 SIGURG,
124 /// `SIGXCPU`
125 SIGXCPU,
126 /// `SIGXFSZ`
127 SIGXFSZ,
128 /// `SIGVTALRM`
129 #[doc(alias = "Vtalrm")]
130 SIGVTALRM,
131 /// `SIGPROF`
132 SIGPROF,
133 /// `SIGWINCH`
134 SIGWINCH,
135 /// `SIGIO`, aka `SIGPOLL`
136 #[doc(alias = "Poll")]
137 SIGIO,
138 /// `SIGSYS`, aka `SIGUNUSED`
139 #[doc(alias = "Unused")]
140 SIGSYS,
141 }
142 }
143
144 /// An event generated by the signal event source
145 #[derive(Copy, Clone, Debug)]
146 pub struct Event {
147 info: siginfo,
148 }
149
150 macro_rules! inner_accessors {
151 ($($name:ident => $sname:ident: $ty:ty),*) => {$(
152 /// Gets the `
153 #[doc = stringify!($sname)]
154 /// ` field.
155 pub fn $name(&self) -> $ty {
156 use core::convert::TryInto;
157 self.info.$sname.try_into().unwrap()
158 }
159 )*}
160 }
161
162 impl Event {
163 /// Retrieve the signal number that was receive
164 pub fn signal(&self) -> Signal {
165 Signal::from_num(self.info.ssi_signo as c_int)
166 }
167
168 inner_accessors! {
169 errno => ssi_errno: i32,
170 code => ssi_code: i32,
171 pid => ssi_pid: u32,
172 uid => ssi_uid: u32,
173 fd => ssi_fd: i32,
174 tid => ssi_tid: u32,
175 bad => ssi_band: u32,
176 overrun => ssi_overrun: u32,
177 trapno => ssi_trapno: u32,
178 status => ssi_status: u32
179 }
180 }
181
182 /// An event source for receiving Unix signals
183 #[derive(Debug)]
184 pub struct Signals {
185 sfd: Generic<FdWrapper<SignalFd>>,
186 mask: SigSet,
187 }
188
189 impl Signals {
190 /// Create a new signal event source listening on the specified list of signals
191 pub fn new(signals: &[Signal]) -> crate::Result<Signals> {
192 let mut mask = SigSet::empty();
193 for &s in signals {
194 mask.add(s.as_nix());
195 }
196
197 // Mask the signals for this thread
198 mask.thread_block().map_err(IoError::from)?;
199 // Create the SignalFd
200 let sfd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK | SfdFlags::SFD_CLOEXEC)
201 .map_err(IoError::from)?;
202
203 Ok(Signals {
204 sfd: Generic::new(unsafe { FdWrapper::new(sfd) }, Interest::READ, Mode::Level),
205 mask,
206 })
207 }
208
209 /// Add a list of signals to the signals source
210 ///
211 /// If this function returns an error, the signal mask of the thread may
212 /// have still been changed.
213 pub fn add_signals(&mut self, signals: &[Signal]) -> crate::Result<()> {
214 for &s in signals {
215 self.mask.add(s.as_nix());
216 }
217 self.mask.thread_block().map_err(IoError::from)?;
218
219 // SAFETY: We don't drop the underlying mask.
220 unsafe {
221 self.sfd
222 .get_mut()
223 .set_mask(&self.mask)
224 .map_err(IoError::from)?;
225 }
226 Ok(())
227 }
228
229 /// Remove a list of signals from the signals source
230 ///
231 /// If this function returns an error, the signal mask of the thread may
232 /// have still been changed.
233 pub fn remove_signals(&mut self, signals: &[Signal]) -> crate::Result<()> {
234 let mut removed = SigSet::empty();
235 for &s in signals {
236 self.mask.remove(s.as_nix());
237 removed.add(s.as_nix());
238 }
239 removed.thread_unblock().map_err(IoError::from)?;
240
241 // SAFETY: We don't drop the underlying mask.
242 unsafe {
243 self.sfd
244 .get_mut()
245 .set_mask(&self.mask)
246 .map_err(IoError::from)?;
247 }
248 Ok(())
249 }
250
251 /// Replace the list of signals of the source
252 ///
253 /// If this function returns an error, the signal mask of the thread may
254 /// have still been changed.
255 pub fn set_signals(&mut self, signals: &[Signal]) -> crate::Result<()> {
256 let mut new_mask = SigSet::empty();
257 for &s in signals {
258 new_mask.add(s.as_nix());
259 }
260
261 self.mask.thread_unblock().map_err(IoError::from)?;
262 new_mask.thread_block().map_err(IoError::from)?;
263
264 // SAFETY: We don't drop the underlying mask.
265 unsafe {
266 self.sfd
267 .get_mut()
268 .set_mask(&new_mask)
269 .map_err(IoError::from)?;
270 }
271 self.mask = new_mask;
272
273 Ok(())
274 }
275 }
276
277 impl Drop for Signals {
278 fn drop(&mut self) {
279 // we cannot handle error here
280 if let Err(e) = self.mask.thread_unblock() {
281 warn!("Failed to unmask signals: {e:?}");
282 }
283 }
284 }
285
286 impl EventSource for Signals {
287 type Event = Event;
288 type Metadata = ();
289 type Ret = ();
290 type Error = SignalError;
291
292 fn process_events<C>(
293 &mut self,
294 readiness: Readiness,
295 token: Token,
296 mut callback: C,
297 ) -> Result<PostAction, Self::Error>
298 where
299 C: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
300 {
301 self.sfd
302 .process_events(readiness, token, |_, sfd| {
303 loop {
304 match unsafe { sfd.get_mut().read_signal() } {
305 Ok(Some(info)) => callback(Event { info }, &mut ()),
306 Ok(None) => break,
307 Err(e) => {
308 warn!("Error reading from signalfd: {e}");
309 return Err(e.into());
310 }
311 }
312 }
313 Ok(PostAction::Continue)
314 })
315 .map_err(|e| SignalError(e.into()))
316 }
317
318 fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> {
319 self.sfd.register(poll, token_factory)
320 }
321
322 fn reregister(
323 &mut self,
324 poll: &mut Poll,
325 token_factory: &mut TokenFactory,
326 ) -> crate::Result<()> {
327 self.sfd.reregister(poll, token_factory)
328 }
329
330 fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> {
331 self.sfd.unregister(poll)
332 }
333 }
334
335 /// An error arising from processing events for a process signal.
336 #[derive(Debug)]
337 pub struct SignalError(Box<dyn std::error::Error + Sync + Send>);
338
339 impl fmt::Display for SignalError {
340 #[cfg_attr(feature = "nightly_coverage", coverage(off))]
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 fmt::Display::fmt(&self.0, f)
343 }
344 }
345
346 impl std::error::Error for SignalError {
347 #[cfg_attr(feature = "nightly_coverage", coverage(off))]
348 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
349 Some(&*self.0)
350 }
351 }