Debian Codegraph @

src/system/signal/stream.rs

raw symbols SCIP
1 use std::{
2 ffi::c_void,
3 io,
4 mem::MaybeUninit,
5 os::{
6 fd::{AsFd, AsRawFd, BorrowedFd},
7 unix::net::UnixStream,
8 },
9 sync::OnceLock,
10 };
11
12 use crate::{cutils::cerr, log::dev_error};
13
14 use super::{
15 SignalNumber, SignalsState,
16 handler::{SignalHandler, SignalHandlerBehavior},
17 info::SignalInfo,
18 signal_name,
19 };
20
21 static STREAM: OnceLock<SignalStream> = OnceLock::new();
22
23 /// # Safety
24 ///
25 /// The `info` parameters has to point to a valid instance of SignalInfo
26 pub(super) unsafe extern "C" fn send_siginfo(
27 _signal: SignalNumber,
28 info: *const SignalInfo,
29 _context: *const c_void,
30 ) {
31 if let Some(tx) = STREAM.get().map(|stream| stream.tx.as_raw_fd()) {
32 // SAFETY: called ensures that info is a valid pointer; any instance of SignalInfo will
33 // consists of SignalInfo::SIZE bytes
34 unsafe { libc::send(tx, info.cast(), SignalInfo::SIZE, libc::MSG_DONTWAIT) };
35 }
36 }
37
38 /// A type able to receive signal information from any [`super::SignalHandler`] with the
39 /// [`super::SignalHandlerBehavior::Stream`] behavior.
40 ///
41 /// This is a singleton type. Meaning that there will be only one value of this type during the
42 /// execution of a program.
43 pub(crate) struct SignalStream {
44 rx: UnixStream,
45 tx: UnixStream,
46 }
47
48 impl SignalStream {
49 /// Create a new [`SignalStream`].
50 ///
51 /// # Panics
52 ///
53 /// If this function has been called before.
54 #[track_caller]
55 pub(crate) fn init() -> io::Result<&'static Self> {
56 let (rx, tx) = UnixStream::pair().map_err(|err| {
57 dev_error!("cannot create socket pair for `SignalStream`: {err}");
58 err
59 })?;
60
61 if STREAM.set(Self { rx, tx }).is_err() {
62 panic!("`SignalStream` has already been initialized");
63 };
64
65 Ok(STREAM.get().unwrap())
66 }
67
68 /// Receives the information related to the arrival of a signal.
69 pub(crate) fn recv(&self) -> io::Result<SignalInfo> {
70 let mut info = MaybeUninit::<SignalInfo>::uninit();
71 let fd = self.rx.as_raw_fd();
72 // SAFETY: type invariant for `SignalStream` ensures that `fd` is a valid file descriptor;
73 // furthermore, `info` is a valid pointer to `siginfo_t` (by virtue of `SignalInfo` being a
74 // transparent newtype for it), which has room for `SignalInfo::SIZE` bytes.
75 let bytes = cerr(unsafe { libc::recv(fd, info.as_mut_ptr().cast(), SignalInfo::SIZE, 0) })?;
76
77 if bytes as usize != SignalInfo::SIZE {
78 return Err(io::Error::new(
79 io::ErrorKind::UnexpectedEof,
80 "Not enough bytes when receiving `siginfo_t`",
81 ));
82 }
83 // SAFETY: we can assume `info` is initialized because `recv` wrote enough bytes to fill
84 // the value and `siginfo_t` is POD.
85 Ok(unsafe { info.assume_init() })
86 }
87 }
88
89 #[track_caller]
90 pub(crate) fn register_handlers<const N: usize>(
91 signals: [SignalNumber; N],
92 original_signals: &mut SignalsState,
93 ) -> io::Result<[SignalHandler; N]> {
94 let mut handlers = signals.map(|signal| (signal, MaybeUninit::uninit()));
95
96 for (signal, handler) in &mut handlers {
97 *handler =
98 SignalHandler::register(*signal, SignalHandlerBehavior::Stream, original_signals)
99 .map(MaybeUninit::new)
100 .map_err(|err| {
101 let name = signal_name(*signal);
102 dev_error!("cannot setup handler for {name}: {err}");
103 err
104 })?;
105 }
106
107 // SAFETY: if the above for-loop has terminated, every handler will have
108 // been written to via "MaybeUnit::new", and so is initialized.
109 Ok(handlers.map(|(_, handler)| unsafe { handler.assume_init() }))
110 }
111
112 impl AsFd for SignalStream {
113 fn as_fd(&self) -> BorrowedFd<'_> {
114 self.rx.as_fd()
115 }
116 }