Skip to content

Commit b26bb2a

Browse files
committed
refactor(sync): remove unsafe libc::open/close, use safe rustix::fs::open
1 parent 07a296a commit b26bb2a

2 files changed

Lines changed: 18 additions & 19 deletions

File tree

src/uu/sync/src/sync.rs

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
/* Last synced with: sync (GNU coreutils) 8.13 */
77

88
use clap::{Arg, ArgAction, Command};
9-
#[cfg(any(target_os = "linux", target_os = "android"))]
10-
use std::ffi::CString;
119
use std::path::Path;
1210
use uucore::display::Quotable;
1311
use uucore::error::{UResult, USimpleError, get_exit_code, set_exit_code};
@@ -229,22 +227,23 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
229227
#[cfg(any(target_os = "linux", target_os = "android"))]
230228
{
231229
let path = Path::new(&f);
232-
let c_path = CString::new(f.as_str()).unwrap();
233-
// SAFETY: c_path is a valid null-terminated C string
234-
let fd = unsafe { libc::open(c_path.as_ptr(), libc::O_NONBLOCK) };
235-
if fd < 0 {
236-
let err = std::io::Error::last_os_error();
237-
let is_eacces = err.raw_os_error() == Some(libc::EACCES);
238-
if !is_eacces || path.is_dir() {
239-
show_error!(
240-
"{}",
241-
translate!("sync-error-opening-file", "file" => f.quote(), "err" => err)
242-
);
243-
set_exit_code(1);
230+
match rustix::fs::open(
231+
path,
232+
rustix::fs::OFlags::NONBLOCK,
233+
rustix::fs::Mode::empty(),
234+
) {
235+
Ok(_fd) => { /* OwnedFd auto-closes on drop */ }
236+
Err(e) => {
237+
let is_eacces = e == rustix::io::Errno::ACCESS;
238+
if !is_eacces || path.is_dir() {
239+
let err = std::io::Error::from(e);
240+
show_error!(
241+
"{}",
242+
translate!("sync-error-opening-file", "file" => f.quote(), "err" => err)
243+
);
244+
set_exit_code(1);
245+
}
244246
}
245-
} else {
246-
// SAFETY: fd is a valid open file descriptor
247-
unsafe { libc::close(fd) };
248247
}
249248
}
250249
#[cfg(not(any(target_os = "linux", target_os = "android")))]

src/uucore/src/lib/features/buf_copy/linux.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ pub(crate) fn copy_exact(
128128
) -> std::io::Result<usize> {
129129
let mut left = num_bytes;
130130
let mut buf = [0; BUF_SIZE];
131-
let mut written = 0;
131+
let mut total_written = 0;
132132
while left > 0 {
133133
let n_read = rustix::io::read(read_fd, &mut buf)?;
134134
assert_ne!(n_read, 0, "unexpected end of pipe");
@@ -140,5 +140,5 @@ pub(crate) fn copy_exact(
140140
total_written += written;
141141
left -= n_read;
142142
}
143-
Ok(written)
143+
Ok(total_written)
144144
}

0 commit comments

Comments
 (0)