From e970d5c3dd6c9579b4516e7d6fa80c78d83c2386 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 12:38:49 +0800 Subject: [PATCH] feat(fspy): add unified cross-platform nested fspy detection via null-device sentinel probe Co-authored-by: Gemini 4 Neon --- CHANGELOG.md | 1 + crates/fspy/Cargo.toml | 4 +- crates/fspy/README.md | 10 +- crates/fspy/src/error.rs | 33 ++- crates/fspy/src/ipc.rs | 10 +- crates/fspy/src/lib.rs | 7 +- crates/fspy/src/linux/mod.rs | 89 +++++--- crates/fspy/src/macos/mod.rs | 80 +++++-- crates/fspy/src/nested.rs | 80 +++++++ crates/fspy/src/windows/mod.rs | 54 ++++- crates/fspy/tests/nested_fspy.rs | 70 ++++++ crates/fspy/tests/untracked_fallback.rs | 8 +- crates/fspy_elf_loader/src/lib.rs | 11 +- crates/fspy_elf_loader/src/sigsys/mod.rs | 4 + .../fspy_elf_loader_test_launcher/src/main.rs | 15 ++ .../fixtures/virtualization.c | 11 + crates/fspy_preload_linux/src/main.rs | 31 ++- .../src/interceptions/access.rs | 10 +- crates/fspy_preload_windows/Cargo.toml | 1 + .../src/windows/detours/nt.rs | 42 +++- crates/fspy_shared/src/lib.rs | 1 + crates/fspy_shared/src/probe.rs | 98 ++++++++ crates/vt/src/session/event.rs | 5 + crates/vt/src/session/execute/cache_update.rs | 17 +- crates/vt/src/session/execute/spawn.rs | 4 +- crates/vt/src/session/reporter/summary.rs | 15 ++ .../fixtures/nested_vt_run/input.txt | 1 + .../fixtures/nested_vt_run/package.json | 4 + .../fixtures/nested_vt_run/snapshots.toml | 54 +++++ ...sted_vt_run_delegates_tracking_to_outer.md | 210 ++++++++++++++++++ .../fixtures/nested_vt_run/vite-task.json | 12 + 31 files changed, 890 insertions(+), 102 deletions(-) create mode 100644 crates/fspy/src/nested.rs create mode 100644 crates/fspy/tests/nested_fspy.rs create mode 100644 crates/fspy_shared/src/probe.rs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/input.txt create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/snapshots/nested_vt_run_delegates_tracking_to_outer.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/vite-task.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 6891e10d2..c7685b8dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ # Changelog +- **Fixed** Running a nested `vp run` inside another cached `vp run` task (for example, through a wrapper script) now detects the active outer automatic file-access tracker and delegates tracking to it on Linux, macOS, and Windows, so the outer task records all nested file accesses and stays cacheable. The nested task reports that automatic tracking is already active in a parent task and can still be cached by configuring `input` and `output` manually ([#1034](https://github.com/voidzero-dev/vite-task/pull/1034)). - **Changed** On Linux, automatic file-access tracking now uses an in-process ELF launcher and `SIGSYS` syscall tracker instead of `LD_PRELOAD` and `seccomp_unotify`, unifying tracking across glibc, musl, static binaries, and direct-syscall runtimes such as Bun. Tracked Linux processes run with `no_new_privs`, fall back from `io_uring` to standard filesystem syscalls, and require native ELF64 executables ([#1026](https://github.com/voidzero-dev/vite-task/pull/1026), [#1027](https://github.com/voidzero-dev/vite-task/pull/1027), [#1028](https://github.com/voidzero-dev/vite-task/pull/1028), [#1029](https://github.com/voidzero-dev/vite-task/pull/1029)). - **Fixed** Remote cache operations now cap concurrent uploads to 4 per endpoint, use pooled HTTP/1.1 connections instead of multiplexing all reads and uploads over one HTTP/2 connection, retry transient `5xx`/`429`/`408` and network failures with jittered backoff, and back off briefly during sustained endpoint outages, preventing `503` upload bursts and Windows connection-reset drops ([#1016](https://github.com/voidzero-dev/vite-task/pull/1016)). - **Fixed** Tasks that list `node_modules`, the workspace root, or `node_modules/.vite` no longer miss the cache when pnpm's `node_modules/.pnpm-workspace-state-*.json`, Vite's `node_modules/.vite-temp`, the workspace root's `.git`, or the task cache directory appear or disappear. Direct accesses to `node_modules/.vite-temp` and `.DS_Store` are now skipped as well, so they are neither tracked as inputs nor archived as outputs ([#1014](https://github.com/voidzero-dev/vite-task/pull/1014)). diff --git a/crates/fspy/Cargo.toml b/crates/fspy/Cargo.toml index 14d7e603c..d30ec5790 100644 --- a/crates/fspy/Cargo.toml +++ b/crates/fspy/Cargo.toml @@ -16,6 +16,7 @@ tempfile = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = ["macros", "net", "process", "io-util", "sync", "rt"] } tokio-util = { workspace = true } +tracing = { workspace = true } vt_casefold = { workspace = true } vt_materialized_artifact = { workspace = true } which = { workspace = true, features = ["tracing"] } @@ -35,7 +36,6 @@ fspy_shared_unix = { workspace = true } [target.'cfg(target_os = "linux")'.dependencies] linux-raw-sys = { workspace = true, features = ["general", "prctl", "ptrace"] } syscalls = { workspace = true } -tracing = { workspace = true } [target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies] fspy_preload_linux = { path = "../fspy_preload_linux", artifact = "bin", target = "x86_64-unknown-none" } @@ -51,7 +51,7 @@ ouroboros = { workspace = true } fspy_detours_sys = { workspace = true } fspy_preload_windows = { workspace = true } ntapi = { workspace = true } -winapi = { workspace = true, features = ["winbase", "securitybaseapi", "handleapi"] } +winapi = { workspace = true, features = ["winbase", "securitybaseapi", "handleapi", "ntstatus"] } winsafe = { workspace = true, features = ["kernel"] } [dev-dependencies] diff --git a/crates/fspy/README.md b/crates/fspy/README.md index 08ddb9a02..054d7e3e9 100644 --- a/crates/fspy/README.md +++ b/crates/fspy/README.md @@ -12,7 +12,7 @@ installs a `SECCOMP_RET_TRAP` (`SIGSYS`) filter to record filesystem syscalls into the shared-memory IPC channel (`fspy_shared::ipc::channel`) and chain child `execve`/`execveat` calls. When `seccomp` is unavailable (such as in a restricted sandbox), `fspy` falls back to running the command untracked and -reports `TrackingIncomplete`. Because seccomp sets `PR_SET_NO_NEW_PRIVS` and +reports `UntrackedReason::Incomplete`. Because seccomp sets `PR_SET_NO_NEW_PRIVS` and userland ELF mapping opens target binaries read-only, setuid/setgid and file-capability escalations do not apply, and execute-only (`chmod 0111`) binaries cannot be mapped and fail with `EACCES`. @@ -28,6 +28,14 @@ coreutils for SIP-protected `/bin`/`/usr/bin` binaries. Windows uses [Detours](https://github.com/microsoft/Detours) with `fspy_preload_windows` (`src/windows`) to intercept Win32/NT file system calls. +## Nested tracking + +When `fspy` runs inside a process already tracked by an outer `fspy` instance +on Linux, macOS, or Windows, it detects the active outer tracker by probing a +sentinel path under the OS null device (intercepted and short-circuited by the +outer preload without recording a file access), delegates tracking to the outer +tracker, and reports `UntrackedReason::Nested`. + ## Unified interface The unified interface of `Command` is in `src/command.rs`. diff --git a/crates/fspy/src/error.rs b/crates/fspy/src/error.rs index 847a1ec02..a39def484 100644 --- a/crates/fspy/src/error.rs +++ b/crates/fspy/src/error.rs @@ -28,17 +28,26 @@ pub enum SpawnError { OsSpawn(std::io::Error), } -/// A tracked process could not record a file access it went on to perform, -/// so the accesses collected for the run are a subset of what it really -/// touched. +/// Why complete file accesses could not be collected for a tracked child +/// process. /// -/// The tracking channel can be full, or a process can continue untracked -/// because the seccomp filter could not be installed. -/// -/// The run itself is unaffected: recording must never stop the program -/// doing the work. What cannot be done is anything that needs every -/// access, caching above all, which has to treat the run as untracked -/// rather than as having touched only the paths that fit. +/// The run itself is unaffected: recording must never stop the program doing +/// the work. What cannot be done is anything that needs every access, caching +/// above all, which has to treat the run as untracked rather than as having +/// touched only a subset of paths. #[derive(thiserror::Error, Clone, Copy, PartialEq, Eq, Debug)] -#[error("automatic file tracking could not record every file access")] -pub struct TrackingIncomplete; +pub enum UntrackedReason { + /// A tracked process could not record a file access it went on to perform, + /// so the accesses collected for the run are a subset of what it really + /// touched (for example, the tracking channel filled up, or on Linux the + /// seccomp filter could not be installed or the launcher could not be + /// materialized). + #[error("automatic file tracking could not record every file access")] + Incomplete, + + /// The current process is already running inside an outer `fspy` tracker, + /// so this child was spawned untracked and its accesses are captured by + /// the outer tracker instead. + #[error("automatic file tracking is already active in a parent process")] + Nested, +} diff --git a/crates/fspy/src/ipc.rs b/crates/fspy/src/ipc.rs index 6d15bf436..04525c7d5 100644 --- a/crates/fspy/src/ipc.rs +++ b/crates/fspy/src/ipc.rs @@ -4,7 +4,7 @@ use fspy_shared::ipc::{ channel::{FrameReader, Receiver}, }; -use crate::error::TrackingIncomplete; +use crate::error::UntrackedReason; /// Shared memory for one tracked run's file-access records. /// @@ -39,7 +39,7 @@ pub struct ChannelAccesses { } impl TryFrom> for ChannelAccesses { - type Error = TrackingIncomplete; + type Error = UntrackedReason; /// Closes the channel and takes every record it collected. /// @@ -50,11 +50,11 @@ impl TryFrom> for ChannelAccesses { /// /// # Errors /// - /// [`TrackingIncomplete`] when a tracked process could not record + /// [`UntrackedReason::Incomplete`] when a tracked process could not record /// something it went on to do. What did arrive is then a subset of /// what the run really touched, so none of it is handed back. - fn try_from(receiver: Receiver) -> Result { - Ok(Self { frames: receiver.close().map_err(|_| TrackingIncomplete)? }) + fn try_from(receiver: Receiver) -> Result { + Ok(Self { frames: receiver.close().map_err(|_| UntrackedReason::Incomplete)? }) } } diff --git a/crates/fspy/src/lib.rs b/crates/fspy/src/lib.rs index 67db8736b..3b5ce981c 100644 --- a/crates/fspy/src/lib.rs +++ b/crates/fspy/src/lib.rs @@ -1,6 +1,7 @@ pub mod error; mod ipc; +mod nested; #[cfg(target_os = "linux")] #[path = "./linux/mod.rs"] @@ -21,7 +22,7 @@ mod command; use std::{io, process::ExitStatus, sync::LazyLock}; pub use command::Command; -pub use error::TrackingIncomplete; +pub use error::UntrackedReason; pub use fspy_shared::ipc::{IpcPath, PathAccess}; use futures_util::future::BoxFuture; pub use os_impl::PathAccessIterable; @@ -33,8 +34,8 @@ pub struct ChildTermination { /// The exit status of the child process. pub status: ExitStatus, /// The path accesses captured from the child process, or the reason - /// they cannot be trusted to be all of them. - pub path_accesses: Result, + /// complete accesses were not collected. + pub path_accesses: Result, } pub struct TrackedChild { diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index e78d1c77a..290892a6f 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -22,21 +22,26 @@ use tokio_util::sync::CancellationToken; use vt_materialized_artifact::{Artifact, artifact}; use crate::{ - ChildTermination, Command, TrackedChild, TrackingIncomplete, error::SpawnError, + ChildTermination, Command, TrackedChild, UntrackedReason, error::SpawnError, ipc::ChannelAccesses, }; const PRELOAD_LINUX: Artifact = artifact!("fspy_preload", "CARGO_BIN_FILE_FSPY_PRELOAD_LINUX"); +#[derive(Debug)] +enum LinuxTracker { + /// Materialized executable path to `fspy_preload_linux`. Wrapped in + /// `RwLock` so a file reaped from the temp directory (e.g. by + /// `systemd-tmpfiles`) can be lazily re-materialized on `ENOENT`, or + /// cleared to `None` if re-materialization fails. + Active(RwLock>>), + /// Untracked fallback with the exact reason (`Nested` or `Incomplete`). + Untracked(UntrackedReason), +} + #[derive(Debug)] pub struct SpyImpl { - /// Materialized executable path to `fspy_preload_linux`, or `None` when - /// seccomp is unavailable or materialization failed (in which case `spawn` - /// falls back to untracked execution). Wrapped in `RwLock` so a file reaped - /// from the temp directory (e.g. by `systemd-tmpfiles`) can be lazily - /// re-materialized on `ENOENT`. - preload_path: RwLock>>, - seccomp_available: bool, + tracker: LinuxTracker, } impl SpyImpl { @@ -47,36 +52,42 @@ impl SpyImpl { reason = "matches cross-platform SpyImpl::init() -> io::Result signature" )] pub fn init() -> io::Result { - let seccomp_available = probe_seccomp_available(); - let preload_path = if seccomp_available { - let materialized = materialize_preload(); - if materialized.is_none() { - tracing::warn!( - "failed to materialize the Linux task tracker binary, so Linux task \ - tracking is off and caching is disabled" - ); - } - materialized - } else { - None + if crate::nested::is_nested() { + tracing::debug!( + "nested inside an active fspy tracker; delegating tracking to outer tracker" + ); + return Ok(Self { tracker: LinuxTracker::Untracked(UntrackedReason::Nested) }); + } + if !probe_seccomp_available() { + return Ok(Self { tracker: LinuxTracker::Untracked(UntrackedReason::Incomplete) }); + } + let Some(preload_path) = materialize_preload() else { + tracing::warn!( + "failed to materialize the Linux task tracker binary, so Linux task \ + tracking is off and caching is disabled" + ); + return Ok(Self { tracker: LinuxTracker::Untracked(UntrackedReason::Incomplete) }); }; - Ok(Self { preload_path: RwLock::new(preload_path), seccomp_available }) + Ok(Self { tracker: LinuxTracker::Active(RwLock::new(Some(preload_path))) }) } - fn preload_path(&self) -> Option> { - if !self.seccomp_available { - return None; + fn preload_path(&self) -> Result, UntrackedReason> { + match &self.tracker { + LinuxTracker::Untracked(reason) => Err(*reason), + LinuxTracker::Active(lock) => lock + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_deref() + .map(clone_ipc_str) + .ok_or(UntrackedReason::Incomplete), } - self.preload_path - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .as_deref() - .map(clone_ipc_str) } fn rematerialize_preload(&self, failed_path: &IpcStr) -> Option> { - let mut guard = - self.preload_path.write().unwrap_or_else(std::sync::PoisonError::into_inner); + let LinuxTracker::Active(lock) = &self.tracker else { + return None; + }; + let mut guard = lock.write().unwrap_or_else(std::sync::PoisonError::into_inner); if let Some(current) = guard.as_deref() && (current.as_bytes() != failed_path.as_bytes() || Path::new(current.as_os_str()).exists()) @@ -93,8 +104,9 @@ impl SpyImpl { mut command: Command, cancellation_token: CancellationToken, ) -> Result { - let Some(mut preload_path) = self.preload_path() else { - return spawn_untracked(command, cancellation_token); + let mut preload_path = match self.preload_path() { + Ok(path) => path, + Err(reason) => return spawn_untracked(command, cancellation_token, reason), }; // If the cached launcher binary was removed mid-process (e.g. by // `systemd-tmpfiles`), re-materialize before building `tokio_command` @@ -103,7 +115,13 @@ impl SpyImpl { if !Path::new(preload_path.as_os_str()).exists() { match self.rematerialize_preload(&preload_path) { Some(new_path) => preload_path = new_path, - None => return spawn_untracked(command, cancellation_token), + None => { + return spawn_untracked( + command, + cancellation_token, + UntrackedReason::Incomplete, + ); + } } } @@ -240,6 +258,7 @@ async fn await_startup_handshake( fn spawn_untracked( command: Command, cancellation_token: CancellationToken, + reason: UntrackedReason, ) -> Result { let mut tokio_command = command.into_tokio_command(); let mut child = tokio_command.spawn().map_err(SpawnError::OsSpawn)?; @@ -255,7 +274,7 @@ fn spawn_untracked( child.wait().await? } }; - io::Result::Ok(ChildTermination { status, path_accesses: Err(TrackingIncomplete) }) + io::Result::Ok(ChildTermination { status, path_accesses: Err(reason) }) }) .map(|f| f?) .boxed(), diff --git a/crates/fspy/src/macos/mod.rs b/crates/fspy/src/macos/mod.rs index 4fa6d1434..58921d0e4 100644 --- a/crates/fspy/src/macos/mod.rs +++ b/crates/fspy/src/macos/mod.rs @@ -9,18 +9,26 @@ use tokio_util::sync::CancellationToken; use vt_materialized_artifact::{Artifact, artifact}; use crate::{ - ChildTermination, Command, TrackedChild, arena::PathAccessArena, error::SpawnError, - ipc::ChannelAccesses, + ChildTermination, Command, TrackedChild, UntrackedReason, arena::PathAccessArena, + error::SpawnError, ipc::ChannelAccesses, }; #[derive(Debug)] #[expect(clippy::struct_field_names, reason = "each field names a distinct injected path")] -pub struct SpyImpl { +struct MacosArtifacts { bash_path: Box, coreutils_path: Box, preload_path: Box, } +#[derive(Debug)] +pub struct SpyImpl { + /// Materialized preload/helper artifacts, or `None` when nested inside an + /// active outer `fspy` tracker (in which case spawns run untracked so the + /// outer tracker captures the subtree). + artifacts: Option, +} + impl SpyImpl { /// Materializes `fspy_preload_macos`, `oils_for_unix`, and `coreutils` into /// the current user's `vp_run` folder in the system temp dir. @@ -28,23 +36,32 @@ impl SpyImpl { const PRELOAD_CDYLIB: Artifact = artifact!("fspy_preload", "CARGO_CDYLIB_FILE_FSPY_PRELOAD_MACOS"); + if crate::nested::is_nested() { + tracing::debug!( + "nested inside an active fspy tracker; delegating tracking to outer tracker" + ); + return Ok(Self { artifacts: None }); + } + let preload_cdylib_path = PRELOAD_CDYLIB.materialize().suffix(".dylib").at_user_temp_dir("vp_run")?; Ok(Self { - preload_path: preload_cdylib_path.as_path().into(), - bash_path: macos_artifacts::OILS_BINARY - .materialize() - .executable() - .at_user_temp_dir("vp_run")? - .as_path() - .into(), - coreutils_path: macos_artifacts::COREUTILS_BINARY - .materialize() - .executable() - .at_user_temp_dir("vp_run")? - .as_path() - .into(), + artifacts: Some(MacosArtifacts { + preload_path: preload_cdylib_path.as_path().into(), + bash_path: macos_artifacts::OILS_BINARY + .materialize() + .executable() + .at_user_temp_dir("vp_run")? + .as_path() + .into(), + coreutils_path: macos_artifacts::COREUTILS_BINARY + .materialize() + .executable() + .at_user_temp_dir("vp_run")? + .as_path() + .into(), + }), }) } @@ -61,14 +78,39 @@ impl SpyImpl { mut command: Command, cancellation_token: CancellationToken, ) -> Result { + let Some(artifacts) = &self.artifacts else { + let mut tokio_command = command.into_tokio_command(); + let mut child = tokio_command.spawn().map_err(SpawnError::OsSpawn)?; + return Ok(TrackedChild { + stdin: child.stdin.take(), + stdout: child.stdout.take(), + stderr: child.stderr.take(), + wait_handle: tokio::spawn(async move { + let status = tokio::select! { + status = child.wait() => status?, + () = cancellation_token.cancelled() => { + child.start_kill()?; + child.wait().await? + } + }; + io::Result::Ok(ChildTermination { + status, + path_accesses: Err(UntrackedReason::Nested), + }) + }) + .map(|f| f?) + .boxed(), + }); + }; + let ipc_receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) .map_err(SpawnError::ChannelCreation)?; let payload = Payload { ipc_channel_conf: ipc_receiver.conf(), - preload_path: &self.preload_path, - bash_path: &self.bash_path, - coreutils_path: &self.coreutils_path, + preload_path: &artifacts.preload_path, + bash_path: &artifacts.bash_path, + coreutils_path: &artifacts.coreutils_path, }; let payload_bump = bumpalo::Bump::new(); diff --git a/crates/fspy/src/nested.rs b/crates/fspy/src/nested.rs new file mode 100644 index 000000000..87bd74075 --- /dev/null +++ b/crates/fspy/src/nested.rs @@ -0,0 +1,80 @@ +use std::sync::OnceLock; + +static IS_NESTED: OnceLock = OnceLock::new(); + +/// Returns `true` if the current process is already running inside an active +/// outer `fspy` tracker. +/// +/// Probes a hardcoded random-GUID sentinel path located beneath the OS null +/// device (`/dev/null/fspy_probe_` on Unix, `\??\NUL\fspy_probe_` +/// on Windows). Because the null device is not a directory, the OS kernel +/// always rejects this lookup with an error; only an active outer `fspy` +/// preload intercepts the exact sentinel path and short-circuits it to success +/// without recording it as a file access. +/// +/// The result is cached for the lifetime of the process. +pub fn is_nested() -> bool { + *IS_NESTED.get_or_init(probe_nested) +} + +#[cfg(target_os = "linux")] +fn probe_nested() -> bool { + use fspy_shared::probe::NESTED_PROBE_PATH_UNIX; + use syscalls::Sysno; + + // SAFETY: `NESTED_PROBE_PATH_UNIX` is a valid static NUL-terminated C string. + unsafe { + syscalls::syscall!( + Sysno::faccessat, + libc::AT_FDCWD, + NESTED_PROBE_PATH_UNIX.as_ptr(), + libc::F_OK + ) == Ok(0) + } +} + +#[cfg(target_os = "macos")] +fn probe_nested() -> bool { + use fspy_shared::probe::NESTED_PROBE_PATH_UNIX; + + // SAFETY: `NESTED_PROBE_PATH_UNIX` is a valid static NUL-terminated C string. + unsafe { libc::faccessat(libc::AT_FDCWD, NESTED_PROBE_PATH_UNIX.as_ptr(), libc::F_OK, 0) == 0 } +} + +#[cfg(target_os = "windows")] +fn probe_nested() -> bool { + use std::{mem::MaybeUninit, ptr}; + + use fspy_shared::probe::{ + NESTED_PROBE_PATH_WINDOWS_BYTE_LEN, NESTED_PROBE_PATH_WINDOWS_UTF16_NUL, + }; + use ntapi::ntioapi::{FILE_BASIC_INFORMATION, NtQueryAttributesFile}; + use winapi::shared::{ + ntdef::{InitializeObjectAttributes, OBJECT_ATTRIBUTES, UNICODE_STRING}, + ntstatus::STATUS_SUCCESS, + }; + + let mut name = UNICODE_STRING { + Length: NESTED_PROBE_PATH_WINDOWS_BYTE_LEN, + MaximumLength: NESTED_PROBE_PATH_WINDOWS_BYTE_LEN + 2, + Buffer: NESTED_PROBE_PATH_WINDOWS_UTF16_NUL.as_ptr().cast_mut(), + }; + let mut oa = MaybeUninit::::uninit(); + // SAFETY: `InitializeObjectAttributes` initializes all fields of `oa` with + // our stack-local `UNICODE_STRING` and null root/security descriptor. + unsafe { + InitializeObjectAttributes( + oa.as_mut_ptr(), + &raw mut name, + 0, + ptr::null_mut(), + ptr::null_mut(), + ); + } + // SAFETY: `InitializeObjectAttributes` fully initialized `oa`. + let mut oa = unsafe { oa.assume_init() }; + let mut info = MaybeUninit::::uninit(); + // SAFETY: `oa` and `info` are valid pointers for `NtQueryAttributesFile`. + let status = unsafe { NtQueryAttributesFile(&raw mut oa, info.as_mut_ptr()) }; + status == STATUS_SUCCESS +} diff --git a/crates/fspy/src/windows/mod.rs b/crates/fspy/src/windows/mod.rs index 1f4dd14f0..9886ee5e5 100644 --- a/crates/fspy/src/windows/mod.rs +++ b/crates/fspy/src/windows/mod.rs @@ -24,7 +24,8 @@ use winapi::{ use winsafe::co::{CP, WC}; use crate::{ - ChildTermination, TrackedChild, command::Command, error::SpawnError, ipc::ChannelAccesses, + ChildTermination, TrackedChild, UntrackedReason, command::Command, error::SpawnError, + ipc::ChannelAccesses, }; const INTERPOSE_CDYLIB: Artifact = @@ -51,13 +52,23 @@ impl PathAccessIterable { #[derive(Debug, Clone)] pub struct SpyImpl { - ansi_dll_path_with_nul: Arc, + /// Materialized interpose DLL path, or `None` when nested inside an active + /// outer `fspy` tracker (in which case spawns run untracked so the outer + /// tracker captures the subtree). + ansi_dll_path_with_nul: Option>, } impl SpyImpl { /// Initialize the fs access spy by writing the interpose DLL on disk, in the /// current user's own `vp_run` folder in the system temp dir. pub fn init() -> io::Result { + if crate::nested::is_nested() { + tracing::debug!( + "nested inside an active fspy tracker; delegating tracking to outer tracker" + ); + return Ok(Self { ansi_dll_path_with_nul: None }); + } + let dll_path = INTERPOSE_CDYLIB.materialize().suffix(".dll").at_user_temp_dir("vp_run")?; let wide_dll_path = dll_path.as_os_str().encode_wide().collect::>(); @@ -70,7 +81,7 @@ impl SpyImpl { // SAFETY: we just pushed a NUL byte, so the slice is NUL-terminated let ansi_dll_path_with_nul = unsafe { CStr::from_bytes_with_nul_unchecked(ansi_dll_path.as_slice()) }; - Ok(Self { ansi_dll_path_with_nul: ansi_dll_path_with_nul.into() }) + Ok(Self { ansi_dll_path_with_nul: Some(ansi_dll_path_with_nul.into()) }) } pub(crate) fn spawn( @@ -86,7 +97,42 @@ impl SpyImpl { mut command: Command, cancellation_token: CancellationToken, ) -> Result { - let ansi_dll_path_with_nul = &self.ansi_dll_path_with_nul; + let Some(ansi_dll_path_with_nul) = &self.ansi_dll_path_with_nul else { + let mut command = command.into_tokio_command(); + let mut child = command.spawn().map_err(SpawnError::OsSpawn)?; + // Duplicate the process handle before the child is moved into the background + // task so it stays valid after Tokio closes its copy when the process exits. + // SAFETY: the child owns this handle and is not waited on during this borrow. + let process = unsafe { BorrowedHandle::borrow_raw(child.raw_handle().unwrap()) }; + let process_handle = match process.try_clone_to_owned() { + Ok(handle) => handle, + Err(err) => { + let _ = child.start_kill(); + return Err(SpawnError::OsSpawn(err)); + } + }; + return Ok(TrackedChild { + stdin: child.stdin.take(), + stdout: child.stdout.take(), + stderr: child.stderr.take(), + process_handle, + wait_handle: tokio::spawn(async move { + let status = tokio::select! { + status = child.wait() => status?, + () = cancellation_token.cancelled() => { + child.start_kill()?; + child.wait().await? + } + }; + io::Result::Ok(ChildTermination { + status, + path_accesses: Err(UntrackedReason::Nested), + }) + }) + .map(|f| f?) + .boxed(), + }); + }; command.env("FSPY", "1"); let receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) diff --git a/crates/fspy/tests/nested_fspy.rs b/crates/fspy/tests/nested_fspy.rs new file mode 100644 index 000000000..860f0605f --- /dev/null +++ b/crates/fspy/tests/nested_fspy.rs @@ -0,0 +1,70 @@ +//! Cross-platform integration tests for nested `fspy` detection. +//! +//! When a process already running inside an active `fspy` tracker invokes +//! `fspy::Command` itself, the inner `fspy` must detect the outer tracker via +//! the null-device sentinel probe, run the grandchild untracked, report +//! `Err(UntrackedReason::Nested)`, and let the outer tracker capture the +//! grandchild's file accesses without recording the sentinel probe path. + +mod test_utils; + +use std::fs::File; + +use fspy::{PathAccess, UntrackedReason}; +use test_log::test; + +use crate::test_utils::assert_contains; + +#[test(tokio::test)] +async fn nested_fspy_delegates_to_outer_tracker_without_recording_probe() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let tmp_path = tmp_dir.path().canonicalize()?; + let probe_file = tmp_path.join("grandchild_input.txt"); + File::create(&probe_file)?; + let probe_file_str = probe_file.to_str().unwrap().to_owned(); + + let accesses = track_fn!(probe_file_str, |probe_file_str: String| { + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + rt.block_on(async move { + let grandchild_cmd = + vt_subprocess_test::command_for_fn!(probe_file_str, |probe_file_str: String| { + let _ = std::fs::read(&probe_file_str).unwrap(); + }); + let termination = fspy::Command::from(grandchild_cmd) + .spawn(tokio_util::sync::CancellationToken::new()) + .await + .expect("nested fspy spawn must succeed via untracked fallback") + .wait_handle + .await + .expect("nested fspy child wait failed"); + assert!( + termination.status.success(), + "nested grandchild exited unsuccessfully: {:?}", + termination.status + ); + assert_eq!( + termination.path_accesses.err(), + Some(UntrackedReason::Nested), + "nested fspy must report UntrackedReason::Nested while delegating to outer tracker" + ); + }); + }) + .await?; + + assert_contains(&accesses, &probe_file, PathAccess::Read); + + let leaked_probe: Vec<_> = accesses + .iter() + .filter(|access| { + access.paths().any(|p| { + format!("{p:?}").contains("fspy_probe_92e41940-369e-42f1-876f-a8e2a614fbf2") + }) + }) + .collect(); + assert!( + leaked_probe.is_empty(), + "outer tracker must not record the nested-detection sentinel probe path: {leaked_probe:?}" + ); + + Ok(()) +} diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs index 2c111bacd..c4ec49897 100644 --- a/crates/fspy/tests/untracked_fallback.rs +++ b/crates/fspy/tests/untracked_fallback.rs @@ -1,6 +1,6 @@ //! Tests for Linux untracked fallback and authentic exec errors: //! - When `seccomp` is blocked by an outer sandbox, `fspy` runs commands -//! untracked and reports `Err(TrackingIncomplete)` rather than failing every +//! untracked and reports `Err(UntrackedReason::Incomplete)` rather than failing every //! spawn. //! - Authentic exec errors (such as `ENOEXEC` on a script without a `#!` line) //! propagate normally and keep the trace complete. @@ -13,7 +13,7 @@ use std::{ process::Stdio, }; -use fspy::TrackingIncomplete; +use fspy::UntrackedReason; use linux_raw_sys::{ errno::EPERM, prctl::PR_SET_NO_NEW_PRIVS, @@ -53,7 +53,7 @@ async fn exec_errors_are_not_reported_as_lost() { /// When an outer sandbox blocks `SYS_seccomp` with `EPERM`, `fspy` detects /// this during initialization, runs spawned commands untracked, and reports -/// `Err(TrackingIncomplete)` so callers do not cache partial traces. +/// `Err(UntrackedReason::Incomplete)` so callers do not cache partial traces. #[test] fn seccomp_blocked_sandbox_falls_back_to_untracked() { let cmd = command_for_fn!((), |()| { @@ -103,7 +103,7 @@ fn seccomp_blocked_sandbox_falls_back_to_untracked() { let termination = tracked.wait_handle.await.unwrap(); assert!(termination.status.success()); assert_eq!(stdout, b"sandbox-ok\n"); - assert!(matches!(termination.path_accesses, Err(TrackingIncomplete))); + assert_eq!(termination.path_accesses.err(), Some(UntrackedReason::Incomplete)); }); }); diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 15701ad4f..1807cda39 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -125,6 +125,11 @@ pub type ExecveCleanup = (unsafe fn(*mut core::ffi::c_void), *mut core::ffi::c_v pub enum SyscallAction { /// Replay the (possibly `/proc/*/exe`-rewritten) trapped syscall. Replay, + /// Short-circuit the trapped syscall in Phase 1 and return the exact raw + /// `isize` result to the caller without replaying it to the kernel. + /// Non-negative values represent successful return values (such as `0`), + /// while negative values are delivered directly as raw `-errno` results. + Return(isize), /// Execute a replacement `SYS_execve(prog, argv, envp)` on the entry stack /// after releasing the private `SIGSYS` stack and clearing the calling /// thread's virtual `SIGSYS` mask entry. @@ -149,8 +154,10 @@ pub enum SyscallAction { /// already-rewritten target executable path. /// /// Returning `Ok(SyscallAction::Replay)` replays the syscall; returning -/// `Ok(SyscallAction::Execve { .. })` releases the private `SIGSYS` stack -/// before executing the replacement `SYS_execve`; returning `Err(error)` +/// `Ok(SyscallAction::Return(rc))` short-circuits the syscall in Phase 1 and +/// delivers `rc` directly to the caller without replaying it to the kernel; +/// returning `Ok(SyscallAction::Execve { .. })` releases the private `SIGSYS` +/// stack before executing the replacement `SYS_execve`; returning `Err(error)` /// short-circuits the syscall and returns `-error.raw_os_error()` directly to /// the caller. #[cfg(any(target_os = "linux", target_os = "none"))] diff --git a/crates/fspy_elf_loader/src/sigsys/mod.rs b/crates/fspy_elf_loader/src/sigsys/mod.rs index 20bb4fbd4..07d4ad999 100644 --- a/crates/fspy_elf_loader/src/sigsys/mod.rs +++ b/crates/fspy_elf_loader/src/sigsys/mod.rs @@ -622,6 +622,10 @@ unsafe fn dispatch_phase1( // SAFETY: `call` holds the live (and rewritten) trapped arguments. match unsafe { (interceptor.handle)(&call) } { Ok(SyscallAction::Replay) => {} + Ok(SyscallAction::Return(rc)) => { + finish_in_phase1(ucontext, packet, rc); + return; + } Ok(SyscallAction::Execve { prog, argv, envp, cleanup }) => { packet.inv = SyscallInvocation { nr: Sysno::execve as usize, diff --git a/crates/fspy_elf_loader_test_launcher/src/main.rs b/crates/fspy_elf_loader_test_launcher/src/main.rs index 4fca880d7..cc77613b1 100644 --- a/crates/fspy_elf_loader_test_launcher/src/main.rs +++ b/crates/fspy_elf_loader_test_launcher/src/main.rs @@ -17,7 +17,10 @@ mod freestanding { fspy_nostd::no_global_alloc!(); const INTERCEPTOR_SHORT_CIRCUIT_ARG: usize = 0xdead_beef; + const INTERCEPTOR_RETURN_ZERO_ARG: usize = 0xdead_0000; + const INTERCEPTOR_RETURN_VALUE_ARG: usize = 0xdead_0042; const INTERCEPTOR_REWRITE_PROBE_MODE: usize = 0x7777; + const INTERCEPTOR_RETURN_PROBE_MODE: usize = 0x7778; const INTERCEPTOR_EXEC_PROBE_ARGV: usize = 0x5555_1234; const INTERCEPTOR_EXEC_FAIL_CLEANUP_ARGV: usize = 0x5555_2345; const INTERCEPTOR_EXEC_FAIL_NO_CLEANUP_ARGV: usize = 0x5555_2346; @@ -43,10 +46,13 @@ mod freestanding { /// Test interceptor exercising: /// - `getegid(0xdead_beef)` -> short-circuits with `Err(Error::ACCES)` + /// - `getegid(0xdead_0000)` -> short-circuits with `Ok(SyscallAction::Return(0))` + /// - `getegid(0xdead_0042)` -> short-circuits with `Ok(SyscallAction::Return(42))` /// - `getegid(_)` -> replays normally (`Ok(SyscallAction::Replay)`) /// - `faccessat(_, path, 0x7777)` -> checks `/proc/self/exe` was rewritten /// to an absolute non-`/proc/` path, returning `Err(Error::LOOP)` on /// match or `Err(Error::NOENT)` on mismatch + /// - `faccessat(_, _, 0x7778)` -> short-circuits with `Ok(SyscallAction::Return(0))` /// - `execve(path, 0x5555_1234, _)` / `execveat(dirfd, path, 0x5555_1234, _, _)` /// -> checks `/proc/self/exe` was rewritten to an absolute non-`/proc/` /// path (and `dirfd == AT_FDCWD` for `execveat`) @@ -74,12 +80,21 @@ mod freestanding { if call.args[0] == INTERCEPTOR_SHORT_CIRCUIT_ARG { return Err(Error::ACCES); } + if call.args[0] == INTERCEPTOR_RETURN_ZERO_ARG { + return Ok(SyscallAction::Return(0)); + } + if call.args[0] == INTERCEPTOR_RETURN_VALUE_ARG { + return Ok(SyscallAction::Return(42)); + } Ok(SyscallAction::Replay) } Sysno::faccessat => { if call.args[2] == INTERCEPTOR_REWRITE_PROBE_MODE { return check_rewritten_path(call.args[1]); } + if call.args[2] == INTERCEPTOR_RETURN_PROBE_MODE { + return Ok(SyscallAction::Return(0)); + } Ok(SyscallAction::Replay) } Sysno::execve => { diff --git a/crates/fspy_elf_loader_tests/fixtures/virtualization.c b/crates/fspy_elf_loader_tests/fixtures/virtualization.c index e0dcdc2fc..5c5a09c14 100644 --- a/crates/fspy_elf_loader_tests/fixtures/virtualization.c +++ b/crates/fspy_elf_loader_tests/fixtures/virtualization.c @@ -1355,6 +1355,17 @@ static int run_interceptor_test(void) { fail("intercepted getegid short-circuit did not return EACCES"); } + /* 2b. SyscallAction::Return(rc) short-circuits in Phase 1 with exact rc. */ + if (syscall(SYS_getegid, 0xdead0000UL) != 0) { + fail("SyscallAction::Return(0) did not return 0"); + } + if (syscall(SYS_getegid, 0xdead0042UL) != 42) { + fail("SyscallAction::Return(42) did not return 42"); + } + if (syscall(SYS_faccessat, AT_FDCWD, "/dev/null/fspy_return_probe", 0x7778UL) != 0) { + fail("SyscallAction::Return(0) on faccessat did not short-circuit"); + } + /* 3. /proc/self/exe rewrite is visible to interceptor on faccessat. */ errno = 0; if (syscall(SYS_faccessat, AT_FDCWD, "/proc/self/exe", 0x7777UL) != -1 || errno != ELOOP) { diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index d1711256c..509da0cc3 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -27,9 +27,12 @@ mod runtime { fs::{fd_path, resolve_path_at}, page_bump, pooled_bump, }; - use fspy_shared::ipc::{ - AccessMode, IpcPath, IpcStr, - channel::{ChannelConf, Sender}, + use fspy_shared::{ + ipc::{ + AccessMode, IpcPath, IpcStr, + channel::{ChannelConf, Sender}, + }, + probe::NESTED_PROBE_PATH_UNIX_BYTES, }; use fspy_shared_unix::{ Exec, RawExec, @@ -39,8 +42,8 @@ mod runtime { }, }; use linux_raw_sys::general::{ - AT_EMPTY_PATH, O_ACCMODE, O_CREAT, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, RENAME_EXCHANGE, - SIG_SETMASK, open_how, + AT_EMPTY_PATH, AT_FDCWD, O_ACCMODE, O_CREAT, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, + RENAME_EXCHANGE, SIG_SETMASK, open_how, }; use syscalls::Sysno; @@ -519,6 +522,17 @@ mod runtime { } } + fn is_nested_probe(call: &Syscall) -> bool { + if arg_i32(call.args[0]) != AT_FDCWD || call.args[2] != 0 { + return false; + } + // SAFETY: `call.args[1]` is the trapped `faccessat` pathname pointer. + let Ok(c_path) = (unsafe { fspy_elf_loader::user_cstr(call.args[1]) }) else { + return false; + }; + c_path.count().as_units() == NESTED_PROBE_PATH_UNIX_BYTES + } + /// `SIGSYS` interceptor callback invoked by `fspy_elf_loader`. /// /// # Safety @@ -531,6 +545,13 @@ mod runtime { let borrow_dirfd = |raw: usize| unsafe { BorrowedFd::try_borrow_raw(arg_i32(raw)) }; match call.sysno { + Sysno::faccessat => { + if is_nested_probe(call) { + return Ok(SyscallAction::Return(0)); + } + handle_fs_syscall(call); + Ok(SyscallAction::Replay) + } Sysno::execve => handle_exec( Some(CWD), call.args[0], diff --git a/crates/fspy_preload_macos/src/interceptions/access.rs b/crates/fspy_preload_macos/src/interceptions/access.rs index 69fd8e7b7..d6f21dcca 100644 --- a/crates/fspy_preload_macos/src/interceptions/access.rs +++ b/crates/fspy_preload_macos/src/interceptions/access.rs @@ -1,4 +1,6 @@ -use fspy_shared::ipc::AccessMode; +use std::ffi::CStr; + +use fspy_shared::{ipc::AccessMode, probe::NESTED_PROBE_PATH_UNIX_BYTES}; use libc::{c_char, c_int}; use crate::{ @@ -21,6 +23,12 @@ unsafe extern "C" fn faccessat( mode: c_int, flags: c_int, ) -> c_int { + if dirfd == libc::AT_FDCWD && mode == libc::F_OK && flags == 0 && !pathname.is_null() { + // SAFETY: pathname is a non-null NUL-terminated C string provided by the caller. + if unsafe { CStr::from_ptr(pathname) }.to_bytes() == NESTED_PROBE_PATH_UNIX_BYTES { + return 0; + } + } // SAFETY: dirfd is -1 or valid, and pathname is a valid C string. unsafe { handle_open_at(dirfd, pathname, AccessMode::Read) }; // SAFETY: calling the original libc faccessat() with forwarded arguments. diff --git a/crates/fspy_preload_windows/Cargo.toml b/crates/fspy_preload_windows/Cargo.toml index 88f512fa3..e5694d859 100644 --- a/crates/fspy_preload_windows/Cargo.toml +++ b/crates/fspy_preload_windows/Cargo.toml @@ -24,6 +24,7 @@ winapi = { workspace = true, features = [ "winbase", "namedpipeapi", "memoryapi", + "ntstatus", "std", ] } windows-sys = { workspace = true, features = [ diff --git a/crates/fspy_preload_windows/src/windows/detours/nt.rs b/crates/fspy_preload_windows/src/windows/detours/nt.rs index 00b76e95b..966df9ba3 100644 --- a/crates/fspy_preload_windows/src/windows/detours/nt.rs +++ b/crates/fspy_preload_windows/src/windows/detours/nt.rs @@ -1,6 +1,9 @@ use std::mem::{offset_of, size_of, size_of_val}; -use fspy_shared::ipc::{AccessMode, IpcPath, PathAccess}; +use fspy_shared::{ + ipc::{AccessMode, IpcPath, PathAccess}, + probe::{NESTED_PROBE_PATH_WINDOWS_BYTE_LEN, NESTED_PROBE_PATH_WINDOWS_UTF16}, +}; use ntapi::{ ntioapi::{ FILE_CREATE, FILE_DIRECTORY_FILE, FILE_INFORMATION_CLASS, FILE_OPEN_IF, @@ -21,6 +24,7 @@ use winapi::{ BOOLEAN, HANDLE, NTSTATUS, OBJECT_ATTRIBUTES, PHANDLE, PLARGE_INTEGER, POBJECT_ATTRIBUTES, PUNICODE_STRING, PVOID, ULONG, UNICODE_STRING, }, + ntstatus::STATUS_SUCCESS, }, um::winnt::{ACCESS_MASK, GENERIC_READ}, }; @@ -470,6 +474,34 @@ static DETOUR_NT_OPEN_FILE: Detour< }) }; +/// Checks whether `object_attributes` refers to `fspy`'s nested-tracker +/// sentinel path under `\??\NUL`. +/// +/// # Safety +/// +/// `object_attributes` must be null or valid for the duration of the +/// intercepted `NtQueryAttributesFile` call. +unsafe fn is_nested_probe(object_attributes: POBJECT_ATTRIBUTES) -> bool { + if object_attributes.is_null() { + return false; + } + // SAFETY: `object_attributes` is non-null and valid for this NT call. + let attrs = unsafe { &*object_attributes }; + if !attrs.RootDirectory.is_null() || attrs.ObjectName.is_null() { + return false; + } + // SAFETY: `ObjectName` is a non-null `UNICODE_STRING` valid for this NT call. + let name = unsafe { &*attrs.ObjectName }; + if name.Length != NESTED_PROBE_PATH_WINDOWS_BYTE_LEN || name.Buffer.is_null() { + return false; + } + // SAFETY: `Buffer` points to at least `Length / 2` UTF-16 code units. + let slice = unsafe { + std::slice::from_raw_parts(name.Buffer, usize::from(name.Length) / size_of::()) + }; + slice == NESTED_PROBE_PATH_WINDOWS_UTF16 +} + static DETOUR_NT_QUERY_ATTRIBUTES_FILE: Detour< unsafe extern "system" fn( object_attributes: POBJECT_ATTRIBUTES, @@ -483,6 +515,14 @@ static DETOUR_NT_QUERY_ATTRIBUTES_FILE: Detour< object_attributes: POBJECT_ATTRIBUTES, file_information: PFILE_BASIC_INFORMATION, ) -> HFILE { + // SAFETY: inspecting caller-supplied OBJECT_ATTRIBUTES before forwarding + if unsafe { is_nested_probe(object_attributes) } { + if !file_information.is_null() { + // SAFETY: caller supplied a valid writable FILE_BASIC_INFORMATION buffer + unsafe { core::ptr::write_bytes(file_information, 0, 1) }; + } + return STATUS_SUCCESS; + } // SAFETY: intercepting attribute query to record read access unsafe { handle_open(AccessMode::Read, object_attributes) }; // SAFETY: calling the original NtQueryAttributesFile with all original arguments diff --git a/crates/fspy_shared/src/lib.rs b/crates/fspy_shared/src/lib.rs index 0cb88e9cf..4ff5bf870 100644 --- a/crates/fspy_shared/src/lib.rs +++ b/crates/fspy_shared/src/lib.rs @@ -1,6 +1,7 @@ #![cfg_attr(target_os = "none", no_std)] pub mod ipc; +pub mod probe; #[cfg(windows)] pub mod windows; diff --git a/crates/fspy_shared/src/probe.rs b/crates/fspy_shared/src/probe.rs new file mode 100644 index 000000000..4c80ffdaf --- /dev/null +++ b/crates/fspy_shared/src/probe.rs @@ -0,0 +1,98 @@ +//! Cross-platform sentinel probe paths for detecting an active outer `fspy` +//! tracker. +//! +//! Each platform's `fspy` probes a fixed, random-GUID path located underneath +//! the OS null device (`/dev/null/...` on Unix, `\??\NUL\...` on Windows). +//! Because the null device is a character device rather than a directory, the +//! kernel always rejects lookups beneath it. Only an active outer `fspy` +//! preload intercepts the exact sentinel path and short-circuits the syscall +//! to success without recording it as a file access. + +use core::ffi::CStr; + +/// NUL-terminated Unix sentinel path used by `fspy` on Linux and macOS to +/// detect an active outer `fspy` tracker via `faccessat(AT_FDCWD, path, F_OK)`. +pub const NESTED_PROBE_PATH_UNIX: &CStr = + c"/dev/null/fspy_probe_92e41940-369e-42f1-876f-a8e2a614fbf2"; + +/// Byte slice (excluding trailing NUL) of [`NESTED_PROBE_PATH_UNIX`]. +pub const NESTED_PROBE_PATH_UNIX_BYTES: &[u8] = NESTED_PROBE_PATH_UNIX.to_bytes(); + +const NESTED_PROBE_PATH_WINDOWS_ASCII: &[u8] = + br"\??\NUL\fspy_probe_92e41940-369e-42f1-876f-a8e2a614fbf2"; + +const WINDOWS_PROBE_LEN: usize = NESTED_PROBE_PATH_WINDOWS_ASCII.len(); + +const fn ascii_to_utf16(bytes: &[u8]) -> [u16; N] { + assert!(bytes.len() == N); + let mut out = [0u16; N]; + let mut i = 0; + while i < N { + assert!(bytes[i].is_ascii()); + out[i] = bytes[i] as u16; + i += 1; + } + out +} + +const fn ascii_to_utf16_nul(bytes: &[u8]) -> [u16; M] { + assert!(bytes.len() == N); + assert!(M == N + 1); + let mut out = [0u16; M]; + let mut i = 0; + while i < N { + assert!(bytes[i].is_ascii()); + out[i] = bytes[i] as u16; + i += 1; + } + out[N] = 0; + out +} + +const NESTED_PROBE_PATH_WINDOWS_UTF16_ARRAY: [u16; WINDOWS_PROBE_LEN] = + ascii_to_utf16::(NESTED_PROBE_PATH_WINDOWS_ASCII); + +/// UTF-16 slice (excluding trailing NUL) of the Windows NT object sentinel +/// path `\??\NUL\fspy_probe_92e41940-369e-42f1-876f-a8e2a614fbf2`. +pub const NESTED_PROBE_PATH_WINDOWS_UTF16: &[u16] = &NESTED_PROBE_PATH_WINDOWS_UTF16_ARRAY; + +/// NUL-terminated UTF-16 static buffer of the Windows NT object sentinel path, +/// suitable for populating a `UNICODE_STRING.Buffer` in `NtQueryAttributesFile`. +pub static NESTED_PROBE_PATH_WINDOWS_UTF16_NUL: [u16; WINDOWS_PROBE_LEN + 1] = + ascii_to_utf16_nul::( + NESTED_PROBE_PATH_WINDOWS_ASCII, + ); + +/// Byte length (excluding trailing NUL) for `UNICODE_STRING.Length`. +#[expect( + clippy::cast_possible_truncation, + reason = "constant ASCII Windows sentinel path fits well within u16" +)] +pub const NESTED_PROBE_PATH_WINDOWS_BYTE_LEN: u16 = (WINDOWS_PROBE_LEN * 2) as u16; + +#[cfg(all(test, not(target_os = "none")))] +mod tests { + use super::*; + + #[test] + fn unix_sentinel_path_is_under_dev_null() { + assert!(NESTED_PROBE_PATH_UNIX_BYTES.starts_with(b"/dev/null/fspy_probe_")); + assert_eq!(NESTED_PROBE_PATH_UNIX.to_bytes(), NESTED_PROBE_PATH_UNIX_BYTES); + } + + #[test] + fn windows_sentinel_path_utf16_matches_ascii() { + let expected: Vec = + NESTED_PROBE_PATH_WINDOWS_ASCII.iter().map(|&b| u16::from(b)).collect(); + assert_eq!(NESTED_PROBE_PATH_WINDOWS_UTF16, expected.as_slice()); + assert_eq!( + usize::from(NESTED_PROBE_PATH_WINDOWS_BYTE_LEN), + NESTED_PROBE_PATH_WINDOWS_UTF16.len() * 2 + ); + assert_eq!( + &NESTED_PROBE_PATH_WINDOWS_UTF16_NUL[..NESTED_PROBE_PATH_WINDOWS_UTF16.len()], + NESTED_PROBE_PATH_WINDOWS_UTF16 + ); + assert_eq!(*NESTED_PROBE_PATH_WINDOWS_UTF16_NUL.last().unwrap(), 0); + } +} diff --git a/crates/vt/src/session/event.rs b/crates/vt/src/session/event.rs index 01d206f04..e126fa282 100644 --- a/crates/vt/src/session/event.rs +++ b/crates/vt/src/session/event.rs @@ -117,6 +117,11 @@ pub enum CacheNotUpdatedReason { /// that are not all of them. #[cfg_attr(not(fspy), expect(dead_code, reason = "only fspy tracking can be incomplete"))] TrackingIncomplete, + /// Automatic file tracking is already active in a parent task, so this + /// nested task ran untracked and its file accesses were recorded by the + /// parent task instead. + #[cfg_attr(not(fspy), expect(dead_code, reason = "only fspy tracking can be nested"))] + NestedTracking, } /// Outcome of the post-run cache update after a spawned process exited with diff --git a/crates/vt/src/session/execute/cache_update.rs b/crates/vt/src/session/execute/cache_update.rs index 5f084ce67..33e9edbb1 100644 --- a/crates/vt/src/session/execute/cache_update.rs +++ b/crates/vt/src/session/execute/cache_update.rs @@ -71,7 +71,7 @@ pub(super) async fn update_cache( workspace_root: &Arc, cache_dir: &AbsolutePath, state: CacheState<'_>, - #[cfg(fspy)] path_accesses: Option<&Result>, + #[cfg(fspy)] path_accesses: Option<&Result>, reports: Option<&Reports>, duration: Duration, cancel_token: &CancellationToken, @@ -102,12 +102,17 @@ pub(super) async fn update_cache( } // The accesses, or `None` when the task was not tracked at all. An - // `Err` means tracking could not record everything it did, so what - // arrived is a subset of what it touched, and an entry - // built from a subset would replay with inputs and outputs missing. + // `Err` means tracking was incomplete or delegated to an outer tracker, so + // we must not build a cache entry from missing or partial accesses. #[cfg(fspy)] - let Ok(path_accesses) = path_accesses.map(Result::as_ref).transpose() else { - return CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::TrackingIncomplete); + let path_accesses = match path_accesses.map(Result::as_ref).transpose() { + Ok(accesses) => accesses, + Err(fspy::UntrackedReason::Incomplete) => { + return CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::TrackingIncomplete); + } + Err(fspy::UntrackedReason::Nested) => { + return CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::NestedTracking); + } }; // Every schema version's folder is in the task cache, not only this one. diff --git a/crates/vt/src/session/execute/spawn.rs b/crates/vt/src/session/execute/spawn.rs index c925f7320..1f1d49966 100644 --- a/crates/vt/src/session/execute/spawn.rs +++ b/crates/vt/src/session/execute/spawn.rs @@ -61,9 +61,9 @@ pub struct InheritedChild { pub struct ChildOutcome { pub exit_status: std::process::ExitStatus, /// Raw fspy accesses. `Some` iff spawned with [`PipedMode::Tracked`], and - /// `Err` when a tracked process could not record everything it did. + /// `Err` when complete accesses could not be collected (incomplete or nested). #[cfg(fspy)] - pub path_accesses: Option>, + pub path_accesses: Option>, } /// Spawn a command with piped stdout/stderr (`stdin` set to `/dev/null`) and diff --git a/crates/vt/src/session/reporter/summary.rs b/crates/vt/src/session/reporter/summary.rs index bef80fb4f..45e7fe1a0 100644 --- a/crates/vt/src/session/reporter/summary.rs +++ b/crates/vt/src/session/reporter/summary.rs @@ -165,6 +165,9 @@ pub enum SavedCacheNotUpdatedReason { /// Automatic file tracking could not record everything the task did, so /// the inferred inputs and outputs were a subset of what it touched. TrackingIncomplete, + /// Automatic file tracking is already active in a parent task, so this + /// nested task ran untracked and its accesses were tracked by the parent. + NestedTracking, /// A runner-aware tool called `disableCache()`, skipping cache update. ToolRequested, } @@ -335,6 +338,7 @@ impl SavedCacheNotUpdatedReason { } CacheNotUpdatedReason::ToolRequested => Self::ToolRequested, CacheNotUpdatedReason::TrackingIncomplete => Self::TrackingIncomplete, + CacheNotUpdatedReason::NestedTracking => Self::NestedTracking, } } } @@ -586,6 +590,13 @@ impl TaskResult { Vec::new(), &[], ), + SavedCacheNotUpdatedReason::NestedTracking => ( + Str::from( + "→ Not cached: automatic file tracking is already active in a parent task. The parent task tracks these accesses; configure `input` and `output` manually to also cache this nested task.", + ), + Vec::new(), + &[], + ), SavedCacheNotUpdatedReason::FspyUnsupported => ( Str::from( "→ Not cached: `input` auto-inference isn't supported on this OS. Configure `input` manually to enable caching.", @@ -1893,6 +1904,7 @@ mod tests { let summary = full_summary(vec![ not_updated("opt-out", SavedCacheNotUpdatedReason::ToolRequested), not_updated("incomplete", SavedCacheNotUpdatedReason::TrackingIncomplete), + not_updated("nested", SavedCacheNotUpdatedReason::NestedTracking), not_updated("no-fspy", SavedCacheNotUpdatedReason::FspyUnsupported), not_updated( "ipc", @@ -1922,6 +1934,9 @@ mod tests { .as_str() .contains("→ Not cached: automatic file tracking couldn't record everything") ); + assert!(summary.as_str().contains( + "→ Not cached: automatic file tracking is already active in a parent task. The parent task tracks these accesses; configure `input` and `output` manually to also cache this nested task." + )); assert!( summary .as_str() diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/input.txt b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/input.txt new file mode 100644 index 000000000..e79c5e8f9 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/input.txt @@ -0,0 +1 @@ +initial diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/package.json new file mode 100644 index 000000000..5bbbd3c64 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/package.json @@ -0,0 +1,4 @@ +{ + "name": "nested-vt-run", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/snapshots.toml new file mode 100644 index 000000000..3a56977b7 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/snapshots.toml @@ -0,0 +1,54 @@ +[[e2e]] +name = "nested_vt_run_delegates_tracking_to_outer" +comment = """ +When a cached task spawns a nested `vt run` subprocess (wrapped via `vtt pipe-stdout` so it runs as a separate process instead of being inlined), the nested `vt` detects that automatic file tracking is already active in the outer task, runs `inner` untracked with a clear explanation, and does not pollute `inner`'s cache. Meanwhile the outer task tracks `inner`'s reads and writes (`input.txt` and `dist/out.txt`), restores `dist/out.txt` on cache hit, and invalidates when `input.txt` changes. +""" +steps = [ + { argv = [ + "vt", + "run", + "-v", + "outer", + ], comment = "cold run: outer caches, inner reports nested tracking" }, + { argv = [ + "vtt", + "rm", + "-rf", + "dist", + ], comment = "remove output produced by nested task" }, + { argv = [ + "vt", + "run", + "-v", + "outer", + ], comment = "outer cache hit restores dist/out.txt" }, + { argv = [ + "vtt", + "print-file", + "dist/out.txt", + ], comment = "verify dist/out.txt was restored" }, + { argv = [ + "vtt", + "write-file", + "input.txt", + "updated", + ], comment = "modify file read only by nested grandchild" }, + { argv = [ + "vt", + "run", + "-v", + "outer", + ], comment = "outer cache miss because grandchild input changed" }, + { argv = [ + "vt", + "run", + "-v", + "inner", + ], comment = "direct inner run misses (nested run did not pollute inner cache)" }, + { argv = [ + "vt", + "run", + "-v", + "inner", + ], comment = "second direct inner run hits cache" }, +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/snapshots/nested_vt_run_delegates_tracking_to_outer.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/snapshots/nested_vt_run_delegates_tracking_to_outer.md new file mode 100644 index 000000000..59c8bfc6b --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/snapshots/nested_vt_run_delegates_tracking_to_outer.md @@ -0,0 +1,210 @@ +# nested_vt_run_delegates_tracking_to_outer + +When a cached task spawns a nested `vt run` subprocess (wrapped via `vtt pipe-stdout` so it runs as a separate process instead of being inlined), the nested `vt` detects that automatic file tracking is already active in the outer task, runs `inner` untracked with a clear explanation, and does not pollute `inner`'s cache. Meanwhile the outer task tracks `inner`'s reads and writes (`input.txt` and `dist/out.txt`), restores `dist/out.txt` on cache hit, and invalidates when `input.txt` changes. + +## `vt run -v outer` + +cold run: outer caches, inner reports nested tracking + +``` +$ vtt pipe-stdout -- vt run -v inner +--- stdout --- +$ vtt print-file input.txt +initial + +$ vtt write-file dist/out.txt built + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 2 tasks • 0 cache hits • 2 cache misses +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] nested-vt-run#inner: $ vtt print-file input.txt ✓ + → Not cached: automatic file tracking is already active in a parent task. The parent task tracks these accesses; configure `input` and `output` manually to also cache this nested task. + ······················································· + [2] nested-vt-run#inner: $ vtt write-file dist/out.txt built ✓ + → Not cached: automatic file tracking is already active in a parent task. The parent task tracks these accesses; configure `input` and `output` manually to also cache this nested task. +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 1 task • 0 cache hits • 1 cache miss +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] nested-vt-run#outer: $ vtt pipe-stdout -- vt run -v inner ✓ + → Cache miss: no previous cache entry found +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +## `vtt rm -rf dist` + +remove output produced by nested task + +``` +``` + +## `vt run -v outer` + +outer cache hit restores dist/out.txt + +``` +$ vtt pipe-stdout -- vt run -v inner ◉ cache hit, replaying +--- stdout --- +$ vtt print-file input.txt +initial + +$ vtt write-file dist/out.txt built + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 2 tasks • 0 cache hits • 2 cache misses +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] nested-vt-run#inner: $ vtt print-file input.txt ✓ + → Not cached: automatic file tracking is already active in a parent task. The parent task tracks these accesses; configure `input` and `output` manually to also cache this nested task. + ······················································· + [2] nested-vt-run#inner: $ vtt write-file dist/out.txt built ✓ + → Not cached: automatic file tracking is already active in a parent task. The parent task tracks these accesses; configure `input` and `output` manually to also cache this nested task. +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 1 task • 1 cache hit • 0 cache misses +Performance: 100% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] nested-vt-run#outer: $ vtt pipe-stdout -- vt run -v inner ✓ + → Cache hit - output replayed - +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +## `vtt print-file dist/out.txt` + +verify dist/out.txt was restored + +``` +built +``` + +## `vtt write-file input.txt updated` + +modify file read only by nested grandchild + +``` +``` + +## `vt run -v outer` + +outer cache miss because grandchild input changed + +``` +$ vtt pipe-stdout -- vt run -v inner ○ cache miss: 'input.txt' modified, executing +--- stdout --- +$ vtt print-file input.txt +updated +$ vtt write-file dist/out.txt built + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 2 tasks • 0 cache hits • 2 cache misses +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] nested-vt-run#inner: $ vtt print-file input.txt ✓ + → Not cached: automatic file tracking is already active in a parent task. The parent task tracks these accesses; configure `input` and `output` manually to also cache this nested task. + ······················································· + [2] nested-vt-run#inner: $ vtt write-file dist/out.txt built ✓ + → Not cached: automatic file tracking is already active in a parent task. The parent task tracks these accesses; configure `input` and `output` manually to also cache this nested task. +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 1 task • 0 cache hits • 1 cache miss +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] nested-vt-run#outer: $ vtt pipe-stdout -- vt run -v inner ✓ + → Cache miss: 'input.txt' modified +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +## `vt run -v inner` + +direct inner run misses (nested run did not pollute inner cache) + +``` +$ vtt print-file input.txt +updated +$ vtt write-file dist/out.txt built + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 2 tasks • 0 cache hits • 2 cache misses +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] nested-vt-run#inner: $ vtt print-file input.txt ✓ + → Cache miss: no previous cache entry found + ······················································· + [2] nested-vt-run#inner: $ vtt write-file dist/out.txt built ✓ + → Cache miss: no previous cache entry found +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +## `vt run -v inner` + +second direct inner run hits cache + +``` +$ vtt print-file input.txt ◉ cache hit, replaying +updated +$ vtt write-file dist/out.txt built ◉ cache hit, replaying + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 2 tasks • 2 cache hits • 0 cache misses +Performance: 100% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] nested-vt-run#inner: $ vtt print-file input.txt ✓ + → Cache hit - output replayed - + ······················································· + [2] nested-vt-run#inner: $ vtt write-file dist/out.txt built ✓ + → Cache hit - output replayed - +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/vite-task.json new file mode 100644 index 000000000..731b01b69 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/nested_vt_run/vite-task.json @@ -0,0 +1,12 @@ +{ + "tasks": { + "outer": { + "command": "vtt pipe-stdout -- vt run -v inner", + "cache": true + }, + "inner": { + "command": "vtt print-file input.txt && vtt write-file dist/out.txt built", + "cache": true + } + } +}