Skip to content

Commit ca9a3c9

Browse files
committed
Make sockaddr_un safe and use copy_nonoverlapping
The creation of libc::sockaddr_un is a safe operation, no need for it to be unsafe. This also uses the more performant copy_nonoverlapping instead of an iterator.
1 parent c1cd200 commit ca9a3c9

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

library/std/src/os/unix/net/addr.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::ffi::OsStr;
22
use crate::os::unix::ffi::OsStrExt;
33
use crate::path::Path;
44
use crate::sys::cvt;
5-
use crate::{ascii, fmt, io, iter, mem, ptr};
5+
use crate::{ascii, fmt, io, mem, ptr};
66

77
// FIXME(#43348): Make libc adapt #[doc(cfg(...))] so we don't need these fake definitions here?
88
#[cfg(not(unix))]
@@ -22,8 +22,9 @@ fn sun_path_offset(addr: &libc::sockaddr_un) -> usize {
2222
path - base
2323
}
2424

25-
pub(super) unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
26-
let mut addr: libc::sockaddr_un = mem::zeroed();
25+
pub(super) fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
26+
// SAFETY: All zeros is a valid representation for `sockaddr_un`.
27+
let mut addr: libc::sockaddr_un = unsafe { mem::zeroed() };
2728
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
2829

2930
let bytes = path.as_os_str().as_bytes();
@@ -41,11 +42,13 @@ pub(super) unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un,
4142
&"path must be shorter than SUN_LEN",
4243
));
4344
}
44-
for (dst, src) in iter::zip(&mut addr.sun_path, bytes) {
45-
*dst = *src as libc::c_char;
46-
}
47-
// null byte for pathname addresses is already there because we zeroed the
48-
// struct
45+
// SAFETY: `bytes` and `addr.sun_path` are not overlapping and
46+
// both point to valid memory.
47+
// NOTE: We zeroed the memory above, so the path is already null
48+
// terminated.
49+
unsafe {
50+
ptr::copy_nonoverlapping(bytes.as_ptr(), addr.sun_path.as_mut_ptr().cast(), bytes.len())
51+
};
4952

5053
let mut len = sun_path_offset(&addr) + bytes.len();
5154
match bytes.get(0) {

0 commit comments

Comments
 (0)