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.
This commit is contained in:
parent
c1cd200922
commit
ca9a3c9a9f
1 changed files with 11 additions and 8 deletions
|
@ -2,7 +2,7 @@ use crate::ffi::OsStr;
|
||||||
use crate::os::unix::ffi::OsStrExt;
|
use crate::os::unix::ffi::OsStrExt;
|
||||||
use crate::path::Path;
|
use crate::path::Path;
|
||||||
use crate::sys::cvt;
|
use crate::sys::cvt;
|
||||||
use crate::{ascii, fmt, io, iter, mem, ptr};
|
use crate::{ascii, fmt, io, mem, ptr};
|
||||||
|
|
||||||
// FIXME(#43348): Make libc adapt #[doc(cfg(...))] so we don't need these fake definitions here?
|
// FIXME(#43348): Make libc adapt #[doc(cfg(...))] so we don't need these fake definitions here?
|
||||||
#[cfg(not(unix))]
|
#[cfg(not(unix))]
|
||||||
|
@ -22,8 +22,9 @@ fn sun_path_offset(addr: &libc::sockaddr_un) -> usize {
|
||||||
path - base
|
path - base
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
|
pub(super) fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
|
||||||
let mut addr: libc::sockaddr_un = mem::zeroed();
|
// SAFETY: All zeros is a valid representation for `sockaddr_un`.
|
||||||
|
let mut addr: libc::sockaddr_un = unsafe { mem::zeroed() };
|
||||||
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
|
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
|
||||||
|
|
||||||
let bytes = path.as_os_str().as_bytes();
|
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,
|
||||||
&"path must be shorter than SUN_LEN",
|
&"path must be shorter than SUN_LEN",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
for (dst, src) in iter::zip(&mut addr.sun_path, bytes) {
|
// SAFETY: `bytes` and `addr.sun_path` are not overlapping and
|
||||||
*dst = *src as libc::c_char;
|
// both point to valid memory.
|
||||||
}
|
// NOTE: We zeroed the memory above, so the path is already null
|
||||||
// null byte for pathname addresses is already there because we zeroed the
|
// terminated.
|
||||||
// struct
|
unsafe {
|
||||||
|
ptr::copy_nonoverlapping(bytes.as_ptr(), addr.sun_path.as_mut_ptr().cast(), bytes.len())
|
||||||
|
};
|
||||||
|
|
||||||
let mut len = sun_path_offset(&addr) + bytes.len();
|
let mut len = sun_path_offset(&addr) + bytes.len();
|
||||||
match bytes.get(0) {
|
match bytes.get(0) {
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue