Fix UB in epoll_ctl
When passing None as an argument to `epoll_ctl`, UB is elicited within
the `Into<&EpollEvent>` impl because it passes a null pointer as a
`&mut EpollEvent`. Instead we remove that implementation completely and
handle this case directly within the `epoll_ctl` function.
Thanks to Arnavion for helping to debug this.
@@ -65,16 +65,6 @@ impl EpollEvent {
}
}
-impl<'a> Into<&'a mut EpollEvent> for Option<&'a mut EpollEvent> {
- #[inline]
- fn into(self) -> &'a mut EpollEvent {
- match self {
- Some(epoll_event) => epoll_event,
- None => unsafe { &mut *ptr::null_mut::<EpollEvent>() }
- }
- }
-}
-
#[inline]
pub fn epoll_create() -> Result<RawFd> {
let res = unsafe { libc::epoll_create(1024) };
@@ -91,13 +81,19 @@ pub fn epoll_create1(flags: EpollCreateFlags) -> Result<RawFd> {
#[inline]
pub fn epoll_ctl<'a, T>(epfd: RawFd, op: EpollOp, fd: RawFd, event: T) -> Result<()>
- where T: Into<&'a mut EpollEvent>
+ where T: Into<Option<&'a mut EpollEvent>>
{
- let event: &mut EpollEvent = event.into();
- if event as *const EpollEvent == ptr::null() && op != EpollOp::EpollCtlDel {
+ let mut event: Option<&mut EpollEvent> = event.into();
+ if event.is_none() && op != EpollOp::EpollCtlDel {
Err(Error::Sys(Errno::EINVAL))
} else {
- let res = unsafe { libc::epoll_ctl(epfd, op as c_int, fd, &mut event.event) };
+ let res = unsafe {
+ if let Some(ref mut event) = event {
+ libc::epoll_ctl(epfd, op as c_int, fd, &mut event.event)
+ } else {
+ libc::epoll_ctl(epfd, op as c_int, fd, ptr::null_mut())
+ }
+ };
Errno::result(res).map(drop)
}
}
