| 1 | use std::{ |
| 2 | ffi::c_short, |
| 3 | fmt::Debug, |
| 4 | io, |
| 5 | os::fd::{AsFd, AsRawFd, RawFd}, |
| 6 | }; |
| 7 | |
| 8 | use libc::{POLLIN, POLLOUT, pollfd}; |
| 9 | |
| 10 | use crate::common::{HARDENED_ENUM_VALUE_0, HARDENED_ENUM_VALUE_1}; |
| 11 | use crate::{cutils::cerr, log::dev_debug}; |
| 12 | |
| 13 | pub(super) trait Process: Sized { |
| 14 | /// IO Events that this process should handle. |
| 15 | type Event: Copy + Debug; |
| 16 | /// Reason why the event loop should break. |
| 17 | /// |
| 18 | /// See [`EventRegistry::set_break`] for more information. |
| 19 | type Break; |
| 20 | /// Reason why the event loop should exit. |
| 21 | /// |
| 22 | /// See [`EventRegistry::set_exit`] for more information. |
| 23 | type Exit; |
| 24 | /// Handle the corresponding event. |
| 25 | fn on_event(&mut self, event: Self::Event, registry: &mut EventRegistry<Self>); |
| 26 | } |
| 27 | |
| 28 | #[repr(u32)] |
| 29 | enum Status<T: Process> { |
| 30 | Continue = HARDENED_ENUM_VALUE_0, |
| 31 | Stop(StopReason<T>) = HARDENED_ENUM_VALUE_1, |
| 32 | } |
| 33 | |
| 34 | impl<T: Process> Status<T> { |
| 35 | fn is_break(&self) -> bool { |
| 36 | matches!(self, Self::Stop(StopReason::Break(_))) |
| 37 | } |
| 38 | |
| 39 | fn take_stop(&mut self) -> Option<StopReason<T>> { |
| 40 | // If the status ends up to be `Continue`, we are replacing it by another `Continue`. |
| 41 | let status = std::mem::replace(self, Self::Continue); |
| 42 | match status { |
| 43 | Status::Continue => None, |
| 44 | Status::Stop(reason) => Some(reason), |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | fn take_exit(&mut self) -> Option<T::Exit> { |
| 49 | match self.take_stop()? { |
| 50 | reason @ StopReason::Break(_) => { |
| 51 | // Replace back the status because it was not an `Exit`. |
| 52 | *self = Self::Stop(reason); |
| 53 | None |
| 54 | } |
| 55 | StopReason::Exit(exit_reason) => Some(exit_reason), |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | pub(super) enum StopReason<T: Process> { |
| 61 | Break(T::Break), |
| 62 | Exit(T::Exit), |
| 63 | } |
| 64 | |
| 65 | #[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Copy)] |
| 66 | struct EventId(usize); |
| 67 | |
| 68 | pub(super) struct EventHandle { |
| 69 | id: EventId, |
| 70 | should_poll: bool, |
| 71 | } |
| 72 | |
| 73 | impl EventHandle { |
| 74 | /// Ignore the event associated with this handle, meaning that the file descriptor for this |
| 75 | /// event will not be polled anymore for that specific event. |
| 76 | pub(super) fn ignore<T: Process>(&mut self, registry: &mut EventRegistry<T>) { |
| 77 | if self.should_poll { |
| 78 | if let Some(poll_fd) = registry.poll_fds.get_mut(self.id.0) { |
| 79 | poll_fd.should_poll = false; |
| 80 | self.should_poll = false; |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// Stop ignoring the event associated with this handle, meaning that the file descriptor for |
| 86 | /// this event will be polled for that specific event. |
| 87 | pub(super) fn resume<T: Process>(&mut self, registry: &mut EventRegistry<T>) { |
| 88 | if !self.should_poll { |
| 89 | if let Some(poll_fd) = registry.poll_fds.get_mut(self.id.0) { |
| 90 | poll_fd.should_poll = true; |
| 91 | self.should_poll = true; |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// Is this event handle ready to be processed? |
| 97 | pub(super) fn is_active(&self) -> bool { |
| 98 | self.should_poll |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// The kind of event that will be monitored for a file descriptor. |
| 103 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] |
| 104 | pub enum PollEvent { |
| 105 | /// Data may be read without blocking. |
| 106 | Readable, |
| 107 | /// Data may be written without blocking. |
| 108 | Writable, |
| 109 | } |
| 110 | |
| 111 | struct PollFd<T: Process> { |
| 112 | // FIXME ensure that the fd is not closed while the event registry is still open |
| 113 | raw_fd: RawFd, |
| 114 | event_flags: c_short, |
| 115 | should_poll: bool, |
| 116 | event: T::Event, |
| 117 | } |
| 118 | |
| 119 | /// A type able to register file descriptors to be polled. |
| 120 | pub(super) struct EventRegistry<T: Process> { |
| 121 | poll_fds: Vec<PollFd<T>>, |
| 122 | status: Status<T>, |
| 123 | } |
| 124 | |
| 125 | impl<T: Process> EventRegistry<T> { |
| 126 | /// Create a new and empty registry.. |
| 127 | pub(super) const fn new() -> Self { |
| 128 | Self { |
| 129 | poll_fds: Vec::new(), |
| 130 | status: Status::Continue, |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | /// Set the `fd` descriptor to be polled for `poll_event` events and produce `event` when `fd` is |
| 135 | /// ready. |
| 136 | pub(super) fn register_event<F: AsFd>( |
| 137 | &mut self, |
| 138 | fd: &F, |
| 139 | poll_event: PollEvent, |
| 140 | event_fn: impl Fn(PollEvent) -> T::Event, |
| 141 | ) -> EventHandle { |
| 142 | let id = EventId(self.poll_fds.len()); |
| 143 | |
| 144 | self.poll_fds.push(PollFd { |
| 145 | raw_fd: fd.as_fd().as_raw_fd(), |
| 146 | event_flags: match poll_event { |
| 147 | PollEvent::Readable => POLLIN, |
| 148 | PollEvent::Writable => POLLOUT, |
| 149 | }, |
| 150 | should_poll: true, |
| 151 | event: event_fn(poll_event), |
| 152 | }); |
| 153 | |
| 154 | EventHandle { |
| 155 | id, |
| 156 | should_poll: true, |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// Poll the file descriptors of that are not being ignored and return the ID of the |
| 161 | /// descriptors that are ready to be read or written. |
| 162 | /// |
| 163 | /// Calling this function will block until one of the file descriptors in the set is ready. |
| 164 | fn poll(&mut self) -> io::Result<Vec<EventId>> { |
| 165 | let (mut ids, mut fds): (Vec<EventId>, Vec<pollfd>) = self |
| 166 | .poll_fds |
| 167 | .iter() |
| 168 | .enumerate() |
| 169 | .filter_map(|(index, poll_fd)| { |
| 170 | poll_fd.should_poll.then_some({ |
| 171 | ( |
| 172 | EventId(index), |
| 173 | pollfd { |
| 174 | fd: poll_fd.raw_fd, |
| 175 | events: poll_fd.event_flags, |
| 176 | revents: 0, |
| 177 | }, |
| 178 | ) |
| 179 | }) |
| 180 | }) |
| 181 | .unzip(); |
| 182 | |
| 183 | // Don't call poll if there are no file descriptors to be polled. |
| 184 | if ids.is_empty() { |
| 185 | return Ok(ids); |
| 186 | } |
| 187 | |
| 188 | // SAFETY: `poll` expects a pointer to an array of file descriptors (first argument), |
| 189 | // the length of which is indicated by the second argument; the third argument being -1 |
| 190 | // denotes an infinite timeout. |
| 191 | // FIXME: we should set either a timeout or use ppoll when available. |
| 192 | cerr(unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as _, -1) })?; |
| 193 | |
| 194 | // Remove the ids that correspond to file descriptors that were not ready. |
| 195 | for (i, fd) in fds.iter().enumerate().rev() { |
| 196 | let events = fd.events & fd.revents; |
| 197 | if !((events & POLLIN != 0) || (events & POLLOUT != 0)) { |
| 198 | ids.remove(i); |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | Ok(ids) |
| 203 | } |
| 204 | |
| 205 | /// Stop the event loop when the current event has been handled and set a reason for it. |
| 206 | /// |
| 207 | /// This means that the event loop will stop even if other events are ready. |
| 208 | pub(super) fn set_break(&mut self, reason: T::Break) { |
| 209 | self.status = Status::Stop(StopReason::Break(reason)); |
| 210 | } |
| 211 | |
| 212 | /// Stop the event loop when the events that are ready by now have been handled and set a |
| 213 | /// reason for it. |
| 214 | pub(super) fn set_exit(&mut self, reason: T::Exit) { |
| 215 | self.status = Status::Stop(StopReason::Exit(reason)); |
| 216 | } |
| 217 | |
| 218 | /// Return whether a break reason has been set already. |
| 219 | pub(super) fn got_break(&self) -> bool { |
| 220 | self.status.is_break() |
| 221 | } |
| 222 | |
| 223 | /// Run the event loop over this registry using `process` to handle the produced events. |
| 224 | /// |
| 225 | /// The event loop will continue indefinitely unless you call [`EventRegistry::set_break`] or |
| 226 | /// [`EventRegistry::set_exit`]. |
| 227 | #[track_caller] |
| 228 | pub(super) fn event_loop(mut self, process: &mut T) -> StopReason<T> { |
| 229 | let mut event_queue = Vec::with_capacity(self.poll_fds.len()); |
| 230 | |
| 231 | loop { |
| 232 | // FIXME: maybe we should return the IO error instead. |
| 233 | if let Ok(ids) = self.poll() { |
| 234 | for EventId(index) in ids { |
| 235 | let event = self.poll_fds[index].event; |
| 236 | dev_debug!("event {event:?} is ready"); |
| 237 | event_queue.push(event); |
| 238 | } |
| 239 | |
| 240 | for event in event_queue.drain(..) { |
| 241 | process.on_event(event, &mut self); |
| 242 | |
| 243 | if let Some(reason) = self.status.take_exit() { |
| 244 | return StopReason::Exit(reason); |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | if let Some(reason) = self.status.take_stop() { |
| 250 | return reason; |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | } |