Skip to content

Commit ac4a66f

Browse files
authored
Improve strict-provenance compatibility in the epoll API. (#693)
Change the user-data field of epoll's `Event` from a bare `u64` to a `union` which can be either a `u64` or a `*mut c_void` to allowe users to store pointers in it that preserve strict provenance. Also, rename `epoll::epoll_add` and similar to just `epoll::add` and similar, for tidiness.
1 parent 58152e9 commit ac4a66f

File tree

5 files changed

+317
-91
lines changed

5 files changed

+317
-91
lines changed

src/backend/libc/event/epoll.rs

Lines changed: 145 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -25,27 +25,32 @@
2525
//!
2626
//! // Create an epoll object. Using `Owning` here means the epoll object will
2727
//! // take ownership of the file descriptors registered with it.
28-
//! let epoll = epoll::epoll_create(epoll::CreateFlags::CLOEXEC)?;
28+
//! let epoll = epoll::create(epoll::CreateFlags::CLOEXEC)?;
2929
//!
3030
//! // Register the socket with the epoll object.
31-
//! epoll::epoll_add(&epoll, &listen_sock, 1, epoll::EventFlags::IN)?;
31+
//! epoll::add(
32+
//! &epoll,
33+
//! &listen_sock,
34+
//! epoll::EventData::new_u64(1),
35+
//! epoll::EventFlags::IN,
36+
//! )?;
3237
//!
3338
//! // Keep track of the sockets we've opened.
34-
//! let mut next_id = 2;
39+
//! let mut next_id = epoll::EventData::new_u64(2);
3540
//! let mut sockets = HashMap::new();
3641
//!
3742
//! // Process events.
3843
//! let mut event_list = epoll::EventVec::with_capacity(4);
3944
//! loop {
40-
//! epoll::epoll_wait(&epoll, &mut event_list, -1)?;
45+
//! epoll::wait(&epoll, &mut event_list, -1)?;
4146
//! for event in &event_list {
4247
//! let target = event.data;
43-
//! if target == 1 {
48+
//! if target.u64() == 1 {
4449
//! // Accept a new connection, set it to non-blocking, and
4550
//! // register to be notified when it's ready to write to.
4651
//! let conn_sock = accept(&listen_sock)?;
4752
//! ioctl_fionbio(&conn_sock, true)?;
48-
//! epoll::epoll_add(
53+
//! epoll::add(
4954
//! &epoll,
5055
//! &conn_sock,
5156
//! next_id,
@@ -54,12 +59,12 @@
5459
//!
5560
//! // Keep track of the socket.
5661
//! sockets.insert(next_id, conn_sock);
57-
//! next_id += 1;
62+
//! next_id = epoll::EventData::new_u64(next_id.u64() + 1);
5863
//! } else {
5964
//! // Write a message to the stream and then unregister it.
6065
//! let target = sockets.remove(&target).unwrap();
6166
//! write(&target, b"hello\n")?;
62-
//! let _ = epoll::epoll_del(&epoll, &target)?;
67+
//! let _ = epoll::delete(&epoll, &target)?;
6368
//! }
6469
//! }
6570
//! }
@@ -72,12 +77,16 @@ use crate::backend::c;
7277
use crate::backend::conv::{ret, ret_owned_fd, ret_u32};
7378
use crate::fd::{AsFd, AsRawFd, OwnedFd};
7479
use crate::io;
80+
use crate::utils::as_mut_ptr;
7581
use alloc::vec::Vec;
7682
use bitflags::bitflags;
83+
use core::ffi::c_void;
84+
use core::hash::{Hash, Hasher};
7785
use core::ptr::null_mut;
86+
use core::slice;
7887

7988
bitflags! {
80-
/// `EPOLL_*` for use with [`Epoll::new`].
89+
/// `EPOLL_*` for use with [`new`].
8190
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
8291
pub struct CreateFlags: c::c_int {
8392
/// `EPOLL_CLOEXEC`
@@ -86,7 +95,7 @@ bitflags! {
8695
}
8796

8897
bitflags! {
89-
/// `EPOLL*` for use with [`Epoll::add`].
98+
/// `EPOLL*` for use with [`add`].
9099
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Debug)]
91100
pub struct EventFlags: u32 {
92101
/// `EPOLLIN`
@@ -137,82 +146,91 @@ bitflags! {
137146
}
138147
}
139148

140-
/// `epoll_create1(flags)`—Creates a new `Epoll`.
149+
/// `epoll_create1(flags)`—Creates a new epoll object.
141150
///
142151
/// Use the [`CreateFlags::CLOEXEC`] flag to prevent the resulting file
143152
/// descriptor from being implicitly passed across `exec` boundaries.
144153
#[inline]
145154
#[doc(alias = "epoll_create1")]
146-
pub fn epoll_create(flags: CreateFlags) -> io::Result<OwnedFd> {
155+
pub fn create(flags: CreateFlags) -> io::Result<OwnedFd> {
147156
// SAFETY: We're calling `epoll_create1` via FFI and we know how it
148157
// behaves.
149158
unsafe { ret_owned_fd(c::epoll_create1(flags.bits())) }
150159
}
151160

152161
/// `epoll_ctl(self, EPOLL_CTL_ADD, data, event)`—Adds an element to an
153-
/// `Epoll`.
162+
/// epoll object.
154163
///
155-
/// If `epoll_del` is not called on the I/O source passed into this function
164+
/// This registers interest in any of the events set in `events` occurring
165+
/// on the file descriptor associated with `data`.
166+
///
167+
/// If [`delete`] is not called on the I/O source passed into this function
156168
/// before the I/O source is `close`d, then the `epoll` will act as if the I/O
157169
/// source is still registered with it. This can lead to spurious events being
158-
/// returned from `epoll_wait`. If a file descriptor is an
170+
/// returned from [`wait`]. If a file descriptor is an
159171
/// `Arc<dyn SystemResource>`, then `epoll` can be thought to maintain a
160172
/// `Weak<dyn SystemResource>` to the file descriptor.
161173
#[doc(alias = "epoll_ctl")]
162-
pub fn epoll_add(
174+
pub fn add(
163175
epoll: impl AsFd,
164176
source: impl AsFd,
165-
data: u64,
177+
data: EventData,
166178
event_flags: EventFlags,
167179
) -> io::Result<()> {
168180
// SAFETY: We're calling `epoll_ctl` via FFI and we know how it
169-
// behaves.
181+
// behaves. We use our own `Event` struct instead of libc's because
182+
// ours preserves pointer provenance instead of just using a `u64`,
183+
// and we have tests elsehwere for layout equivalence.
170184
unsafe {
171185
let raw_fd = source.as_fd().as_raw_fd();
172186
ret(c::epoll_ctl(
173187
epoll.as_fd().as_raw_fd(),
174188
c::EPOLL_CTL_ADD,
175189
raw_fd,
176-
&mut c::epoll_event {
177-
events: event_flags.bits(),
178-
r#u64: data,
179-
},
190+
as_mut_ptr(&mut Event {
191+
flags: event_flags,
192+
data,
193+
})
194+
.cast(),
180195
))
181196
}
182197
}
183198

184199
/// `epoll_ctl(self, EPOLL_CTL_MOD, target, event)`—Modifies an element in
185-
/// this `Epoll`.
200+
/// a given epoll object.
186201
///
187202
/// This sets the events of interest with `target` to `events`.
188203
#[doc(alias = "epoll_ctl")]
189-
pub fn epoll_mod(
204+
pub fn modify(
190205
epoll: impl AsFd,
191206
source: impl AsFd,
192-
data: u64,
207+
data: EventData,
193208
event_flags: EventFlags,
194209
) -> io::Result<()> {
195210
let raw_fd = source.as_fd().as_raw_fd();
196211

197212
// SAFETY: We're calling `epoll_ctl` via FFI and we know how it
198-
// behaves.
213+
// behaves. We use our own `Event` struct instead of libc's because
214+
// ours preserves pointer provenance instead of just using a `u64`,
215+
// and we have tests elsehwere for layout equivalence.
199216
unsafe {
200217
ret(c::epoll_ctl(
201218
epoll.as_fd().as_raw_fd(),
202219
c::EPOLL_CTL_MOD,
203220
raw_fd,
204-
&mut c::epoll_event {
205-
events: event_flags.bits(),
206-
r#u64: data,
207-
},
221+
as_mut_ptr(&mut Event {
222+
flags: event_flags,
223+
data,
224+
})
225+
.cast(),
208226
))
209227
}
210228
}
211229

212230
/// `epoll_ctl(self, EPOLL_CTL_DEL, target, NULL)`—Removes an element in
213-
/// this `Epoll`.
231+
/// a given epoll object.
214232
#[doc(alias = "epoll_ctl")]
215-
pub fn epoll_del(epoll: impl AsFd, source: impl AsFd) -> io::Result<()> {
233+
pub fn delete(epoll: impl AsFd, source: impl AsFd) -> io::Result<()> {
216234
// SAFETY: We're calling `epoll_ctl` via FFI and we know how it
217235
// behaves.
218236
unsafe {
@@ -231,11 +249,7 @@ pub fn epoll_del(epoll: impl AsFd, source: impl AsFd) -> io::Result<()> {
231249
///
232250
/// For each event of interest, an element is written to `events`. On
233251
/// success, this returns the number of written elements.
234-
pub fn epoll_wait(
235-
epoll: impl AsFd,
236-
event_list: &mut EventVec,
237-
timeout: c::c_int,
238-
) -> io::Result<()> {
252+
pub fn wait(epoll: impl AsFd, event_list: &mut EventVec, timeout: c::c_int) -> io::Result<()> {
239253
// SAFETY: We're calling `epoll_wait` via FFI and we know how it
240254
// behaves.
241255
unsafe {
@@ -254,12 +268,13 @@ pub fn epoll_wait(
254268

255269
/// An iterator over the `Event`s in an `EventVec`.
256270
pub struct Iter<'a> {
257-
iter: core::slice::Iter<'a, Event>,
271+
iter: slice::Iter<'a, Event>,
258272
}
259273

260274
impl<'a> Iterator for Iter<'a> {
261275
type Item = &'a Event;
262276

277+
#[inline]
263278
fn next(&mut self) -> Option<Self::Item> {
264279
self.iter.next()
265280
}
@@ -280,11 +295,91 @@ impl<'a> Iterator for Iter<'a> {
280295
)]
281296
pub struct Event {
282297
/// Which specific event(s) occurred.
283-
// Match the layout of `c::epoll_event`. We just use a `u64` instead of
284-
// the full union.
285-
pub event_flags: EventFlags,
298+
pub flags: EventFlags,
286299
/// User data.
287-
pub data: u64,
300+
pub data: EventData,
301+
}
302+
303+
/// Data assocated with an [`Event`]. This can either be a 64-bit integer value
304+
/// or a pointer which preserves pointer provenance.
305+
#[repr(C)]
306+
#[derive(Copy, Clone)]
307+
pub union EventData {
308+
/// A 64-bit integer value.
309+
as_u64: u64,
310+
311+
/// A `*mut c_void` which preserves pointer provenance, extended to be
312+
/// 64-bit so that if we read the value as a `u64` union field, we don't
313+
/// get uninitialized memory.
314+
sixty_four_bit_pointer: SixtyFourBitPointer,
315+
}
316+
317+
impl EventData {
318+
/// Construct a new value containing a `u64`.
319+
#[inline]
320+
pub fn new_u64(value: u64) -> Self {
321+
Self { as_u64: value }
322+
}
323+
324+
/// Construct a new value containing a `*mut c_void`.
325+
#[inline]
326+
pub fn new_ptr(value: *mut c_void) -> Self {
327+
Self {
328+
sixty_four_bit_pointer: SixtyFourBitPointer {
329+
pointer: value,
330+
#[cfg(target_pointer_width = "32")]
331+
_padding: 0,
332+
},
333+
}
334+
}
335+
336+
/// Return the value as a `u64`.
337+
///
338+
/// If the stored value was a pointer, the pointer is zero-extended to
339+
/// a `u64`.
340+
#[inline]
341+
pub fn u64(self) -> u64 {
342+
unsafe { self.as_u64 }
343+
}
344+
345+
/// Return the value as a `*mut c_void`.
346+
///
347+
/// If the stored value was a `u64`, the least-significant bits of the
348+
/// `u64` are returned as a pointer value.
349+
#[inline]
350+
pub fn ptr(self) -> *mut c_void {
351+
unsafe { self.sixty_four_bit_pointer.pointer }
352+
}
353+
}
354+
355+
impl PartialEq for EventData {
356+
#[inline]
357+
fn eq(&self, other: &EventData) -> bool {
358+
self.u64() == other.u64()
359+
}
360+
}
361+
362+
impl Eq for EventData {}
363+
364+
impl Hash for EventData {
365+
#[inline]
366+
fn hash<H: Hasher>(&self, state: &mut H) {
367+
self.u64().hash(state)
368+
}
369+
}
370+
371+
#[repr(C)]
372+
#[derive(Copy, Clone)]
373+
struct SixtyFourBitPointer {
374+
#[cfg(target_endian = "big")]
375+
#[cfg(target_pointer_width = "32")]
376+
_padding: u32,
377+
378+
pointer: *mut c_void,
379+
380+
#[cfg(target_endian = "little")]
381+
#[cfg(target_pointer_width = "32")]
382+
_padding: u32,
288383
}
289384

290385
/// A vector of `Event`s, plus context for interpreting them.
@@ -375,3 +470,11 @@ impl<'a> IntoIterator for &'a EventVec {
375470
self.iter()
376471
}
377472
}
473+
474+
#[test]
475+
fn test_epoll_layouts() {
476+
check_renamed_type!(Event, epoll_event);
477+
check_renamed_type!(Event, epoll_event);
478+
check_renamed_struct_renamed_field!(Event, epoll_event, flags, events);
479+
check_renamed_struct_renamed_field!(Event, epoll_event, data, u64);
480+
}

src/backend/linux_raw/c.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ pub(crate) use linux_raw_sys::general::{
5151
O_CLOEXEC, O_NONBLOCK, O_NONBLOCK as PIDFD_NONBLOCK, P_ALL, P_PID, P_PIDFD,
5252
};
5353
pub(crate) use linux_raw_sys::general::{AT_FDCWD, O_NOCTTY, O_RDWR};
54+
55+
#[cfg(feature = "event")]
56+
#[cfg(test)]
57+
pub(crate) use linux_raw_sys::general::epoll_event;
58+
5459
#[cfg(feature = "fs")]
5560
pub(crate) use linux_raw_sys::general::{NFS_SUPER_MAGIC, PROC_SUPER_MAGIC, UTIME_NOW, UTIME_OMIT};
5661
#[cfg(feature = "fs")]

0 commit comments

Comments
 (0)