diff --git a/nvx-rs/README.md b/nvx-rs/README.md index 085e2d630..c0404acf8 100644 --- a/nvx-rs/README.md +++ b/nvx-rs/README.md @@ -1587,6 +1587,14 @@ mount whose attachment fails and which cannot be detached keeps its mount descriptor, so rollback and teardown can retry cleanup without trusting its original path. +`Root::switch`: the switch into the root, which an init makes once for its VM: +it moves the root's mount onto `/`, then makes the root the caller's root +directory with `chroot`, and its working directory with `chdir`. Once the mount +is on `/`, the root has switched for good: a second switch and the teardown are +refused, and dropping the root unmounts nothing, while descriptors opened before +the switch, such as a `TargetRoot` and a `SourceRoot`, still map. A move that +fails leaves the root where it was. + `Root::teardown`: the shares and mappings in reverse order, a runtime mount whose attachment failed and which could not be detached, then the mounts of an aggregate, of the export, and of the runtime, the later first, the overlay, @@ -1596,9 +1604,10 @@ ext4 scratch's file system is synced before its unmount, since a mount namespace that copied the root's mounts keeps them, unsynced, after this one unmounts them, and a scratch whose sync fails stays mounted. -Each failure is a typed `Error`. The operations collect no child's status, -change neither the caller's root nor its credentials, start no async runtime, -and never power the VM off. +Each failure is a typed `Error`, or a `SwitchError` for the switch. The +operations collect no child's status, change the caller's root only by the +switch and never its credentials, start no async runtime, and never power the VM +off. ### `nvx::guest::gpt` @@ -2868,11 +2877,13 @@ NVX_BUNDLE=skip cargo test --locked --all-features --lib -- \ --ignored --exact guest::root::tests::a_thread_with_private_tables_finds_its_mount_points_and_options ``` -Ignored tests of `Root::mount_runtime` mount the runtime's file systems on a -temporary tmpfs root, in a thread's private mount namespace, and check their -options, device nodes, and time status, a call's undo, the teardown, and the -order of the runtime and the mappings beneath `/run`. They need root and Linux -6.8 or later; run them as root with: +Ignored tests of `Root::mount_runtime` and `Root::switch` mount the runtime's +file systems on a temporary tmpfs root, in a thread's private mount namespace, +and check their options, device nodes, and time status, a call's undo, the +teardown, and the order of the runtime and the mappings beneath `/run`. They +also switch into the root from a thread with root and working directories of +its own, and check the mounts that stay and a mapping through descriptors opened +before the switch. They need root and Linux 6.8 or later; run them as root with: ```bash NVX_BUNDLE=skip cargo test --locked --all-features --lib -- \ diff --git a/nvx-rs/src/guest/root.rs b/nvx-rs/src/guest/root.rs index 148a7d482..abebcdf72 100644 --- a/nvx-rs/src/guest/root.rs +++ b/nvx-rs/src/guest/root.rs @@ -27,6 +27,10 @@ //! as an init does once for its VM, before the root's first live share or mapping: it makes //! every mount of the root's tree `nosuid` and `nodev`, then mounts `/proc`, `/sys`, `/dev` with //! `/dev/pts` and `/dev/shm`, and `/run`, and binds the guest's time status at `/run/nvx/time`. +//! - `Root::switch`, which is crate-private, switches into the root, as an init does once for its +//! VM: it moves the root's mount onto `/`, then makes the root the caller's root directory and +//! working directory. The root's mounts stay from then on: its teardown refuses, and dropping it +//! unmounts nothing. //! - [`Root::teardown`] unmounts, in order, the live shares and mappings in reverse order, the //! mounts of an aggregate live share, of the host export, and of the runtime, the later first, //! the overlay, the layers from the top down, and the upper, whose file system it syncs first @@ -36,8 +40,9 @@ //! //! A failure is an [`Error`] that names what failed. The operations need the guest's root user, //! in the guest's initial mount and cgroup namespaces. They never collect a child's status, -//! change the caller's root directory or credentials, start an async runtime, or power the VM -//! off, so a caller that is not PID 1 keeps its own reaping, transport, and shutdown. +//! change the caller's credentials, start an async runtime, or power the VM off, and only +//! `Root::switch` changes the caller's root directory, so a caller that is not PID 1 keeps its own +//! reaping, transport, and shutdown. //! //! # Runtime directory //! @@ -626,6 +631,7 @@ fn assemble_with( mapper: None, mapped: Vec::new(), latched: false, + switched: false, reservation: None, }; match root.mount_layers(paths, assembly, deadline, contents) { @@ -679,8 +685,9 @@ impl Lower { /// those of its live shares, host export, and mappings, and reports what the assembly mounted. /// /// [`teardown`](Self::teardown) unmounts them and reports each failure. Dropping the root -/// unmounts them the same way, and ignores failures. Until then, the root holds the lock of its -/// runtime directory, where no other root assembles. +/// unmounts them the same way, and ignores failures, unless `Root::switch` has switched into the +/// root: it then unmounts nothing. Until then, the root holds the lock of its runtime directory, +/// where no other root assembles. pub struct Root { /// The kernel that mounts and unmounts. kernel: Box, @@ -716,13 +723,17 @@ pub struct Root { /// Whether a share, the export, or a mapping failed, after which the root refuses every later /// one. latched: bool, + /// Whether the root's mount has moved onto `/`, after which the root refuses another switch + /// and its teardown, and unmounts nothing. + switched: bool, /// The exclusive lock of the runtime directory, from the start of the assembly; dropping the /// root releases it after the unmounts. reservation: Option, } impl Root { - /// Returns the root: the overlay's mount point, `rootfs` in the runtime directory. + /// Returns the root's original overlay mount point, `rootfs` in the runtime directory. + /// This path is unchanged by `Root::switch`; paths then resolve inside the switched root. pub fn path(&self) -> &Path { &self.path } @@ -781,6 +792,9 @@ impl Root { /// goes, which may be after the VM powers off. So a teardown that succeeds leaves every write /// to the root on the scratch device. A scratch whose sync fails is not unmounted, and the /// failure is reported as its own. + /// + /// Once `Root::switch` has switched into the root, the teardown refuses: it unmounts nothing, + /// and its error's `TeardownError::is_switched` is true. pub fn teardown(mut self) -> Result<(), TeardownError> { self.unmount() } @@ -938,6 +952,44 @@ impl Root { Ok(()) } + /// Switches into the root, as an init does once for its VM, after the mounts and the + /// descriptors that it needs: it moves the root's mount onto `/`, as an execution's child + /// moves its root in its own mount namespace, then makes the root the calling process's root + /// directory, with `chroot`, and its working directory, with `chdir`. The move is in the + /// caller's mount namespace, and the root and working directories are those that the caller's + /// threads share, but for a thread that unshared them. + /// + /// A root switches once, for good: a second switch is refused as [`SwitchError::Switched`]. + /// Once its mount is on `/`, the root has switched, even if entering it then fails: from then + /// on its [`teardown`](Self::teardown) refuses and dropping it unmounts nothing, so its mounts + /// stay until the VM powers off. A move that fails leaves the root where it was, unswitched. + /// + /// Paths resolve in the root from then on, but descriptors opened before the switch stay + /// usable: a [`Mapper`] still maps from a [`SourceRoot`](super::mappings::SourceRoot) beneath + /// a [`TargetRoot`] opened before it, as [`map`](Self::map) does if the root had mounted a + /// live share or a mapping before it. + #[cfg_attr(not(test), expect(dead_code, reason = "nvx-init calls it (#1115)"))] + pub(crate) fn switch(&mut self) -> Result<(), SwitchError> { + if self.switched { + return Err(SwitchError::Switched); + } + let moved = |error: Errno| SwitchError::Move { + error: error.into(), + }; + // The root is entered through its descriptor, so a move that fails changes nothing. + let directory = share::open_mount_point(&self.path).map_err(moved)?; + let root = sys::path_c_string(&self.path).map_err(moved)?; + self.kernel + .mount(Some(root.as_c_str()), c"/", None, MountFlags::MS_MOVE, None) + .map_err(moved)?; + self.switched = true; + self.kernel + .enter_root(&directory) + .map_err(|error| SwitchError::Enter { + error: error.into(), + }) + } + /// Implements [`assemble`]'s steps after the first, waiting for each device until `deadline` /// at the latest, if any, and accepting the upper's `contents`. fn mount_layers( @@ -1278,8 +1330,14 @@ impl Root { } /// Unmounts what the root has mounted, as [`teardown`](Self::teardown) describes, and - /// forgets it, failed unmounts included. + /// forgets it, failed unmounts included, unless the root has switched. fn unmount(&mut self) -> Result<(), TeardownError> { + if self.switched { + // An empty list of failures is a switched root's refusal. + return Err(TeardownError { + failures: Vec::new(), + }); + } let mut failures = Vec::new(); // The mapper's descriptor of the root keeps the overlay busy, so it goes first. if let Some(mut mapper) = self.mapper.take() { @@ -1350,7 +1408,8 @@ impl Root { } impl Drop for Root { - /// Unmounts what the root has mounted, as [`Root::teardown`] does, and ignores failures. + /// Unmounts what the root has mounted, as [`Root::teardown`] does, and ignores failures. A + /// root that has switched unmounts nothing. fn drop(&mut self) { let _ = self.unmount(); } @@ -1375,6 +1434,7 @@ impl fmt::Debug for Root { .field("runtime_stray", &self.runtime_stray) .field("mapped", &self.mapped) .field("latched", &self.latched) + .field("switched", &self.switched) .finish_non_exhaustive() } } @@ -2145,24 +2205,69 @@ impl fmt::Display for AssemblyError { impl std::error::Error for AssemblyError {} -/// The syncs and unmounts of a teardown that failed, in the order in which they were attempted. +/// Why [`Root::switch`] failed. Its text names the step that failed, and the system's error, if +/// any. +#[derive(Debug)] +pub(crate) enum SwitchError { + /// The root has switched already, and a root switches once. + Switched, + /// Opening the root or moving its mount onto `/` failed: the root stays where it was, and + /// has not switched. + Move { + /// The system's error. + error: io::Error, + }, + /// Making the root the caller's root directory and working directory failed once its mount + /// was on `/`: the root has switched. + Enter { + /// The system's error. + error: io::Error, + }, +} + +impl fmt::Display for SwitchError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Switched => formatter.write_str("the root has switched already"), + Self::Move { error } => write!(formatter, "failed to move the root onto /: {error}"), + Self::Enter { error } => write!( + formatter, + "failed to enter the root, whose mount is on / already: {error}" + ), + } + } +} + +impl std::error::Error for SwitchError {} + +/// The syncs and unmounts of a teardown that failed, in the order in which they were attempted, +/// or the refusal of a root that has switched. #[derive(Debug)] pub struct TeardownError { - /// The failures, which is never empty. + /// The failures, which is empty only for the refusal of a root that has switched. failures: Vec, } impl TeardownError { /// Returns the failures, each of a mount that stays in place, in the order in which they were - /// attempted. + /// attempted: none if the root had switched. pub fn failures(&self) -> &[Unmount] { &self.failures } + + /// Returns whether the teardown was refused because the root had + /// [switched](Root::switch), so that it unmounted nothing. + pub(crate) fn is_switched(&self) -> bool { + self.failures.is_empty() + } } impl fmt::Display for TeardownError { - /// Writes each failure, separated by `; `. + /// Writes each failure, separated by `; `, or the refusal. fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.is_switched() { + return formatter.write_str("the root has switched, so its mounts stay"); + } for (index, failure) in self.failures.iter().enumerate() { if index > 0 { formatter.write_str("; ")?; diff --git a/nvx-rs/src/guest/root/kernel.rs b/nvx-rs/src/guest/root/kernel.rs index 796eb0b46..5c58418c1 100644 --- a/nvx-rs/src/guest/root/kernel.rs +++ b/nvx-rs/src/guest/root/kernel.rs @@ -7,7 +7,8 @@ //! or a read of a GPT disk's partition table at the geometry that its block device reports, and //! the writes to the kernel's control files, the check for a mount point, and the options of a //! mount, whose effects and answers a test simulates, go through a [`Kernel`], which also performs -//! the mapper's operations for the root's live shares and mappings, and the runtime's mounts. +//! the mapper's operations for the root's live shares and mappings, the runtime's mounts, and the +//! switch into the root. use std::ffi::CStr; use std::fs::{self, File}; @@ -31,8 +32,9 @@ const MOUNT_TABLE: &str = "/proc/thread-self/mountinfo"; /// disk's partition table, writes of a control file, and the sleeps between two polls for a block /// device; the check for a mount point and the options of a mount, which depend on them; since /// only a block device reports its geometry, the read of a GPT disk's partition table; the -/// mapper's operations, through which the root mounts its live shares and mappings; and the new -/// mounts, the restriction of the root's tree, and the device nodes of the runtime's file systems. +/// mapper's operations, through which the root mounts its live shares and mappings; the new +/// mounts, the restriction of the root's tree, and the device nodes of the runtime's file systems; +/// and the change of root directory into a switched root. /// /// [`SystemKernel`] performs them. The tests' fake records the operations, simulates the effect /// of a cgroup's membership file and its own mounts, reads a GPT disk's table from a regular @@ -101,6 +103,10 @@ pub(super) trait Kernel: MappingKernel + Send + Sync { /// Creates the device nodes and the symbolic links of an execution's `/dev` in the directory /// `dev`, the nodes with mode 0666 whatever the umask. fn create_devices(&mut self, dev: &FileDescriptor) -> Result<(), Errno>; + + /// Makes the directory `root` the calling process's root directory, then its working + /// directory the new root's top: `chroot`, then `chdir`. + fn enter_root(&mut self, root: &FileDescriptor) -> Result<(), Errno>; } impl Kernel for SystemKernel { @@ -196,6 +202,11 @@ impl Kernel for SystemKernel { fn create_devices(&mut self, dev: &FileDescriptor) -> Result<(), Errno> { sys::create_devices(dev) } + + fn enter_root(&mut self, root: &FileDescriptor) -> Result<(), Errno> { + sys::enter_root(root)?; + nix::unistd::chdir(c"/") + } } /// Returns the options of the file system of the mount whose ID is `mount`, the last field of its diff --git a/nvx-rs/src/guest/root/kernel/tests.rs b/nvx-rs/src/guest/root/kernel/tests.rs index d4d626790..71e16f3d1 100644 --- a/nvx-rs/src/guest/root/kernel/tests.rs +++ b/nvx-rs/src/guest/root/kernel/tests.rs @@ -64,6 +64,9 @@ pub(crate) enum Operation { Options, /// A new mount of a file system, which its type names. NewMount, + /// An entry into a directory as the root directory and the working directory, which the + /// directory names. + EnterRoot, } /// One operation that the fake kernel recorded, with its paths and options as text. @@ -133,6 +136,9 @@ pub(crate) enum Call { RestrictTree(String), /// A creation of the device nodes and the links of a `/dev`, which its directory names. CreateDevices(String), + /// An entry into a directory as the root directory and the working directory, which the + /// directory names. + EnterRoot(String), } /// The type of the action that runs after each sleep. @@ -733,6 +739,12 @@ impl Kernel for FakeKernel { let call = Call::CreateDevices(path.display().to_string()); self.record(call, Operation::Create, &path) } + + fn enter_root(&mut self, root: &FileDescriptor) -> Result<(), Errno> { + let path = path_of(root)?; + let call = Call::EnterRoot(path.display().to_string()); + self.record(call, Operation::EnterRoot, &path) + } } impl MappingKernel for FakeKernel { diff --git a/nvx-rs/src/guest/root/tests.rs b/nvx-rs/src/guest/root/tests.rs index fbfa2c59d..8b3fdf851 100644 --- a/nvx-rs/src/guest/root/tests.rs +++ b/nvx-rs/src/guest/root/tests.rs @@ -19,6 +19,7 @@ use crate::guest::sys::MountAttributes; mod privileged; mod runtime; +mod switch; /// The base address of the distro device's MMIO window. const DISTRO: u64 = 0xd000_0000; diff --git a/nvx-rs/src/guest/root/tests/privileged.rs b/nvx-rs/src/guest/root/tests/privileged.rs index ec01ea39c..999891903 100644 --- a/nvx-rs/src/guest/root/tests/privileged.rs +++ b/nvx-rs/src/guest/root/tests/privileged.rs @@ -1,17 +1,21 @@ -//! Tests of [`Root::mount_runtime`] with the kernel itself, which need the privilege to mount and -//! Linux 6.8 or later, for the unique mount IDs. Each runs in a private mount namespace of its own -//! thread, on a tmpfs root below a temporary directory, and they are ignored unless asked for: -//! `cargo test --all-features -- --ignored guest::root::tests::privileged`, as root. +//! Tests of [`Root::mount_runtime`] and [`Root::switch`] with the kernel itself, which need the +//! privilege to mount and Linux 6.8 or later, for the unique mount IDs. Each runs in a private +//! mount namespace of its own thread, on a tmpfs root below a temporary directory, and they are +//! ignored unless asked for: `cargo test --all-features -- --ignored +//! guest::root::tests::privileged`, as root. //! //! They cover what the fake kernel cannot: the runtime's file systems and their options, the //! device nodes, with their mode whatever the umask, and the links, the time status's read-only //! bind, the undo of a call that fails part of the way, a second call's refusal, the teardown's //! unmounts, and the order of the runtime and the mappings beneath `/run`: a call after a mapping //! is refused and leaves it reachable, and a mapping after the runtime is on the `/run` tmpfs. +//! They also cover a switch into the root, in a thread with root and working directories of its +//! own, after which the root's mounts stay and descriptors opened before it still map. use std::os::unix::fs::FileTypeExt; use super::*; +use crate::guest::mappings::Reserved; /// The options of a mount that the tests check, as the kernel's mount table shows them. const CHECKED: [&str; 5] = ["ro", "rw", "nosuid", "nodev", "noexec"]; @@ -89,6 +93,7 @@ impl Scene { mapper: None, mapped: Vec::new(), latched: false, + switched: false, reservation: None, } } @@ -386,3 +391,60 @@ fn mappings_beneath_run_after_the_runtime_are_on_its_tmpfs_and_go_with_it() { ) ); } + +#[test] +#[ignore = "needs root and Linux 6.8 or later"] +fn a_switched_root_keeps_its_mounts_and_maps_through_earlier_descriptors() { + let Some(scene) = Scene::new() else { + return; + }; + let base = scene.path("root"); + fs::write(base.join("marker"), b"the root").unwrap(); + let source = scene.path("source"); + fs::create_dir(&source).unwrap(); + fs::create_dir(source.join("early")).unwrap(); + fs::write(source.join("early/data"), b"early").unwrap(); + fs::write(source.join("late"), b"late").unwrap(); + let mut root = scene.root(); + root.mount_runtime(None).unwrap(); + // The root's own mapper, a target root, and a source root are opened before the switch. + let sources = SourceRoot::open(&source).unwrap(); + let early = Mapping::new("early", "/srv/early", Access::ReadOnly).unwrap(); + root.map(&sources, &[early]).unwrap(); + let target = TargetRoot::open(&base).unwrap(); + + // The thread that switches has root and working directories of its own, so the test's + // thread still reaches the temporary directory afterwards. + std::thread::scope(|scope| { + scope.spawn(move || { + nix::sched::unshare(nix::sched::CloneFlags::CLONE_FS).unwrap(); + root.switch().unwrap(); + assert_eq!(std::env::current_dir().unwrap(), Path::new("/")); + assert_eq!(fs::read("/marker").unwrap(), b"the root"); + assert!(!source.exists()); + assert_eq!(fs::read("/srv/early/data").unwrap(), b"early"); + + // A mapper maps beneath the target root, from the source root, which no path + // reaches any more. + let mut mapper = Mapper::new(target, Reserved::container_root()); + let late = Mapping::new("late", "/srv/late", Access::ReadOnly).unwrap(); + mapper.apply(&sources, &[late]).unwrap(); + assert_eq!(fs::read("/srv/late").unwrap(), b"late"); + + // A second switch and the teardown are refused, and the drop that follows unmounts + // nothing: the runtime's mounts and the root's mapping stay. + let mounts = mounts_below(Path::new("/")); + for point in ["/proc", "/dev/pts", "/run", "/srv/early", "/srv/late"] { + assert!( + mounts.contains(&PathBuf::from(point)), + "{point}: {mounts:?}" + ); + } + let error = root.switch().unwrap_err(); + assert!(matches!(error, SwitchError::Switched), "{error:?}"); + assert!(root.teardown().unwrap_err().is_switched()); + assert_eq!(mounts_below(Path::new("/")), mounts); + assert_eq!(fs::read("/srv/early/data").unwrap(), b"early"); + }); + }); +} diff --git a/nvx-rs/src/guest/root/tests/switch.rs b/nvx-rs/src/guest/root/tests/switch.rs new file mode 100644 index 000000000..ac9b45b71 --- /dev/null +++ b/nvx-rs/src/guest/root/tests/switch.rs @@ -0,0 +1,114 @@ +//! Tests of [`Root::switch`] with the fake kernel: the move of the root's mount onto `/` before +//! the entry into the root, the refusal of a second switch, the teardown of a switched root, +//! which refuses, and its drop, neither of which unmounts anything, a move that fails, after +//! which the root has not switched, and an entry that fails, after which it has. + +use super::*; + +/// Returns the calls with which the fake kernel records the switch into `guest`'s root: the move +/// of the root's mount onto `/`, then the entry into the root. +fn switch_calls(guest: &Guest) -> [Call; 2] { + let root = guest.text("run/nvx/rootfs"); + [ + Call::Mount { + source: Some(root.clone()), + target: "/".to_owned(), + filesystem: None, + flags: MountFlags::MS_MOVE, + data: None, + }, + Call::EnterRoot(root), + ] +} + +/// Returns the mount points of the assembly's mounts, in the order of their unmounts. +fn assembly_unmounts(guest: &Guest) -> Vec { + ["rootfs", "layers/distro", "scratch"] + .iter() + .map(|mount| guest.text(&format!("run/nvx/{mount}"))) + .collect() +} + +#[test] +fn a_root_switches_once_and_its_teardown_then_unmounts_nothing() { + let guest = Guest::new(); + let mut root = guest.assemble(&guest.assembly()).unwrap(); + root.mount_runtime(None).unwrap(); + let before = guest.kernel.calls().len(); + root.switch().unwrap(); + assert_eq!(guest.kernel.calls()[before..], switch_calls(&guest)); + + // A second switch is refused before any call. + let error = root.switch().unwrap_err(); + assert!(matches!(error, SwitchError::Switched), "{error:?}"); + assert_eq!(error.to_string(), "the root has switched already"); + + // The teardown refuses, and neither it nor the drop that follows unmounts anything. + let error = root.teardown().unwrap_err(); + assert!(error.is_switched(), "{error:?}"); + assert!(error.failures().is_empty(), "{error:?}"); + assert_eq!( + error.to_string(), + "the root has switched, so its mounts stay" + ); + assert_eq!(guest.kernel.calls().len(), before + 2); + assert_eq!(guest.kernel.unmounts(), Vec::::new()); +} + +#[test] +fn a_switched_root_that_is_dropped_unmounts_nothing() { + let guest = Guest::new(); + let mut root = guest.assemble(&guest.assembly()).unwrap(); + root.switch().unwrap(); + drop(root); + assert_eq!(guest.kernel.unmounts(), Vec::::new()); +} + +#[test] +fn a_move_that_fails_leaves_the_root_unswitched() { + let guest = Guest::new(); + let mut root = guest.assemble(&guest.assembly()).unwrap(); + guest.kernel.fail(Operation::Mount, "/", Errno::EINVAL); + let before = guest.kernel.calls().len(); + let error = root.switch().unwrap_err(); + assert!( + matches!( + &error, + SwitchError::Move { error } if error.raw_os_error() == Some(Errno::EINVAL as i32) + ), + "{error:?}" + ); + assert_eq!( + error.to_string(), + "failed to move the root onto /: Invalid argument (os error 22)" + ); + // Nothing entered the root, and its teardown unmounts the assembly's mounts. + assert_eq!(guest.kernel.calls()[before..], switch_calls(&guest)[..1]); + root.teardown().unwrap(); + assert_eq!(guest.kernel.unmounts(), assembly_unmounts(&guest)); +} + +#[test] +fn a_root_whose_entry_fails_has_switched() { + let guest = Guest::new(); + let mut root = guest.assemble(&guest.assembly()).unwrap(); + let path = guest.path("run/nvx/rootfs"); + guest.kernel.fail(Operation::EnterRoot, path, Errno::EACCES); + let error = root.switch().unwrap_err(); + assert!( + matches!( + &error, + SwitchError::Enter { error } if error.raw_os_error() == Some(Errno::EACCES as i32) + ), + "{error:?}" + ); + assert_eq!( + error.to_string(), + "failed to enter the root, whose mount is on / already: Permission denied (os error 13)" + ); + // The root's mount is on `/`, so the root refuses another switch and its teardown. + let error = root.switch().unwrap_err(); + assert!(matches!(error, SwitchError::Switched), "{error:?}"); + assert!(root.teardown().unwrap_err().is_switched()); + assert_eq!(guest.kernel.unmounts(), Vec::::new()); +} diff --git a/nvx-rs/src/guest/sys/mod.rs b/nvx-rs/src/guest/sys/mod.rs index 439cab0c3..3a1a640c3 100644 --- a/nvx-rs/src/guest/sys/mod.rs +++ b/nvx-rs/src/guest/sys/mod.rs @@ -148,7 +148,7 @@ pub(crate) use sock_diag::{ INET_DIAG_BUFFER_LENGTH, InetDiagMessage, decode_inet_diag_dump, dump_ipv6_tcp_sockets, }; pub(crate) use socket::{UdpSocket, connect_datagram}; -pub(crate) use spawn::{ChildSpec, PreparedChild, REPORT_LENGTH}; +pub(crate) use spawn::{ChildSpec, PreparedChild, REPORT_LENGTH, enter_root}; pub(crate) use terminal::{configure_raw, drain}; pub(crate) use timer::Timer; diff --git a/nvx-rs/src/guest/sys/spawn.rs b/nvx-rs/src/guest/sys/spawn.rs index 1f76e05a1..c94aed313 100644 --- a/nvx-rs/src/guest/sys/spawn.rs +++ b/nvx-rs/src/guest/sys/spawn.rs @@ -793,7 +793,7 @@ fn close_range(first: c_uint, last: c_uint) -> Result<(), Errno> { } /// Makes `root` the calling process's root directory and working directory. -fn enter_root(root: &FileDescriptor) -> Result<(), Errno> { +pub(crate) fn enter_root(root: &FileDescriptor) -> Result<(), Errno> { nix::unistd::fchdir(root.borrowed())?; nix::unistd::chroot(c".") } diff --git a/scripts/test-layout-allowlist.json b/scripts/test-layout-allowlist.json index 0ad55db1e..b87859ae0 100644 --- a/scripts/test-layout-allowlist.json +++ b/scripts/test-layout-allowlist.json @@ -7,7 +7,7 @@ "nvx-rs/src/guest/entry.rs": 1, "nvx-rs/src/guest/exec.rs": 4, "nvx-rs/src/guest/reseed.rs": 1, - "nvx-rs/src/guest/root.rs": 1, + "nvx-rs/src/guest/root.rs": 2, "nvx-rs/src/guest/sys/entry.rs": 3, "nvx-rs/src/guest/sys/spawn.rs": 6, "nvx-rs/src/guest/time/system.rs": 3,