Skip to content

Commit

Permalink
Assert validity on the raw socket in SockRef::from
Browse files Browse the repository at this point in the history
Since we now use the niche feature on Unix it's unsound to use
SockRef::from(-1), but it can be done without any unsafe. This change
adds an assertion to ensure we hit this soundness issue.

Still need to wait on the I/O safety RFC:
https://github.com/rust-lang/rfcs/blob/master/text/3128-io-safety.md
Tracking issue: rust-lang/rust#87074
Implementation pr: rust-lang/rust#87329
  • Loading branch information
Thomasdezeeuw committed Jul 28, 2021
1 parent e00edab commit f32461a
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/sockref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,10 @@ where
{
/// The caller must ensure `S` is actually a socket.
fn from(socket: &'s S) -> Self {
let fd = socket.as_raw_fd();
assert!(fd >= 0);
SockRef {
socket: ManuallyDrop::new(unsafe { Socket::from_raw_fd(socket.as_raw_fd()) }),
socket: ManuallyDrop::new(unsafe { Socket::from_raw_fd(fd) }),
_lifetime: PhantomData,
}
}
Expand All @@ -125,8 +127,10 @@ where
{
/// See the `From<&impl AsRawFd>` implementation.
fn from(socket: &'s S) -> Self {
let socket = socket.as_raw_socket();
assert!(socket != winapi::um::winsock2::INVALID_SOCKET as _);
SockRef {
socket: ManuallyDrop::new(unsafe { Socket::from_raw_socket(socket.as_raw_socket()) }),
socket: ManuallyDrop::new(unsafe { Socket::from_raw_socket(socket) }),
_lifetime: PhantomData,
}
}
Expand All @@ -141,3 +145,11 @@ impl fmt::Debug for SockRef<'_> {
.finish()
}
}

#[test]
#[should_panic]
#[cfg(unix)]
fn sockref_from_invalid_fd() {
let raw: std::os::unix::io::RawFd = -1;
let _ = SockRef::from(&raw);
}

0 comments on commit f32461a

Please sign in to comment.