1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 03:27:44 +00:00

add some missing unsafe

This commit is contained in:
Sylvestre Ledru 2025-03-08 15:36:51 +01:00
parent 85c5d39fd7
commit b4ac10769d
12 changed files with 61 additions and 49 deletions

View file

@ -69,7 +69,9 @@ fuzz_target!(|_data: &[u8]| {
// Use C locale to avoid false positives, like in https://github.com/uutils/coreutils/issues/5378, // Use C locale to avoid false positives, like in https://github.com/uutils/coreutils/issues/5378,
// because uutils expr doesn't support localization yet // because uutils expr doesn't support localization yet
// TODO remove once uutils expr supports localization // TODO remove once uutils expr supports localization
env::set_var("LC_COLLATE", "C"); unsafe {
env::set_var("LC_COLLATE", "C");
}
let rust_result = generate_and_run_uumain(&args, uumain, None); let rust_result = generate_and_run_uumain(&args, uumain, None);
let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, None) { let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, None) {

View file

@ -84,7 +84,9 @@ fuzz_target!(|_data: &[u8]| {
let rust_result = generate_and_run_uumain(&args, uumain, None); let rust_result = generate_and_run_uumain(&args, uumain, None);
// TODO remove once uutils printf supports localization // TODO remove once uutils printf supports localization
env::set_var("LC_ALL", "C"); unsafe {
env::set_var("LC_ALL", "C");
}
let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, None) { let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, None) {
Ok(result) => result, Ok(result) => result,
Err(error_result) => { Err(error_result) => {

View file

@ -60,7 +60,9 @@ fuzz_target!(|_data: &[u8]| {
let rust_result = generate_and_run_uumain(&args, uumain, Some(&input_lines)); let rust_result = generate_and_run_uumain(&args, uumain, Some(&input_lines));
// TODO remove once uutils sort supports localization // TODO remove once uutils sort supports localization
env::set_var("LC_ALL", "C"); unsafe {
env::set_var("LC_ALL", "C");
}
let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, Some(&input_lines)) { let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, Some(&input_lines)) {
Ok(result) => result, Ok(result) => result,
Err(error_result) => { Err(error_result) => {

View file

@ -294,8 +294,8 @@ mod tests {
#[test] #[test]
fn test_default_block_size() { fn test_default_block_size() {
assert_eq!(BlockSize::Bytes(1024), BlockSize::default()); assert_eq!(BlockSize::Bytes(1024), BlockSize::default());
env::set_var("POSIXLY_CORRECT", "1"); unsafe { env::set_var("POSIXLY_CORRECT", "1") };
assert_eq!(BlockSize::Bytes(512), BlockSize::default()); assert_eq!(BlockSize::Bytes(512), BlockSize::default());
env::remove_var("POSIXLY_CORRECT"); unsafe { env::remove_var("POSIXLY_CORRECT") };
} }
} }

View file

@ -743,7 +743,7 @@ mod tests {
#[test] #[test]
fn test_split_string_environment_vars_test() { fn test_split_string_environment_vars_test() {
std::env::set_var("FOO", "BAR"); unsafe { std::env::set_var("FOO", "BAR") };
assert_eq!( assert_eq!(
NCvt::convert(vec!["FOO=bar", "sh", "-c", "echo xBARx =$FOO="]), NCvt::convert(vec!["FOO=bar", "sh", "-c", "echo xBARx =$FOO="]),
parse_args_from_str(&NCvt::convert(r#"FOO=bar sh -c "echo x${FOO}x =\$FOO=""#)) parse_args_from_str(&NCvt::convert(r#"FOO=bar sh -c "echo x${FOO}x =\$FOO=""#))

View file

@ -660,7 +660,7 @@ mod audit {
} }
pub type c_auditinfo_addr_t = c_auditinfo_addr; pub type c_auditinfo_addr_t = c_auditinfo_addr;
extern "C" { unsafe extern "C" {
pub fn getaudit(auditinfo_addr: *mut c_auditinfo_addr_t) -> c_int; pub fn getaudit(auditinfo_addr: *mut c_auditinfo_addr_t) -> c_int;
} }
} }

View file

@ -177,7 +177,7 @@ fn find_stdout() -> UResult<File> {
} }
#[cfg(target_vendor = "apple")] #[cfg(target_vendor = "apple")]
extern "C" { unsafe extern "C" {
fn _vprocmgr_detach_from_console(flags: u32) -> *const libc::c_int; fn _vprocmgr_detach_from_console(flags: u32) -> *const libc::c_int;
} }

View file

@ -67,12 +67,12 @@ fn set_buffer(stream: *mut FILE, value: &str) {
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
pub unsafe extern "C" fn __stdbuf() { pub unsafe extern "C" fn __stdbuf() {
if let Ok(val) = env::var("_STDBUF_E") { if let Ok(val) = env::var("_STDBUF_E") {
set_buffer(__stdbuf_get_stderr(), &val); set_buffer(unsafe { __stdbuf_get_stderr() }, &val);
} }
if let Ok(val) = env::var("_STDBUF_I") { if let Ok(val) = env::var("_STDBUF_I") {
set_buffer(__stdbuf_get_stdin(), &val); set_buffer(unsafe { __stdbuf_get_stdin() }, &val);
} }
if let Ok(val) = env::var("_STDBUF_O") { if let Ok(val) = env::var("_STDBUF_O") {
set_buffer(__stdbuf_get_stdout(), &val); set_buffer(unsafe { __stdbuf_get_stdout() }, &val);
} }
} }

View file

@ -43,8 +43,10 @@ mod platform {
// see https://github.com/rust-lang/libc/pull/2161 // see https://github.com/rust-lang/libc/pull/2161
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
libc::syscall(libc::SYS_sync); libc::syscall(libc::SYS_sync);
#[cfg(not(target_os = "android"))] unsafe {
libc::sync(); #[cfg(not(target_os = "android"))]
libc::sync()
};
Ok(()) Ok(())
} }
@ -55,7 +57,7 @@ mod platform {
for path in files { for path in files {
let f = File::open(path).unwrap(); let f = File::open(path).unwrap();
let fd = f.as_raw_fd(); let fd = f.as_raw_fd();
libc::syscall(libc::SYS_syncfs, fd); unsafe { libc::syscall(libc::SYS_syncfs, fd) };
} }
Ok(()) Ok(())
} }
@ -67,7 +69,7 @@ mod platform {
for path in files { for path in files {
let f = File::open(path).unwrap(); let f = File::open(path).unwrap();
let fd = f.as_raw_fd(); let fd = f.as_raw_fd();
libc::syscall(libc::SYS_fdatasync, fd); unsafe { libc::syscall(libc::SYS_fdatasync, fd) };
} }
Ok(()) Ok(())
} }
@ -92,13 +94,13 @@ mod platform {
/// This function is unsafe because it calls an unsafe function. /// This function is unsafe because it calls an unsafe function.
unsafe fn flush_volume(name: &str) -> UResult<()> { unsafe fn flush_volume(name: &str) -> UResult<()> {
let name_wide = name.to_wide_null(); let name_wide = name.to_wide_null();
if GetDriveTypeW(name_wide.as_ptr()) == DRIVE_FIXED { if unsafe { GetDriveTypeW(name_wide.as_ptr()) } == DRIVE_FIXED {
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
match OpenOptions::new().write(true).open(sliced_name) { match OpenOptions::new().write(true).open(sliced_name) {
Ok(file) => { Ok(file) => {
if FlushFileBuffers(file.as_raw_handle() as HANDLE) == 0 { if unsafe { FlushFileBuffers(file.as_raw_handle() as HANDLE) } == 0 {
Err(USimpleError::new( Err(USimpleError::new(
GetLastError() as i32, unsafe { GetLastError() } as i32,
"failed to flush file buffer", "failed to flush file buffer",
)) ))
} else { } else {
@ -119,10 +121,10 @@ mod platform {
/// This function is unsafe because it calls an unsafe function. /// This function is unsafe because it calls an unsafe function.
unsafe fn find_first_volume() -> UResult<(String, HANDLE)> { unsafe fn find_first_volume() -> UResult<(String, HANDLE)> {
let mut name: [u16; MAX_PATH as usize] = [0; MAX_PATH as usize]; let mut name: [u16; MAX_PATH as usize] = [0; MAX_PATH as usize];
let handle = FindFirstVolumeW(name.as_mut_ptr(), name.len() as u32); let handle = unsafe { FindFirstVolumeW(name.as_mut_ptr(), name.len() as u32) };
if handle == INVALID_HANDLE_VALUE { if handle == INVALID_HANDLE_VALUE {
return Err(USimpleError::new( return Err(USimpleError::new(
GetLastError() as i32, unsafe { GetLastError() } as i32,
"failed to find first volume", "failed to find first volume",
)); ));
} }
@ -132,14 +134,16 @@ mod platform {
/// # Safety /// # Safety
/// This function is unsafe because it calls an unsafe function. /// This function is unsafe because it calls an unsafe function.
unsafe fn find_all_volumes() -> UResult<Vec<String>> { unsafe fn find_all_volumes() -> UResult<Vec<String>> {
let (first_volume, next_volume_handle) = find_first_volume()?; let (first_volume, next_volume_handle) = unsafe { find_first_volume()? };
let mut volumes = vec![first_volume]; let mut volumes = vec![first_volume];
loop { loop {
let mut name: [u16; MAX_PATH as usize] = [0; MAX_PATH as usize]; let mut name: [u16; MAX_PATH as usize] = [0; MAX_PATH as usize];
if FindNextVolumeW(next_volume_handle, name.as_mut_ptr(), name.len() as u32) == 0 { if unsafe { FindNextVolumeW(next_volume_handle, name.as_mut_ptr(), name.len() as u32) }
return match GetLastError() { == 0
{
return match unsafe { GetLastError() } {
ERROR_NO_MORE_FILES => { ERROR_NO_MORE_FILES => {
FindVolumeClose(next_volume_handle); unsafe { FindVolumeClose(next_volume_handle) };
Ok(volumes) Ok(volumes)
} }
err => Err(USimpleError::new(err as i32, "failed to find next volume")), err => Err(USimpleError::new(err as i32, "failed to find next volume")),
@ -153,9 +157,9 @@ mod platform {
/// # Safety /// # Safety
/// This function is unsafe because it calls `find_all_volumes` which is unsafe. /// This function is unsafe because it calls `find_all_volumes` which is unsafe.
pub unsafe fn do_sync() -> UResult<()> { pub unsafe fn do_sync() -> UResult<()> {
let volumes = find_all_volumes()?; let volumes = unsafe { find_all_volumes()? };
for vol in &volumes { for vol in &volumes {
flush_volume(vol)?; unsafe { flush_volume(vol)? };
} }
Ok(()) Ok(())
} }
@ -164,15 +168,17 @@ mod platform {
/// This function is unsafe because it calls `find_all_volumes` which is unsafe. /// This function is unsafe because it calls `find_all_volumes` which is unsafe.
pub unsafe fn do_syncfs(files: Vec<String>) -> UResult<()> { pub unsafe fn do_syncfs(files: Vec<String>) -> UResult<()> {
for path in files { for path in files {
flush_volume( unsafe {
Path::new(&path) flush_volume(
.components() Path::new(&path)
.next() .components()
.unwrap() .next()
.as_os_str() .unwrap()
.to_str() .as_os_str()
.unwrap(), .to_str()
)?; .unwrap(),
)?
};
} }
Ok(()) Ok(())
} }

View file

@ -593,33 +593,33 @@ mod tests {
#[test] #[test]
fn test_backup_mode_short_does_not_ignore_env() { fn test_backup_mode_short_does_not_ignore_env() {
let _dummy = TEST_MUTEX.lock().unwrap(); let _dummy = TEST_MUTEX.lock().unwrap();
env::set_var(ENV_VERSION_CONTROL, "numbered"); unsafe { env::set_var(ENV_VERSION_CONTROL, "numbered") };
let matches = make_app().get_matches_from(vec!["command", "-b"]); let matches = make_app().get_matches_from(vec!["command", "-b"]);
let result = determine_backup_mode(&matches).unwrap(); let result = determine_backup_mode(&matches).unwrap();
assert_eq!(result, BackupMode::NumberedBackup); assert_eq!(result, BackupMode::NumberedBackup);
env::remove_var(ENV_VERSION_CONTROL); unsafe { env::remove_var(ENV_VERSION_CONTROL) };
} }
// --backup can be passed without an argument, but reads env var if existent // --backup can be passed without an argument, but reads env var if existent
#[test] #[test]
fn test_backup_mode_long_without_args_with_env() { fn test_backup_mode_long_without_args_with_env() {
let _dummy = TEST_MUTEX.lock().unwrap(); let _dummy = TEST_MUTEX.lock().unwrap();
env::set_var(ENV_VERSION_CONTROL, "none"); unsafe { env::set_var(ENV_VERSION_CONTROL, "none") };
let matches = make_app().get_matches_from(vec!["command", "--backup"]); let matches = make_app().get_matches_from(vec!["command", "--backup"]);
let result = determine_backup_mode(&matches).unwrap(); let result = determine_backup_mode(&matches).unwrap();
assert_eq!(result, BackupMode::NoBackup); assert_eq!(result, BackupMode::NoBackup);
env::remove_var(ENV_VERSION_CONTROL); unsafe { env::remove_var(ENV_VERSION_CONTROL) };
} }
// --backup errors on invalid VERSION_CONTROL env var // --backup errors on invalid VERSION_CONTROL env var
#[test] #[test]
fn test_backup_mode_long_with_env_var_invalid() { fn test_backup_mode_long_with_env_var_invalid() {
let _dummy = TEST_MUTEX.lock().unwrap(); let _dummy = TEST_MUTEX.lock().unwrap();
env::set_var(ENV_VERSION_CONTROL, "foobar"); unsafe { env::set_var(ENV_VERSION_CONTROL, "foobar") };
let matches = make_app().get_matches_from(vec!["command", "--backup"]); let matches = make_app().get_matches_from(vec!["command", "--backup"]);
let result = determine_backup_mode(&matches); let result = determine_backup_mode(&matches);
@ -627,14 +627,14 @@ mod tests {
assert!(result.is_err()); assert!(result.is_err());
let text = format!("{}", result.unwrap_err()); let text = format!("{}", result.unwrap_err());
assert!(text.contains("invalid argument 'foobar' for '$VERSION_CONTROL'")); assert!(text.contains("invalid argument 'foobar' for '$VERSION_CONTROL'"));
env::remove_var(ENV_VERSION_CONTROL); unsafe { env::remove_var(ENV_VERSION_CONTROL) };
} }
// --backup errors on ambiguous VERSION_CONTROL env var // --backup errors on ambiguous VERSION_CONTROL env var
#[test] #[test]
fn test_backup_mode_long_with_env_var_ambiguous() { fn test_backup_mode_long_with_env_var_ambiguous() {
let _dummy = TEST_MUTEX.lock().unwrap(); let _dummy = TEST_MUTEX.lock().unwrap();
env::set_var(ENV_VERSION_CONTROL, "n"); unsafe { env::set_var(ENV_VERSION_CONTROL, "n") };
let matches = make_app().get_matches_from(vec!["command", "--backup"]); let matches = make_app().get_matches_from(vec!["command", "--backup"]);
let result = determine_backup_mode(&matches); let result = determine_backup_mode(&matches);
@ -642,20 +642,20 @@ mod tests {
assert!(result.is_err()); assert!(result.is_err());
let text = format!("{}", result.unwrap_err()); let text = format!("{}", result.unwrap_err());
assert!(text.contains("ambiguous argument 'n' for '$VERSION_CONTROL'")); assert!(text.contains("ambiguous argument 'n' for '$VERSION_CONTROL'"));
env::remove_var(ENV_VERSION_CONTROL); unsafe { env::remove_var(ENV_VERSION_CONTROL) };
} }
// --backup accepts shortened env vars (si for simple) // --backup accepts shortened env vars (si for simple)
#[test] #[test]
fn test_backup_mode_long_with_env_var_shortened() { fn test_backup_mode_long_with_env_var_shortened() {
let _dummy = TEST_MUTEX.lock().unwrap(); let _dummy = TEST_MUTEX.lock().unwrap();
env::set_var(ENV_VERSION_CONTROL, "si"); unsafe { env::set_var(ENV_VERSION_CONTROL, "si") };
let matches = make_app().get_matches_from(vec!["command", "--backup"]); let matches = make_app().get_matches_from(vec!["command", "--backup"]);
let result = determine_backup_mode(&matches).unwrap(); let result = determine_backup_mode(&matches).unwrap();
assert_eq!(result, BackupMode::SimpleBackup); assert_eq!(result, BackupMode::SimpleBackup);
env::remove_var(ENV_VERSION_CONTROL); unsafe { env::remove_var(ENV_VERSION_CONTROL) };
} }
#[test] #[test]

View file

@ -367,7 +367,7 @@ use libc::c_int;
target_os = "netbsd", target_os = "netbsd",
target_os = "openbsd" target_os = "openbsd"
))] ))]
extern "C" { unsafe extern "C" {
#[cfg(all(target_vendor = "apple", target_arch = "x86_64"))] #[cfg(all(target_vendor = "apple", target_arch = "x86_64"))]
#[link_name = "getmntinfo$INODE64"] #[link_name = "getmntinfo$INODE64"]
fn get_mount_info(mount_buffer_p: *mut *mut StatFs, flags: c_int) -> c_int; fn get_mount_info(mount_buffer_p: *mut *mut StatFs, flags: c_int) -> c_int;

View file

@ -45,11 +45,11 @@ mod tests {
// default // default
assert_eq!(posix_version(), None); assert_eq!(posix_version(), None);
// set specific version // set specific version
env::set_var("_POSIX2_VERSION", OBSOLETE.to_string()); unsafe { env::set_var("_POSIX2_VERSION", OBSOLETE.to_string()) };
assert_eq!(posix_version(), Some(OBSOLETE)); assert_eq!(posix_version(), Some(OBSOLETE));
env::set_var("_POSIX2_VERSION", TRADITIONAL.to_string()); unsafe { env::set_var("_POSIX2_VERSION", TRADITIONAL.to_string()) };
assert_eq!(posix_version(), Some(TRADITIONAL)); assert_eq!(posix_version(), Some(TRADITIONAL));
env::set_var("_POSIX2_VERSION", MODERN.to_string()); unsafe { env::set_var("_POSIX2_VERSION", MODERN.to_string()) };
assert_eq!(posix_version(), Some(MODERN)); assert_eq!(posix_version(), Some(MODERN));
} }
} }