Debian Codegraph @

third_party/rust/rustix/src/event/epoll.rs

raw
1 //! Linux `epoll` support.
2 //!
3 //! # Examples
4 //!
5 //! ```no_run
6 //! # #[cfg(feature = "net")]
7 //! # fn main() -> std::io::Result<()> {
8 //! use rustix::event::epoll;
9 //! use rustix::fd::AsFd;
10 //! use rustix::io::{ioctl_fionbio, read, write};
11 //! use rustix::net::{
12 //! accept, bind_v4, listen, socket, AddressFamily, Ipv4Addr, SocketAddrV4, SocketType,
13 //! };
14 //! use std::collections::HashMap;
15 //! use std::os::unix::io::AsRawFd;
16 //!
17 //! // Create a socket and listen on it.
18 //! let listen_sock = socket(AddressFamily::INET, SocketType::STREAM, None)?;
19 //! bind_v4(&listen_sock, &SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0))?;
20 //! listen(&listen_sock, 1)?;
21 //!
22 //! // Create an epoll object. Using `Owning` here means the epoll object will
23 //! // take ownership of the file descriptors registered with it.
24 //! let epoll = epoll::create(epoll::CreateFlags::CLOEXEC)?;
25 //!
26 //! // Register the socket with the epoll object.
27 //! epoll::add(
28 //! &epoll,
29 //! &listen_sock,
30 //! epoll::EventData::new_u64(1),
31 //! epoll::EventFlags::IN,
32 //! )?;
33 //!
34 //! // Keep track of the sockets we've opened.
35 //! let mut next_id = epoll::EventData::new_u64(2);
36 //! let mut sockets = HashMap::new();
37 //!
38 //! // Process events.
39 //! let mut event_list = epoll::EventVec::with_capacity(4);
40 //! loop {
41 //! epoll::wait(&epoll, &mut event_list, -1)?;
42 //! for event in &event_list {
43 //! let target = event.data;
44 //! if target.u64() == 1 {
45 //! // Accept a new connection, set it to non-blocking, and
46 //! // register to be notified when it's ready to write to.
47 //! let conn_sock = accept(&listen_sock)?;
48 //! ioctl_fionbio(&conn_sock, true)?;
49 //! epoll::add(
50 //! &epoll,
51 //! &conn_sock,
52 //! next_id,
53 //! epoll::EventFlags::OUT | epoll::EventFlags::ET,
54 //! )?;
55 //!
56 //! // Keep track of the socket.
57 //! sockets.insert(next_id, conn_sock);
58 //! next_id = epoll::EventData::new_u64(next_id.u64() + 1);
59 //! } else {
60 //! // Write a message to the stream and then unregister it.
61 //! let target = sockets.remove(&target).unwrap();
62 //! write(&target, b"hello\n")?;
63 //! let _ = epoll::delete(&epoll, &target)?;
64 //! }
65 //! }
66 //! }
67 //! # }
68 //! # #[cfg(not(feature = "net"))]
69 //! # fn main() {}
70 //! ```
71
72 #![allow(unsafe_code)]
73 #![allow(unused_qualifications)]
74
75 use super::epoll;
76 #[cfg(feature = "alloc")]
77 use crate::backend::c;
78 pub use crate::backend::event::epoll::*;
79 use crate::backend::event::syscalls;
80 use crate::fd::{AsFd, OwnedFd};
81 use crate::io;
82 #[cfg(feature = "alloc")]
83 use alloc::vec::Vec;
84 use core::ffi::c_void;
85 use core::hash::{Hash, Hasher};
86 use core::slice;
87
88 /// `epoll_create1(flags)`—Creates a new epoll object.
89 ///
90 /// Use the [`epoll::CreateFlags::CLOEXEC`] flag to prevent the resulting file
91 /// descriptor from being implicitly passed across `exec` boundaries.
92 ///
93 /// # References
94 /// - [Linux]
95 ///
96 /// [Linux]: https://man7.org/linux/man-pages/man2/epoll_create.2.html
97 #[inline]
98 #[doc(alias = "epoll_create1")]
99 pub fn create(flags: epoll::CreateFlags) -> io::Result<OwnedFd> {
100 syscalls::epoll_create(flags)
101 }
102
103 /// `epoll_ctl(self, EPOLL_CTL_ADD, data, event)`—Adds an element to an epoll
104 /// object.
105 ///
106 /// This registers interest in any of the events set in `event_flags` occurring
107 /// on the file descriptor associated with `data`.
108 ///
109 /// Note that `close`ing a file descriptor does not necessarily unregister
110 /// interest which can lead to spurious events being returned from
111 /// [`epoll::wait`]. If a file descriptor is an `Arc<dyn SystemResource>`, then
112 /// `epoll` can be thought to maintain a `Weak<dyn SystemResource>` to the file
113 /// descriptor. Check the [faq] for details.
114 ///
115 /// # References
116 /// - [Linux]
117 ///
118 /// [Linux]: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html
119 /// [faq]: https://man7.org/linux/man-pages/man7/epoll.7.html#:~:text=Will%20closing%20a%20file%20descriptor%20cause%20it%20to%20be%20removed%20from%20all%0A%20%20%20%20%20%20%20%20%20%20epoll%20interest%20lists%3F
120 #[doc(alias = "epoll_ctl")]
121 #[inline]
122 pub fn add(
123 epoll: impl AsFd,
124 source: impl AsFd,
125 data: epoll::EventData,
126 event_flags: epoll::EventFlags,
127 ) -> io::Result<()> {
128 syscalls::epoll_add(
129 epoll.as_fd(),
130 source.as_fd(),
131 &Event {
132 flags: event_flags,
133 data,
134 #[cfg(all(libc, target_os = "redox"))]
135 _pad: 0,
136 },
137 )
138 }
139
140 /// `epoll_ctl(self, EPOLL_CTL_MOD, target, event)`—Modifies an element in a
141 /// given epoll object.
142 ///
143 /// This sets the events of interest with `target` to `events`.
144 ///
145 /// # References
146 /// - [Linux]
147 ///
148 /// [Linux]: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html
149 #[doc(alias = "epoll_ctl")]
150 #[inline]
151 pub fn modify(
152 epoll: impl AsFd,
153 source: impl AsFd,
154 data: epoll::EventData,
155 event_flags: epoll::EventFlags,
156 ) -> io::Result<()> {
157 syscalls::epoll_mod(
158 epoll.as_fd(),
159 source.as_fd(),
160 &Event {
161 flags: event_flags,
162 data,
163 #[cfg(all(libc, target_os = "redox"))]
164 _pad: 0,
165 },
166 )
167 }
168
169 /// `epoll_ctl(self, EPOLL_CTL_DEL, target, NULL)`—Removes an element in a
170 /// given epoll object.
171 ///
172 /// # References
173 /// - [Linux]
174 ///
175 /// [Linux]: https://man7.org/linux/man-pages/man2/epoll_ctl.2.html
176 #[doc(alias = "epoll_ctl")]
177 #[inline]
178 pub fn delete(epoll: impl AsFd, source: impl AsFd) -> io::Result<()> {
179 syscalls::epoll_del(epoll.as_fd(), source.as_fd())
180 }
181
182 /// `epoll_wait(self, events, timeout)`—Waits for registered events of
183 /// interest.
184 ///
185 /// For each event of interest, an element is written to `events`. On
186 /// success, this returns the number of written elements.
187 ///
188 /// # References
189 /// - [Linux]
190 ///
191 /// [Linux]: https://man7.org/linux/man-pages/man2/epoll_wait.2.html
192 #[cfg(feature = "alloc")]
193 #[cfg_attr(docsrs, doc(cfg(feature = "alloc"), alias = "epoll_wait"))]
194 #[inline]
195 pub fn wait(epoll: impl AsFd, event_list: &mut EventVec, timeout: c::c_int) -> io::Result<()> {
196 // SAFETY: We're calling `epoll_wait` via FFI and we know how it
197 // behaves.
198 unsafe {
199 event_list.events.clear();
200 let nfds = syscalls::epoll_wait(
201 epoll.as_fd(),
202 event_list.events.spare_capacity_mut(),
203 timeout,
204 )?;
205 event_list.events.set_len(nfds);
206 }
207
208 Ok(())
209 }
210
211 /// An iterator over the [`epoll::Event`]s in an [`epoll::EventVec`].
212 pub struct Iter<'a> {
213 /// Use `Copied` to copy the struct, since `Event` is `packed` on some
214 /// platforms, and it's common for users to directly destructure it, which
215 /// would lead to errors about forming references to packed fields.
216 iter: core::iter::Copied<slice::Iter<'a, Event>>,
217 }
218
219 impl<'a> Iterator for Iter<'a> {
220 type Item = epoll::Event;
221
222 #[inline]
223 fn next(&mut self) -> Option<Self::Item> {
224 self.iter.next()
225 }
226
227 #[inline]
228 fn size_hint(&self) -> (usize, Option<usize>) {
229 self.iter.size_hint()
230 }
231 }
232
233 /// A record of an event that occurred.
234 #[repr(C)]
235 #[cfg_attr(all(not(libc), target_arch = "x86_64"), repr(packed))]
236 #[cfg_attr(
237 all(
238 libc,
239 linux_kernel,
240 any(
241 all(
242 target_arch = "x86",
243 not(target_env = "musl"),
244 not(target_os = "android"),
245 ),
246 target_arch = "x86_64",
247 )
248 ),
249 repr(packed)
250 )]
251 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
252 pub struct Event {
253 /// Which specific event(s) occurred.
254 pub flags: EventFlags,
255 /// User data.
256 pub data: EventData,
257
258 #[cfg(all(libc, target_os = "redox"))]
259 _pad: u64,
260 }
261
262 /// Data associated with an [`epoll::Event`]. This can either be a 64-bit
263 /// integer value or a pointer which preserves pointer provenance.
264 #[repr(C)]
265 #[derive(Copy, Clone)]
266 pub union EventData {
267 /// A 64-bit integer value.
268 as_u64: u64,
269
270 /// A `*mut c_void` which preserves pointer provenance, extended to be
271 /// 64-bit so that if we read the value as a `u64` union field, we don't
272 /// get uninitialized memory.
273 sixty_four_bit_pointer: SixtyFourBitPointer,
274 }
275
276 impl EventData {
277 /// Construct a new value containing a `u64`.
278 #[inline]
279 pub const fn new_u64(value: u64) -> Self {
280 Self { as_u64: value }
281 }
282
283 /// Construct a new value containing a `*mut c_void`.
284 #[inline]
285 pub const fn new_ptr(value: *mut c_void) -> Self {
286 Self {
287 sixty_four_bit_pointer: SixtyFourBitPointer {
288 pointer: value,
289 #[cfg(target_pointer_width = "32")]
290 _padding: 0,
291 },
292 }
293 }
294
295 /// Return the value as a `u64`.
296 ///
297 /// If the stored value was a pointer, the pointer is zero-extended to a
298 /// `u64`.
299 #[inline]
300 pub fn u64(self) -> u64 {
301 unsafe { self.as_u64 }
302 }
303
304 /// Return the value as a `*mut c_void`.
305 ///
306 /// If the stored value was a `u64`, the least-significant bits of the
307 /// `u64` are returned as a pointer value.
308 #[inline]
309 pub fn ptr(self) -> *mut c_void {
310 unsafe { self.sixty_four_bit_pointer.pointer }
311 }
312 }
313
314 impl PartialEq for EventData {
315 #[inline]
316 fn eq(&self, other: &Self) -> bool {
317 self.u64() == other.u64()
318 }
319 }
320
321 impl Eq for EventData {}
322
323 impl Hash for EventData {
324 #[inline]
325 fn hash<H: Hasher>(&self, state: &mut H) {
326 self.u64().hash(state)
327 }
328 }
329
330 #[repr(C)]
331 #[derive(Copy, Clone)]
332 struct SixtyFourBitPointer {
333 #[cfg(target_endian = "big")]
334 #[cfg(target_pointer_width = "32")]
335 _padding: u32,
336
337 pointer: *mut c_void,
338
339 #[cfg(target_endian = "little")]
340 #[cfg(target_pointer_width = "32")]
341 _padding: u32,
342 }
343
344 /// A vector of `epoll::Event`s, plus context for interpreting them.
345 #[cfg(feature = "alloc")]
346 pub struct EventVec {
347 events: Vec<Event>,
348 }
349
350 #[cfg(feature = "alloc")]
351 impl EventVec {
352 /// Constructs an `epoll::EventVec` from raw pointer, length, and capacity.
353 ///
354 /// # Safety
355 ///
356 /// This function calls [`Vec::from_raw_parts`] with its arguments.
357 ///
358 /// [`Vec::from_raw_parts`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.from_raw_parts
359 #[inline]
360 pub unsafe fn from_raw_parts(ptr: *mut Event, len: usize, capacity: usize) -> Self {
361 Self {
362 events: Vec::from_raw_parts(ptr, len, capacity),
363 }
364 }
365
366 /// Constructs an `epoll::EventVec` with memory for `capacity`
367 /// `epoll::Event`s.
368 #[inline]
369 pub fn with_capacity(capacity: usize) -> Self {
370 Self {
371 events: Vec::with_capacity(capacity),
372 }
373 }
374
375 /// Returns the current `epoll::Event` capacity of this `epoll::EventVec`.
376 #[inline]
377 pub fn capacity(&self) -> usize {
378 self.events.capacity()
379 }
380
381 /// Reserves enough memory for at least `additional` more `epoll::Event`s.
382 #[inline]
383 pub fn reserve(&mut self, additional: usize) {
384 self.events.reserve(additional);
385 }
386
387 /// Reserves enough memory for exactly `additional` more `epoll::Event`s.
388 #[inline]
389 pub fn reserve_exact(&mut self, additional: usize) {
390 self.events.reserve_exact(additional);
391 }
392
393 /// Clears all the `epoll::Events` out of this `epoll::EventVec`.
394 #[inline]
395 pub fn clear(&mut self) {
396 self.events.clear();
397 }
398
399 /// Shrinks the capacity of this `epoll::EventVec` as much as possible.
400 #[inline]
401 pub fn shrink_to_fit(&mut self) {
402 self.events.shrink_to_fit();
403 }
404
405 /// Returns an iterator over the `epoll::Event`s in this `epoll::EventVec`.
406 #[inline]
407 pub fn iter(&self) -> Iter<'_> {
408 Iter {
409 iter: self.events.iter().copied(),
410 }
411 }
412
413 /// Returns the number of `epoll::Event`s logically contained in this
414 /// `epoll::EventVec`.
415 #[inline]
416 pub fn len(&mut self) -> usize {
417 self.events.len()
418 }
419
420 /// Tests whether this `epoll::EventVec` is logically empty.
421 #[inline]
422 pub fn is_empty(&mut self) -> bool {
423 self.events.is_empty()
424 }
425 }
426
427 #[cfg(feature = "alloc")]
428 impl<'a> IntoIterator for &'a EventVec {
429 type IntoIter = Iter<'a>;
430 type Item = epoll::Event;
431
432 #[inline]
433 fn into_iter(self) -> Self::IntoIter {
434 self.iter()
435 }
436 }
437
438 #[cfg(test)]
439 mod tests {
440 use super::*;
441
442 #[test]
443 fn test_epoll_layouts() {
444 check_renamed_type!(Event, epoll_event);
445 check_renamed_type!(Event, epoll_event);
446 check_renamed_struct_renamed_field!(Event, epoll_event, flags, events);
447 #[cfg(libc)]
448 check_renamed_struct_renamed_field!(Event, epoll_event, data, u64);
449 #[cfg(not(libc))]
450 check_renamed_struct_renamed_field!(Event, epoll_event, data, data);
451 }
452 }