| 1 | use std::{cell::RefCell, convert::TryInto, os::unix::io::RawFd, rc::Rc, time::Duration}; |
| 2 | use vec_map::VecMap; |
| 3 | |
| 4 | use crate::{loop_logic::CalloopKey, sources::timer::TimerWheel}; |
| 5 | |
| 6 | #[cfg(any(target_os = "linux", target_os = "android"))] |
| 7 | mod epoll; |
| 8 | #[cfg(any(target_os = "linux", target_os = "android"))] |
| 9 | use epoll::Epoll as Poller; |
| 10 | |
| 11 | #[cfg(any( |
| 12 | target_os = "dragonfly", |
| 13 | target_os = "freebsd", |
| 14 | target_os = "netbsd", |
| 15 | target_os = "openbsd", |
| 16 | target_os = "macos" |
| 17 | ))] |
| 18 | mod kqueue; |
| 19 | #[cfg(any( |
| 20 | target_os = "dragonfly", |
| 21 | target_os = "freebsd", |
| 22 | target_os = "netbsd", |
| 23 | target_os = "openbsd", |
| 24 | target_os = "macos" |
| 25 | ))] |
| 26 | use kqueue::Kqueue as Poller; |
| 27 | |
| 28 | /// Possible modes for registering a file descriptor |
| 29 | #[derive(Copy, Clone, Debug)] |
| 30 | pub enum Mode { |
| 31 | /// Single event generation |
| 32 | /// |
| 33 | /// This FD will be disabled as soon as it has generated one event. |
| 34 | /// |
| 35 | /// The user will need to use `LoopHandle::update()` to re-enable it if |
| 36 | /// desired. |
| 37 | OneShot, |
| 38 | /// Level-triggering |
| 39 | /// |
| 40 | /// This FD will report events on every poll as long as the requested interests |
| 41 | /// are available. If the same FD is inserted in multiple event loops, all of |
| 42 | /// them are notified of readiness. |
| 43 | Level, |
| 44 | /// Edge-triggering |
| 45 | /// |
| 46 | /// This FD will report events only when it *gains* one of the requested interests. |
| 47 | /// it must thus be fully processed before it'll generate events again. If the same |
| 48 | /// FD is inserted on multiple event loops, it may be that not all of them are notified |
| 49 | /// of readiness, and not necessarily always the same(s) (at least one is notified). |
| 50 | Edge, |
| 51 | } |
| 52 | |
| 53 | /// Interest to register regarding the file descriptor |
| 54 | #[derive(Copy, Clone, Debug)] |
| 55 | pub struct Interest { |
| 56 | /// Wait for the FD to be readable |
| 57 | pub readable: bool, |
| 58 | /// Wait for the FD to be writable |
| 59 | pub writable: bool, |
| 60 | } |
| 61 | |
| 62 | impl Interest { |
| 63 | /// Shorthand for empty interest |
| 64 | pub const EMPTY: Interest = Interest { |
| 65 | readable: false, |
| 66 | writable: false, |
| 67 | }; |
| 68 | /// Shorthand for read interest |
| 69 | pub const READ: Interest = Interest { |
| 70 | readable: true, |
| 71 | writable: false, |
| 72 | }; |
| 73 | /// Shorthand for write interest |
| 74 | pub const WRITE: Interest = Interest { |
| 75 | readable: false, |
| 76 | writable: true, |
| 77 | }; |
| 78 | /// Shorthand for read and write interest |
| 79 | pub const BOTH: Interest = Interest { |
| 80 | readable: true, |
| 81 | writable: true, |
| 82 | }; |
| 83 | } |
| 84 | |
| 85 | /// Readiness for a file descriptor notification |
| 86 | #[derive(Copy, Clone, Debug)] |
| 87 | pub struct Readiness { |
| 88 | /// Is the FD readable |
| 89 | pub readable: bool, |
| 90 | /// Is the FD writable |
| 91 | pub writable: bool, |
| 92 | /// Is the FD in an error state |
| 93 | pub error: bool, |
| 94 | } |
| 95 | |
| 96 | impl Readiness { |
| 97 | /// Shorthand for empty readiness |
| 98 | pub const EMPTY: Readiness = Readiness { |
| 99 | readable: false, |
| 100 | writable: false, |
| 101 | error: false, |
| 102 | }; |
| 103 | } |
| 104 | |
| 105 | #[derive(Debug)] |
| 106 | pub(crate) struct PollEvent { |
| 107 | pub(crate) readiness: Readiness, |
| 108 | pub(crate) token: Token, |
| 109 | } |
| 110 | |
| 111 | /// Factory for creating tokens in your registrations |
| 112 | /// |
| 113 | /// When composing event sources, each sub-source needs to |
| 114 | /// have its own token to identify itself. This factory is |
| 115 | /// provided to produce such unique tokens. |
| 116 | |
| 117 | #[derive(Debug)] |
| 118 | pub struct TokenFactory { |
| 119 | key: CalloopKey, |
| 120 | sub_id: u32, |
| 121 | } |
| 122 | |
| 123 | impl TokenFactory { |
| 124 | pub(crate) fn new(key: CalloopKey) -> TokenFactory { |
| 125 | TokenFactory { key, sub_id: 0 } |
| 126 | } |
| 127 | |
| 128 | /// Produce a new unique token |
| 129 | pub fn token(&mut self) -> Token { |
| 130 | let token = Token { |
| 131 | key: self.key, |
| 132 | sub_id: self.sub_id, |
| 133 | }; |
| 134 | self.sub_id += 1; |
| 135 | token |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | /// A token (for implementation of the [`EventSource`](crate::EventSource) trait) |
| 140 | /// |
| 141 | /// This token is produced by the [`TokenFactory`] and is used when calling the |
| 142 | /// [`EventSource`](crate::EventSource) implementations to process event, in order |
| 143 | /// to identify which sub-source produced them. |
| 144 | /// |
| 145 | /// You should forward it to the [`Poll`] when registering your file descriptors. |
| 146 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 147 | pub struct Token { |
| 148 | pub(crate) key: CalloopKey, |
| 149 | pub(crate) sub_id: u32, |
| 150 | } |
| 151 | |
| 152 | /// The polling system |
| 153 | /// |
| 154 | /// This type represents the polling system of calloop, on which you |
| 155 | /// can register your file descriptors. This interface is only accessible in |
| 156 | /// implementations of the [`EventSource`](crate::EventSource) trait. |
| 157 | /// |
| 158 | /// You only need to interact with this type if you are implementing your |
| 159 | /// own event sources, while implementing the [`EventSource`](crate::EventSource) trait. |
| 160 | /// And even in this case, you can often just use the [`Generic`](crate::generic::Generic) event |
| 161 | /// source and delegate the implementations to it. |
| 162 | pub struct Poll { |
| 163 | poller: Poller, |
| 164 | |
| 165 | // It is essential for safe use of this type that the pointers passed in to |
| 166 | // the underlying poller API are properly managed. Each time an event source |
| 167 | // is registered, the token it passes in is Boxed and converted to a raw |
| 168 | // pointer to be passed to the polling system by FFI. This pointer is what's |
| 169 | // stored in the map. When the event source is re- or unregistered, the same |
| 170 | // raw pointer can then be converted back into the Box and dropped, safely |
| 171 | // deallocating it. To put it another way, we effectively "own" the Token |
| 172 | // memory on behalf of the underlying polling mechanism. |
| 173 | // |
| 174 | // All the platforms we currently support follow the rule that file |
| 175 | // descriptors must be "small", positive integers. This means we can use a |
| 176 | // VecMap which has that exact constraint for its keys. If that ever |
| 177 | // changes, this will need to be changed to a different structure. |
| 178 | tokens: VecMap<*mut Token>, |
| 179 | pub(crate) timers: Rc<RefCell<TimerWheel>>, |
| 180 | } |
| 181 | |
| 182 | impl std::fmt::Debug for Poll { |
| 183 | #[cfg_attr(coverage, no_coverage)] |
| 184 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 185 | f.write_str("Poll { ... }") |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | impl Poll { |
| 190 | pub(crate) fn new(high_precision: bool) -> crate::Result<Poll> { |
| 191 | Ok(Poll { |
| 192 | poller: Poller::new(high_precision)?, |
| 193 | tokens: VecMap::new(), |
| 194 | timers: Rc::new(RefCell::new(TimerWheel::new())), |
| 195 | }) |
| 196 | } |
| 197 | |
| 198 | pub(crate) fn poll( |
| 199 | &mut self, |
| 200 | mut timeout: Option<std::time::Duration>, |
| 201 | ) -> crate::Result<Vec<PollEvent>> { |
| 202 | let now = std::time::Instant::now(); |
| 203 | // adjust the timeout for the timers |
| 204 | if let Some(next_timeout) = self.timers.borrow().next_deadline() { |
| 205 | if next_timeout <= now { |
| 206 | timeout = Some(Duration::ZERO); |
| 207 | } else if let Some(deadline) = timeout { |
| 208 | timeout = Some(std::cmp::min(deadline, next_timeout - now)); |
| 209 | } else { |
| 210 | timeout = Some(next_timeout - now); |
| 211 | } |
| 212 | }; |
| 213 | |
| 214 | let mut events = self.poller.poll(timeout)?; |
| 215 | |
| 216 | // Update 'now' as some time may have elapsed in poll() |
| 217 | let now = std::time::Instant::now(); |
| 218 | let mut timers = self.timers.borrow_mut(); |
| 219 | while let Some((_, token)) = timers.next_expired(now) { |
| 220 | events.push(PollEvent { |
| 221 | readiness: Readiness { |
| 222 | readable: true, |
| 223 | writable: false, |
| 224 | error: false, |
| 225 | }, |
| 226 | token, |
| 227 | }); |
| 228 | } |
| 229 | |
| 230 | Ok(events) |
| 231 | } |
| 232 | |
| 233 | /// Register a new file descriptor for polling |
| 234 | /// |
| 235 | /// The file descriptor will be registered with given interest, |
| 236 | /// mode and token. This function will fail if given a |
| 237 | /// bad file descriptor or if the provided file descriptor is already |
| 238 | /// registered. |
| 239 | /// |
| 240 | /// # Leaking tokens |
| 241 | /// |
| 242 | /// If your event source is dropped without being unregistered, the token |
| 243 | /// passed in here will remain on the heap and continue to be used by the |
| 244 | /// polling system even though no event source will match it. |
| 245 | pub fn register( |
| 246 | &mut self, |
| 247 | fd: RawFd, |
| 248 | interest: Interest, |
| 249 | mode: Mode, |
| 250 | token: Token, |
| 251 | ) -> crate::Result<()> { |
| 252 | let token_box = Box::new(token); |
| 253 | let token_ptr = Box::into_raw(token_box); |
| 254 | |
| 255 | let registration_result = self.poller.register(fd, interest, mode, token_ptr); |
| 256 | |
| 257 | if registration_result.is_err() { |
| 258 | // If registration did not work, do not add the file descriptor to |
| 259 | // the token map. Instead, reconstruct the Box and drop it. This is |
| 260 | // safe because it's from Box::into_raw() above. |
| 261 | let token_box = unsafe { Box::from_raw(token_ptr) }; |
| 262 | std::mem::drop(token_box); |
| 263 | } else { |
| 264 | // Registration worked, keep the token pointer until it's replaced |
| 265 | // or removed. |
| 266 | let index = index_from_fd(fd); |
| 267 | if self.tokens.insert(index, token_ptr).is_some() { |
| 268 | // If there is already a file descriptor associated with a |
| 269 | // token, then replacing that entry will leak the token, but |
| 270 | // converting it back into a Box might leave a dangling pointer |
| 271 | // somewhere. We can theoretically continue safely by choosing |
| 272 | // to leak, but one of our assumptions is no longer valid, so |
| 273 | // panic. |
| 274 | panic!("File descriptor ({}) already registered", fd); |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | registration_result |
| 279 | } |
| 280 | |
| 281 | /// Update the registration for a file descriptor |
| 282 | /// |
| 283 | /// This allows you to change the interest, mode or token of a file |
| 284 | /// descriptor. Fails if the provided fd is not currently registered. |
| 285 | /// |
| 286 | /// See note on [`register()`](Self::register()) regarding leaking. |
| 287 | pub fn reregister( |
| 288 | &mut self, |
| 289 | fd: RawFd, |
| 290 | interest: Interest, |
| 291 | mode: Mode, |
| 292 | token: Token, |
| 293 | ) -> crate::Result<()> { |
| 294 | let token_box = Box::new(token); |
| 295 | let token_ptr = Box::into_raw(token_box); |
| 296 | |
| 297 | let reregistration_result = self.poller.reregister(fd, interest, mode, token_ptr); |
| 298 | |
| 299 | if reregistration_result.is_err() { |
| 300 | // If registration did not work, do not add the file descriptor to |
| 301 | // the token map. Instead, reconstruct the Box and drop it. This is |
| 302 | // safe because it's from Box::into_raw() above. |
| 303 | let token_box = unsafe { Box::from_raw(token_ptr) }; |
| 304 | std::mem::drop(token_box); |
| 305 | } else { |
| 306 | // Registration worked, drop the old token memory and keep the new |
| 307 | // token pointer until it's replaced or removed. |
| 308 | let index = index_from_fd(fd); |
| 309 | if let Some(previous) = self.tokens.insert(index, token_ptr) { |
| 310 | // This is safe because it's from Box::into_raw() from a |
| 311 | // previous (re-)register() call. |
| 312 | let token_box = unsafe { Box::from_raw(previous) }; |
| 313 | std::mem::drop(token_box); |
| 314 | } else { |
| 315 | // If there is no previous token registered for this file |
| 316 | // descriptor, either the event source has wrongly called |
| 317 | // reregister() without first being registered, or the |
| 318 | // underlying poller has a dangling pointer. In the first case, |
| 319 | // the reregistration should have failed; in the second case, we |
| 320 | // cannot safely proceed. |
| 321 | panic!("File descriptor ({}) had no previous registration", fd); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | reregistration_result |
| 326 | } |
| 327 | |
| 328 | /// Unregister a file descriptor |
| 329 | /// |
| 330 | /// This file descriptor will no longer generate events. Fails if the |
| 331 | /// provided file descriptor is not currently registered. |
| 332 | pub fn unregister(&mut self, fd: RawFd) -> crate::Result<()> { |
| 333 | let unregistration_result = self.poller.unregister(fd); |
| 334 | |
| 335 | if unregistration_result.is_ok() { |
| 336 | // The source was unregistered, we can remove the old token data. |
| 337 | let index = index_from_fd(fd); |
| 338 | if let Some(previous) = self.tokens.remove(index) { |
| 339 | // This is safe because it's from Box::into_raw() from a |
| 340 | // previous (re-)register() call. |
| 341 | let token_box = unsafe { Box::from_raw(previous) }; |
| 342 | std::mem::drop(token_box); |
| 343 | } else { |
| 344 | // If there is no previous token registered for this file |
| 345 | // descriptor, either the event source has wrongly called |
| 346 | // unregister() without first being registered, or the |
| 347 | // underlying poller has a dangling pointer. In the first case, |
| 348 | // the reregistration should have failed; in the second case, we |
| 349 | // cannot safely proceed. |
| 350 | panic!("File descriptor ({}) had no previous registration", fd); |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | unregistration_result |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | /// Converts a file descriptor into an index for the token map. Panics if the |
| 359 | /// file descriptor is negative. |
| 360 | fn index_from_fd(fd: RawFd) -> usize { |
| 361 | fd.try_into() |
| 362 | .unwrap_or_else(|_| panic!("File descriptor ({}) is invalid", fd)) |
| 363 | } |