From 90af16891f48a7c13a9403dd7b86cc54dd07a326 Mon Sep 17 00:00:00 2001 From: oech3 <79379754+oech3@users.noreply.github.com> Date: Tue, 28 Apr 2026 19:51:22 +0900 Subject: [PATCH] chroot: start removing unsafe (#12053) --- Cargo.lock | 1 + src/uu/chroot/Cargo.toml | 1 + src/uu/chroot/src/chroot.rs | 26 ++++++-------------------- 3 files changed, 8 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cc90422b4..ef225867b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3370,6 +3370,7 @@ version = "0.8.0" dependencies = [ "clap", "fluent", + "rustix", "thiserror 2.0.18", "uucore", ] diff --git a/src/uu/chroot/Cargo.toml b/src/uu/chroot/Cargo.toml index 7cb7528bd..d4f707d3d 100644 --- a/src/uu/chroot/Cargo.toml +++ b/src/uu/chroot/Cargo.toml @@ -21,6 +21,7 @@ doctest = false [dependencies] clap = { workspace = true } +rustix = { workspace = true } thiserror = { workspace = true } uucore = { workspace = true, features = ["entries", "fs"] } fluent = { workspace = true } diff --git a/src/uu/chroot/src/chroot.rs b/src/uu/chroot/src/chroot.rs index 68e8fe2ed..bed981b38 100644 --- a/src/uu/chroot/src/chroot.rs +++ b/src/uu/chroot/src/chroot.rs @@ -8,16 +8,15 @@ mod error; use crate::error::ChrootError; use clap::{Arg, ArgAction, Command}; -use std::ffi::{CString, OsStr}; +use std::ffi::OsStr; use std::io::{Error, ErrorKind}; -use std::os::unix::prelude::OsStrExt; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process; use uucore::entries::{Locate, Passwd, grp2gid, usr2gid, usr2uid}; use uucore::error::{UResult, UUsageError}; use uucore::fs::{MissingHandling, ResolveMode, canonicalize}; -use uucore::libc::{self, chroot, setgid, setgroups, setuid}; +use uucore::libc::{self, setgid, setgroups, setuid}; use uucore::{format_usage, show}; use uucore::translate; @@ -424,22 +423,9 @@ fn set_context(options: &Options) -> UResult<()> { } fn enter_chroot(root: &Path, skip_chdir: bool) -> UResult<()> { - let err = unsafe { - chroot( - CString::new(root.as_os_str().as_bytes().to_vec()) - .map_err(|e| ChrootError::CannotEnter("root".into(), e.into()))? - .as_bytes_with_nul() - .as_ptr() - .cast(), - ) - }; - - if err == 0 { - if !skip_chdir { - std::env::set_current_dir("/")?; - } - Ok(()) - } else { - Err(ChrootError::CannotEnter(root.into(), Error::last_os_error()).into()) + rustix::process::chroot(root).map_err(|e| ChrootError::CannotEnter(root.into(), e.into()))?; + if !skip_chdir { + std::env::set_current_dir("/")?; } + Ok(()) }