From 39f5de8a4891e7c8e4859776f7ee65316a53687e Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Tue, 24 Nov 2026 01:53:16 -0800 Subject: [PATCH 1/3] nvx: end a one-shot run's OpenVMM with the run on Windows On Windows, terminating `nvx.exe` during `nvx sandbox run` left its `openvmm.exe` running without a parent, as when a supervisor ends a run (microsoft/nvx#1910, case 1). The one-shot runs, `nvx run` and `nvx sandbox run`, start OpenVMM in the foreground: in the caller's console and jobs, and in the job named after its log. Nothing ended it once `nvx` was gone, since the log's job does not kill its processes when it closes, and the spawn closes its handle at once. A foreground spawn now also starts OpenVMM in an owning job: an unnamed job object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, whose only handle, which is never inheritable, the returned launch holds. The job list names it after the log's job, in which it nests, and both nest in the jobs of `nvx` that keep their processes' children. Windows closes the handle when `nvx` ends, however it ends, which ends OpenVMM; releasing the launch does too. Detached spawns, those of managed sandboxes and of the library, are unchanged. This is the second option of microsoft/nvx#780. Evidence on Windows 11 with WHP and the v0.1.0-dev.efe086d96205 artifacts: killing `nvx.exe` 10 s into `sandbox run --hypervisor whp --upper ram --entrypoint /bin/sleep --arg 300` left OpenVMM running 10 s later at 6681c2e1217; with this change OpenVMM is gone. Tests: a foreground child ends once its spawn is dropped, while a detached one keeps running, and a `sandbox run` whose CLI is killed ends its fake OpenVMM. Both fail at the base revision. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/run.md | 6 +- doc/usage.md | 13 ++- nvx/README.md | 9 +- nvx/src/host/platform/windows/spawn.rs | 127 +++++++++++++++++++------ nvx/src/host/platform/windows/tests.rs | 75 +++++++++++++++ nvx/src/host/spawn.rs | 17 ++-- nvx/src/host/vm.rs | 7 +- nvx/tests/cli.rs | 96 +++++++++++++++++++ 8 files changed, 304 insertions(+), 46 deletions(-) diff --git a/doc/run.md b/doc/run.md index 442a8e261..7d8b1eb15 100644 --- a/doc/run.md +++ b/doc/run.md @@ -1028,7 +1028,11 @@ category and status of the outcome report that OpenVMM published, such as `guest-exit status 125`. `--outcome-report` forwards that report, of the VM's stop, with the permissions that OpenVMM gave it. Ctrl-C ends the VM, and the run then exits with status 130. `--dry-run` prints the command and launches -nothing. +nothing. On Windows, OpenVMM runs in a job object that only the run holds and +that ends OpenVMM once it closes, so the VM ends with the run, whatever ends +the run, as when a supervisor terminates `nvx.exe`. OpenVMM also stays in the +jobs of `nvx.exe`, as its other child processes do, unless a job lets them +leave it silently, so that such a job can end it too. CI runs `/sbin/nvx-sandbox-smoke`, with `--arg init`, as below, as the workload of `sandbox run` and `sandbox exec`, to verify the security profile of the diff --git a/doc/usage.md b/doc/usage.md index ff440b08c..b76ec9b70 100644 --- a/doc/usage.md +++ b/doc/usage.md @@ -208,10 +208,13 @@ combined with `--network-egress-allow` rules for direct connections. `nvx run` checks its options, prints the OpenVMM command of a cold boot after `>> `, and unless `--dry-run` is given, runs OpenVMM in a private temporary VM directory, which it removes once OpenVMM has exited, on the -terminal. A cold boot attaches the guest's console, the boot console `hvc1`, -to the standard streams, so that the terminal's input reaches the guest through -it rather than through the byte channel, `hvc0`, whose output, such as the -kernel's early messages, goes to standard error with OpenVMM's log. It exits +terminal. On Windows, a cold boot's OpenVMM ends with `nvx run`, whatever ends +it, in a job object that only the run holds, as the OpenVMM of a +[`sandbox run`](#sandbox) does. A cold boot attaches the guest's console, the +boot console `hvc1`, to the standard streams, so that the terminal's input +reaches the guest through it rather than through the byte channel, `hvc0`, +whose output, such as the kernel's early messages, goes to standard error with +OpenVMM's log. It exits with status 1 for an error, 2 for a usage error, and 130 after Ctrl-C, and otherwise with the status that OpenVMM returns. Its errors and usage errors carry their [error codes](#error-codes), as `error[CODE]: MESSAGE` and @@ -394,7 +397,7 @@ it launches the VM that a `provision` and a `start` of its options would launch, in a temporary VM directory that it removes, executes its workload once, as `exec` does, with its streams, has the guest shut the VM down, which it terminates if it does not exit within `--timeout` seconds, and exits with -the workload's status; see +the workload's status. On Windows, its VM ends with it, whatever ends it; see [Experimental single-workload sandbox](run.md#experimental-single-workload-sandbox). See [Run](run.md) for artifact preparation, the security boundary, the diff --git a/nvx/README.md b/nvx/README.md index b0eaf1c32..017755d7d 100644 --- a/nvx/README.md +++ b/nvx/README.md @@ -1523,7 +1523,9 @@ boot prints `>> COMMAND`, OpenVMM's command line, quoted as `sandbox run` quotes it, and unless `--dry-run` is given, it runs OpenVMM with the standard streams, so that the guest's console and the terminal settings that OpenVMM restores behave as they do for OpenVMM itself, and exits with OpenVMM's -status; a restore does none of these, as the second item says. +status; a restore does none of these, as the second item says. On Windows, a +cold boot's OpenVMM runs in a job object that only `nvx` holds, as that of a +`sandbox run` does, which ends OpenVMM with `nvx`, whatever ends it. - A cold boot runs the kernel and the initramfs of `--guest`, `alpine` by default, with `--memory-mib` or else the guest's default, 128 MiB for Alpine @@ -1604,7 +1606,10 @@ before them. shut the VM down, waits up to `--timeout` seconds for OpenVMM to exit before it terminates it, removes the VM directory, and exits with the workload's status. `--outcome-report` forwards OpenVMM's outcome report of the VM's - stop. + stop. On Windows, OpenVMM runs in a job object that only the run holds, + which ends OpenVMM once it closes, so that the VM never outlives the run, + whatever ends the run, and in the jobs of `nvx` that keep their processes' + children. - `provision` records the sandbox in its state directory. `start` launches OpenVMM detached with the managed lifecycle, passes it a fresh capability through its standard input, and waits until the guest answers. `exec` runs a diff --git a/nvx/src/host/platform/windows/spawn.rs b/nvx/src/host/platform/windows/spawn.rs index b181fdd4a..9467a6601 100644 --- a/nvx/src/host/platform/windows/spawn.rs +++ b/nvx/src/host/platform/windows/spawn.rs @@ -13,6 +13,10 @@ use windows_sys::Win32::Foundation::{ GetHandleInformation, HANDLE, HANDLE_FLAG_INHERIT, SetHandleInformation, WAIT_OBJECT_0, WAIT_TIMEOUT, }; +use windows_sys::Win32::System::JobObjects::{ + CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JobObjectExtendedLimitInformation, SetInformationJobObject, +}; use windows_sys::Win32::System::Threading::{ CREATE_BREAKAWAY_FROM_JOB, CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW, CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DeleteProcThreadAttributeList, @@ -29,12 +33,17 @@ use crate::host::platform::check_working_dir; use crate::host::platform::inherit::{Inherited, lock_spawns}; use crate::host::platform::unconfirmed_exit; -/// An OpenVMM process launched by this caller, held through its process handle. +/// An OpenVMM process launched by this caller, held through its process handle, and, for a +/// foreground spawn, through the job that ends it once this is dropped, as [`owning_job`] +/// describes. pub(crate) struct LaunchedProcess { /// Process handle retained for termination and waiting. pub(super) process: OwnedHandle, /// Numeric process identifier reported to instance state. pid: u32, + /// The only handle of the job that ends the process once it closes, which a foreground spawn + /// creates; `None` for a detached one. + _owner: Option, } impl LaunchedProcess { @@ -185,8 +194,10 @@ impl Drop for InheritableForSpawn { } } -/// Starts OpenVMM without the caller's console so it outlives the caller, in the job object -/// `job`, if any, which [`create_log_job`] creates for the log of its standard output. +/// Starts OpenVMM, in the job object `job`, if any, which [`create_log_job`] creates for the log +/// of its standard output: as `mode` says, without the caller's console, so that it outlives the +/// caller, or in the foreground, in the caller's console and in a job of its own that ends it with +/// the caller, as [`owning_job`] describes. /// /// `std::process::Command` lets the child inherit every inheritable handle of the caller. A /// caller whose own standard output is a pipe, such as a phase process whose parent collects @@ -210,7 +221,9 @@ impl Drop for InheritableForSpawn { /// `stdio` handles until after the spawn closes them, so that a process that inherits the log in /// the window inherits the job too, and keeps it open while it holds the log: [`log_claim_held`] /// then decides the log's claim by the processes of the job, of which that process is none. The -/// spawn closes its own handle of `job` before it returns. +/// spawn closes its own handle of `job` before it returns. A foreground OpenVMM also joins its +/// owning job, which nests in `job`, as jobs nest in the jobs of the processes in them, and whose +/// handle, which is never inheritable, the returned [`LaunchedProcess`] holds. /// /// Fails with [`io::ErrorKind::InvalidInput`] for a working directory beyond Windows' limit or /// for a batch file, as [`refuse_batch_file`] says. @@ -227,32 +240,22 @@ pub(crate) fn spawn_with_stdio( mode: SpawnMode, job: Option, ) -> io::Result { - let flags = match mode { - SpawnMode::Foreground => 0, - SpawnMode::Detached { breakaway_from_job } => { - CREATE_NEW_PROCESS_GROUP - | CREATE_NO_WINDOW - | if breakaway_from_job { - CREATE_BREAKAWAY_FROM_JOB - } else { - 0 - } - } - }; spawn_listed( program, arguments, Some(working_dir), stdio.map(Some), inherit, + mode, job, - flags, ) } /// Whether the child stays in the caller's console and job. pub(crate) enum SpawnMode { - /// Keeps the caller's console, process group, and job membership. + /// Keeps the caller's console, process group, and job membership, and starts in an + /// [`owning_job`] too, which ends the child once the [`LaunchedProcess`] that the spawn returns + /// is dropped, or the caller ends. Foreground, /// Starts without a console, in a new process group. Detached { @@ -261,19 +264,72 @@ pub(crate) enum SpawnMode { }, } -/// Starts `program` with `arguments` in `working_dir`, or in the caller's working directory, with -/// the creation flags `flags`, the handles `stdio` as its standard handles, a missing one null, -/// and the caller's handles `inherit`, and no other handle of the caller, in the job object -/// `job`, if any, as [`spawn_with_stdio`] describes. Fails with [`io::ErrorKind::InvalidInput`] for -/// a working directory beyond Windows' limit or for a batch file, as [`refuse_batch_file`] says. +impl SpawnMode { + /// Returns the creation flags of a child that starts as the mode says. + fn flags(&self) -> PROCESS_CREATION_FLAGS { + match self { + Self::Foreground => 0, + Self::Detached { breakaway_from_job } => { + CREATE_NEW_PROCESS_GROUP + | CREATE_NO_WINDOW + | if *breakaway_from_job { + CREATE_BREAKAWAY_FROM_JOB + } else { + 0 + } + } + } + } +} + +/// Creates the job that owns a foreground child: it limits no resource, but ends every process +/// in it, the child and any process that the child starts, which cannot break away from it, once +/// its last handle closes. That handle is the caller's alone: no name leads to the job, and its +/// handle is not inheritable, so no process inherits it, even in the window of another spawn. +/// Windows closes it when the caller ends, whatever ends the caller, such as a +/// `TerminateProcess` that gives it no chance to stop the child, so that the child never outlives +/// the caller. +/// +/// A child of a caller in a job of its own starts in that job too, unless the job lets it break +/// away, and its owning job then nests in the caller's, as Windows nests jobs since Windows 8, +/// when neither sets limits on the user interface. The caller's job, too, can end the child. +fn owning_job() -> io::Result { + // SAFETY: null attributes give the job the default security and a handle that is not + // inheritable, and a null name leaves it unnamed. + let job = owned(unsafe { CreateJobObjectW(ptr::null(), ptr::null()) }) + .ok_or_else(io::Error::last_os_error)?; + let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + // SAFETY: the handle is a new job object with every access, and the information has the size + // given. + if unsafe { + SetInformationJobObject( + raw(&job), + JobObjectExtendedLimitInformation, + (&raw const limits).cast(), + mem::size_of_val(&limits) as u32, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + Ok(job) +} + +/// Starts `program` with `arguments` in `working_dir`, or in the caller's working directory, as +/// `mode` says, with the handles `stdio` as its standard handles, a missing one null, and the +/// caller's handles `inherit`, and no other handle of the caller, in the job object `job`, if +/// any, and, in the foreground, in its [`owning_job`] too, as [`spawn_with_stdio`] describes. +/// Fails with [`io::ErrorKind::InvalidInput`] for a working directory beyond Windows' limit or +/// for a batch file, as [`refuse_batch_file`] says. fn spawn_listed( program: &Path, arguments: &[OsString], working_dir: Option<&Path>, stdio: [Option; 3], inherit: &[Inherited<'_>], + mode: SpawnMode, job: Option, - flags: PROCESS_CREATION_FLAGS, ) -> io::Result { refuse_batch_file(program)?; let application = wide(program); @@ -286,6 +342,10 @@ fn spawn_listed( Ok(wide(&path)) }) .transpose()?; + let owner = match mode { + SpawnMode::Foreground => Some(owning_job()?), + SpawnMode::Detached { .. } => None, + }; // No handle may be inheritable for this spawn outside the lock. Locals are dropped in the // reverse of their order, so every return restores the handles `inherit`, closes the `stdio` // handles and then the job's, which it moves here for that, before it releases the lock. @@ -322,8 +382,14 @@ fn spawn_listed( } } let inheritable = InheritableForSpawn::new(&handles[standard_handles..])?; - let jobs = job.as_ref().map(raw); - let jobs = jobs.as_slice(); + // The child joins the job of its log, and then its owning job, which nests in the first. + let mut jobs = [ptr::null_mut(); 2]; + let mut listed = 0; + for listed_job in [&job, &owner].into_iter().flatten() { + jobs[listed] = raw(listed_job); + listed += 1; + } + let jobs = &jobs[..listed]; // A list cannot be empty: a child that inherits no handle at all is created without one, and // without inheritance. let lists = u32::from(!handles.is_empty()) + u32::from(!jobs.is_empty()); @@ -334,7 +400,7 @@ fn spawn_listed( }; let mut startup = STARTUPINFOEXW::default(); startup.StartupInfo.cb = mem::size_of::() as u32; - let mut flags = flags | CREATE_UNICODE_ENVIRONMENT; + let mut flags = mode.flags() | CREATE_UNICODE_ENVIRONMENT; if let Some(attributes) = &mut attributes { if !handles.is_empty() { // SAFETY: the list has room for this attribute, and `handles` outlives @@ -359,8 +425,8 @@ fn spawn_listed( startup.StartupInfo.hStdError = standard[2]; } if !jobs.is_empty() { - // SAFETY: the list has room for this attribute, and `jobs`, whose handle `job` keeps - // open, outlives CreateProcessW. + // SAFETY: the list has room for this attribute, and `jobs`, whose handles `job` and + // `owner` keep open, outlives CreateProcessW. if unsafe { UpdateProcThreadAttribute( attributes.as_ptr(), @@ -405,7 +471,7 @@ fn spawn_listed( } else { Ok(()) }; - // The child holds its own copies of the handles now, and is in its job, so the caller's need + // The child holds its own copies of the handles now, and is in its jobs, so the caller's need // not be inheritable any longer, and the window closes. drop(inheritable); drop(stdio); @@ -422,6 +488,7 @@ fn spawn_listed( Ok(LaunchedProcess { process, pid: information.dwProcessId, + _owner: owner, }) } diff --git a/nvx/src/host/platform/windows/tests.rs b/nvx/src/host/platform/windows/tests.rs index 4dffc90fe..974e46d00 100644 --- a/nvx/src/host/platform/windows/tests.rs +++ b/nvx/src/host/platform/windows/tests.rs @@ -1154,3 +1154,78 @@ fn a_thread_that_holds_the_spawn_lock_spawns_under_it_until_its_last_lock_is_dro ); assert!(late, "another thread could not take the lock once released"); } + +#[test] +fn a_foreground_child_ends_with_its_spawn_and_a_detached_one_outlives_it() { + use windows_sys::Win32::System::JobObjects::IsProcessInJob; + + let directory = tempfile::tempdir().unwrap(); + let system = std::env::var_os("SystemRoot").unwrap(); + let ping = Path::new(&system).join("System32").join("PING.EXE"); + // A stand-in that runs for a minute in the job of its log, as the spawn of a VMM starts it, + // and a handle of this test to that job. + let start = |name: &str, mode| { + let log = fs::File::create(directory.path().join(name)).unwrap(); + let job = create_log_job(&log) + .unwrap() + .expect("a log on a disk volume has a job"); + let log_job = job.try_clone().unwrap(); + let (stdin, _stdin_writer) = io::pipe().unwrap(); + let stderr = log.try_clone().unwrap(); + let child = spawn_with_stdio( + &ping, + &["-n", "60", "127.0.0.1"].map(OsString::from), + &std::env::temp_dir(), + [stdin.into(), log.into(), stderr.into()], + &[], + mode, + Some(job), + ) + .unwrap(); + (child, log_job) + }; + let (foreground, log_job) = start("foreground.log", SpawnMode::Foreground); + let (detached, _) = start( + "detached.log", + SpawnMode::Detached { + breakaway_from_job: false, + }, + ); + let (foreground_process, _) = foreground.pin().unwrap(); + let (detached_process, _) = detached.pin().unwrap(); + // The foreground child's own job nests in the job of its log, which the child stays in. + let mut in_log_job = 0; + // SAFETY: both handles are open, and the output pointer is valid. + let queried = unsafe { + IsProcessInJob( + raw(&foreground_process.process), + raw(&log_job), + &mut in_log_job, + ) + } != 0; + // Releasing the spawn of the foreground child closes its job, which ends it, but leaves the + // detached child running. + drop(foreground); + let ended = foreground_process + .wait(Instant::now() + WINDOW_TIMEOUT) + .unwrap(); + let running = detached_process.wait(Instant::now()).unwrap(); + detached + .terminate_and_wait() + .expect("the detached child did not exit"); + assert!(queried, "{}", io::Error::last_os_error()); + assert_ne!( + in_log_job, 0, + "the foreground child left the job of its log" + ); + assert_eq!( + ended, + Some(true), + "the foreground child outlived the spawn that held its job" + ); + assert_eq!( + running, + Some(false), + "the detached child ended with its spawn" + ); +} diff --git a/nvx/src/host/spawn.rs b/nvx/src/host/spawn.rs index 292d67d38..66b5b30a3 100644 --- a/nvx/src/host/spawn.rs +++ b/nvx/src/host/spawn.rs @@ -66,7 +66,10 @@ pub(crate) struct VmmCommand<'a> { /// which limits no resource but lets no process that the VMM starts break away from it. A process /// that the caller spawns while the VMM is created, which can inherit the log as [`Inherited`] /// describes, never joins the VMM's job. A `foreground` VMM, which the CLI's one-shot runs start, -/// stays in the caller's session and console instead. +/// stays in the caller's session and console instead, and, on Windows, starts in a job that the +/// returned [`Launched`] alone holds, nested in the job of its log, which ends the VMM once that +/// `Launched` is released, or the caller ends, whatever ends it, so that the VMM of a one-shot run +/// never outlives the run. /// /// Record the VMM's identity right after the spawn, through [`Launched::process`], if the caller /// recovers its launches. Fails, before it creates any child, with @@ -170,9 +173,10 @@ fn spawn_inner( } /// A VMM that [`spawn_vm_with_mode`] started, which the caller has not released yet: on Unix, -/// its child process; on Windows, its process handle. On Unix the child's ID names no other -/// process until [`wait_timeout`](Self::wait_timeout) reaps it; hold it with -/// [`process`](Self::process) before waiting to keep a verified handle after it exits. +/// its child process; on Windows, its process handle, and the job that ends a foreground VMM. On +/// Unix the child's ID names no other process until [`wait_timeout`](Self::wait_timeout) reaps +/// it; hold it with [`process`](Self::process) before waiting to keep a verified handle after it +/// exits. /// /// Hold it with [`process`](Self::process). Then release it with [`detach`](Self::detach), or end it /// with [`kill_and_confirm_exit`](Self::kill_and_confirm_exit); the [`Process`] stays valid @@ -185,7 +189,7 @@ pub(crate) struct Launched { /// Whether the child has been reaped, after which its process ID may name another process. reaped: bool, #[cfg(windows)] - /// Owned Windows process handle and identifier. + /// Owned Windows process handle and identifier, and a foreground VMM's job. process: platform::LaunchedProcess, } @@ -238,7 +242,8 @@ impl Launched { Ok(Process::held(reference, handle)) } - /// Releases the process without waiting for it: it keeps running. + /// Releases the process without waiting for it: it keeps running, but for a foreground VMM on + /// Windows, which its job then ends, as [`spawn_vm_with_mode`] describes. /// /// On Unix a background thread reaps the child once it exits so it does not linger as a /// zombie while this process lives. If that thread cannot start, the child becomes a zombie diff --git a/nvx/src/host/vm.rs b/nvx/src/host/vm.rs index 1777d224c..e23e4302e 100644 --- a/nvx/src/host/vm.rs +++ b/nvx/src/host/vm.rs @@ -964,12 +964,15 @@ pub struct Launched { pub capability: Capability, /// The preparation's same restore-ready listener, absent for a cold launch. pub ready: Option, - /// Retains only a foreground caller's child, for its status. + /// Retains only a foreground caller's child, for its status, and on Windows its job, which + /// ends the child once this is dropped. #[cfg(feature = "cli")] child: ForegroundChild, } -/// Reaps a foreground child on release without adding `Drop` to the public launch value. +/// Reaps a foreground child on release without adding `Drop` to the public launch value; on +/// Windows, the release closes the job that ends the child if it still runs, as the job does when +/// its caller ends, however that ends. #[cfg(feature = "cli")] #[derive(Debug)] struct ForegroundChild(Option); diff --git a/nvx/tests/cli.rs b/nvx/tests/cli.rs index 02834b97c..9da037560 100644 --- a/nvx/tests/cli.rs +++ b/nvx/tests/cli.rs @@ -2317,6 +2317,102 @@ fn a_run_refuses_a_batch_file_as_openvmm() { assert!(!marker.exists()); } +/// Starts `nvx sandbox run` in the background, with `--timeout` of `timeout` and the temporary +/// directory `temporary`, whose workload leaves the marker that it returns once it runs and then +/// sleeps. +#[cfg(windows)] +fn background_run(root: &Root, timeout: &str, temporary: &Path) -> (std::process::Child, PathBuf) { + let path = |name: &str| root.path.join(name).to_str().unwrap().to_owned(); + let started = root.path.join("started"); + let layer = format!( + "distro,{},11111111-1111-1111-1111-111111111111", + path("distro.erofs") + ); + let scratch = path("scratch.ext4"); + let script = format!("touch {}; sleep 60000", started.display()); + let cli = root + .command(&[ + "sandbox", + "run", + "--layer", + layer.as_str(), + "--scratch", + scratch.as_str(), + "--timeout", + timeout, + "--entrypoint", + "/bin/sh", + "--arg=-c", + "--arg", + script.as_str(), + ]) + .env("TMP", temporary) + .env("TEMP", temporary) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + (cli, started) +} + +/// Opens process `pid` to wait for its exit, which the handle shows whatever process takes its ID +/// afterwards. +#[cfg(windows)] +fn exit_handle(pid: u32) -> std::os::windows::io::OwnedHandle { + use std::os::windows::io::FromRawHandle; + + use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE}; + + // SAFETY: OpenProcess has no memory-safety preconditions. + let process = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + assert!( + !process.is_null(), + "cannot open process {pid}: {}", + std::io::Error::last_os_error() + ); + // SAFETY: the handle is new, and nothing else owns it. + unsafe { std::os::windows::io::OwnedHandle::from_raw_handle(process) } +} + +/// Returns whether the process of `handle` exits within `timeout`. +#[cfg(windows)] +fn exits_within(handle: &std::os::windows::io::OwnedHandle, timeout: Duration) -> bool { + use std::os::windows::io::AsRawHandle; + + use windows_sys::Win32::Foundation::WAIT_OBJECT_0; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + + let milliseconds = u32::try_from(timeout.as_millis()).unwrap(); + // SAFETY: the handle has synchronize access. + unsafe { WaitForSingleObject(handle.as_raw_handle(), milliseconds) == WAIT_OBJECT_0 } +} + +#[cfg(windows)] +#[test] +fn a_run_whose_cli_is_killed_ends_its_openvmm() { + let root = Root::new(); + let temporary = root.path.join("tmp"); + fs::create_dir(&temporary).unwrap(); + let (mut cli, started) = background_run(&root, "60", &temporary); + wait_for(&started); + let openvmm = children_named(cli.id(), "openvmm.exe"); + let handles: Vec<_> = openvmm.iter().map(|&pid| exit_handle(pid)).collect(); + // `TerminateProcess` gives the CLI no chance to stop its VM. + cli.kill().unwrap(); + cli.wait().unwrap(); + let ended: Vec = handles + .iter() + .map(|handle| exits_within(handle, Duration::from_secs(30))) + .collect(); + for (&pid, &ended) in openvmm.iter().zip(&ended) { + if !ended { + harness::kill(u64::from(pid)); + } + } + assert_eq!(openvmm.len(), 1, "{openvmm:?}"); + assert_eq!(ended, [true], "OpenVMM outlived the run that was killed"); +} + #[test] fn artifacts_default_to_the_checkout_that_holds_the_executable() { let output = Command::new(NVX) From 5074c50cdda7eadd8c1ff474b68f3b6a76eec81a Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Tue, 24 Nov 2026 02:08:23 -0800 Subject: [PATCH 2/3] sandbox: force a timed-out run's VM down as stop does When `--timeout` expired while the workload of `nvx sandbox run` was busy, the run terminated OpenVMM, waited a fixed 10 s for its exit, and then failed with `error[still-running]: cannot confirm exit of VM process `, dropping the workload's own `timed-out` error and keeping the VM directory, while `openvmm.exe` stayed listed (microsoft/nvx#1910, case 2). Windows keeps a terminated process until its pending I/O completes or is canceled, and an OpenVMM that was terminated during heavy virtio-fs I/O stayed so until the host restarted (case 3), in the same state as a process whose debugger holds its exit: exit code set, no handles, and not signaled. The run now forces its VM down as `sandbox stop` does once its grace has passed: through `force_exit`, which `stop` shares, it terminates OpenVMM and waits up to `--timeout` seconds, and at least the 10 s that it waited before, for the exit, in a wait that Ctrl-C ends. After Ctrl-C, whenever it comes, the run terminates OpenVMM at once and waits 10 s for it without heeding Ctrl-C, as it did before, and then ends as interrupted. It takes whether OpenVMM exited on its own from the outcome of that stop, since a stop that finds the VM exited after the termination reports it as exited. It reports the workload's error, and then, when it cannot confirm the exit, the stop's, also after Ctrl-C, after which `nvx` would otherwise print only `Interrupted`, but not a failure that came after Ctrl-C, as when the terminal's Ctrl-C also ends OpenVMM. `vm::stop` now says that a process that its termination reached, but that has not exited, is stuck exiting; such a process runs no code of its own any longer, so the run removes its VM directory, as a second termination that succeeds shows, and keeps it only for a VM that no termination reached. Evidence on Windows 11 with WHP and the v0.1.0-dev.efe086d96205 artifacts, with a debugger that holds the exit of the real OpenVMM of `sandbox run --timeout 15` and a busy workload: at 6681c2e1217 the run failed after 30 s with only `error[still-running]: cannot confirm exit of VM process 14648` and kept its directory; with this change it fails after 34 s with `error[timed-out]: managed control response timed out` and `error[still-running]: cannot confirm exit of VM process 5112: it is stuck exiting after its forced termination`, and removes its directory. A busy workload without the debugger still fails with `timed-out` alone and leaves nothing. Tests: `vm::stop` says that a terminated process whose debugger holds its exit is stuck exiting, and a `sandbox run` whose fake OpenVMM is held so reports both errors and removes its VM directory. Both fail at the base revision; the debuggers need the Win32 debugging API of windows-sys in the development dependencies. With Ctrl-C raised in a console of their own, the run's forced stop still waits for the exit that a debugger holds and then says that it is stuck, and a `sandbox run` that Ctrl-C interrupts while its workload runs, while its VM stops after the guest refused the workload, or while it forces its VM down after the workload outlived `--timeout`, reports the workload's error, the held OpenVMM as stuck exiting, and `Interrupted`. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/run.md | 21 +- doc/usage.md | 7 +- nvx/Cargo.toml | 4 +- nvx/README.md | 23 +- nvx/src/host/cli/sandbox/lifecycle/start.rs | 102 ++++- .../host/cli/sandbox/lifecycle/start/tests.rs | 86 ++++ nvx/src/host/cli/sandbox/lifecycle/stop.rs | 17 +- nvx/src/host/platform/tests.rs | 9 +- nvx/src/host/platform/windows/tests.rs | 223 ++++++++++ nvx/src/host/vm.rs | 17 +- nvx/src/host/vm/tests.rs | 38 ++ nvx/tests/cli.rs | 402 +++++++++++++++++- 12 files changed, 884 insertions(+), 65 deletions(-) diff --git a/doc/run.md b/doc/run.md index 7d8b1eb15..33fbbe951 100644 --- a/doc/run.md +++ b/doc/run.md @@ -1021,8 +1021,20 @@ control session, as [`sandbox exec`](#managed-lifecycle) does, with the same its standard input, output and error as `sandbox exec` does. It then asks nvx-init to stop the VM, terminates OpenVMM if it does not exit within `--timeout` seconds, warning that it did, and removes the VM directory, and -finally exits with the workload's status. A VM that exits before nvx-init is -ready, as when the guest +finally exits with the workload's status. A workload that outlives +`--timeout` fails the run with `timed-out`, and the run then terminates +OpenVMM as `stop` does once its grace has passed, waiting up to `--timeout` +seconds, and at least 10, for OpenVMM to exit, a wait that ends at most 10 +seconds after Ctrl-C. When the run cannot confirm that OpenVMM exited, it fails +with `still-running`, after the workload's own error, and after Ctrl-C it +reports that error before it exits with status 130. An OpenVMM that the +termination reached runs no code of its own any longer, so the error says that +it is stuck exiting, and the run removes the VM directory all the same. Windows +keeps a terminated process until its pending I/O completes or is canceled, and +an OpenVMM terminated while its virtio-fs device had I/O in flight has stayed +so until the host restarted +([#1910](https://github.com/microsoft/nvx/issues/1910)). A VM that exits before +nvx-init is ready, as when the guest refuses the workload identity, fails the run as it fails a `start`, with the category and status of the outcome report that OpenVMM published, such as `guest-exit status 125`. `--outcome-report` forwards that report, of the VM's @@ -1788,7 +1800,10 @@ terminates its OpenVMM without a guest shutdown, waits up to `--timeout` seconds for it to exit, and warns that it did. A `stop` that cannot determine the OpenVMM process, whose terminated OpenVMM does not exit in time, or whose wait Ctrl-C ends, keeps the sandbox's runtime record, and the next `stop` -retries. The store's records belong to the version of NVX that wrote them, so +retries. The error of one whose terminated OpenVMM does not exit in time, +`still-running`, says that OpenVMM is stuck exiting, as for +[`sandbox run`](#experimental-single-workload-sandbox). The store's records +belong to the version of NVX that wrote them, so stop and deprovision each sandbox with the version that started it before you switch versions, as [Upgrades](#upgrades) says. diff --git a/doc/usage.md b/doc/usage.md index b76ec9b70..200dc371a 100644 --- a/doc/usage.md +++ b/doc/usage.md @@ -115,7 +115,7 @@ each code, which callers of the `nvx` library see in its place. | `outcome-report-exists` | 1 | A file exists at the `--outcome-report` path. | | `scratch-claimed` | 1 | Another sandbox claims the scratch image. | | `exited` | 1 | OpenVMM exited, as when a start fails, whose message names the category and status of OpenVMM's outcome report when it has one. | -| `still-running` | 1 | A stop could not confirm the VM process's exit, so the caller keeps its verified process. | +| `still-running` | 1 | A stop could not confirm the VM process's exit, so the caller keeps its verified process. The message says that a process that its forced termination reached is stuck exiting. | | `exec-refused` | 1 | The guest agent refused the workload, as for a working directory that it cannot use. | | `endpoint-closed` | 1 | OpenVMM closed the control endpoint, as it does when the VM shuts down. | | `protocol` | 1 | The control session failed otherwise, as when the guest breaks the protocol or the session is reset. | @@ -396,8 +396,9 @@ artifacts before they launch, as `nvx run` does. A `run` keeps no state: it launches the VM that a `provision` and a `start` of its options would launch, in a temporary VM directory that it removes, executes its workload once, as `exec` does, with its streams, has the guest shut the VM down, which -it terminates if it does not exit within `--timeout` seconds, and exits with -the workload's status. On Windows, its VM ends with it, whatever ends it; see +it terminates if it does not exit within `--timeout` seconds, as it terminates +the VM of a workload that outlives `--timeout`, and exits with the workload's +status. On Windows, its VM ends with it, whatever ends it; see [Experimental single-workload sandbox](run.md#experimental-single-workload-sandbox). See [Run](run.md) for artifact preparation, the security boundary, the diff --git a/nvx/Cargo.toml b/nvx/Cargo.toml index f1a9656ea..d9f02ab5e 100644 --- a/nvx/Cargo.toml +++ b/nvx/Cargo.toml @@ -94,13 +94,15 @@ serde_json = "1.0.120" tempfile = "3.10" # The job objects, process security descriptors, handles, and process lists of the process -# supervision and CLI tests, and the command-line splitting and file deletions of the CLI tests. +# supervision and CLI tests, the debuggers that hold the exits of their processes, and the +# command-line splitting and file deletions of the CLI tests. [target.'cfg(windows)'.dev-dependencies] windows-sys = { version = "0.61", features = [ "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", + "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Threading", diff --git a/nvx/README.md b/nvx/README.md index 017755d7d..6fd2527de 100644 --- a/nvx/README.md +++ b/nvx/README.md @@ -468,7 +468,9 @@ OpenVMM's verified process once the grace deadline passes, and returns a `Stopped` only once the process exited, with the read of its outcome report kept apart, so that a report that can't be read never hides the exit. An exit that it cannot confirm fails with `ErrorKind::StillRunning`, and the caller -keeps the process. +keeps the process. The error says that a process that the termination reached, +which runs no code of its own any longer, is stuck exiting, as Windows keeps a +terminated process until its pending I/O completes or is canceled. `SavedVm` bundles what a caller saves to find its VM again: the `VmDir`, the control endpoint, the capability's bytes, the process's `ProcessRef`, and the @@ -1324,7 +1326,9 @@ exit with status 2, as `argparse` does, and help exits with status 0. Callers tell errors apart by their codes and by stable fragments of their messages, such as the names of options, fields, and files, since the wording may change. Ctrl-C prints `Interrupted` and exits with status 130, without a code, since it -reports no error. `run`, `sandbox run`, and `sandbox exec` exit with the status +reports no error; a `sandbox run` reports first the error of a workload that +failed before Ctrl-C, and the `still-running` error of an OpenVMM whose exit it +cannot confirm. `run`, `sandbox run`, and `sandbox exec` exit with the status of OpenVMM or of the workload, which is no error of `nvx` either. Text ends its lines as Python's `print` ends them, with `\r\n` on Windows and `\n` elsewhere, while workload output passes through unchanged; an error that @@ -1606,10 +1610,13 @@ before them. shut the VM down, waits up to `--timeout` seconds for OpenVMM to exit before it terminates it, removes the VM directory, and exits with the workload's status. `--outcome-report` forwards OpenVMM's outcome report of the VM's - stop. On Windows, OpenVMM runs in a job object that only the run holds, - which ends OpenVMM once it closes, so that the VM never outlives the run, - whatever ends the run, and in the jobs of `nvx` that keep their processes' - children. + stop. A workload that outlives `--timeout` fails with `timed-out`, after + which the run terminates OpenVMM as `stop` does, waiting up to `--timeout` + seconds, and at least 10, for it to exit, and fails with `still-running`, + which says that OpenVMM is stuck exiting, if it has not. On Windows, OpenVMM + runs in a job object that only the run holds, which ends OpenVMM once it + closes, so that the VM never outlives the run, whatever ends the run, and in + the jobs of `nvx` that keep their processes' children. - `provision` records the sandbox in its state directory. `start` launches OpenVMM detached with the managed lifecycle, passes it a fresh capability through its standard input, and waits until the guest answers. `exec` runs a @@ -1975,7 +1982,7 @@ wording of a message may change; callers of the CLI also have its codes. | `Unavailable` | A missing or unusable artifact, hypervisor, or release, or an unsupported host | | `Unsupported` | A request that NVX refuses: a value that it does not accept, such as a malformed or out-of-range one, options that it cannot combine, or a request that it cannot represent or enforce, such as a policy beyond a limit of OpenVMM or the guest agent | | `Exited` | The VM's OpenVMM process exited | -| `StillRunning` | The exit of a VM's process could not be confirmed, so the VM may still run: a stop's, whose caller keeps its verified process, or that of the process that a failed spawn started and tried to end | +| `StillRunning` | The exit of a VM's process could not be confirmed, so the VM may still run: a stop's, whose caller keeps its verified process, or that of the process that a failed spawn started and tried to end; a process that a stop's termination reached is stuck exiting | | `Io` | A host I/O failure, or state that NVX recorded on the host and cannot read | | `NotFound` | State that an operation names and that does not exist on the host, such as the store of a sandbox that was never created or that a removal deleted | | `Protocol` | A control session that failed, or a request that the guest agent refused | @@ -2005,7 +2012,7 @@ has. | `unavailable` | `Unavailable` | A dependency is missing or unusable, other than as a finer code says: install metadata, the hypervisor, a release, a distro layer or scratch image that the request names, or a host that NVX does not support | | `unsupported` | `Unsupported` | NVX refuses the request: options that it cannot combine, a value that it does not accept, or a policy that it cannot represent or enforce. The message names the option or field | | `exited` | `Exited` | OpenVMM exited, as when a start fails, whose message names the category and status of OpenVMM's outcome report when it has one | -| `still-running` | `StillRunning` | The exit of a VM's process could not be confirmed, as by a stop or after a start whose launch failed, so the VM may still run | +| `still-running` | `StillRunning` | The exit of a VM's process could not be confirmed, as by a stop or after a start whose launch failed, so the VM may still run; the message says that a process that the stop's termination reached is stuck exiting | | `io` | `Io` | A host I/O operation failed, or state that NVX recorded on the host is unreadable or malformed | | `not-found` | `NotFound` | Other state that the operation names does not exist on the host | | `protocol` | `Protocol` | The control session failed otherwise: the peer violated the protocol, reset the session, or failed authentication | diff --git a/nvx/src/host/cli/sandbox/lifecycle/start.rs b/nvx/src/host/cli/sandbox/lifecycle/start.rs index 83133153e..7a76514f0 100644 --- a/nvx/src/host/cli/sandbox/lifecycle/start.rs +++ b/nvx/src/host/cli/sandbox/lifecycle/start.rs @@ -14,6 +14,7 @@ use serde_json::Value; use super::directory::prepare_state_directory; use super::outcome::{copy_openvmm_outcome, validate_outcome_destination}; +use super::stop::StopOutcome; use super::{ CONFIG_NAME, Found, ProvisionConfig, connect, find_vm, mismatched, require_config, running_vm, runtime_for, @@ -39,7 +40,7 @@ use crate::host::cli::store::StateFile; use crate::host::cli::{Exit, Result, io_error, output, random_bytes}; use crate::host::config::{COMMAND_LINE_BUDGET, RootConfig, UpperConfig, VmConfig}; use crate::host::platform; -use crate::host::process::KILL_TIMEOUT; +use crate::host::process::{KILL_TIMEOUT, Process}; use crate::host::report::Report; use crate::host::restore::{Attribution, RestoreError, RestoreEvidence}; use crate::host::restore_driver::{self, Cancel, ControlRestoreError, Workload}; @@ -48,7 +49,7 @@ use crate::host::sandbox::distro::DISTRO_POLICY_REVISION; use crate::host::sandbox::scratch::{CLAIM_RELEASE_WAIT, CheckedScratch}; use crate::host::session::{ExecEvent, SessionError}; use crate::host::snapshot::OPENVMM_DIR; -use crate::host::vm::{self, Launched, Prepared, SavedVm, VmDir}; +use crate::host::vm::{self, Launched, Prepared, SavedVm, VmDir, VmOutputs}; use crate::protocol::cmdline::{self, Parameter}; use crate::protocol::root::RootLayout; use crate::protocol::v2::Outcome; @@ -609,10 +610,16 @@ pub(crate) fn exec_workload( /// /// Once nvx-init is ready and has mapped the shares, the run executes `request` over NVXC, asks /// nvx-init to stop the VM, and waits up to `--timeout` seconds for the VM to exit before it -/// forces it down. A VM that exits before it is ready fails the run as it fails `start`. Once the -/// VM has exited, the run forwards OpenVMM's outcome report to `--outcome-report`, if given, and -/// removes the VM directory, which it keeps only if it cannot confirm that exit. It holds `held`, -/// the lock of the downloads, until the VM is ready or has failed to be. +/// forces it down, as `stop` does: it terminates OpenVMM and waits up to `--timeout` seconds, and +/// at least [`KILL_TIMEOUT`], for it to exit, a wait that Ctrl-C ends. After Ctrl-C, it forces the +/// VM down at once, and waits [`KILL_TIMEOUT`] for it. A VM that exits before it is ready fails the +/// run as it fails `start`. Once the VM has exited, the run forwards OpenVMM's outcome report to +/// `--outcome-report`, if given, and removes the VM directory. A VM whose exit it cannot confirm +/// fails the run with `still-running`, after the workload's own failure, if any: the run then +/// removes the VM directory only if it terminated the VM, which runs no code of its own any +/// longer, even while it is stuck exiting. On Windows, the VM ends with the run, whatever ends +/// the run, as the job that owns a one-shot run's OpenVMM ensures. It holds `held`, the lock of +/// the downloads, until the VM is ready or has failed to be. pub(crate) fn run( distro: &RecordedDistro, scratch: Option<&Path>, @@ -721,7 +728,6 @@ pub(crate) fn run( cleanup = error.kind() != ErrorKind::StillRunning; error_with_cause(error) })?; - cleanup = false; let saved = SavedVm { vm_dir: dir.clone(), endpoint: launched.outputs.endpoint.clone(), @@ -748,6 +754,9 @@ pub(crate) fn run( .exec(request, timeout) }); open_line.set(executed.as_ref().ok().and_then(|result| result.stderr_end)); + // A failure that came before Ctrl-C is the workload's own; one that came after it may be + // Ctrl-C's, as when the terminal's Ctrl-C also ends OpenVMM, which closes its endpoint. + let ended_before_interrupt = !platform::interrupted(); // A VM whose control endpoint closed is shutting down already. let requested = match session.take() { Some(mut session) @@ -765,19 +774,50 @@ pub(crate) fn run( Deadline::after(0.0) }; let mut executed = executed; - // No record of the VM outlives the run, so it forces the VM down whatever ended the wait. - if let Err(error) = super::stop::wait_for_exit(&launched.process, grace) { - executed = Err(error); + // No record of the VM outlives the run, so it forces the VM down whatever ended the wait, + // Ctrl-C included, which leaves the workload's own failure for the run to report below. + match super::stop::wait_for_exit(&launched.process, grace) { + Ok(_) | Err(Exit::Interrupted) => {} + Err(error) => executed = Err(error), } - let now = Instant::now(); - let stopped = vm::stop( + let stopped = force_down( &launched.process, &launched.outputs, - |_| false, - now, - now + KILL_TIMEOUT, - ) - .map_err(error_with_cause)?; + Deadline::after(timeout.max(KILL_TIMEOUT.as_secs_f64())), + ); + // A run that Ctrl-C reached ends as interrupted, which is all that `main` reports of it, so + // the run reports itself a failure of the workload that came before Ctrl-C, and below the + // stop's. + let interrupted = platform::interrupted(); + if interrupted + && let Err(failure) = std::mem::replace(&mut executed, Err(Exit::Interrupted)) + && ended_before_interrupt + && !matches!(failure, Exit::Interrupted) + { + end_line(); + failure.report(); + } + let (self_exited, stopped) = match stopped { + Ok(stopped) => stopped, + Err(error) => { + // A VM that a termination reached runs no code of its own any longer, even while + // it is stuck exiting, as a second termination shows, so its directory can go; + // one that no termination reached may still write there. + cleanup = launched.process.kill().is_ok(); + if let Err(failure) = executed + && !matches!(failure, Exit::Interrupted) + { + end_line(); + failure.report(); + } + if interrupted { + end_line(); + error.report(); + return Err(Exit::Interrupted); + } + return Err(error); + } + }; cleanup = true; if let Some(report) = &options.outcome_report && let Err(error) = copy_openvmm_outcome(&launched.outputs.outcome, report) @@ -796,10 +836,10 @@ pub(crate) fn run( } if !started { let report = stopped.report.map_err(error_with_cause)?; - if stopped.self_exited && !stopping && !matches!(executed, Err(Exit::Interrupted)) { + if self_exited && !stopping && !matches!(executed, Err(Exit::Interrupted)) { return Err(exited_during_startup(report)); } - } else if executed.is_ok() && stopped.forced { + } else if executed.is_ok() && !self_exited { end_line(); output::print_stderr("warning: OpenVMM was forcibly terminated after the run"); } @@ -818,6 +858,30 @@ pub(crate) fn run( result } +/// Forces down the VM of a run, whose verified process is `process`, once the run's grace has +/// passed, and returns whether OpenVMM exited before its termination, and what it left. +/// +/// As `stop` does, it terminates OpenVMM and waits until `deadline` for it to exit, a wait that +/// Ctrl-C ends. Ctrl-C would end a wait that heeds it at once, so after Ctrl-C, before the stop or +/// during it, it terminates OpenVMM at once and waits [`KILL_TIMEOUT`] for it without heeding +/// Ctrl-C, as a run always did. An OpenVMM that has not exited by then fails the stop with +/// `still-running`. +fn force_down( + process: &Process, + outputs: &VmOutputs, + deadline: Deadline, +) -> Result<(bool, vm::Stopped)> { + match super::stop::force_exit(process, outputs, deadline) { + Err(Exit::Interrupted) => { + let now = Instant::now(); + vm::stop(process, outputs, |_| false, now, now + KILL_TIMEOUT) + .map(|stopped| (stopped.self_exited, stopped)) + .map_err(error_with_cause) + } + forced => forced.map(|(outcome, stopped)| (outcome == StopOutcome::Graceful, stopped)), + } +} + /// Returns the configuration that `provision` records for the options of `config`, with the /// distro layer `distro` at the path that `provision` records, over `scratch`, the scratch image of /// an upper on scratch, as given, as `start` reads it back and checks it, shares included. diff --git a/nvx/src/host/cli/sandbox/lifecycle/start/tests.rs b/nvx/src/host/cli/sandbox/lifecycle/start/tests.rs index 90c6caedb..e106c243c 100644 --- a/nvx/src/host/cli/sandbox/lifecycle/start/tests.rs +++ b/nvx/src/host/cli/sandbox/lifecycle/start/tests.rs @@ -187,6 +187,92 @@ fn starts_check_the_kernel_command_line_that_they_launch() { ); } +/// A run that Ctrl-C interrupts while it forces its VM down still waits for the VM's exit, for +/// [`KILL_TIMEOUT`], without heeding Ctrl-C, as after Ctrl-C during the workload, and says that a +/// VM that has not exited by then is stuck exiting. Ctrl-C reaches every process of a console, so +/// a helper of a console of its own raises it. +#[cfg(windows)] +#[test] +fn a_run_that_ctrl_c_interrupts_while_it_forces_its_vm_down_waits_for_the_vm_all_the_same() { + let output = platform::tests::in_private_console( + "host::cli::sandbox::lifecycle::start::tests::interrupted_force_down", + ); + assert!(output.status.success(), "{output:?}"); +} + +/// The helper of the test above, which runs in a console of its own. +#[cfg(windows)] +#[test] +#[ignore = "run in a console of its own by the test that raises Ctrl-C there"] +fn interrupted_force_down() { + use std::time::Duration; + + use crate::host::process::{BootId, Opened, ProcessRef}; + + platform::tests::watch_private_interrupts(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("vm"); + vm::create_private_dir(&path).unwrap(); + let outputs = VmDir::open(&path).unwrap().outputs(false).unwrap(); + let open = |pid| { + let reference = ProcessRef { + pid, + start_time: platform::process_start_time(pid).unwrap().unwrap(), + boot: BootId::current().unwrap(), + }; + let Opened::Running(process) = Process::open(&reference).unwrap() else { + panic!("the debugged process runs"); + }; + process + }; + // Ctrl-C comes while the run waits for the exit of the VM that it terminated, which the + // debugger holds until shortly after. + let mut held = platform::tests::HeldExit::start(); + let process = open(held.pid()); + let stopped = thread::scope(|scope| { + let held = &mut held; + scope.spawn(move || { + let until = Instant::now() + Duration::from_secs(30); + while !held.exiting() { + assert!(Instant::now() < until, "the run did not terminate the VM"); + thread::sleep(Duration::from_millis(5)); + } + platform::tests::interrupt_private_console(); + thread::sleep(Duration::from_millis(500)); + held.release(); + }); + force_down(&process, &outputs, Deadline::after(60.0)) + }); + let exited = process.wait(Instant::now()).unwrap(); + let (self_exited, _) = stopped.unwrap(); + assert!(!self_exited); + assert!(exited.is_some(), "the run returned before the VM exited"); + // Ctrl-C has come before the run forces another VM down, whose exit the debugger holds past + // the wait. + let mut held = platform::tests::HeldExit::start(); + let pid = held.pid(); + let process = open(pid); + let began = Instant::now(); + let stopped = force_down(&process, &outputs, Deadline::after(60.0)); + let waited = began.elapsed(); + let unconfirmed = process.wait(Instant::now()).unwrap(); + held.release(); + let error = stopped.unwrap_err(); + assert_eq!(error.code(), Some(ErrorCode::StillRunning), "{error:?}"); + assert_eq!( + error.message(), + Some( + format!( + "cannot confirm exit of VM process {pid}: it is stuck exiting after its forced \ + termination" + ) + .as_str() + ) + ); + assert!(waited >= KILL_TIMEOUT, "{waited:?}"); + assert!(unconfirmed.is_none(), "the held exit showed"); +} + /// A run removes its VM directory with the staging file of an outcome report that OpenVMM did /// not finish writing, as one that the run forced down can leave, and keeps a directory that /// holds a file of another name. diff --git a/nvx/src/host/cli/sandbox/lifecycle/stop.rs b/nvx/src/host/cli/sandbox/lifecycle/stop.rs index a7b1a49ed..1da9e0635 100644 --- a/nvx/src/host/cli/sandbox/lifecycle/stop.rs +++ b/nvx/src/host/cli/sandbox/lifecycle/stop.rs @@ -90,12 +90,25 @@ fn stop_verified( endpoint: saved.endpoint.clone(), console: None, }; + force_exit(process, &outputs, Deadline::after(timeout)) +} + +/// Ends the OpenVMM of `outputs` through its verified process without a guest shutdown, as +/// [`terminate_within`] does by `deadline`, and returns how its stop ended and what it left. +/// +/// Fails if Ctrl-C ends the wait, or with the error of [`vm::stop`] if OpenVMM has not exited by +/// `deadline`, which says that OpenVMM is stuck exiting if the termination reached it. +pub(super) fn force_exit( + process: &Process, + outputs: &VmOutputs, + deadline: Deadline, +) -> Result<(StopOutcome, vm::Stopped)> { let (mut stopped, mut failure) = (None, None); let outcome = terminate_within( - Deadline::after(timeout), + deadline, |bound| { let now = Instant::now(); - match vm::stop(process, &outputs, |_| false, now, now + bound) { + match vm::stop(process, outputs, |_| false, now, now + bound) { Ok(result) => { let outcome = if result.forced { StopOutcome::Forced diff --git a/nvx/src/host/platform/tests.rs b/nvx/src/host/platform/tests.rs index 790a485e9..91d89d7b6 100644 --- a/nvx/src/host/platform/tests.rs +++ b/nvx/src/host/platform/tests.rs @@ -5,11 +5,16 @@ pub(crate) use super::windows::tests::disconnect_control; #[cfg(windows)] pub(crate) use super::windows::tests::set_access; #[cfg(windows)] -pub(crate) use super::windows::tests::{accept_control, control_server, wait_exit_handle}; +pub(crate) use super::windows::tests::{ + HeldExit, accept_control, control_server, wait_exit_handle, +}; #[cfg(windows)] pub(crate) use super::windows::tests::{access, inherits_file, untrusted_log_job, user_sid}; #[cfg(all(windows, feature = "cli"))] -pub(crate) use super::windows::tests::{claim_released_within, with_spawn_window}; +pub(crate) use super::windows::tests::{ + claim_released_within, in_private_console, interrupt_private_console, watch_private_interrupts, + with_spawn_window, +}; use super::*; #[test] diff --git a/nvx/src/host/platform/windows/tests.rs b/nvx/src/host/platform/windows/tests.rs index 974e46d00..03d7a1381 100644 --- a/nvx/src/host/platform/windows/tests.rs +++ b/nvx/src/host/platform/windows/tests.rs @@ -1229,3 +1229,226 @@ fn a_foreground_child_ends_with_its_spawn_and_a_detached_one_outlives_it() { "the detached child ended with its spawn" ); } + +/// A process whose exit a debugger, a thread of the test, holds once the exit has begun, as +/// Windows holds the exit of a terminated process until a driver completes or cancels its pending +/// I/O: Windows signals the exit of a debugged process only once its debugger continues the event +/// of that exit, which this one does when it is released, or dropped. +pub(crate) struct HeldExit { + /// The process, held with every access, to end it when the test did not. + process: OwnedHandle, + /// The process's ID. + pid: u32, + /// Lets the process exit when it sends or is dropped. + release: Option>, + /// The debugger. + debugger: Option>, +} + +impl HeldExit { + /// Starts `PING.EXE`, which runs for a minute, under a debugger that holds its exit. + pub(crate) fn start() -> Self { + use windows_sys::Win32::Foundation::{CloseHandle, DBG_CONTINUE}; + use windows_sys::Win32::System::Diagnostics::Debug::{ + CREATE_PROCESS_DEBUG_EVENT, ContinueDebugEvent, DEBUG_EVENT, EXIT_PROCESS_DEBUG_EVENT, + LOAD_DLL_DEBUG_EVENT, WaitForDebugEvent, + }; + use windows_sys::Win32::System::Threading::{ + CREATE_NO_WINDOW, CreateProcessW, DEBUG_ONLY_THIS_PROCESS, PROCESS_INFORMATION, + STARTUPINFOW, + }; + + let (started, debuggee) = std::sync::mpsc::channel(); + let (release, released) = std::sync::mpsc::channel::<()>(); + // A debugger receives the events of a process on the thread that started it. + let debugger = thread::spawn(move || { + let system = std::env::var_os("SystemRoot").unwrap(); + let ping = Path::new(&system).join("System32").join("PING.EXE"); + let arguments = ["-n", "60", "127.0.0.1"].map(OsString::from); + let mut command_line = match command_line(ping.as_os_str(), &arguments) { + Ok(line) => line, + Err(error) => { + let _ = started.send(Err(error)); + return; + } + }; + let startup = STARTUPINFOW { + cb: mem::size_of::() as u32, + ..Default::default() + }; + let mut information = PROCESS_INFORMATION::default(); + // SAFETY: the command line is mutable and NUL-terminated, the structures outlive the + // call, and the child inherits no handle. + let created = unsafe { + CreateProcessW( + ptr::null(), + command_line.as_mut_ptr(), + ptr::null(), + ptr::null(), + 0, + DEBUG_ONLY_THIS_PROCESS | CREATE_NO_WINDOW, + ptr::null(), + ptr::null(), + &startup, + &mut information, + ) + } != 0; + if !created { + let _ = started.send(Err(io::Error::last_os_error())); + return; + } + drop(owned(information.hThread)); + let process = owned(information.hProcess).expect("CreateProcessW returned a process"); + let _ = started.send(Ok((process, information.dwProcessId))); + loop { + let mut event = DEBUG_EVENT::default(); + // SAFETY: the output pointer is valid. + if unsafe { WaitForDebugEvent(&mut event, INFINITE) } == 0 { + return; + } + match event.dwDebugEventCode { + // SAFETY: the union holds the information of the event's code, whose file + // handle the debugger closes. + CREATE_PROCESS_DEBUG_EVENT => unsafe { + CloseHandle(event.u.CreateProcessInfo.hFile); + }, + // SAFETY: as above. + LOAD_DLL_DEBUG_EVENT => unsafe { + CloseHandle(event.u.LoadDll.hFile); + }, + EXIT_PROCESS_DEBUG_EVENT => { + let _ = released.recv(); + } + _ => {} + } + // SAFETY: the event is this thread's debuggee's. + unsafe { ContinueDebugEvent(event.dwProcessId, event.dwThreadId, DBG_CONTINUE) }; + if event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT { + return; + } + } + }); + let (process, pid) = debuggee.recv().unwrap().unwrap(); + Self { + process, + pid, + release: Some(release), + debugger: Some(debugger), + } + } + + /// Returns the process's ID. + pub(crate) fn pid(&self) -> u32 { + self.pid + } + + /// Returns whether the process has begun its exit, as its termination begins it, although + /// the debugger holds the exit. + #[cfg(feature = "cli")] + pub(crate) fn exiting(&self) -> bool { + use windows_sys::Win32::Foundation::STILL_ACTIVE; + use windows_sys::Win32::System::Threading::GetExitCodeProcess; + + let mut status = 0u32; + // SAFETY: the handle has every access, and the output pointer is valid. + assert_ne!( + unsafe { GetExitCodeProcess(raw(&self.process), &mut status) }, + 0 + ); + status != STILL_ACTIVE as u32 + } + + /// Lets the process exit, once it has begun to, and waits for its debugger to end. + pub(crate) fn release(&mut self) { + drop(self.release.take()); + if let Some(debugger) = self.debugger.take() { + debugger.join().unwrap(); + } + } +} + +impl Drop for HeldExit { + fn drop(&mut self) { + if self.debugger.is_some() { + // A process that the test did not end begins its exit, which its debugger then lets + // it finish. + // SAFETY: the handle has every access. + unsafe { TerminateProcess(raw(&self.process), 1) }; + self.release(); + } + } +} + +/// The variable that marks the test helper that [`in_private_console`] runs. +#[cfg(feature = "cli")] +const PRIVATE_CONSOLE: &str = "NVX_TEST_PRIVATE_CONSOLE"; + +/// Runs `test`, an ignored test of this test executable, in a console of its own, where it may +/// raise Ctrl-C, which reaches every process of a console, with [`interrupt_private_console`], +/// and returns its output. +#[cfg(feature = "cli")] +pub(crate) fn in_private_console(test: &str) -> std::process::Output { + use std::os::windows::process::CommandExt; + + use windows_sys::Win32::System::Threading::CREATE_NEW_CONSOLE; + + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + test, + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env(PRIVATE_CONSOLE, "interrupt") + .creation_flags(CREATE_NEW_CONSOLE) + .output() + .unwrap() +} + +/// Records Ctrl-C for [`interrupted`] in the test helper that [`in_private_console`] runs, once +/// it has checked that the helper is alone in its console. +#[cfg(feature = "cli")] +pub(crate) fn watch_private_interrupts() { + use windows_sys::Win32::System::Console::SetConsoleCtrlHandler; + + assert_eq!( + std::env::var(PRIVATE_CONSOLE).as_deref(), + Ok("interrupt"), + "only a test in a console of its own raises Ctrl-C" + ); + assert_alone_in_console(); + // A parent that ignores Ctrl-C, as one created with CREATE_NEW_PROCESS_GROUP does, passes + // that on to the helper, whose handler would then never see the event. + // SAFETY: this changes only the Ctrl-C processing of the helper, alone in its console. + assert_ne!(unsafe { SetConsoleCtrlHandler(None, 0) }, 0); + watch_interrupts().unwrap(); +} + +/// Raises Ctrl-C in the console of the test helper that [`in_private_console`] runs, once it +/// has checked that the helper is alone there, and waits until [`interrupted`] records it. +#[cfg(feature = "cli")] +pub(crate) fn interrupt_private_console() { + use windows_sys::Win32::System::Console::{CTRL_C_EVENT, GenerateConsoleCtrlEvent}; + + assert_alone_in_console(); + // SAFETY: the console holds the helper alone, so the event reaches no other process. + assert_ne!(unsafe { GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) }, 0); + let deadline = Instant::now() + Duration::from_secs(2); + while !interrupted() { + assert!(Instant::now() < deadline, "Ctrl-C was not recorded"); + thread::sleep(Duration::from_millis(5)); + } +} + +/// Checks that the console of this process holds no other process. +#[cfg(feature = "cli")] +fn assert_alone_in_console() { + use windows_sys::Win32::System::Console::GetConsoleProcessList; + + let mut members = [0u32; 4]; + // SAFETY: the array is writable for its length. + let count = unsafe { GetConsoleProcessList(members.as_mut_ptr(), members.len() as u32) }; + assert_eq!(count, 1, "the console holds other processes: {members:?}"); + assert_eq!(members[0], std::process::id()); +} diff --git a/nvx/src/host/vm.rs b/nvx/src/host/vm.rs index e23e4302e..d1c79c6c7 100644 --- a/nvx/src/host/vm.rs +++ b/nvx/src/host/vm.rs @@ -1096,7 +1096,10 @@ pub struct Stopped { /// when that final wait confirms exit. /// /// An unconfirmed exit fails with [`ErrorKind::StillRunning`](crate::ErrorKind::StillRunning), -/// retaining host errors. The caller keeps the process in that case. +/// retaining host errors. The caller keeps the process in that case. A process that the forced +/// termination reached, but that has not exited by `deadline`, is stuck exiting, and the error +/// says so: it runs no code of its own any longer, but the host has not let it exit, as Windows +/// keeps a process whose I/O a driver neither completes nor cancels. /// Report-read errors have kind [`ErrorKind::Io`](crate::ErrorKind::Io) /// inside [`Stopped::report`], never hiding confirmed exit. pub fn stop( @@ -1134,10 +1137,16 @@ pub fn stop( .wait(deadline) .map_err(|error| failure(kill_error.as_ref()).with_source(error))?; if exited.is_none() { - let error = failure(kill_error.as_ref()); return Err(match kill_error { - Some(source) => error.with_source(source), - None => error, + Some(source) => failure(Some(&source)).with_source(source), + None => Error::new( + crate::ErrorKind::StillRunning, + format!( + "cannot confirm exit of VM process {}: it is stuck exiting after its forced \ + termination", + process.reference().pid + ), + ), }); } } diff --git a/nvx/src/host/vm/tests.rs b/nvx/src/host/vm/tests.rs index 54e521515..83c7f21f4 100644 --- a/nvx/src/host/vm/tests.rs +++ b/nvx/src/host/vm/tests.rs @@ -2728,3 +2728,41 @@ fn stop_returns_still_running_without_exit_confirmation_at_its_deadline() { assert!(process.wait(Instant::now()).unwrap().is_none()); assert!(child.child.try_wait().unwrap().is_none()); } + +#[cfg(windows)] +#[test] +fn stop_says_that_a_process_that_its_forced_termination_reached_is_stuck_exiting() { + let (_directory, vm) = vm_dir(); + let outputs = vm.outputs(false).unwrap(); + let mut held = platform::tests::HeldExit::start(); + let reference = crate::host::process::ProcessRef { + pid: held.pid(), + start_time: platform::process_start_time(held.pid()).unwrap().unwrap(), + boot: crate::host::process::BootId::current().unwrap(), + }; + let Opened::Running(process) = Process::open(&reference).unwrap() else { + panic!("the debugged process runs"); + }; + let grace = Instant::now(); + let deadline = grace + Duration::from_millis(500); + let error = stop(&process, &outputs, |_| false, grace, deadline).unwrap_err(); + let unconfirmed = process.wait(Instant::now()).unwrap(); + held.release(); + let exited = process + .wait(Instant::now() + Duration::from_secs(30)) + .unwrap(); + assert!(Instant::now() >= deadline); + assert_eq!(error.kind(), ErrorKind::StillRunning); + assert_eq!( + error.message(), + format!( + "cannot confirm exit of VM process {}: it is stuck exiting after its forced \ + termination", + reference.pid + ) + ); + // The termination reached the process, so no error of the host caused the failure. + assert!(std::error::Error::source(&error).is_none(), "{error:?}"); + assert!(unconfirmed.is_none(), "the held exit showed"); + assert!(exited.is_some(), "the process did not exit once released"); +} diff --git a/nvx/tests/cli.rs b/nvx/tests/cli.rs index 9da037560..7c6db5c9c 100644 --- a/nvx/tests/cli.rs +++ b/nvx/tests/cli.rs @@ -2317,27 +2317,44 @@ fn a_run_refuses_a_batch_file_as_openvmm() { assert!(!marker.exists()); } -/// Starts `nvx sandbox run` in the background, with `--timeout` of `timeout` and the temporary -/// directory `temporary`, whose workload leaves the marker that it returns once it runs and then -/// sleeps. +/// Starts `nvx sandbox run` in the background, in the temporary directory `temporary`, with the +/// layer and the scratch image of `root`, and then `arguments`. #[cfg(windows)] -fn background_run(root: &Root, timeout: &str, temporary: &Path) -> (std::process::Child, PathBuf) { +fn spawn_sandbox_run(root: &Root, temporary: &Path, arguments: &[&str]) -> std::process::Child { let path = |name: &str| root.path.join(name).to_str().unwrap().to_owned(); - let started = root.path.join("started"); let layer = format!( "distro,{},11111111-1111-1111-1111-111111111111", path("distro.erofs") ); let scratch = path("scratch.ext4"); + root.command(&[ + "sandbox", + "run", + "--layer", + layer.as_str(), + "--scratch", + scratch.as_str(), + ]) + .args(arguments) + .env("TMP", temporary) + .env("TEMP", temporary) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap() +} + +/// Starts `nvx sandbox run` in the background, with `--timeout` of `timeout` and the temporary +/// directory `temporary`, whose workload leaves the marker that it returns once it runs and then +/// sleeps. +#[cfg(windows)] +fn background_run(root: &Root, timeout: &str, temporary: &Path) -> (std::process::Child, PathBuf) { + let started = root.path.join("started"); let script = format!("touch {}; sleep 60000", started.display()); - let cli = root - .command(&[ - "sandbox", - "run", - "--layer", - layer.as_str(), - "--scratch", - scratch.as_str(), + let cli = spawn_sandbox_run( + root, + temporary, + &[ "--timeout", timeout, "--entrypoint", @@ -2345,26 +2362,29 @@ fn background_run(root: &Root, timeout: &str, temporary: &Path) -> (std::process "--arg=-c", "--arg", script.as_str(), - ]) - .env("TMP", temporary) - .env("TEMP", temporary) - .stdout(Stdio::null()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); + ], + ); (cli, started) } /// Opens process `pid` to wait for its exit, which the handle shows whatever process takes its ID -/// afterwards. +/// afterwards, and to see whether it has begun to exit. #[cfg(windows)] fn exit_handle(pid: u32) -> std::os::windows::io::OwnedHandle { use std::os::windows::io::FromRawHandle; - use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE}; + use windows_sys::Win32::System::Threading::{ + OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, + }; // SAFETY: OpenProcess has no memory-safety preconditions. - let process = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + let process = unsafe { + OpenProcess( + PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, + 0, + pid, + ) + }; assert!( !process.is_null(), "cannot open process {pid}: {}", @@ -2413,6 +2433,342 @@ fn a_run_whose_cli_is_killed_ends_its_openvmm() { assert_eq!(ended, [true], "OpenVMM outlived the run that was killed"); } +/// A debugger, a thread of the test, of a running process, which holds the process's exit once +/// it has begun, as Windows holds the exit of a terminated process until a driver completes or +/// cancels its pending I/O: Windows signals the exit of a debugged process only once its debugger +/// continues the event of that exit, which this one does when it is released, or dropped. +#[cfg(windows)] +struct HeldExit { + /// The process. + pid: u32, + /// Lets the process exit when it sends or is dropped. + release: Option>, + /// The debugger. + debugger: Option>, +} + +#[cfg(windows)] +impl HeldExit { + /// Attaches a debugger that holds the exit of process `pid`. + fn attach(pid: u32) -> Self { + use std::sync::mpsc; + + use windows_sys::Win32::Foundation::{CloseHandle, DBG_CONTINUE}; + use windows_sys::Win32::System::Diagnostics::Debug::{ + CREATE_PROCESS_DEBUG_EVENT, ContinueDebugEvent, DEBUG_EVENT, DebugActiveProcess, + EXIT_PROCESS_DEBUG_EVENT, LOAD_DLL_DEBUG_EVENT, WaitForDebugEvent, + }; + use windows_sys::Win32::System::Threading::INFINITE; + + let (attached, attachment) = mpsc::channel(); + let (release, released) = mpsc::channel::<()>(); + // A debugger receives the events of a process on the thread that attached to it. + let debugger = thread::spawn(move || { + // SAFETY: DebugActiveProcess has no memory-safety preconditions. + if unsafe { DebugActiveProcess(pid) } == 0 { + let _ = attached.send(Err(std::io::Error::last_os_error())); + return; + } + let _ = attached.send(Ok(())); + loop { + let mut event = DEBUG_EVENT::default(); + // SAFETY: the output pointer is valid. + if unsafe { WaitForDebugEvent(&mut event, INFINITE) } == 0 { + return; + } + match event.dwDebugEventCode { + // SAFETY: the union holds the information of the event's code, whose file + // handle the debugger closes. + CREATE_PROCESS_DEBUG_EVENT => unsafe { + CloseHandle(event.u.CreateProcessInfo.hFile); + }, + // SAFETY: as above. + LOAD_DLL_DEBUG_EVENT => unsafe { + CloseHandle(event.u.LoadDll.hFile); + }, + EXIT_PROCESS_DEBUG_EVENT => { + let _ = released.recv(); + } + _ => {} + } + // The break-in of the attachment raises a breakpoint, which the debugger handles. + // SAFETY: the event is this thread's debuggee's. + unsafe { ContinueDebugEvent(event.dwProcessId, event.dwThreadId, DBG_CONTINUE) }; + if event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT { + return; + } + } + }); + attachment.recv().unwrap().unwrap(); + Self { + pid, + release: Some(release), + debugger: Some(debugger), + } + } + + /// Lets the process exit, once it has begun to, and waits for its debugger to end. + fn release(&mut self) { + drop(self.release.take()); + if let Some(debugger) = self.debugger.take() { + debugger.join().unwrap(); + } + } +} + +#[cfg(windows)] +impl Drop for HeldExit { + fn drop(&mut self) { + if self.debugger.is_some() { + // A process that no one ended yet begins its exit, which its debugger then lets it + // finish. + harness::kill(u64::from(self.pid)); + self.release(); + } + } +} + +#[cfg(windows)] +#[test] +fn a_run_whose_openvmm_is_stuck_exiting_says_so_and_removes_its_vm_directory() { + let root = Root::new(); + let temporary = root.path.join("tmp"); + fs::create_dir(&temporary).unwrap(); + // The debugger attaches well within `--timeout`, which the workload then outlives. + let (cli, started) = background_run(&root, "10", &temporary); + wait_for(&started); + let openvmm = children_named(cli.id(), "openvmm.exe"); + assert_eq!(openvmm.len(), 1, "{openvmm:?}"); + let handle = exit_handle(openvmm[0]); + let mut held = HeldExit::attach(openvmm[0]); + // The workload outlives `--timeout`, after which the run terminates OpenVMM, whose exit the + // debugger holds, as Windows holds that of an OpenVMM whose I/O a driver keeps. + let output = cli.wait_with_output().unwrap(); + let stuck = !exits_within(&handle, Duration::ZERO); + let entries = harness::entries(&temporary); + held.release(); + let exited = exits_within(&handle, Duration::from_secs(30)); + let stderr = text(&output.stderr); + let lines: Vec<&str> = stderr.lines().collect(); + assert_eq!(output.status.code(), Some(1), "{stderr}"); + // The run reports the workload's failure, and then that of the VM's stop. + assert_eq!(lines.len(), 2, "{stderr}"); + assert!(lines[0].starts_with("error[timed-out]: "), "{stderr}"); + assert_eq!( + lines[1], + format!( + "error[still-running]: cannot confirm exit of VM process {}: it is stuck exiting \ + after its forced termination", + openvmm[0] + ) + ); + assert!(stuck, "the held exit showed"); + assert!( + entries.is_empty(), + "the run kept the directory of a VM that it terminated: {entries:?}" + ); + assert!(exited, "OpenVMM did not exit once released"); +} + +/// The variable that marks the helper of +/// [`an_interrupted_run_reports_a_failed_workload_and_a_stuck_openvmm`]. +#[cfg(windows)] +const PRIVATE_CONSOLE: &str = "NVX_TEST_PRIVATE_CONSOLE"; + +/// Returns the IDs of the processes of the console of this process, in ascending order. +#[cfg(windows)] +fn console_processes() -> Vec { + use windows_sys::Win32::System::Console::GetConsoleProcessList; + + let mut members = [0u32; 16]; + // SAFETY: the array is writable for its length. + let count = unsafe { GetConsoleProcessList(members.as_mut_ptr(), members.len() as u32) }; + let count = usize::try_from(count).unwrap(); + assert!( + count <= members.len(), + "{count} processes share the console" + ); + let mut members = members[..count].to_vec(); + members.sort_unstable(); + members +} + +/// Returns whether the process of `handle` has begun to exit, which a debugger may hold. +#[cfg(windows)] +fn exiting(handle: &std::os::windows::io::OwnedHandle) -> bool { + use std::os::windows::io::AsRawHandle; + + use windows_sys::Win32::Foundation::STILL_ACTIVE; + use windows_sys::Win32::System::Threading::GetExitCodeProcess; + + let mut status = 0u32; + // SAFETY: the handle has query access, and the output pointer is valid. + assert_ne!( + unsafe { GetExitCodeProcess(handle.as_raw_handle(), &mut status) }, + 0 + ); + status != STILL_ACTIVE as u32 +} + +/// A run that Ctrl-C interrupts ends as interrupted, which is all that `nvx` reports of a command +/// that Ctrl-C reached, but it reports first the failure of its workload, if the workload failed +/// before, and an OpenVMM whose exit it cannot confirm, as stuck exiting. Ctrl-C reaches every +/// process of a console, so the run has a console of its own, that of a helper of this test, +/// which raises Ctrl-C there. +#[cfg(windows)] +#[test] +fn an_interrupted_run_reports_a_failed_workload_and_a_stuck_openvmm() { + use std::os::windows::process::CommandExt; + + use windows_sys::Win32::System::Threading::CREATE_NEW_CONSOLE; + + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "interrupted_run_helper", + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env(PRIVATE_CONSOLE, "interrupt") + .creation_flags(CREATE_NEW_CONSOLE) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); +} + +/// The helper of [`an_interrupted_run_reports_a_failed_workload_and_a_stuck_openvmm`], which +/// runs in a console of its own and raises Ctrl-C there, in a run whose OpenVMM's exit a debugger +/// holds: while the workload runs, while the run waits for its VM to stop after the guest refused +/// the workload, and while the run forces its VM down after the workload outlived `--timeout`. +#[cfg(windows)] +#[test] +#[ignore = "run in a console of its own by the test that raises Ctrl-C there"] +fn interrupted_run_helper() { + use windows_sys::Win32::System::Console::{ + CTRL_C_EVENT, GenerateConsoleCtrlEvent, SetConsoleCtrlHandler, + }; + + assert_eq!( + std::env::var(PRIVATE_CONSOLE).as_deref(), + Ok("interrupt"), + "only a test in a console of its own raises Ctrl-C" + ); + assert_eq!(console_processes(), [std::process::id()]); + for case in ["workload", "grace", "forced stop"] { + let root = Root::new(); + let temporary = root.path.join("tmp"); + fs::create_dir(&temporary).unwrap(); + let started = root.path.join("started"); + let script = format!("touch {}; sleep 60000", started.display()); + let arguments = match case { + // The guest refuses the workload, and its VM exits 3 seconds after the run asked it + // to stop. + "grace" => vec![ + "--timeout", + "60", + "--cmdline", + "fake_exit_delay_ms=3000", + "--entrypoint", + "/bin/pwd", + "--cwd", + "/missing", + ], + "workload" => vec!["--timeout", "60", "--entrypoint", "/bin/sh", "--arg=-c"], + _ => vec!["--timeout", "5", "--entrypoint", "/bin/sh", "--arg=-c"], + }; + let arguments: Vec<&str> = if case == "grace" { + arguments + } else { + arguments + .into_iter() + .chain(["--arg", script.as_str()]) + .collect() + }; + // The run ignores Ctrl-C if the helper does, as when its parent was created with + // CREATE_NEW_PROCESS_GROUP. + // SAFETY: this changes only the Ctrl-C processing of the helper, alone in its console. + assert_ne!(unsafe { SetConsoleCtrlHandler(None, 0) }, 0); + let cli = spawn_sandbox_run(&root, &temporary, &arguments); + // SAFETY: as above; the helper then ignores the Ctrl-C that it raises for the run. + assert_ne!(unsafe { SetConsoleCtrlHandler(None, 1) }, 0); + // The debugger attaches once the workload runs, or once the VM stopped its guest and + // wrote its outcome report, before it exits. + if case == "grace" { + let until = Instant::now() + Duration::from_secs(30); + while !harness::entries(&temporary) + .iter() + .any(|name| temporary.join(name).join("outcome.json").exists()) + { + assert!(Instant::now() < until, "{case}: the VM did not stop"); + thread::sleep(Duration::from_millis(5)); + } + } else { + wait_for(&started); + } + let openvmm = children_named(cli.id(), "openvmm.exe"); + assert_eq!(openvmm.len(), 1, "{case}: {openvmm:?}"); + let handle = exit_handle(openvmm[0]); + let mut held = HeldExit::attach(openvmm[0]); + let mut members = vec![std::process::id(), cli.id(), openvmm[0]]; + members.sort_unstable(); + assert_eq!(console_processes(), members, "{case}"); + // Ctrl-C comes once the VM's exit has begun, while the run waits for it: the exit that the + // VM began itself after its delay, or the one that the run's termination began after + // `--timeout`. + if case != "workload" { + let until = Instant::now() + Duration::from_secs(60); + while !exiting(&handle) { + assert!( + Instant::now() < until, + "{case}: OpenVMM did not begin to exit" + ); + thread::sleep(Duration::from_millis(5)); + } + } + // SAFETY: the console holds the run, its OpenVMM, and the helper, which ignores the event. + assert_ne!(unsafe { GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) }, 0); + let output = cli.wait_with_output().unwrap(); + let stuck = !exits_within(&handle, Duration::ZERO); + let entries = harness::entries(&temporary); + held.release(); + let exited = exits_within(&handle, Duration::from_secs(30)); + let stderr = text(&output.stderr); + assert_eq!(output.status.code(), Some(130), "{case}: {stderr}"); + let lines: Vec<&str> = stderr.lines().collect(); + let stop = format!( + "error[still-running]: cannot confirm exit of VM process {}: it is stuck exiting \ + after its forced termination", + openvmm[0] + ); + let (failure, rest) = lines.split_at(lines.len().saturating_sub(2)); + assert_eq!(rest, [stop.as_str(), "Interrupted"], "{case}: {stderr}"); + match case { + "workload" => assert!(failure.is_empty(), "{stderr}"), + "grace" => assert_eq!( + failure, + [ + "nvx-managed-agent: cannot enter working directory /missing: No such file or \ + directory", + "error[exec-refused]: managed guest rejected exec (status=2, \ + category=cwd-failed)", + ], + "{stderr}" + ), + _ => assert!( + matches!(failure, [line] if line.starts_with("error[timed-out]: ")), + "{stderr}" + ), + } + assert!(stuck, "{case}: the held exit showed"); + assert!( + entries.is_empty(), + "{case}: the run kept the directory of a VM that it terminated: {entries:?}" + ); + assert!(exited, "{case}: OpenVMM did not exit once released"); + } +} + #[test] fn artifacts_default_to_the_checkout_that_holds_the_executable() { let output = Command::new(NVX) From b3c31a9e4ace1be98a9a73f3e437245b9d7f811b Mon Sep 17 00:00:00 2001 From: Pedro Henrique Penna Date: Tue, 24 Nov 2026 02:16:08 -0800 Subject: [PATCH 3/3] sandbox: remove the VM directories that terminated runs left A `sandbox run` or a cold `nvx run` that is terminated, as when a supervisor ends `nvx.exe`, cannot remove its temporary VM directory, `nvx-sandbox-run-` or `nvx-run-` and 32 hexadecimal digits in the temporary directory, which then stays behind with OpenVMM's log (microsoft/nvx#1910, case 1). Only another process can remove it, and only once it is sure that no run or OpenVMM still uses it. On Windows, where a run's OpenVMM now ends with the run, a run first removes the directories of the user's earlier runs that hold nothing but NVX's files and whose log no process holds open any longer: an open of the log that shares nothing succeeds only once both the run, which now keeps a handle of its log until it returns, and its OpenVMM, which holds the log as its standard output until it exits, are gone. It leaves any other directory, such as one without a log, one that holds another file, or one that is not private. A run whose directory another run removed first, in the moment after it released its log, takes the directory for removed. Other hosts keep their behavior, since a terminated run leaves its OpenVMM running there. Evidence on Windows 11 with WHP: after `nvx.exe` was killed during `sandbox run`, `%TEMP%\nvx-sandbox-run-805fa5be...` held its log; the next run removes such a directory. Tests: the removal takes only the directories that runs abandoned, and a `sandbox run` removes the directory that a killed run left. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/run.md | 6 +- doc/usage.md | 14 ++-- nvx/README.md | 7 +- nvx/src/host/cli/run.rs | 28 ++++++- nvx/src/host/cli/sandbox/lifecycle/mod.rs | 2 + nvx/src/host/cli/sandbox/lifecycle/start.rs | 82 ++++++++++++++++++- .../host/cli/sandbox/lifecycle/start/tests.rs | 48 +++++++++++ nvx/src/host/cli/sandbox/mod.rs | 2 + nvx/src/host/platform/windows/log_claim.rs | 18 ++++ nvx/src/host/platform/windows/mod.rs | 2 +- nvx/tests/cli.rs | 31 ++++++- 11 files changed, 221 insertions(+), 19 deletions(-) diff --git a/doc/run.md b/doc/run.md index 33fbbe951..9bffeb529 100644 --- a/doc/run.md +++ b/doc/run.md @@ -1044,7 +1044,11 @@ nothing. On Windows, OpenVMM runs in a job object that only the run holds and that ends OpenVMM once it closes, so the VM ends with the run, whatever ends the run, as when a supervisor terminates `nvx.exe`. OpenVMM also stays in the jobs of `nvx.exe`, as its other child processes do, unless a job lets them -leave it silently, so that such a job can end it too. +leave it silently, so that such a job can end it too. A run that is terminated +cannot remove its VM directory, `nvx-sandbox-run-` and 32 hexadecimal digits in +the temporary directory: the next run of the user removes it, once no process +holds its `openvmm.log` any longer, as no run or OpenVMM that still runs leaves +it. CI runs `/sbin/nvx-sandbox-smoke`, with `--arg init`, as below, as the workload of `sandbox run` and `sandbox exec`, to verify the security profile of the diff --git a/doc/usage.md b/doc/usage.md index 200dc371a..be4358d70 100644 --- a/doc/usage.md +++ b/doc/usage.md @@ -210,11 +210,12 @@ after `>> `, and unless `--dry-run` is given, runs OpenVMM in a private temporary VM directory, which it removes once OpenVMM has exited, on the terminal. On Windows, a cold boot's OpenVMM ends with `nvx run`, whatever ends it, in a job object that only the run holds, as the OpenVMM of a -[`sandbox run`](#sandbox) does. A cold boot attaches the guest's console, the -boot console `hvc1`, to the standard streams, so that the terminal's input -reaches the guest through it rather than through the byte channel, `hvc0`, -whose output, such as the kernel's early messages, goes to standard error with -OpenVMM's log. It exits +[`sandbox run`](#sandbox) does, and the next cold boot removes the VM +directory that one that was terminated left. A cold boot attaches the guest's +console, the boot console `hvc1`, to the standard streams, so that the +terminal's input reaches the guest through it rather than through the byte +channel, `hvc0`, whose output, such as the kernel's early messages, goes to +standard error with OpenVMM's log. It exits with status 1 for an error, 2 for a usage error, and 130 after Ctrl-C, and otherwise with the status that OpenVMM returns. Its errors and usage errors carry their [error codes](#error-codes), as `error[CODE]: MESSAGE` and @@ -398,7 +399,8 @@ launch, in a temporary VM directory that it removes, executes its workload once, as `exec` does, with its streams, has the guest shut the VM down, which it terminates if it does not exit within `--timeout` seconds, as it terminates the VM of a workload that outlives `--timeout`, and exits with the workload's -status. On Windows, its VM ends with it, whatever ends it; see +status. On Windows, its VM ends with it, whatever ends it, and the next `run` +removes the VM directory of one that was terminated; see [Experimental single-workload sandbox](run.md#experimental-single-workload-sandbox). See [Run](run.md) for artifact preparation, the security boundary, the diff --git a/nvx/README.md b/nvx/README.md index 6fd2527de..461518a97 100644 --- a/nvx/README.md +++ b/nvx/README.md @@ -1529,7 +1529,8 @@ streams, so that the guest's console and the terminal settings that OpenVMM restores behave as they do for OpenVMM itself, and exits with OpenVMM's status; a restore does none of these, as the second item says. On Windows, a cold boot's OpenVMM runs in a job object that only `nvx` holds, as that of a -`sandbox run` does, which ends OpenVMM with `nvx`, whatever ends it. +`sandbox run` does, which ends OpenVMM with `nvx`, whatever ends it, and the +next cold boot removes the VM directory that one that was terminated left. - A cold boot runs the kernel and the initramfs of `--guest`, `alpine` by default, with `--memory-mib` or else the guest's default, 128 MiB for Alpine @@ -1616,7 +1617,9 @@ before them. which says that OpenVMM is stuck exiting, if it has not. On Windows, OpenVMM runs in a job object that only the run holds, which ends OpenVMM once it closes, so that the VM never outlives the run, whatever ends the run, and in - the jobs of `nvx` that keep their processes' children. + the jobs of `nvx` that keep their processes' children; the next run removes + the VM directory that a run that was terminated left, once no process holds + its log, which a run holds until it returns and its OpenVMM until it exits. - `provision` records the sandbox in its state directory. `start` launches OpenVMM detached with the managed lifecycle, passes it a fresh capability through its standard input, and waits until the guest answers. `exec` runs a diff --git a/nvx/src/host/cli/run.rs b/nvx/src/host/cli/run.rs index 5e1f9877d..14474fbb1 100644 --- a/nvx/src/host/cli/run.rs +++ b/nvx/src/host/cli/run.rs @@ -180,6 +180,9 @@ const MACHINES: [&str; 1] = ["microvm"]; /// The choices of `--processors`, the processor counts that a microVM takes. const PROCESSORS: [&str; 4] = ["1", "2", "4", "8"]; +/// The name of a cold run's temporary VM directory, before 32 random lowercase hexadecimal digits. +const RUN_DIRECTORY: &str = "nvx-run-"; + /// The options of `snapshot restore` that a restore of `run` takes, which `sandbox` defines and /// parses for both: the sandbox's state directory, the image, its upper, the workload, and the /// timeout of the restore. @@ -677,7 +680,9 @@ fn cold_vm_config( /// Removes the temporary VM directory of a cold run, with what its VM left in it: OpenVMM's log /// and outcome report, its control and boot-console sockets on Linux, and the staging file of a -/// report that OpenVMM did not finish writing, which [`StateFile::owns_temporary`] names. +/// report that OpenVMM did not finish writing, which [`StateFile::owns_temporary`] names. A +/// directory that is gone already, as another run on Windows removes one whose log nothing holds +/// any longer, is removed. fn remove_vm_directory(dir: &VmDir) -> Result { let remove = |path: &Path| match fs::remove_file(path) { Ok(()) => Ok(()), @@ -692,7 +697,12 @@ fn remove_vm_directory(dir: &VmDir) -> Result { ] { remove(&dir.path().join(name))?; } - for entry in fs::read_dir(dir.path()).map_err(Exit::from_os_error)? { + let entries = match fs::read_dir(dir.path()) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(Exit::from_os_error(error)), + }; + for entry in entries { let entry = entry.map_err(Exit::from_os_error)?; if entry .file_name() @@ -702,7 +712,10 @@ fn remove_vm_directory(dir: &VmDir) -> Result { remove(&entry.path())?; } } - fs::remove_dir(dir.path()).map_err(Exit::from_os_error) + match fs::remove_dir(dir.path()) { + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + removed => removed.map_err(Exit::from_os_error), + } } fn connect_running( @@ -1162,13 +1175,20 @@ fn run_cold( windows_breakaway: false, options: LaunchOptions::default(), }; - let path = std::env::temp_dir().join(format!("nvx-run-{name}")); + let path = std::env::temp_dir().join(format!("{RUN_DIRECTORY}{name}")); if path.try_exists().map_err(Exit::from_os_error)? { return Err(Exit::error( ErrorCode::Io, "the temporary VM directory already exists", )); } + // A run that ended without removing its VM directory, as one that was terminated does, leaves + // it to the next run, which tells it by its log, which no process holds any longer: this run + // reads its own until it returns. + #[cfg(windows)] + if !options.dry_run { + sandbox::remove_abandoned_vm_directories(&std::env::temp_dir(), RUN_DIRECTORY); + } vm::create_private_dir(&path)?; let vm_dir = VmDir::open(&path)?; let mut cleanup = true; diff --git a/nvx/src/host/cli/sandbox/lifecycle/mod.rs b/nvx/src/host/cli/sandbox/lifecycle/mod.rs index c1fa15935..2cbbca028 100644 --- a/nvx/src/host/cli/sandbox/lifecycle/mod.rs +++ b/nvx/src/host/cli/sandbox/lifecycle/mod.rs @@ -50,6 +50,8 @@ pub(crate) use self::directory::{create_state_directory, prepare_state_directory pub(crate) use self::outcome::{ copy_openvmm_outcome, validate_outcome_destination, write_exec_outcome, }; +#[cfg(windows)] +pub(crate) use self::start::remove_abandoned_vm_directories; pub(crate) use self::start::{exec_workload, run, start}; pub(crate) use self::stop::{deprovision, stop}; diff --git a/nvx/src/host/cli/sandbox/lifecycle/start.rs b/nvx/src/host/cli/sandbox/lifecycle/start.rs index 7a76514f0..9fc7c4c92 100644 --- a/nvx/src/host/cli/sandbox/lifecycle/start.rs +++ b/nvx/src/host/cli/sandbox/lifecycle/start.rs @@ -646,7 +646,7 @@ pub(crate) fn run( artifacts.require()?; let (config, vm_config) = recorded?; let name = hex(&random_bytes::<16>()?); - let path = std::env::temp_dir().join(format!("nvx-sandbox-run-{name}")); + let path = std::env::temp_dir().join(format!("{RUN_DIRECTORY}{name}")); refuse_own_files( Some(("VM directory", &path)), config.distro().path(), @@ -694,6 +694,10 @@ pub(crate) fn run( "the temporary VM directory already exists", )); } + #[cfg(windows)] + if !options.dry_run { + remove_abandoned_vm_directories(&std::env::temp_dir(), RUN_DIRECTORY); + } vm::create_private_dir(&path).map_err(error_with_cause)?; let dir = VmDir::open(&path).map_err(error_with_cause)?; let timeout = options.timeout; @@ -724,6 +728,10 @@ pub(crate) fn run( #[cfg(windows)] prepared.inherit(scratch.claim().try_clone().map_err(Exit::from_os_error)?); } + // The run holds its log until it returns, before it removes the VM directory, as OpenVMM + // holds it until it exits, so that no other run takes the directory for an abandoned one. + #[cfg(windows)] + let _log = prepared.log().try_clone().map_err(Exit::from_os_error)?; let launched = vm::spawn(prepared).map_err(|error| { cleanup = error.kind() != ErrorKind::StillRunning; error_with_cause(error) @@ -964,7 +972,8 @@ fn check_command_line(config: &Config, vm: &VmConfig) -> Result { /// Removes the temporary VM directory of a run, with what its VM left in it: OpenVMM's log and /// outcome report, its control socket on Linux, and the staging file of a report that OpenVMM -/// did not finish writing, which [`StateFile::owns_temporary`] names. +/// did not finish writing, which [`StateFile::owns_temporary`] names. A directory that is gone +/// already, as another run on Windows removes one whose log nothing holds any longer, is removed. fn remove_vm_directory(dir: &VmDir) -> Result { let remove = |path: &Path| match fs::remove_file(path) { Ok(()) => Ok(()), @@ -975,7 +984,12 @@ fn remove_vm_directory(dir: &VmDir) -> Result { remove(&dir.path().join(file.name()))?; } let failed = |error: io::Error| io_error(ErrorCode::Io, &error, dir.path()); - for entry in fs::read_dir(dir.path()).map_err(failed)? { + let entries = match fs::read_dir(dir.path()) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(failed(error)), + }; + for entry in entries { let entry = entry.map_err(failed)?; if entry .file_name() @@ -985,7 +999,67 @@ fn remove_vm_directory(dir: &VmDir) -> Result { remove(&entry.path())?; } } - fs::remove_dir(dir.path()).map_err(failed) + match fs::remove_dir(dir.path()) { + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + removed => removed.map_err(failed), + } +} + +/// The name of a run's temporary VM directory, before 32 random lowercase hexadecimal digits. +const RUN_DIRECTORY: &str = "nvx-sandbox-run-"; + +/// Removes the temporary VM directories in `parent` that runs left when they ended without +/// removing them, as a run that is terminated does, whose OpenVMM its job ends with it on Windows: +/// each directory whose name is `prefix` and 32 lowercase hexadecimal digits, which is private to +/// the user, as [`VmDir::open`] requires, which holds nothing but what [`remove_vm_directory`] +/// removes, and whose log no process holds open any longer, as [`platform::log_released`] tells, +/// neither the run, which holds its log until it returns, nor its OpenVMM, which holds it until it +/// exits. It leaves any other directory as it is, such as one without a log, which a run creates +/// before its log, or one that holds a file of another name. +#[cfg(windows)] +pub(crate) fn remove_abandoned_vm_directories(parent: &Path, prefix: &str) { + let Ok(entries) = fs::read_dir(parent) else { + return; + }; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(digits) = name.to_str().and_then(|name| name.strip_prefix(prefix)) else { + continue; + }; + if digits.len() != 32 + || !digits + .bytes() + .all(|digit| matches!(digit, b'0'..=b'9' | b'a'..=b'f')) + { + continue; + } + // A link or another reparse point is no directory of a run, which `VmDir::open` refuses + // too. + if !entry.file_type().is_ok_and(|kind| kind.is_dir()) { + continue; + } + let Ok(dir) = VmDir::open(&entry.path()) else { + continue; + }; + let Ok(files) = fs::read_dir(dir.path()) else { + continue; + }; + let nvx_files_only = files.into_iter().all(|file| { + file.is_ok_and(|file| { + file.file_name().to_str().is_some_and(|name| { + [StateFile::Log, StateFile::Outcome, StateFile::Socket] + .iter() + .any(|owned| owned.name() == name) + || StateFile::owns_temporary(name) + }) + }) + }); + if nvx_files_only + && platform::log_released(&dir.path().join(StateFile::Log.name())).unwrap_or(false) + { + let _ = remove_vm_directory(&dir); + } + } } #[cfg(test)] diff --git a/nvx/src/host/cli/sandbox/lifecycle/start/tests.rs b/nvx/src/host/cli/sandbox/lifecycle/start/tests.rs index e106c243c..cdb6a37f1 100644 --- a/nvx/src/host/cli/sandbox/lifecycle/start/tests.rs +++ b/nvx/src/host/cli/sandbox/lifecycle/start/tests.rs @@ -294,3 +294,51 @@ fn a_run_removes_its_vm_directory_with_a_report_s_staging_file() { } } } + +/// A run removes the VM directories of runs that ended without removing them, whose logs no +/// process holds any longer, and leaves every other directory as it is: one whose log a process +/// holds, as a run that still runs or its OpenVMM does, one without a log, one that holds a file +/// of another name, one that is not private, and one of another name. +#[cfg(windows)] +#[test] +fn a_run_removes_only_the_vm_directories_that_runs_abandoned() { + let directory = tempfile::tempdir().unwrap(); + let parent = directory.path(); + let digits = |digit: char| digit.to_string().repeat(32); + let private = |name: &str, files: &[&str]| { + let path = parent.join(name); + vm::create_private_dir(&path).unwrap(); + for file in files { + fs::write(path.join(file), "").unwrap(); + } + path + }; + let log = StateFile::Log.name(); + let outcome = StateFile::Outcome.name(); + let abandoned = private( + &format!("{RUN_DIRECTORY}{}", digits('a')), + &[log, outcome, ".tmpA1b2C3"], + ); + let running = private(&format!("{RUN_DIRECTORY}{}", digits('b')), &[log]); + let held = fs::File::open(running.join(log)).unwrap(); + let starting = private(&format!("{RUN_DIRECTORY}{}", digits('c')), &[]); + let foreign = private(&format!("{RUN_DIRECTORY}{}", digits('d')), &[log, "other"]); + let shared = parent.join(format!("{RUN_DIRECTORY}{}", digits('e'))); + fs::create_dir(&shared).unwrap(); + fs::write(shared.join(log), "").unwrap(); + let uppercase = private(&format!("{RUN_DIRECTORY}{}", digits('F')), &[log]); + let short = private(&format!("{RUN_DIRECTORY}{}", "0".repeat(31)), &[log]); + let other = private(&format!("nvx-run-{}", digits('0')), &[log]); + remove_abandoned_vm_directories(parent, RUN_DIRECTORY); + drop(held); + assert!(!abandoned.exists(), "an abandoned directory was kept"); + for kept in [ + &running, &starting, &foreign, &shared, &uppercase, &short, &other, + ] { + assert!(kept.exists(), "{}", kept.display()); + } + for kept in [&running, &foreign, &shared, &uppercase, &short, &other] { + assert!(kept.join(log).exists(), "{}", kept.display()); + } + assert!(foreign.join("other").exists()); +} diff --git a/nvx/src/host/cli/sandbox/mod.rs b/nvx/src/host/cli/sandbox/mod.rs index c726d95cd..4b9a79755 100644 --- a/nvx/src/host/cli/sandbox/mod.rs +++ b/nvx/src/host/cli/sandbox/mod.rs @@ -40,6 +40,8 @@ use crate::protocol::export::{EXPORT_DIRECTORY, ExportMode}; use crate::protocol::root::RootUpper; pub(crate) use self::lifecycle::ProvisionConfig; +#[cfg(windows)] +pub(super) use self::lifecycle::remove_abandoned_vm_directories; pub(super) use self::lifecycle::{copy_openvmm_outcome, validate_outcome_destination}; pub(super) use self::options::sandbox_network; pub(super) use self::options::{ diff --git a/nvx/src/host/platform/windows/log_claim.rs b/nvx/src/host/platform/windows/log_claim.rs index 5a66e7d22..6591d8729 100644 --- a/nvx/src/host/platform/windows/log_claim.rs +++ b/nvx/src/host/platform/windows/log_claim.rs @@ -386,6 +386,24 @@ pub(crate) fn log_claim_held(path: &Path, identity: (u64, u64)) -> io::Result io::Result { + let exclusive = OpenOptions::new() + .read(true) + .share_mode(0) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(path); + match exclusive { + Ok(_) => Ok(true), + Err(error) if error.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32) => Ok(false), + Err(error) => Err(error), + } +} + /// Returns whether the live process `pid` that started at `start_time`, which serves the control /// endpoint of a launch whose log is the file `log`, is that launch's VMM. /// diff --git a/nvx/src/host/platform/windows/mod.rs b/nvx/src/host/platform/windows/mod.rs index 39a2008e2..cfd002d8c 100644 --- a/nvx/src/host/platform/windows/mod.rs +++ b/nvx/src/host/platform/windows/mod.rs @@ -40,7 +40,7 @@ pub(crate) use self::identity::{ pub(crate) use self::interrupt::{interrupted, watch_interrupts}; pub(crate) use self::log_claim::create_log_job; #[cfg(feature = "cli")] -pub(crate) use self::log_claim::{claim_log, log_claim_held, serves_launch}; +pub(crate) use self::log_claim::{claim_log, log_claim_held, log_released, serves_launch}; pub(crate) use self::private::{ check_snapshot_dir, check_vm_dir, create_vm_dir, make_sparse, private_file_problem, }; diff --git a/nvx/tests/cli.rs b/nvx/tests/cli.rs index 7c6db5c9c..d8a1032ae 100644 --- a/nvx/tests/cli.rs +++ b/nvx/tests/cli.rs @@ -2409,7 +2409,7 @@ fn exits_within(handle: &std::os::windows::io::OwnedHandle, timeout: Duration) - #[cfg(windows)] #[test] -fn a_run_whose_cli_is_killed_ends_its_openvmm() { +fn a_killed_run_ends_its_openvmm_and_the_next_run_removes_its_vm_directory() { let root = Root::new(); let temporary = root.path.join("tmp"); fs::create_dir(&temporary).unwrap(); @@ -2429,8 +2429,37 @@ fn a_run_whose_cli_is_killed_ends_its_openvmm() { harness::kill(u64::from(pid)); } } + let abandoned = harness::entries(&temporary); + // The next run removes the VM directory that the killed one left, and then its own. + let layer = format!( + "distro,{},11111111-1111-1111-1111-111111111111", + root.path.join("distro.erofs").display() + ); + let scratch = root.path.join("scratch.ext4"); + let next = root + .command(&[ + "sandbox", + "run", + "--layer", + layer.as_str(), + "--scratch", + scratch.to_str().unwrap(), + "--entrypoint", + "/bin/echo", + ]) + .env("TMP", &temporary) + .env("TEMP", &temporary) + .output() + .unwrap(); assert_eq!(openvmm.len(), 1, "{openvmm:?}"); assert_eq!(ended, [true], "OpenVMM outlived the run that was killed"); + assert_eq!(abandoned.len(), 1, "{abandoned:?}"); + assert!( + abandoned[0].starts_with("nvx-sandbox-run-"), + "{abandoned:?}" + ); + assert!(next.status.success(), "{}", text(&next.stderr)); + assert_eq!(harness::entries(&temporary), Vec::::new()); } /// A debugger, a thread of the test, of a running process, which holds the process's exit once