Debian Codegraph @

src/os/kqueue.rs

raw symbols SCIP
1 //! Functionality that is only available for `kqueue`-based platforms.
2
3 use crate::sys::{mode_to_flags, SourceId};
4 use crate::{PollMode, Poller};
5
6 use std::io;
7 use std::marker::PhantomData;
8 use std::process::Child;
9 use std::time::Duration;
10
11 use rustix::event::kqueue;
12
13 use super::__private::PollerSealed;
14 use __private::FilterSealed;
15
16 // TODO(notgull): We should also have EVFILT_AIO, EVFILT_VNODE and EVFILT_USER. However, the current
17 // API makes it difficult to effectively express events from these filters. At the next breaking
18 // change, we should change `Event` to be a struct with private fields, and encode additional
19 // information in there.
20
21 /// Functionality that is only available for `kqueue`-based platforms.
22 ///
23 /// `kqueue` is able to monitor much more than just read/write readiness on file descriptors. Using
24 /// this extension trait, you can monitor for signals, process exits, and more. See the implementors
25 /// of the [`Filter`] trait for more information.
26 pub trait PollerKqueueExt<F: Filter>: PollerSealed {
27 /// Add a filter to the poller.
28 ///
29 /// This is similar to [`add`][Poller::add], but it allows you to specify a filter instead of
30 /// a socket. See the implementors of the [`Filter`] trait for more information.
31 ///
32 /// # Examples
33 ///
34 /// ```no_run
35 /// use polling::{Events, Poller, PollMode};
36 /// use polling::os::kqueue::{Filter, PollerKqueueExt, Signal};
37 ///
38 /// let poller = Poller::new().unwrap();
39 ///
40 /// // Register the SIGINT signal.
41 /// poller.add_filter(Signal(rustix::process::Signal::INT.as_raw()), 0, PollMode::Oneshot).unwrap();
42 ///
43 /// // Wait for the signal.
44 /// let mut events = Events::new();
45 /// poller.wait(&mut events, None).unwrap();
46 /// # let _ = events;
47 /// ```
48 fn add_filter(&self, filter: F, key: usize, mode: PollMode) -> io::Result<()>;
49
50 /// Modify a filter in the poller.
51 ///
52 /// This is similar to [`modify`][Poller::modify], but it allows you to specify a filter
53 /// instead of a socket. See the implementors of the [`Filter`] trait for more information.
54 ///
55 /// # Examples
56 ///
57 /// ```no_run
58 /// use polling::{Events, Poller, PollMode};
59 /// use polling::os::kqueue::{Filter, PollerKqueueExt, Signal};
60 ///
61 /// let poller = Poller::new().unwrap();
62 ///
63 /// // Register the SIGINT signal.
64 /// poller.add_filter(Signal(rustix::process::Signal::INT.as_raw()), 0, PollMode::Oneshot).unwrap();
65 ///
66 /// // Re-register with a different key.
67 /// poller.modify_filter(Signal(rustix::process::Signal::INT.as_raw()), 1, PollMode::Oneshot).unwrap();
68 ///
69 /// // Wait for the signal.
70 /// let mut events = Events::new();
71 /// poller.wait(&mut events, None).unwrap();
72 /// # let _ = events;
73 /// ```
74 fn modify_filter(&self, filter: F, key: usize, mode: PollMode) -> io::Result<()>;
75
76 /// Remove a filter from the poller.
77 ///
78 /// This is used to remove filters that were previously added with
79 /// [`add_filter`](PollerKqueueExt::add_filter).
80 ///
81 /// # Examples
82 ///
83 /// ```no_run
84 /// use polling::{Poller, PollMode};
85 /// use polling::os::kqueue::{Filter, PollerKqueueExt, Signal};
86 ///
87 /// let poller = Poller::new().unwrap();
88 ///
89 /// // Register the SIGINT signal.
90 /// poller.add_filter(Signal(rustix::process::Signal::INT.as_raw()), 0, PollMode::Oneshot).unwrap();
91 ///
92 /// // Remove the filter.
93 /// poller.delete_filter(Signal(rustix::process::Signal::INT.as_raw())).unwrap();
94 /// ```
95 fn delete_filter(&self, filter: F) -> io::Result<()>;
96 }
97
98 impl<F: Filter> PollerKqueueExt<F> for Poller {
99 #[inline(always)]
100 fn add_filter(&self, filter: F, key: usize, mode: PollMode) -> io::Result<()> {
101 // No difference between adding and modifying in kqueue.
102 self.poller.add_source(filter.source_id())?;
103 self.modify_filter(filter, key, mode)
104 }
105
106 fn modify_filter(&self, filter: F, key: usize, mode: PollMode) -> io::Result<()> {
107 self.poller.has_source(filter.source_id())?;
108
109 // Convert the filter into a kevent.
110 let event = filter.filter(kqueue::EventFlags::ADD | mode_to_flags(mode), key);
111
112 // Modify the filter.
113 self.poller.submit_changes([event])
114 }
115
116 fn delete_filter(&self, filter: F) -> io::Result<()> {
117 // Convert the filter into a kevent.
118 let event = filter.filter(kqueue::EventFlags::DELETE, 0);
119
120 // Delete the filter.
121 self.poller.submit_changes([event])?;
122
123 self.poller.remove_source(filter.source_id())
124 }
125 }
126
127 /// A filter that can be registered into a `kqueue`.
128 pub trait Filter: FilterSealed {}
129
130 unsafe impl<T: FilterSealed + ?Sized> FilterSealed for &T {
131 #[inline(always)]
132 fn filter(&self, flags: kqueue::EventFlags, key: usize) -> kqueue::Event {
133 (**self).filter(flags, key)
134 }
135
136 #[inline(always)]
137 fn source_id(&self) -> SourceId {
138 (**self).source_id()
139 }
140 }
141
142 impl<T: Filter + ?Sized> Filter for &T {}
143
144 /// Monitor this signal number.
145 ///
146 /// No matter what `PollMode` is specified, this filter will always be
147 /// oneshot-only.
148 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
149 pub struct Signal(pub std::os::raw::c_int);
150
151 unsafe impl FilterSealed for Signal {
152 #[inline(always)]
153 fn filter(&self, flags: kqueue::EventFlags, key: usize) -> kqueue::Event {
154 kqueue::Event::new(
155 kqueue::EventFilter::Signal {
156 signal: rustix::process::Signal::from_named_raw(self.0)
157 .expect("invalid signal number"),
158 times: 0,
159 },
160 flags | kqueue::EventFlags::RECEIPT,
161 key as _,
162 )
163 }
164
165 #[inline(always)]
166 fn source_id(&self) -> SourceId {
167 SourceId::Signal(self.0)
168 }
169 }
170
171 impl Filter for Signal {}
172
173 /// Monitor a child process.
174 #[derive(Debug)]
175 pub struct Process<'a> {
176 /// The process ID to monitor.
177 pid: rustix::process::Pid,
178
179 /// The operation to monitor.
180 ops: ProcessOps,
181
182 /// Lifetime of the underlying process.
183 _lt: PhantomData<&'a Child>,
184 }
185
186 /// The operations that a monitored process can perform.
187 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
188 #[non_exhaustive]
189 pub enum ProcessOps {
190 /// The process exited.
191 Exit,
192
193 /// The process was forked.
194 Fork,
195
196 /// The process executed a new process.
197 Exec,
198 }
199
200 impl<'a> Process<'a> {
201 /// Monitor a child process.
202 ///
203 /// # Safety
204 ///
205 /// Once registered into the `Poller`, the `Child` object must outlive this filter's
206 /// registration into the poller.
207 pub unsafe fn new(child: &'a Child, ops: ProcessOps) -> Self {
208 Self {
209 pid: rustix::process::Pid::from_child(child),
210 ops,
211 _lt: PhantomData,
212 }
213 }
214
215 /// Create a `Process` from a PID.
216 ///
217 /// # Safety
218 ///
219 /// The PID must be tied to an actual child process.
220 pub unsafe fn from_pid(pid: std::num::NonZeroI32, ops: ProcessOps) -> Self {
221 Self {
222 pid: unsafe { rustix::process::Pid::from_raw_unchecked(pid.get()) },
223 ops,
224 _lt: PhantomData,
225 }
226 }
227 }
228
229 unsafe impl FilterSealed for Process<'_> {
230 #[inline(always)]
231 fn filter(&self, flags: kqueue::EventFlags, key: usize) -> kqueue::Event {
232 let events = match self.ops {
233 ProcessOps::Exit => kqueue::ProcessEvents::EXIT,
234 ProcessOps::Fork => kqueue::ProcessEvents::FORK,
235 ProcessOps::Exec => kqueue::ProcessEvents::EXEC,
236 };
237
238 kqueue::Event::new(
239 kqueue::EventFilter::Proc {
240 // SAFETY: We know that the PID is nonzero.
241 pid: self.pid,
242 flags: events,
243 },
244 flags | kqueue::EventFlags::RECEIPT,
245 key as _,
246 )
247 }
248
249 #[inline(always)]
250 fn source_id(&self) -> SourceId {
251 // SAFETY: We know that the PID is nonzero
252 SourceId::Pid(self.pid)
253 }
254 }
255
256 impl Filter for Process<'_> {}
257
258 /// Wait for a timeout to expire.
259 ///
260 /// Modifying the timeout after it has been added to the poller will reset it.
261 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
262 pub struct Timer {
263 /// Identifier for the timer.
264 pub id: usize,
265
266 /// The timeout to wait for.
267 pub timeout: Duration,
268 }
269
270 unsafe impl FilterSealed for Timer {
271 fn filter(&self, flags: kqueue::EventFlags, key: usize) -> kqueue::Event {
272 kqueue::Event::new(
273 kqueue::EventFilter::Timer {
274 ident: self.id as _,
275 timer: Some(self.timeout),
276 },
277 flags | kqueue::EventFlags::RECEIPT,
278 key as _,
279 )
280 }
281
282 #[inline(always)]
283 fn source_id(&self) -> SourceId {
284 SourceId::Timer(self.id)
285 }
286 }
287
288 impl Filter for Timer {}
289
290 mod __private {
291 use crate::sys::SourceId;
292 use rustix::event::kqueue;
293
294 #[doc(hidden)]
295 pub unsafe trait FilterSealed {
296 /// Get the filter for the given event.
297 ///
298 /// This filter's flags must have `EV_RECEIPT`.
299 fn filter(&self, flags: kqueue::EventFlags, key: usize) -> kqueue::Event;
300
301 /// Get the source ID for this source.
302 fn source_id(&self) -> SourceId;
303 }
304 }