diff --git a/library/std/src/sys/unix/ext/fs.rs b/library/std/src/sys/unix/ext/fs.rs index 9a982a4acd9e2..9cf51be2836fb 100644 --- a/library/std/src/sys/unix/ext/fs.rs +++ b/library/std/src/sys/unix/ext/fs.rs @@ -884,3 +884,29 @@ impl DirBuilderExt for fs::DirBuilder { self } } + +/// Change the root directory of the current process to the specified path. +/// +/// This typically requires privileges, such as root or a specific capability. +/// +/// This does not change the current working directory; you should call +/// [`std::env::set_current_dir`][`crate::env::set_current_dir`] afterwards. +/// +/// # Examples +/// +/// ```no_run +/// #![feature(unix_chroot)] +/// use std::os::unix::fs; +/// +/// fn main() -> std::io::Result<()> { +/// fs::chroot("/sandbox")?; +/// std::env::set_current_dir("/")?; +/// // continue working in sandbox +/// Ok(()) +/// } +/// ``` +#[unstable(feature = "unix_chroot", issue = "84715")] +#[cfg(not(target_os = "fuchsia"))] +pub fn chroot>(dir: P) -> io::Result<()> { + sys::fs::chroot(dir.as_ref()) +} diff --git a/library/std/src/sys/unix/fs.rs b/library/std/src/sys/unix/fs.rs index 16a7f727696ec..45bae25a0c382 100644 --- a/library/std/src/sys/unix/fs.rs +++ b/library/std/src/sys/unix/fs.rs @@ -1328,3 +1328,10 @@ pub fn copy(from: &Path, to: &Path) -> io::Result { })?; Ok(bytes_copied as u64) } + +#[cfg(not(target_os = "fuchsia"))] +pub fn chroot(dir: &Path) -> io::Result<()> { + let dir = cstr(dir)?; + cvt(unsafe { libc::chroot(dir.as_ptr()) })?; + Ok(()) +}