diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7d508cca..c6f0b0ee8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,8 +67,8 @@ jobs: # --locked: verify Cargo.lock is up to date (replaces the removed `cargo check --locked`) - run: cargo clippy --locked --all-targets --all-features -- -D warnings - run: | - cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher --target x86_64-unknown-none -- -D warnings - cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher --target aarch64-unknown-none-softfloat -- -D warnings + cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher -p fspy_preload_linux --target x86_64-unknown-none -- -D warnings + cargo clippy --locked -p fspy_elf_loader -p fspy_elf_loader_test_launcher -p fspy_preload_linux --target aarch64-unknown-none-softfloat -- -D warnings # fspy builds only on Windows, macOS, and Linux, but vp must still build # without it on other platforms. Cross-building `vt_bin` for FreeBSD catches @@ -390,6 +390,11 @@ jobs: - uses: oxc-project/setup-node@f46a72f95efdc55273fcd042d61c84e723b2892c # v1.4.1 + # Run only Bun's postinstall on musl (`deno` and `workerd` do not ship + # musl binaries and their tests are filtered out on `target_env = "musl"`). + - name: Install Bun runtime binary + run: pnpm --filter vite-task-tools rebuild bun + - name: Run ignored tests run: cargo test -- --ignored diff --git a/CHANGELOG.md b/CHANGELOG.md index ad334a2d7..6891e10d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ # Changelog +- **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)). - **Fixed** When a command handler sets a working directory for a command it generates, `vp run` now runs that command in the selected directory and includes the directory in its cache fingerprint ([#1005](https://github.com/voidzero-dev/vite-task/pull/1005)). diff --git a/Cargo.lock b/Cargo.lock index 3532803f6..baa89acfb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -161,16 +161,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "assertables" -version = "10.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b3cadd448c7cd878da49dac40adcd0f7248d2911afe5102267f68c352d87882" -dependencies = [ - "regex", - "walkdir", -] - [[package]] name = "async-trait" version = "0.1.89" @@ -1373,28 +1363,32 @@ dependencies = [ "csv-async", "ctor", "derive_more", + "elf", "flate2", "fspy_detours_sys", - "fspy_preload_unix", + "fspy_preload_linux", + "fspy_preload_macos", "fspy_preload_windows", - "fspy_seccomp_unotify", "fspy_shared", "fspy_shared_unix", "fspy_test_bin", "futures-util", "libc", + "linux-raw-sys 0.12.1", "nix 0.31.2", "ntapi", "ntest", "ouroboros", "rustc-hash", "sha2 0.11.0", + "syscalls", "tar", "tempfile", "test-log", "thiserror 2.0.18", "tokio", "tokio-util", + "tracing", "vt_casefold", "vt_materialized_artifact", "vt_subprocess_test", @@ -1430,22 +1424,6 @@ version = "0.0.0" name = "fspy_benchmark_target" version = "0.0.0" -[[package]] -name = "fspy_client_unix" -version = "0.0.0" -dependencies = [ - "allocator-api2", - "anyhow", - "bstr", - "fspy_nostd", - "fspy_nostd_alloc", - "fspy_shared", - "fspy_shared_unix", - "itoa", - "libc", - "nix 0.31.2", -] - [[package]] name = "fspy_detours_sys" version = "0.0.0" @@ -1526,20 +1504,33 @@ dependencies = [ ] [[package]] -name = "fspy_preload_unix" +name = "fspy_preload_linux" version = "0.0.0" dependencies = [ "allocator-api2", + "bstr", + "fspy_elf_loader", + "fspy_nostd", + "fspy_nostd_alloc", + "fspy_shared", + "fspy_shared_unix", + "linux-raw-sys 0.12.1", + "syscalls", +] + +[[package]] +name = "fspy_preload_macos" +version = "0.0.0" +dependencies = [ + "allocator-api2", + "bstr", "ctor", - "fspy_client_unix", "fspy_nostd", "fspy_nostd_alloc", "fspy_shared", "fspy_shared_unix", "libc", - "nix 0.31.2", "static_cell", - "syscalls", ] [[package]] @@ -1562,24 +1553,6 @@ dependencies = [ "winsafe 0.0.27", ] -[[package]] -name = "fspy_seccomp_unotify" -version = "0.1.0" -dependencies = [ - "assertables", - "futures-util", - "libc", - "nix 0.31.2", - "passfd", - "seccompiler", - "syscalls", - "tempfile", - "test-log", - "tokio", - "tracing", - "wincode", -] - [[package]] name = "fspy_shared" version = "0.0.0" @@ -1610,17 +1583,15 @@ name = "fspy_shared_unix" version = "0.0.0" dependencies = [ "allocator-api2", - "anyhow", "base64 0.22.1", + "bitflags 2.13.2", "bstr", - "elf", "fspy_nostd", "fspy_nostd_alloc", - "fspy_seccomp_unotify", "fspy_shared", - "memmap2", - "nix 0.31.2", + "linux-raw-sys 0.12.1", "phf 0.13.1", + "tempfile", "wincode", ] @@ -2510,15 +2481,6 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" -[[package]] -name = "memmap2" -version = "0.9.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" -dependencies = [ - "libc", -] - [[package]] name = "memmem" version = "0.1.1" @@ -2693,7 +2655,6 @@ dependencies = [ "cfg-if", "cfg_aliases 0.2.1", "libc", - "memoffset", ] [[package]] @@ -3028,16 +2989,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "passfd" -version = "0.2.0" -source = "git+https://github.com/polachok/passfd?rev=d55881752c16aced1a49a75f9c428d38d3767213#d55881752c16aced1a49a75f9c428d38d3767213" -dependencies = [ - "futures-core", - "libc", - "tokio", -] - [[package]] name = "pastey" version = "0.2.3" @@ -3856,14 +3807,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "seccompiler" -version = "0.5.0" -source = "git+https://github.com/rust-vmm/seccompiler?rev=08587106340b8e3cb361c7561411510039436857#08587106340b8e3cb361c7561411510039436857" -dependencies = [ - "libc", -] - [[package]] name = "security-framework" version = "3.7.0" diff --git a/Cargo.toml b/Cargo.toml index ce4b0b9de..f40b0b4b3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,9 +43,8 @@ allocator-api2 = { version = "0.2", default-features = false } anstream = "1.0.0" anyhow = "1.0.103" assert2 = "0.4.0" -assertables = "10.0.0" async-trait = "0.1.89" -base64 = "0.22.1" +base64 = { version = "0.22.1", default-features = false } bytes = "1.11.1" url = "2.5.8" wincode = { version = "0.6.0", default-features = false, features = ["alloc"] } @@ -80,11 +79,9 @@ flate2 = "1.0.35" fspy = { path = "crates/fspy" } fspy_benchmark_launcher = { path = "crates/fspy_benchmark_launcher", artifact = "bin" } fspy_benchmark_target = { path = "crates/fspy_benchmark_target", artifact = "bin" } -fspy_client_unix = { path = "crates/fspy_client_unix" } fspy_detours_sys = { path = "crates/fspy_detours_sys" } -fspy_preload_unix = { path = "crates/fspy_preload_unix", artifact = "cdylib" } +fspy_preload_macos = { path = "crates/fspy_preload_macos", artifact = "cdylib" } fspy_preload_windows = { path = "crates/fspy_preload_windows", artifact = "cdylib" } -fspy_seccomp_unotify = { path = "crates/fspy_seccomp_unotify" } fspy_shm = { path = "crates/fspy_shm" } fspy_shared = { path = "crates/fspy_shared" } fspy_shared_unix = { path = "crates/fspy_shared_unix" } @@ -93,12 +90,10 @@ futures-util = "0.3.31" globset = "0.4.18" getrandom = "0.4.2" hashbrown = { version = "0.16.1", default-features = false, features = ["inline-more"] } -itoa = "1.0.17" jsonc-parser = "0.32.0" libc = "0.2.185" linux-raw-sys = { version = "0.12", default-features = false } libtest-mimic = "0.8.2" -memmap2 = "0.9.11" monostate = "1.0.2" napi = "3" napi-build = "2" @@ -111,7 +106,6 @@ once_cell = "1.19" os_str_bytes = "7.1.1" ouroboros = "0.18.5" owo-colors = "4.1.0" -passfd = { git = "https://github.com/polachok/passfd", rev = "d55881752c16aced1a49a75f9c428d38d3767213", default-features = false } notify = "8.0.0" path-clean = "1.0.1" pathdiff = "0.2.3" @@ -130,8 +124,6 @@ rusqlite = "0.41.0" rustc-hash = "2.1.1" rustls = { version = "0.23.44", default-features = false } schemars = "1.2.3" -# SeccompAction::UserNotif (SECCOMP_RET_USER_NOTIF) was added after the latest published release (v0.5.0) -seccompiler = { git = "https://github.com/rust-vmm/seccompiler", rev = "08587106340b8e3cb361c7561411510039436857" } serde = "1.0.219" serde-untagged = "0.1.9" serde_bytes = "0.11.19" @@ -204,7 +196,7 @@ zstd = "0.14" [workspace.metadata.cargo-shear] ignored = [ # These are artifact dependencies. They are not directly `use`d in Rust code. - "fspy_preload_unix", + "fspy_preload_macos", "fspy_preload_windows", "vt_client_napi", ] diff --git a/crates/fspy/Cargo.toml b/crates/fspy/Cargo.toml index 049050ac6..3a6214648 100644 --- a/crates/fspy/Cargo.toml +++ b/crates/fspy/Cargo.toml @@ -7,44 +7,45 @@ publish = false [dependencies] allocator-api2 = { workspace = true, features = ["alloc"] } -wincode = { workspace = true } -bumpalo = { workspace = true, features = ["allocator-api2", "collections"] } derive_more = { workspace = true, features = ["debug"] } -vt_materialized_artifact = { workspace = true } fspy_shared = { workspace = true } futures-util = { workspace = true } libc = { workspace = true } -ouroboros = { workspace = true } rustc-hash = { workspace = true } tempfile = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = ["macros", "net", "process", "io-util", "sync", "rt"] } tokio-util = { workspace = true } vt_casefold = { workspace = true } +vt_materialized_artifact = { workspace = true } which = { workspace = true, features = ["tracing"] } - -[target.'cfg(target_os = "linux")'.dependencies] -fspy_seccomp_unotify = { workspace = true, features = ["supervisor"] } -nix = { workspace = true, features = ["uio"] } -tokio = { workspace = true, features = ["bytes"] } +wincode = { workspace = true } [target.'cfg(unix)'.dependencies] +bumpalo = { workspace = true, features = ["allocator-api2", "collections"] } fspy_shared_unix = { workspace = true } -nix = { workspace = true, features = ["fs", "process", "socket", "feature"] } # The preload artifact deps live under `[dependencies]` — not # `[build-dependencies]`, where Cargo would compile them with the # build-override profile (opt-level 0 in release; see # https://github.com/rust-lang/cargo/issues/16719) — so they get the normal # profile, in this workspace and downstream ones, with no per-package profile -# overrides. Cargo provides `CARGO_CDYLIB_FILE_*` while compiling this crate -# for `artifact!` to embed. Each dep is scoped to the targets whose code -# embeds it, so other targets (e.g. musl, which never dynamically links a -# preload) don't build a useless empty cdylib. Scoping artifact deps under -# `[target.cfg…]` is only safe for normal deps: the same shape under -# `[target.cfg….build-dependencies]` panics cargo's resolver on cross-compile. -[target.'cfg(all(unix, not(target_env = "musl")))'.dependencies] -fspy_preload_unix = { workspace = true } +# overrides. Cargo provides `CARGO_BIN_FILE_*` / `CARGO_CDYLIB_FILE_*` while +# compiling this crate for `artifact!` to embed. +[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" } + +[target.'cfg(all(target_os = "linux", target_arch = "aarch64"))'.dependencies] +fspy_preload_linux = { path = "../fspy_preload_linux", artifact = "bin", target = "aarch64-unknown-none-softfloat" } + +[target.'cfg(target_os = "macos")'.dependencies] +fspy_preload_macos = { workspace = true } +ouroboros = { workspace = true } [target.'cfg(target_os = "windows")'.dependencies] fspy_detours_sys = { workspace = true } @@ -53,17 +54,20 @@ ntapi = { workspace = true } winapi = { workspace = true, features = ["winbase", "securitybaseapi", "handleapi"] } winsafe = { workspace = true, features = ["kernel"] } -[target.'cfg(target_os = "macos")'.dev-dependencies] -tempfile = { workspace = true } - [dev-dependencies] anyhow = { workspace = true } csv-async = { workspace = true, features = ["tokio"] } ctor = { workspace = true } ntest = { workspace = true } -vt_subprocess_test = { workspace = true, features = ["fspy"] } test-log = { workspace = true, features = ["trace"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros", "fs", "io-std"] } +vt_subprocess_test = { workspace = true, features = ["fspy"] } + +[target.'cfg(unix)'.dev-dependencies] +nix = { workspace = true, features = ["fs"] } + +[target.'cfg(target_os = "linux")'.dev-dependencies] +elf = { workspace = true } [target.'cfg(all(target_os = "linux", target_arch = "aarch64"))'.dev-dependencies] fspy_test_bin = { path = "../fspy_test_bin", artifact = "bin", target = "aarch64-unknown-linux-musl" } @@ -84,4 +88,10 @@ workspace = true doctest = false [package.metadata.cargo-shear] -ignored = ["ctor", "fspy_test_bin", "fspy_preload_unix", "fspy_preload_windows"] +ignored = [ + "ctor", + "fspy_test_bin", + "fspy_preload_linux", + "fspy_preload_macos", + "fspy_preload_windows", +] diff --git a/crates/fspy/README.md b/crates/fspy/README.md index e80355d9b..0589836c9 100644 --- a/crates/fspy/README.md +++ b/crates/fspy/README.md @@ -2,27 +2,29 @@ Run a command and capture all the paths it tries to access. -## macOS/Linux (glibc) implementation +## Linux implementation -It uses `DYLD_INSERT_LIBRARIES` on macOS and `LD_PRELOAD` on Linux to inject a shared library that intercepts file system calls. -The injection process is almost identical on both platforms other than the environment variable name. The implementation is in `src/unix`. +Linux uses `fspy_preload_linux` (`src/linux`), a freestanding fixed-address ELF64 +loader (`x86_64-unknown-none` / `aarch64-unknown-none-softfloat`) built on +`fspy_elf_loader`. `fspy` spawns `fspy_preload_linux`, which maps the target +executable (dynamic glibc, musl, static, or custom runtime) in-process and +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`. -## Linux-specific implementation for fully static binaries +## macOS implementation -For fully static binaries (such as `esbuild`), `LD_PRELOAD` does not work. In this case, `seccomp_unotify` is used to intercept direct system calls. The handler is implemented in `src/unix/syscall_handler`. It records accesses into the same shared-memory channel as the preload library (`fspy_shared::ipc::channel`). - -## Linux musl implementation - -On musl targets, only `seccomp_unotify`-based tracking is used (no preload library). +macOS uses `DYLD_INSERT_LIBRARIES` with `fspy_preload_macos` (`src/macos`) to +interpose libc file-access and exec calls, substituting bundled shells and +coreutils for SIP-protected `/bin`/`/usr/bin` binaries. ## Windows implementation -It uses [Detours](https://github.com/microsoft/Detours) to intercept file system calls. The implementation is in `src/windows`. +Windows uses [Detours](https://github.com/microsoft/Detours) with +`fspy_preload_windows` (`src/windows`) to intercept Win32/NT file system calls. ## Unified interface The unified interface of `Command` is in `src/command.rs`. - -## Preload Libraries - -`DYLD_INSERT_LIBRARIES`, `LD_PRELOAD`, `Detours` all require a shared library to be injected. The shared libraries of macOS/Linux are in the `fspy_preload_unix` crate, and the shared library of Windows is in the `fspy_preload_windows` crate. diff --git a/crates/fspy/src/command.rs b/crates/fspy/src/command.rs index 295a3c2d2..abd6d234c 100644 --- a/crates/fspy/src/command.rs +++ b/crates/fspy/src/command.rs @@ -4,10 +4,10 @@ use std::{ process::Stdio, }; -#[cfg(unix)] -use allocator_api2::alloc::Global; -#[cfg(unix)] -use fspy_shared_unix::exec::{Exec, to_vec_in}; +#[cfg(target_os = "macos")] +use allocator_api2::{alloc::Global, vec::Vec as AllocVec}; +#[cfg(target_os = "macos")] +use fspy_shared_unix::Exec; use rustc_hash::FxHashMap; use tokio::process::Command as TokioCommand; use tokio_util::sync::CancellationToken; @@ -53,32 +53,29 @@ impl Command { } } - #[cfg(unix)] + #[cfg(target_os = "macos")] #[must_use] pub(crate) fn get_exec(&self) -> Exec { use std::{iter::once, os::unix::ffi::OsStrExt}; + let copy = |bytes: &[u8]| { + let mut out = AllocVec::with_capacity_in(bytes.len(), Global); + out.extend_from_slice(bytes); + out + }; let arg0 = self.arg0.as_ref().unwrap_or(&self.program); Exec { - program: to_vec_in(self.program.as_bytes(), Global), - args: once(arg0) - .chain(&self.args) - .map(|arg| to_vec_in(arg.as_bytes(), Global)) - .collect(), + program: copy(self.program.as_bytes()), + args: once(arg0).chain(&self.args).map(|arg| copy(arg.as_bytes())).collect(), envs: self .envs .iter() - .map(|(name, value)| { - ( - to_vec_in(name.inner().as_bytes(), Global), - Some(to_vec_in(value.as_bytes(), Global)), - ) - }) + .map(|(name, value)| (copy(name.inner().as_bytes()), Some(copy(value.as_bytes())))) .collect(), } } - #[cfg(unix)] + #[cfg(target_os = "macos")] pub(crate) fn set_exec(&mut self, mut exec: Exec) { use std::os::unix::ffi::OsStrExt; @@ -98,6 +95,20 @@ impl Command { .collect(); } + #[cfg(target_os = "linux")] + #[must_use] + pub(crate) fn target_program(&self) -> &OsStr { + &self.program + } + + #[cfg(target_os = "linux")] + pub(crate) fn redirect_program(&mut self, loader_program: &OsStr) { + if self.arg0.is_none() { + self.arg0 = Some(self.program.clone()); + } + self.program = loader_program.to_os_string(); + } + pub fn env_remove>(&mut self, key: K) -> &mut Self { self.envs.remove(EnvName::from_ref(key.as_ref())); self diff --git a/crates/fspy/src/error.rs b/crates/fspy/src/error.rs index e47f84d42..847a1ec02 100644 --- a/crates/fspy/src/error.rs +++ b/crates/fspy/src/error.rs @@ -16,9 +16,6 @@ pub enum SpawnError { cause: which::Error, }, - #[error("failed to initialize seccomp_unotify supervisor: {0}")] - Supervisor(std::io::Error), - #[error("failed to create IPC channel: {0}")] ChannelCreation(std::io::Error), diff --git a/crates/fspy/src/lib.rs b/crates/fspy/src/lib.rs index 6f47bf749..67db8736b 100644 --- a/crates/fspy/src/lib.rs +++ b/crates/fspy/src/lib.rs @@ -2,15 +2,19 @@ pub mod error; mod ipc; -#[cfg(unix)] -#[path = "./unix/mod.rs"] +#[cfg(target_os = "linux")] +#[path = "./linux/mod.rs"] +mod os_impl; + +#[cfg(target_os = "macos")] +#[path = "./macos/mod.rs"] mod os_impl; #[cfg(target_os = "windows")] #[path = "./windows/mod.rs"] mod os_impl; -#[cfg(unix)] +#[cfg(target_os = "macos")] mod arena; mod command; diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs new file mode 100644 index 000000000..6924b2b4b --- /dev/null +++ b/crates/fspy/src/linux/mod.rs @@ -0,0 +1,338 @@ +use std::{ + ffi::CString, + io, + os::{ + fd::{AsRawFd as _, FromRawFd as _, OwnedFd}, + unix::ffi::OsStrExt as _, + }, + path::{Path, PathBuf}, +}; + +use fspy_shared::ipc::{IpcStr, PathAccess, channel::channel}; +use fspy_shared_unix::linux::{BOOTSTRAP_ENV_NAME, Bootstrap, Target, encode_bootstrap}; +use futures_util::FutureExt as _; +use linux_raw_sys::{ + prctl::PR_SET_NO_NEW_PRIVS, + ptrace::{BPF_K, BPF_RET, SECCOMP_RET_ALLOW, SECCOMP_SET_MODE_FILTER, sock_filter, sock_fprog}, +}; +use syscalls::Sysno; +use tokio::io::AsyncReadExt as _; +use tokio_util::sync::CancellationToken; +use vt_materialized_artifact::{Artifact, artifact}; + +use crate::{ + ChildTermination, Command, TrackedChild, TrackingIncomplete, error::SpawnError, + ipc::ChannelAccesses, +}; + +const PRELOAD_LINUX: Artifact = artifact!("fspy_preload", "CARGO_BIN_FILE_FSPY_PRELOAD_LINUX"); + +#[derive(Debug)] +pub struct SpyImpl { + /// Materialized executable path to `fspy_preload_linux`, or `None` when the + /// temp directory does not permit executing files (e.g. a `noexec` mount), + /// in which case `spawn` falls back to untracked execution. + preload_path: Option>, + seccomp_available: bool, +} + +impl SpyImpl { + /// Materializes `fspy_preload_linux` into the user's temp directory and + /// probes whether this environment permits installing a seccomp filter. + pub fn init() -> io::Result { + let seccomp_available = probe_seccomp_available()?; + let preload_path = if seccomp_available { + let materialized = materialize_executable_preload().map(|p| p.as_path().into()); + if materialized.is_none() { + tracing::warn!( + "the temp directory does not allow executing files, so Linux task \ + tracking is off and caching is disabled; set TMPDIR to a directory \ + on a filesystem without `noexec` to enable it" + ); + } + materialized + } else { + None + }; + Ok(Self { preload_path, seccomp_available }) + } + + pub(crate) async fn spawn( + &self, + mut command: Command, + cancellation_token: CancellationToken, + ) -> Result { + let Some(preload_path) = + (self.seccomp_available).then_some(self.preload_path.as_deref()).flatten() + else { + return spawn_untracked(command, cancellation_token); + }; + + let ipc_receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) + .map_err(SpawnError::ChannelCreation)?; + + let (read_end, write_end) = create_error_pipe().map_err(SpawnError::OsSpawn)?; + let mut pipe_reader = tokio::net::unix::pipe::Receiver::from_owned_fd(read_end) + .map_err(SpawnError::OsSpawn)?; + let write_raw_fd = write_end.as_raw_fd(); + + let target_path: &IpcStr = command.target_program().into(); + let bootstrap = Bootstrap { + ipc_channel_conf: ipc_receiver.conf(), + preload_path, + target: Target::Unresolved { path: target_path, error_pipe_fd: write_raw_fd }, + }; + let bump = bumpalo::Bump::new(); + let encoded = encode_bootstrap(&bootstrap, &bump); + + command.redirect_program(preload_path.as_os_str()); + command.env("FSPY", "1"); + command.env(BOOTSTRAP_ENV_NAME, encoded); + + let mut tokio_command = command.into_tokio_command(); + // SAFETY: `fcntl(F_SETFD, 0)` is async-signal-safe, and `write_raw_fd` + // remains open in the parent until `spawn()` finishes. + unsafe { + tokio_command.pre_exec(move || { + if libc::fcntl(write_raw_fd, libc::F_SETFD, 0) == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + + let mut child = tokio_command.spawn().map_err(SpawnError::OsSpawn)?; + // Close the parent's copy of the write end immediately so EOF fires if + // `fspy_preload_linux` terminates before writing a status code. + drop(write_end); + + let mut buf = [0u8; 4]; + let mut filled = 0usize; + let mut cancelled = false; + while filled < buf.len() { + tokio::select! { + read_res = pipe_reader.read(&mut buf[filled..]) => match read_res { + Ok(0) => break, + Ok(n) => filled += n, + Err(err) if err.kind() == io::ErrorKind::Interrupted => {} + Err(err) => { + let _ = child.start_kill(); + let _ = child.wait().await; + return Err(SpawnError::OsSpawn(err)); + } + }, + () = cancellation_token.cancelled() => { + cancelled = true; + break; + } + } + } + drop(pipe_reader); + + if !cancelled { + if filled < buf.len() { + let _ = child.wait().await; + return Err(SpawnError::OsSpawn(io::Error::new( + io::ErrorKind::UnexpectedEof, + "launcher exited before reporting exec status", + ))); + } + let code = i32::from_ne_bytes(buf); + if code != 0 { + let _ = child.wait().await; + return Err(SpawnError::OsSpawn(io::Error::from_raw_os_error(code))); + } + } + + 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? + } + }; + + let path_accesses = ChannelAccesses::try_from(ipc_receiver) + .map(|ipc_accesses| PathAccessIterable { ipc_accesses }); + io::Result::Ok(ChildTermination { status, path_accesses }) + }) + .map(|f| f?) + .boxed(), + }) + } +} + +fn spawn_untracked( + command: Command, + cancellation_token: CancellationToken, +) -> Result { + let mut tokio_command = command.into_tokio_command(); + let mut child = tokio_command.spawn().map_err(SpawnError::OsSpawn)?; + 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(TrackingIncomplete) }) + }) + .map(|f| f?) + .boxed(), + }) +} + +/// Materializes `fspy_preload_linux` into the user's temp directory, or +/// returns `None` when that directory cannot hold it or sits on a `noexec` +/// mount (such as a CIS-hardened `/tmp`), so `SpyImpl::spawn` falls back to +/// untracked execution. +fn materialize_executable_preload() -> Option { + let path = PRELOAD_LINUX.materialize().executable().at_user_temp_dir("vp_run").ok()?; + is_path_executable(&path).then_some(path) +} + +/// Returns `true` when `path` is executable (`access(X_OK) == 0`) and not on a +/// `noexec` mount (`statvfs.f_flag & ST_NOEXEC == 0`). +fn is_path_executable(path: &Path) -> bool { + let Ok(cpath) = CString::new(path.as_os_str().as_bytes()) else { + return false; + }; + // SAFETY: `cpath` is a valid NUL-terminated path. + if unsafe { libc::access(cpath.as_ptr(), libc::X_OK) } != 0 { + return false; + } + // SAFETY: `libc::statvfs` is a plain C struct valid when zero-initialized. + let mut vfs: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: `cpath` is NUL-terminated and `vfs` is valid writable storage. + if unsafe { libc::statvfs(cpath.as_ptr(), &raw mut vfs) } != 0 { + return false; + } + (vfs.f_flag & libc::ST_NOEXEC) == 0 +} + +/// Probes once in a short-lived forked child whether `PR_SET_NO_NEW_PRIVS` and +/// `seccomp(SECCOMP_SET_MODE_FILTER)` are permitted in the current environment. +fn probe_seccomp_available() -> io::Result { + // SAFETY: `fork()` is safe to call here; the child performs only + // async-signal-safe raw syscalls and exits immediately with `_exit`. + let pid = unsafe { libc::fork() }; + if pid < 0 { + return Err(io::Error::last_os_error()); + } + if pid == 0 { + #[expect(clippy::cast_possible_truncation, reason = "cBPF opcode fits in u16")] + let filter = + [sock_filter { code: (BPF_RET | BPF_K) as u16, jt: 0, jf: 0, k: SECCOMP_RET_ALLOW }]; + let prog = sock_fprog { len: 1, filter: filter.as_ptr().cast_mut() }; + // SAFETY: async-signal-safe raw syscalls on stack-local BPF program. + let ok = unsafe { + syscalls::syscall!(Sysno::prctl, PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0).is_ok() + && syscalls::syscall!(Sysno::seccomp, SECCOMP_SET_MODE_FILTER, 0, &raw const prog) + .is_ok() + }; + // SAFETY: terminates the forked child immediately without running destructors. + unsafe { libc::_exit(i32::from(!ok)) }; + } + + let mut status = 0; + loop { + // SAFETY: `pid` is our child process and `status` is valid writable storage. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + if waited < 0 { + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(err); + } + return Ok(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); + } +} + +/// Creates a `CLOEXEC` pipe whose read end is non-blocking (for tokio's async +/// pipe receiver) and whose write end stays blocking for the 4-byte startup +/// status write from `fspy_preload_linux`. +fn create_error_pipe() -> io::Result<(OwnedFd, OwnedFd)> { + let mut fds = [-1; 2]; + // SAFETY: `fds` is a valid 2-element array for `pipe2`. + if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) } == -1 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `pipe2` returned two newly opened descriptors. + let read_end = unsafe { OwnedFd::from_raw_fd(fds[0]) }; + // SAFETY: `pipe2` returned two newly opened descriptors. + let write_end = unsafe { OwnedFd::from_raw_fd(fds[1]) }; + + // SAFETY: `read_end` is a valid open descriptor. + let flags = unsafe { libc::fcntl(read_end.as_raw_fd(), libc::F_GETFL) }; + if flags == -1 { + return Err(io::Error::last_os_error()); + } + // SAFETY: setting `O_NONBLOCK` on our owned pipe read end. + if unsafe { libc::fcntl(read_end.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 { + return Err(io::Error::last_os_error()); + } + Ok((read_end, write_end)) +} + +pub struct PathAccessIterable { + ipc_accesses: ChannelAccesses, +} + +impl PathAccessIterable { + /// Iterates over the path accesses in the order they were made. + /// + /// Accesses made at the same time by different threads or processes + /// appear in an unspecified order relative to each other. + pub fn iter(&self) -> impl Iterator> { + self.ipc_accesses.iter_path_accesses() + } +} + +#[cfg(test)] +mod tests { + use elf::{ElfBytes, abi, endian::LittleEndian, file::Class}; + + const PRELOAD_LINUX_BYTES: &[u8] = include_bytes!(env!("CARGO_BIN_FILE_FSPY_PRELOAD_LINUX")); + + #[test] + fn preload_linux_image_uses_high_fixed_addresses_without_runtime_relocations() { + let image = ElfBytes::::minimal_parse(PRELOAD_LINUX_BYTES).unwrap(); + assert_eq!(image.ehdr.class, Class::ELF64); + assert_eq!(image.ehdr.e_type, abi::ET_EXEC); + let (base, limit) = match image.ehdr.e_machine { + abi::EM_X86_64 => (0x5500_0000_0000, 0x5a00_0000_0000), + abi::EM_AARCH64 => (0x0002_0000_0000, 0x0005_0000_0000), + machine => panic!("unsupported preload machine: {machine}"), + }; + let segments: Vec<_> = image.segments().unwrap().iter().collect(); + assert!( + !segments + .iter() + .any(|ph| matches!(ph.p_type, abi::PT_INTERP | abi::PT_DYNAMIC | abi::PT_TLS)) + ); + let first_load = segments.iter().find(|ph| ph.p_type == abi::PT_LOAD).unwrap(); + assert_eq!((first_load.p_vaddr, first_load.p_offset), (base, 0)); + for segment in segments.iter().filter(|ph| ph.p_type == abi::PT_LOAD) { + assert!(segment.p_vaddr >= base); + assert!(segment.p_vaddr.checked_add(segment.p_memsz).unwrap() <= limit); + } + assert!(segments.iter().any(|ph| { + ph.p_type == abi::PT_LOAD + && ph.p_flags & abi::PF_X != 0 + && ph.p_vaddr <= image.ehdr.e_entry + && image.ehdr.e_entry < ph.p_vaddr + ph.p_memsz + })); + assert!(image.dynamic().unwrap().is_none()); + } +} diff --git a/crates/fspy/src/unix/macos_artifacts.rs b/crates/fspy/src/macos/macos_artifacts.rs similarity index 95% rename from crates/fspy/src/unix/macos_artifacts.rs rename to crates/fspy/src/macos/macos_artifacts.rs index c348f0649..c4dd70739 100644 --- a/crates/fspy/src/unix/macos_artifacts.rs +++ b/crates/fspy/src/macos/macos_artifacts.rs @@ -7,7 +7,7 @@ pub const OILS_BINARY: Artifact = artifact!("oils_for_unix", "FSPY_MACOS_ARTIFAC mod tests { use std::{process::Command, str::from_utf8}; - use fspy_shared_unix::spawn::COREUTILS_FUNCTIONS_FOR_TEST; + use fspy_shared_unix::macos::COREUTILS_FUNCTIONS_FOR_TEST; use super::*; diff --git a/crates/fspy/src/macos/mod.rs b/crates/fspy/src/macos/mod.rs new file mode 100644 index 000000000..dd60deb02 --- /dev/null +++ b/crates/fspy/src/macos/mod.rs @@ -0,0 +1,130 @@ +mod macos_artifacts; + +use std::io; + +use fspy_shared::ipc::{IpcPath, IpcStr, PathAccess, channel::channel}; +use fspy_shared_unix::macos::{EncodedPayload, Payload}; +use futures_util::FutureExt as _; +use tokio_util::sync::CancellationToken; +use vt_materialized_artifact::{Artifact, artifact}; + +use crate::{ + ChildTermination, Command, TrackedChild, arena::PathAccessArena, error::SpawnError, + ipc::ChannelAccesses, +}; + +#[derive(Debug)] +#[expect(clippy::struct_field_names, reason = "each field names a distinct injected path")] +pub struct SpyImpl { + bash_path: Box, + coreutils_path: Box, + preload_path: Box, +} + +impl SpyImpl { + /// Materializes `fspy_preload_macos`, `oils_for_unix`, and `coreutils` into + /// the current user's `vp_run` folder in the system temp dir. + pub fn init() -> io::Result { + const PRELOAD_CDYLIB: Artifact = + artifact!("fspy_preload", "CARGO_CDYLIB_FILE_FSPY_PRELOAD_MACOS"); + + 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(), + }) + } + + pub(crate) fn spawn( + &self, + command: Command, + cancellation_token: CancellationToken, + ) -> std::future::Ready> { + std::future::ready(self.spawn_inner(command, cancellation_token)) + } + + fn spawn_inner( + &self, + mut command: Command, + cancellation_token: CancellationToken, + ) -> Result { + 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, + }; + + let payload_bump = bumpalo::Bump::new(); + let encoded_payload = EncodedPayload::encode(payload, &payload_bump); + + let mut exec = command.get_exec(); + let mut exec_resolve_accesses = PathAccessArena::default(); + encoded_payload + .prepare_exec(&mut exec, |path| { + exec_resolve_accesses.add(PathAccess::Read(IpcPath::from_bytes(path.as_ref()))); + }) + .map_err(|err| { + SpawnError::Injection(io::Error::from_raw_os_error(err.raw_os_error())) + })?; + command.set_exec(exec); + command.env("FSPY", "1"); + + let mut tokio_command = command.into_tokio_command(); + let mut child = tokio_command.spawn().map_err(SpawnError::OsSpawn)?; + + 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? + } + }; + + let path_accesses = ChannelAccesses::try_from(ipc_receiver) + .map(|ipc_accesses| PathAccessIterable { exec_resolve_accesses, ipc_accesses }); + io::Result::Ok(ChildTermination { status, path_accesses }) + }) + .map(|f| f?) + .boxed(), + }) + } +} + +pub struct PathAccessIterable { + exec_resolve_accesses: PathAccessArena, + ipc_accesses: ChannelAccesses, +} + +impl PathAccessIterable { + /// Iterates over the path accesses in the order they were made. + /// + /// Accesses made at the same time by different threads or processes + /// appear in an unspecified order relative to each other. + pub fn iter(&self) -> impl Iterator> { + let accesses_in_arena = self.exec_resolve_accesses.borrow_accesses().iter().copied(); + let accesses_in_shm = self.ipc_accesses.iter_path_accesses(); + accesses_in_arena.chain(accesses_in_shm) + } +} diff --git a/crates/fspy/src/unix/mod.rs b/crates/fspy/src/unix/mod.rs deleted file mode 100644 index e0e850037..000000000 --- a/crates/fspy/src/unix/mod.rs +++ /dev/null @@ -1,210 +0,0 @@ -#[cfg(target_os = "linux")] -mod syscall_handler; - -#[cfg(target_os = "macos")] -mod macos_artifacts; - -use std::io; -#[cfg(target_os = "linux")] -use std::sync::Arc; - -#[cfg(target_os = "linux")] -use fspy_seccomp_unotify::supervisor::supervise; -#[cfg(not(target_env = "musl"))] -use fspy_shared::ipc::IpcStr; -use fspy_shared::ipc::{PathAccess, channel::channel}; -use fspy_shared_unix::{ - exec::ExecResolveConfig, - payload::{Payload, encode_payload}, - spawn::handle_exec, -}; -use futures_util::FutureExt; -#[cfg(target_os = "linux")] -use syscall_handler::SyscallHandler; -use tokio::task::spawn_blocking; -use tokio_util::sync::CancellationToken; - -use crate::{ - ChildTermination, Command, TrackedChild, arena::PathAccessArena, error::SpawnError, - ipc::ChannelAccesses, -}; - -#[derive(Debug)] -#[cfg_attr( - target_os = "macos", - expect(clippy::struct_field_names, reason = "each field names a distinct injected path") -)] -pub struct SpyImpl { - #[cfg(target_os = "macos")] - bash_path: Box, - #[cfg(target_os = "macos")] - coreutils_path: Box, - - #[cfg(not(target_env = "musl"))] - preload_path: Box, -} - -impl SpyImpl { - /// Initialize the fs access spy by writing the preload library on disk, in - /// the current user's own `vp_run` folder in the system temp dir. - /// - /// On musl targets, we don't build a preload library — - /// only seccomp-based tracking is used. - pub fn init() -> io::Result { - #[cfg(not(target_env = "musl"))] - let preload_path = { - use vt_materialized_artifact::{Artifact, artifact}; - - const PRELOAD_CDYLIB: Artifact = - artifact!("fspy_preload", "CARGO_CDYLIB_FILE_FSPY_PRELOAD_UNIX"); - - let preload_cdylib_path = - PRELOAD_CDYLIB.materialize().suffix(".dylib").at_user_temp_dir("vp_run")?; - preload_cdylib_path.as_path().into() - }; - - Ok(Self { - #[cfg(not(target_env = "musl"))] - preload_path, - #[cfg(target_os = "macos")] - bash_path: macos_artifacts::OILS_BINARY - .materialize() - .executable() - .at_user_temp_dir("vp_run")? - .as_path() - .into(), - #[cfg(target_os = "macos")] - coreutils_path: macos_artifacts::COREUTILS_BINARY - .materialize() - .executable() - .at_user_temp_dir("vp_run")? - .as_path() - .into(), - }) - } - - pub(crate) async fn spawn( - &self, - mut command: Command, - cancellation_token: CancellationToken, - ) -> Result { - let ipc_receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) - .map_err(SpawnError::ChannelCreation)?; - - // The supervisor records the accesses it intercepts into the same - // channel as the preload library. - #[cfg(target_os = "linux")] - let supervisor = { - let ipc_sender = Arc::new(ipc_receiver.sender().map_err(SpawnError::ChannelCreation)?); - supervise(move || SyscallHandler::new(Arc::clone(&ipc_sender))) - .map_err(SpawnError::Supervisor)? - }; - - let payload = Payload { - #[cfg(not(target_env = "musl"))] - ipc_channel_conf: ipc_receiver.conf(), - #[cfg(target_env = "musl")] - ipc_channel_conf: core::marker::PhantomData, - - #[cfg(not(target_env = "musl"))] - preload_path: &self.preload_path, - - #[cfg(target_os = "macos")] - artifacts: fspy_shared_unix::payload::Artifacts { - bash_path: &self.bash_path, - coreutils_path: &self.coreutils_path, - }, - - #[cfg(target_os = "linux")] - seccomp_payload: supervisor.payload().clone(), - }; - - // Spawn-scoped storage for the encoded payload, freed when this - // spawn returns. - let payload_bump = bumpalo::Bump::new(); - let encoded_payload = encode_payload(payload, &payload_bump); - - let mut exec = command.get_exec(); - let mut exec_resolve_accesses = PathAccessArena::default(); - let pre_exec = handle_exec( - &mut exec, - ExecResolveConfig::search_path_enabled(None), - &encoded_payload, - |path| { - exec_resolve_accesses.add(PathAccess::Read(path.into())); - }, - ) - .map_err(|err| SpawnError::Injection(err.into()))?; - command.set_exec(exec); - command.env("FSPY", "1"); - - let mut tokio_command = command.into_tokio_command(); - - // SAFETY: the pre_exec closure only calls pre_exec.run() which is safe to call in a fork context - unsafe { - tokio_command.pre_exec(move || { - if let Some(pre_exec) = pre_exec.as_ref() { - pre_exec.run()?; - } - Ok(()) - }); - } - - // tokio_command.spawn blocks while executing the `pre_exec` closure. - // Run it inside spawn_blocking to avoid blocking the tokio runtime, especially the supervisor loop, - // which needs to accept incoming connections while `pre_exec` is connecting to it. - let mut child = spawn_blocking(move || tokio_command.spawn()) - .await - .map_err(|err| SpawnError::OsSpawn(err.into()))? - .map_err(SpawnError::OsSpawn)?; - - Ok(TrackedChild { - stdin: child.stdin.take(), - stdout: child.stdout.take(), - stderr: child.stderr.take(), - // Keep polling for the child to exit in the background even if `wait_handle` is not awaited, - // because we need to stop the supervisor and close the channel as soon as the child exits. - wait_handle: tokio::spawn(async move { - let status = tokio::select! { - status = child.wait() => status?, - () = cancellation_token.cancelled() => { - child.start_kill()?; - child.wait().await? - } - }; - - // Stop the supervisor before closing the channel, so the - // accesses it intercepted are all recorded in the channel. - #[cfg(target_os = "linux")] - supervisor.stop().await?; - - // Close the ipc channel after the child has exited. - // We are not interested in path accesses from descendants after the main child has exited. - let path_accesses = ChannelAccesses::try_from(ipc_receiver) - .map(|ipc_accesses| PathAccessIterable { exec_resolve_accesses, ipc_accesses }); - - io::Result::Ok(ChildTermination { status, path_accesses }) - }) - .map(|f| f?) // flatten JoinError and io::Result - .boxed(), - }) - } -} - -pub struct PathAccessIterable { - exec_resolve_accesses: PathAccessArena, - ipc_accesses: ChannelAccesses, -} - -impl PathAccessIterable { - /// Iterates over the path accesses in the order they were made. - /// - /// Accesses made at the same time by different threads or processes - /// appear in an unspecified order relative to each other. - pub fn iter(&self) -> impl Iterator> { - // Resolving the program happens before the child is spawned. - let accesses_in_arena = self.exec_resolve_accesses.borrow_accesses().iter().copied(); - let accesses_in_shm = self.ipc_accesses.iter_path_accesses(); - accesses_in_arena.chain(accesses_in_shm) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/execve.rs b/crates/fspy/src/unix/syscall_handler/execve.rs deleted file mode 100644 index d34ac8c2d..000000000 --- a/crates/fspy/src/unix/syscall_handler/execve.rs +++ /dev/null @@ -1,24 +0,0 @@ -use std::io; - -use fspy_seccomp_unotify::supervisor::handler::arg::{CStrPtr, Caller, Fd}; - -use super::SyscallHandler; - -impl SyscallHandler { - fn handle_execve(&mut self, caller: Caller, fd: Fd, path_ptr: CStrPtr) -> io::Result<()> { - // TODO: parse shebangs to track reading interpreters - self.handle_open(caller, fd, path_ptr, libc::O_RDONLY) - } - - pub(super) fn execveat( - &mut self, - caller: Caller, - (fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_execve(caller, fd, path_ptr) - } - - pub(super) fn execve(&mut self, caller: Caller, (path_ptr,): (CStrPtr,)) -> io::Result<()> { - self.handle_execve(caller, Fd::cwd(), path_ptr) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/getdents.rs b/crates/fspy/src/unix/syscall_handler/getdents.rs deleted file mode 100644 index 45eec5320..000000000 --- a/crates/fspy/src/unix/syscall_handler/getdents.rs +++ /dev/null @@ -1,16 +0,0 @@ -use std::io; - -use fspy_seccomp_unotify::supervisor::handler::arg::{Caller, Fd}; - -use super::SyscallHandler; - -impl SyscallHandler { - #[cfg(target_arch = "x86_64")] - pub(super) fn getdents(&mut self, caller: Caller, (fd,): (Fd,)) -> io::Result<()> { - self.handle_open_dir(caller, fd) - } - - pub(super) fn getdents64(&mut self, caller: Caller, (fd,): (Fd,)) -> io::Result<()> { - self.handle_open_dir(caller, fd) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/mod.rs b/crates/fspy/src/unix/syscall_handler/mod.rs deleted file mode 100644 index d55ce8fbb..000000000 --- a/crates/fspy/src/unix/syscall_handler/mod.rs +++ /dev/null @@ -1,120 +0,0 @@ -mod execve; -mod getdents; -mod namespace; -mod open; -mod stat; - -use std::{ - borrow::Cow, - ffi::{OsStr, c_int}, - io, - os::unix::ffi::OsStrExt, - path::{Path, PathBuf}, - sync::Arc, -}; - -use fspy_seccomp_unotify::{ - impl_handler, - supervisor::handler::arg::{CStrPtr, Caller, Fd}, -}; -use fspy_shared::ipc::{AccessMode, PathAccess, channel::Sender}; - -const PATH_MAX: usize = libc::PATH_MAX as usize; - -/// Records the accesses of intercepted syscalls into the IPC channel. -/// -/// The supervisor lets a syscall continue only after its handler returns, so -/// every record is published before the access it describes, as the channel -/// requires of its senders. -pub struct SyscallHandler { - ipc_sender: Arc, - path_read_buf: [u8; PATH_MAX], -} - -impl SyscallHandler { - pub const fn new(ipc_sender: Arc) -> Self { - Self { ipc_sender, path_read_buf: [0; PATH_MAX] } - } - - fn handle_open( - &mut self, - caller: Caller, - dir_fd: Fd, - path_ptr: CStrPtr, - flags: c_int, - ) -> io::Result<()> { - let mode = match flags & libc::O_ACCMODE { - libc::O_RDWR => AccessMode::ReadWrite, - libc::O_WRONLY => AccessMode::Write, - _ => AccessMode::Read, - }; - self.handle_path(caller, dir_fd, path_ptr, mode) - } - - fn handle_path( - &mut self, - caller: Caller, - dir_fd: Fd, - path_ptr: CStrPtr, - mode: AccessMode, - ) -> io::Result<()> { - let Some(path_len) = path_ptr.read(caller, &mut self.path_read_buf)? else { - // Ignore paths that are too long to fit in PATH_MAX - return Ok(()); - }; - let mut path = Cow::Borrowed(Path::new(OsStr::from_bytes(&self.path_read_buf[..path_len]))); - if !path.is_absolute() { - let mut resolved_path = PathBuf::from(dir_fd.get_path(caller)?); - if !nix::NixPath::is_empty(path.as_ref()) { - resolved_path.push(&path); - } - path = Cow::Owned(resolved_path); - } - self.ipc_sender.send(&mode.with_path(path.as_os_str().into())); - Ok(()) - } - - #[expect( - clippy::needless_pass_by_ref_mut, - reason = "same receiver as `handle_open`, which writes `path_read_buf`" - )] - fn handle_open_dir(&mut self, caller: Caller, fd: Fd) -> io::Result<()> { - let path = fd.get_path(caller)?; - self.ipc_sender.send(&PathAccess::ReadDir(OsStr::from_bytes(path.as_bytes()).into())); - Ok(()) - } -} - -impl_handler!( - SyscallHandler: - - #[cfg(target_arch = "x86_64")] open, - openat, - openat2, - - #[cfg(target_arch = "x86_64")] getdents, - getdents64, - - #[cfg(target_arch = "x86_64")] stat, - #[cfg(target_arch = "x86_64")] lstat, - #[cfg(target_arch = "x86_64")] newfstatat, - #[cfg(target_arch = "aarch64")] fstatat, - statx, - - #[cfg(target_arch = "x86_64")] access, - faccessat, - faccessat2, - - #[cfg(target_arch = "x86_64")] mkdir, - mkdirat, - #[cfg(target_arch = "x86_64")] rename, - renameat, - renameat2, - #[cfg(target_arch = "x86_64")] link, - linkat, - #[cfg(target_arch = "x86_64")] symlink, - symlinkat, - - execve, - execveat, -); diff --git a/crates/fspy/src/unix/syscall_handler/namespace.rs b/crates/fspy/src/unix/syscall_handler/namespace.rs deleted file mode 100644 index 2eccd1f4b..000000000 --- a/crates/fspy/src/unix/syscall_handler/namespace.rs +++ /dev/null @@ -1,91 +0,0 @@ -//! Syscalls that make an entry at a path without opening it: mkdir, symlink, -//! and rename and hard link, which put an existing file or folder at a new -//! path. The path of a mkdir is recorded as a mkdir, whether or not the -//! folder is there already; the new path of a rename as a rename target, -//! which may be a whole folder; and that of a symlink, and of a hard link, -//! always a file, as a write. The source of a rename needs no record, and -//! neither does the target of a symlink, which is stored as text, not -//! accessed. - -use std::io; - -use fspy_seccomp_unotify::supervisor::handler::arg::{CStrPtr, Caller, Fd, Ignored}; -use fspy_shared::ipc::AccessMode; - -use super::SyscallHandler; - -impl SyscallHandler { - #[cfg(target_arch = "x86_64")] - pub(super) fn mkdir(&mut self, caller: Caller, (path,): (CStrPtr,)) -> io::Result<()> { - self.handle_path(caller, Fd::cwd(), path, AccessMode::Mkdir) - } - - pub(super) fn mkdirat( - &mut self, - caller: Caller, - (dir_fd, path): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, dir_fd, path, AccessMode::Mkdir) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn rename( - &mut self, - caller: Caller, - (_old, new): (Ignored, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, Fd::cwd(), new, AccessMode::RenameTarget) - } - - pub(super) fn renameat( - &mut self, - caller: Caller, - (_old_dir_fd, _old, new_dir_fd, new): (Ignored, Ignored, Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, new_dir_fd, new, AccessMode::RenameTarget) - } - - /// With `RENAME_EXCHANGE` both paths change; only the destination is - /// recorded, as for a plain rename. - pub(super) fn renameat2( - &mut self, - caller: Caller, - (_old_dir_fd, _old, new_dir_fd, new): (Ignored, Ignored, Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, new_dir_fd, new, AccessMode::RenameTarget) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn link( - &mut self, - caller: Caller, - (_old, new): (Ignored, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, Fd::cwd(), new, AccessMode::Write) - } - - pub(super) fn linkat( - &mut self, - caller: Caller, - (_old_dir_fd, _old, new_dir_fd, new): (Ignored, Ignored, Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, new_dir_fd, new, AccessMode::Write) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn symlink( - &mut self, - caller: Caller, - (_target, link): (Ignored, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, Fd::cwd(), link, AccessMode::Write) - } - - pub(super) fn symlinkat( - &mut self, - caller: Caller, - (_target, new_dir_fd, link): (Ignored, Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_path(caller, new_dir_fd, link, AccessMode::Write) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/open.rs b/crates/fspy/src/unix/syscall_handler/open.rs deleted file mode 100644 index be7ae157e..000000000 --- a/crates/fspy/src/unix/syscall_handler/open.rs +++ /dev/null @@ -1,35 +0,0 @@ -use std::{ffi::c_int, io}; - -use fspy_seccomp_unotify::supervisor::handler::arg::{CStrPtr, Caller, Fd, Ptr}; - -use super::SyscallHandler; - -impl SyscallHandler { - #[cfg(target_arch = "x86_64")] - pub(super) fn open( - &mut self, - caller: Caller, - (path, flags): (CStrPtr, c_int), - ) -> io::Result<()> { - self.handle_open(caller, Fd::cwd(), path, flags) - } - - pub(super) fn openat( - &mut self, - caller: Caller, - (dir_fd, path, flags): (Fd, CStrPtr, c_int), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path, flags) - } - - pub(super) fn openat2( - &mut self, - caller: Caller, - // open_how is a pointer to struct `open_how`, but we only care about flags here, so use `Ptr` - (dir_fd, path, open_how): (Fd, CStrPtr, Ptr), - ) -> io::Result<()> { - // SAFETY: open_how is a valid pointer to struct `open_how` in the target process, which has `flags` as the first field of type `u64` - let flags = unsafe { open_how.read(caller) }?; - self.handle_open(caller, dir_fd, path, c_int::try_from(flags).unwrap_or(libc::O_RDWR)) - } -} diff --git a/crates/fspy/src/unix/syscall_handler/stat.rs b/crates/fspy/src/unix/syscall_handler/stat.rs deleted file mode 100644 index 40d9f76f1..000000000 --- a/crates/fspy/src/unix/syscall_handler/stat.rs +++ /dev/null @@ -1,68 +0,0 @@ -use std::io; - -use fspy_seccomp_unotify::supervisor::handler::arg::{CStrPtr, Caller, Fd}; - -use super::SyscallHandler; - -impl SyscallHandler { - #[cfg(target_arch = "x86_64")] - pub(super) fn stat(&mut self, caller: Caller, (path,): (CStrPtr,)) -> io::Result<()> { - self.handle_open(caller, Fd::cwd(), path, libc::O_RDONLY) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn lstat(&mut self, caller: Caller, (path,): (CStrPtr,)) -> io::Result<()> { - self.handle_open(caller, Fd::cwd(), path, libc::O_RDONLY) - } - - #[cfg(target_arch = "aarch64")] - pub(super) fn fstatat( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } - - #[cfg(target_arch = "x86_64")] - pub(super) fn newfstatat( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } - - /// statx(2) — modern replacement for stat/fstatat used by newer glibc. - pub(super) fn statx( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } - - /// access(2) — check file accessibility (e.g. existsSync in Node.js). - #[cfg(target_arch = "x86_64")] - pub(super) fn access(&mut self, caller: Caller, (path,): (CStrPtr,)) -> io::Result<()> { - self.handle_open(caller, Fd::cwd(), path, libc::O_RDONLY) - } - - /// faccessat(2) — check file accessibility relative to directory fd. - pub(super) fn faccessat( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } - - /// faccessat2(2) — extended faccessat with flags parameter. - pub(super) fn faccessat2( - &mut self, - caller: Caller, - (dir_fd, path_ptr): (Fd, CStrPtr), - ) -> io::Result<()> { - self.handle_open(caller, dir_fd, path_ptr, libc::O_RDONLY) - } -} diff --git a/crates/fspy/tests/exec_empty_path.rs b/crates/fspy/tests/exec_empty_path.rs index d8ad11d3d..529181cab 100644 --- a/crates/fspy/tests/exec_empty_path.rs +++ b/crates/fspy/tests/exec_empty_path.rs @@ -94,10 +94,6 @@ async fn exec_empty_path_fails_like_untraced() -> anyhow::Result<()> { assert_eq!(exec_empty_path(), untraced); }) .await?; - // Seccomp tracking, used on musl, reports the directory an empty path - // is relative to. - if cfg!(not(target_env = "musl")) { - assert_not_contains(&accesses, ¤t_dir()?); - } + assert_not_contains(&accesses, ¤t_dir()?); Ok(()) } diff --git a/crates/fspy/tests/invalid_dirfd.rs b/crates/fspy/tests/invalid_dirfd.rs index 6dfc802a5..bb2f6396e 100644 --- a/crates/fspy/tests/invalid_dirfd.rs +++ b/crates/fspy/tests/invalid_dirfd.rs @@ -30,7 +30,7 @@ const STATX_BASIC_STATS: libc::c_uint = 0x7ff; #[repr(C, align(8))] struct StatxBuf([u8; 256]); -/// Calls `statx` through `syscall`, which fspy intercepts on glibc. +/// Calls `statx` directly through `syscall(2)`. /// /// The libc `statx` wrapper is not called directly: glibc added it in 2.28, /// so a test built for an older glibc fails to link. @@ -55,8 +55,7 @@ fn syscall_statx( } } -/// Calls the glibc `statx` wrapper, resolved at run time. With `LD_PRELOAD`, -/// the lookup finds the fspy interposer first. +/// Calls the glibc `statx` wrapper, resolved at run time. /// /// # Panics /// diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs new file mode 100644 index 000000000..413f1efe9 --- /dev/null +++ b/crates/fspy/tests/linux_hardening.rs @@ -0,0 +1,314 @@ +//! Linux hardening tests covering `vfork`/`posix_spawn` memory reclamation, +//! `memfd_create` + `execveat(AT_EMPTY_PATH)`, `execve("/proc/self/fd/N")`, +//! and deep `execve` chain FD/env/filter hygiene. +#![cfg(target_os = "linux")] + +mod test_utils; + +use std::path::Path; + +use test_log::test; + +use crate::test_utils::{assert_contains, test_bin_path}; + +#[test(tokio::test)] +async fn posix_spawn_parent_rss_stays_bounded() -> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + use std::ffi::CString; + + fn vm_rss_kib() -> usize { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + for line in status.lines() { + if let Some(rest) = line.strip_prefix("VmRSS:") { + return rest.split_whitespace().next().unwrap().parse::().unwrap(); + } + } + panic!("VmRSS not found in /proc/self/status"); + } + + let prog = CString::new("/bin/true").unwrap(); + let arg0 = CString::new("true").unwrap(); + let argv = [arg0.as_ptr().cast_mut(), std::ptr::null_mut()]; + + let mut env_cstrs = Vec::new(); + for (k, v) in std::env::vars() { + env_cstrs.push(CString::new(format!("{k}={v}")).unwrap()); + } + let mut envp: Vec<*mut libc::c_char> = + env_cstrs.iter().map(|s| s.as_ptr().cast_mut()).collect(); + envp.push(std::ptr::null_mut()); + + let mut baseline_rss = 0usize; + for i in 0..200 { + let mut pid: libc::pid_t = 0; + // SAFETY: `prog`, `argv`, and `envp` are valid NUL-terminated arrays. + let rc = unsafe { + libc::posix_spawn( + &raw mut pid, + prog.as_ptr(), + std::ptr::null(), + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + assert_eq!(rc, 0, "posix_spawn iteration {i} failed with errno {rc}"); + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is valid writable storage. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert_eq!(waited, pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); + if i == 10 { + baseline_rss = vm_rss_kib(); + } + } + + let final_rss = vm_rss_kib(); + let growth = final_rss.saturating_sub(baseline_rss); + assert!( + growth < 4096, + "parent VmRSS grew by {growth} KiB across 190 posix_spawns \ + (baseline={baseline_rss} KiB, final={final_rss} KiB)" + ); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} + +#[test(tokio::test)] +async fn memfd_execveat_empty_path_tracks_child_accesses() -> anyhow::Result<()> { + let probe_path = Path::new("/fspy-memfd-execveat-probe"); + let cmd = vt_subprocess_test::command_for_fn!( + (test_bin_path().to_str().unwrap().to_owned(), probe_path.to_str().unwrap().to_owned()), + |(static_bin, probe_path): (String, String)| { + use std::ffi::CString; + + let bin_bytes = std::fs::read(&static_bin).unwrap(); + let name = CString::new("fspy-memfd-test").unwrap(); + // SAFETY: `memfd_create` takes a valid NUL-terminated name and flags. + let fd = libc::c_int::try_from(unsafe { + libc::syscall(libc::SYS_memfd_create, name.as_ptr(), libc::MFD_CLOEXEC) + }) + .unwrap(); + assert!(fd >= 0, "memfd_create failed: {}", std::io::Error::last_os_error()); + + let mut written = 0usize; + while written < bin_bytes.len() { + // SAFETY: `fd` is our open memfd and slice is valid. + let n = unsafe { + libc::write(fd, bin_bytes[written..].as_ptr().cast(), bin_bytes.len() - written) + }; + assert!(n > 0, "write memfd failed: {}", std::io::Error::last_os_error()); + written += usize::try_from(n).unwrap(); + } + + let empty = CString::new("").unwrap(); + let arg0 = CString::new("memfd-bin").unwrap(); + let arg1 = CString::new("open_read").unwrap(); + let arg2 = CString::new(probe_path).unwrap(); + let argv = [arg0.as_ptr(), arg1.as_ptr(), arg2.as_ptr(), std::ptr::null()]; + let envp = [std::ptr::null::()]; + + // SAFETY: `fork()` followed by async-signal-safe `execveat` + `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + // SAFETY: `fd` is open and arguments are valid NUL-terminated arrays. + unsafe { + libc::syscall( + libc::SYS_execveat, + fd, + empty.as_ptr(), + argv.as_ptr(), + envp.as_ptr(), + libc::AT_EMPTY_PATH, + ); + libc::_exit(127); + } + } + + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert_eq!(waited, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "memfd execveat child failed with status {status}" + ); + // SAFETY: closing our owned memfd. + unsafe { libc::close(fd) }; + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn execve_proc_self_fd_of_cloexec_descriptor_runs_and_tracks() -> anyhow::Result<()> { + // `execve("/proc/self/fd/N")` on an `O_CLOEXEC` descriptor (glibc's + // `fexecve` fallback, memfd launchers): the kernel opens the image before + // closing CLOEXEC descriptors, so the launcher must hand the image over by + // descriptor rather than reopen the path after exec. + let probe_path = Path::new("/fspy-proc-self-fd-exec-probe"); + let cmd = vt_subprocess_test::command_for_fn!( + (test_bin_path().to_str().unwrap().to_owned(), probe_path.to_str().unwrap().to_owned()), + |(static_bin, probe_path): (String, String)| { + use std::{ffi::CString, os::fd::AsRawFd as _}; + + // Rust opens files with `O_CLOEXEC`. + let file = std::fs::File::open(&static_bin).unwrap(); + let path = CString::new(format!("/proc/self/fd/{}", file.as_raw_fd())).unwrap(); + let arg0 = CString::new("fd-bin").unwrap(); + let arg1 = CString::new("open_read").unwrap(); + let arg2 = CString::new(probe_path).unwrap(); + let argv = [arg0.as_ptr(), arg1.as_ptr(), arg2.as_ptr(), std::ptr::null()]; + let envp = [std::ptr::null::()]; + + // SAFETY: `fork()` followed by async-signal-safe `execve` + `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + // SAFETY: `path`, `argv`, and `envp` are valid NUL-terminated arrays. + unsafe { + libc::execve(path.as_ptr(), argv.as_ptr(), envp.as_ptr()); + libc::_exit(127); + } + } + + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert_eq!(waited, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "/proc/self/fd execve child failed with status {status}" + ); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn deep_exec_chain_preserves_fd_env_and_seccomp_filter_hygiene() -> anyhow::Result<()> { + // Capture any ambient non-CLOEXEC FDs inherited by the test runner itself + // (e.g. CI runner or jobserver descriptors) so we strictly assert zero + // leaked FDs introduced by `fspy` across the exec chain. + let mut inherited_fds: Vec = std::fs::read_dir("/proc/self/fd") + .unwrap() + .filter_map(|e| e.ok()?.file_name().to_str()?.parse::().ok()) + .collect(); + inherited_fds.retain(|&fd| { + if fd <= 2 { + return false; + } + // SAFETY: `F_GETFD` only queries flags and returns `-1` for the + // already-closed `read_dir("/proc/self/fd")` descriptor. + let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; + flags >= 0 && (flags & libc::FD_CLOEXEC) == 0 + }); + inherited_fds.sort_unstable(); + + let cmd = vt_subprocess_test::command_for_fn!(inherited_fds, |inherited_fds: Vec| { + use std::{ffi::CString, os::unix::ffi::OsStrExt as _}; + + fn seccomp_filters() -> usize { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + for line in status.lines() { + if let Some(rest) = line.strip_prefix("Seccomp_filters:") { + return rest.trim().parse::().unwrap(); + } + } + panic!("Seccomp_filters not found"); + } + + // Verify `__FSPY_BOOTSTRAP` was stripped before entering the target. + assert!( + std::env::var_os("__FSPY_BOOTSTRAP").is_none(), + "__FSPY_BOOTSTRAP leaked into child environment" + ); + + let depth: usize = + std::env::var("FSPY_TEST_EXEC_DEPTH").ok().and_then(|s| s.parse().ok()).unwrap_or(0); + + let cur_filters = seccomp_filters(); + assert!(cur_filters >= 1, "expected at least one seccomp filter"); + + if let Ok(expected) = std::env::var("FSPY_TEST_EXPECTED_FILTERS") { + let expected: usize = expected.parse().unwrap(); + assert_eq!( + cur_filters, expected, + "Seccomp_filters grew across exec chain ({expected} -> {cur_filters})" + ); + } + + // Verify no FDs leaked from the launcher handoff or across execs + // (ignoring stdin/stdout/stderr, the already-closed `/proc/self/fd` + // directory handle, and ambient non-CLOEXEC FDs inherited from the + // parent test runner). + let open_fds: Vec = std::fs::read_dir("/proc/self/fd") + .unwrap() + .filter_map(|e| e.ok()?.file_name().to_str()?.parse::().ok()) + .collect(); + let leaked_fds: Vec = open_fds + .into_iter() + .filter(|&fd| fd > 2 && !inherited_fds.contains(&fd)) + .filter(|&fd| { + // SAFETY: `F_GETFD` only queries descriptor flags and returns + // `-1` for the now-closed `read_dir("/proc/self/fd")` handle. + unsafe { libc::fcntl(fd, libc::F_GETFD) >= 0 } + }) + .collect(); + assert!( + leaked_fds.is_empty(), + "unexpected leaked open FDs at depth {depth} (inherited={inherited_fds:?}): {leaked_fds:?}" + ); + + if depth >= 5 { + return; + } + + let exe = std::fs::read_link("/proc/self/exe").unwrap(); + let prog = CString::new(exe.as_os_str().as_bytes()).unwrap(); + // `vt_subprocess_test` runs inside `.init_array`, where `std::env::args_os()` + // is empty on musl; fall back to `/proc/self/cmdline` just like `vt_subprocess_test`. + let mut args: Vec = + std::env::args_os().map(|a| CString::new(a.as_bytes()).unwrap()).collect(); + if args.is_empty() { + let cmdline = std::fs::read("/proc/self/cmdline").unwrap(); + let mut parts: Vec<&[u8]> = cmdline.split(|&b| b == 0).collect(); + if parts.last().is_some_and(|s| s.is_empty()) { + parts.pop(); + } + args = parts.into_iter().map(|p| CString::new(p).unwrap()).collect(); + } + let mut argv: Vec<*const libc::c_char> = args.iter().map(|s| s.as_ptr()).collect(); + argv.push(std::ptr::null()); + + let mut env_cstrs: Vec = std::env::vars_os() + .filter(|(k, _)| k != "FSPY_TEST_EXEC_DEPTH" && k != "FSPY_TEST_EXPECTED_FILTERS") + .map(|(k, v)| { + let mut bytes = k.as_bytes().to_vec(); + bytes.push(b'='); + bytes.extend_from_slice(v.as_bytes()); + CString::new(bytes).unwrap() + }) + .collect(); + env_cstrs.push(CString::new(format!("FSPY_TEST_EXEC_DEPTH={}", depth + 1)).unwrap()); + env_cstrs.push(CString::new(format!("FSPY_TEST_EXPECTED_FILTERS={cur_filters}")).unwrap()); + let mut envp: Vec<*const libc::c_char> = env_cstrs.iter().map(|s| s.as_ptr()).collect(); + envp.push(std::ptr::null()); + + // SAFETY: `prog`, `argv`, and `envp` are valid NUL-terminated arrays. + unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), envp.as_ptr()) }; + panic!("execve failed at depth {depth}: {}", std::io::Error::last_os_error()); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} diff --git a/crates/fspy/tests/node_fs.rs b/crates/fspy/tests/node_fs.rs index 7430bd6a5..4eed20a74 100644 --- a/crates/fspy/tests/node_fs.rs +++ b/crates/fspy/tests/node_fs.rs @@ -53,13 +53,12 @@ fn track_script( }) } -// Bun's Linux runtime uses direct syscalls, which require universal seccomp -// tracing instead of preload interception. Deno does not distribute a musl -// runtime. Node remains covered on every target. +// Deno does not distribute a musl runtime. Node and Bun are covered on every +// target (Bun's direct syscalls on Linux are traced via `fspy_preload_linux`). #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn read_sync(runtime: &str) -> anyhow::Result<()> { @@ -70,8 +69,8 @@ fn read_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn exist_sync(runtime: &str) -> anyhow::Result<()> { @@ -82,8 +81,8 @@ fn exist_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn stat_sync(runtime: &str) -> anyhow::Result<()> { @@ -94,8 +93,8 @@ fn stat_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn create_read_stream(runtime: &str) -> anyhow::Result<()> { @@ -110,8 +109,8 @@ fn create_read_stream(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn create_write_stream(runtime: &str) -> anyhow::Result<()> { @@ -128,8 +127,8 @@ fn create_write_stream(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn write_sync(runtime: &str) -> anyhow::Result<()> { @@ -146,8 +145,8 @@ fn write_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn symlink_junction_sync(runtime: &str) -> anyhow::Result<()> { @@ -174,8 +173,8 @@ fn symlink_junction_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn read_dir_sync(runtime: &str) -> anyhow::Result<()> { @@ -186,8 +185,8 @@ fn read_dir_sync(runtime: &str) -> anyhow::Result<()> { #[test_case("node")] #[ignore = "requires node"] -#[cfg_attr(not(target_os = "linux"), test_case("bun"))] -#[cfg_attr(not(target_os = "linux"), ignore = "requires node")] +#[test_case("bun")] +#[ignore = "requires node"] #[cfg_attr(not(target_env = "musl"), test_case("deno"))] #[cfg_attr(not(target_env = "musl"), ignore = "requires node")] fn subprocess(runtime: &str) -> anyhow::Result<()> { @@ -204,3 +203,35 @@ fn subprocess(runtime: &str) -> anyhow::Result<()> { assert_contains(&accesses, current_dir().unwrap().join("hello").as_path(), PathAccess::Read); Ok(()) } + +#[test_case("node")] +#[ignore = "requires node"] +#[test_case("bun")] +#[ignore = "requires node"] +#[cfg_attr(not(target_env = "musl"), test_case("deno"))] +#[cfg_attr(not(target_env = "musl"), ignore = "requires node")] +fn fork_ipc(runtime: &str) -> anyhow::Result<()> { + let tmpdir = tempfile::tempdir()?; + let tmp_path = std::fs::canonicalize(tmpdir.path())?; + let data_path = tmp_path.join("data.txt"); + std::fs::write(&data_path, "hello-ipc")?; + let child_path = tmp_path.join("child.cjs"); + std::fs::write( + &child_path, + "const fs = require('node:fs');\n\ + const content = fs.readFileSync(process.argv.at(-1), 'utf8');\n\ + process.send(content, () => { process.disconnect(); });\n", + )?; + let accesses = track_script( + runtime, + "const child = child_process.fork(process.argv.at(-2), [process.argv.at(-1)]); \ + let received = null; \ + child.on('message', (msg) => { received = msg; }); \ + child.on('exit', (code) => { \ + if (code !== 0 || received !== 'hello-ipc') process.exit(1); \ + });", + &[child_path.as_os_str(), data_path.as_os_str()], + )?; + assert_contains(&accesses, &data_path, PathAccess::Read); + Ok(()) +} diff --git a/crates/fspy/tests/rust_std.rs b/crates/fspy/tests/rust_std.rs index 9bbbc37b4..59adf7b4d 100644 --- a/crates/fspy/tests/rust_std.rs +++ b/crates/fspy/tests/rust_std.rs @@ -217,24 +217,31 @@ async fn syscall_during_dlopen() { // The interposer used to resolve libc's syscall with dlsym, which waits for dlopen, // so a second thread calling syscall waited for the first through futex, re-entering // the interposer until its stack overflowed. - fn call_syscall_during_dlopen(fifo_path: &str) { - // This waits for dlopen to open the FIFO, which it reads until writers close. + // Hold each FIFO writer open across a barrier so `dlopen` cannot read EOF and close + // the FIFO before the other writer calls `open` (which would block forever). + fn call_syscall_during_dlopen(fifo_path: &str, barrier: &std::sync::Barrier) { + // This waits for dlopen to open the FIFO, which it reads until all writers close. let _writer = OpenOptions::new().write(true).open(fifo_path).unwrap(); // SAFETY: getpid takes no arguments. unsafe { libc::syscall(libc::SYS_getpid) }; + barrier.wait(); } // Opening files and spawning threads can also wait for dlopen, so do both first. File::open("/").unwrap(); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); let path = fifo_path.clone(); - std::thread::spawn(move || { + let barrier_clone = std::sync::Arc::clone(&barrier); + let worker = std::thread::spawn(move || { let c = std::ffi::CString::new(path.as_str()).unwrap(); // SAFETY: dlopen fails on the FIFO's empty contents. - std::thread::spawn(move || unsafe { + let loader = std::thread::spawn(move || unsafe { libc::dlopen(c.as_ptr(), libc::RTLD_NOW); }); - call_syscall_during_dlopen(&path); + call_syscall_during_dlopen(&path, &barrier_clone); + loader.join().unwrap(); }); - call_syscall_during_dlopen(&fifo_path); + call_syscall_during_dlopen(&fifo_path, &barrier); + worker.join().unwrap(); }) .await .unwrap(); diff --git a/crates/fspy/tests/shebang.rs b/crates/fspy/tests/shebang.rs index def96b7a1..f1c60874a 100644 --- a/crates/fspy/tests/shebang.rs +++ b/crates/fspy/tests/shebang.rs @@ -42,21 +42,21 @@ async fn spawn_sh_shebang() -> anyhow::Result<()> { Ok(()) } -// Skipped on musl: fspy tracks only through seccomp there, which doesn't -// record the interpreter, because the kernel opens it without a syscall. -#[cfg(not(target_env = "musl"))] #[test(tokio::test)] async fn spawn_shebang_with_long_interpreter_path() -> anyhow::Result<()> { let tmp_dir = tempfile::TempDir::new()?; // Kernels read 256 (Linux) or 512 (macOS) bytes of the shebang line, so a - // 200-byte interpreter path must be kept whole. - let mut interpreter = tmp_dir.path().to_path_buf(); - while interpreter.as_os_str().len() < 150 { - interpreter.push("d".repeat(40)); + // 200-byte interpreter path must be kept whole. Keep the symlink basename + // `sh` so multi-call binaries like Alpine's BusyBox `/bin/sh` dispatch to + // the `sh` applet. + let mut dir = tmp_dir.path().to_path_buf(); + while dir.as_os_str().len() < 150 { + dir.push("d".repeat(40)); } - fs::create_dir_all(&interpreter).await?; - interpreter.push("x".repeat(200 - interpreter.as_os_str().len() - 1)); + dir.push("d".repeat(200 - "/sh".len() - dir.as_os_str().len() - 1)); + fs::create_dir_all(&dir).await?; + let interpreter = dir.join("sh"); assert_eq!(interpreter.as_os_str().len(), 200); fs::symlink("/bin/sh", &interpreter).await?; diff --git a/crates/fspy/tests/static_executable.rs b/crates/fspy/tests/static_executable.rs index 9de887a03..330a26bbe 100644 --- a/crates/fspy/tests/static_executable.rs +++ b/crates/fspy/tests/static_executable.rs @@ -1,8 +1,5 @@ -//! Tests for fspy tracing of statically-linked executables (seccomp path). -//! Skipped on musl: the test binary is an artifact dep targeting musl, and when -//! the CI builds with `-crt-static` the binary becomes dynamically linked, -//! defeating the purpose of these tests. -#![cfg(all(target_os = "linux", not(target_env = "musl")))] +//! Tests for fspy tracing of statically-linked executables on Linux. +#![cfg(target_os = "linux")] use std::path::Path; use fspy::PathAccessIterable; diff --git a/crates/fspy/tests/test_utils/mod.rs b/crates/fspy/tests/test_utils/mod.rs index e8ded0561..2b26be639 100644 --- a/crates/fspy/tests/test_utils/mod.rs +++ b/crates/fspy/tests/test_utils/mod.rs @@ -162,8 +162,8 @@ pub async fn spawn_command(cmd: vt_subprocess_test::Command) -> anyhow::Result

&'static Path { sync::LazyLock, }; - use fspy_shared_unix::is_dynamically_linked_to_libc; - const TEST_BIN_CONTENT: &[u8] = include_bytes!(env!("CARGO_BIN_FILE_FSPY_TEST_BIN")); static TEST_BIN_PATH: LazyLock = LazyLock::new(|| { - assert_eq!( - is_dynamically_linked_to_libc(TEST_BIN_CONTENT), - Ok(false), - "Test binary is not a static executable" - ); - - let test_bin_path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")) - .join(concat!("fspy-test-bin-", env!("CARGO_CRATE_NAME"))); - fs::write(&test_bin_path, TEST_BIN_CONTENT).expect("failed to write test binary"); - fs::set_permissions(&test_bin_path, Permissions::from_mode(0o755)) + let dir = + std::env::var_os("CARGO_TARGET_TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from); + let test_bin_path = dir.join(concat!("fspy-test-bin-", env!("CARGO_CRATE_NAME"))); + let tmp_path = dir.join(format!( + "fspy-test-bin-{}-{}.tmp", + env!("CARGO_CRATE_NAME"), + std::process::id() + )); + fs::write(&tmp_path, TEST_BIN_CONTENT).expect("failed to write test binary"); + fs::set_permissions(&tmp_path, Permissions::from_mode(0o755)) .expect("failed to set permissions on test binary"); + fs::rename(&tmp_path, &test_bin_path).expect("failed to install test binary"); test_bin_path }); diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs index c3e95b94b..2c111bacd 100644 --- a/crates/fspy/tests/untracked_fallback.rs +++ b/crates/fspy/tests/untracked_fallback.rs @@ -1,128 +1,117 @@ -//! Tests for the untracked-exec fallback: when the preload cannot install -//! the seccomp filter, the exec must proceed untracked and the run must be -//! reported as incompletely tracked (so it is not cached), rather than -//! every spawn failing. Skipped on musl: no preload library exists there. -#![cfg(all(target_os = "linux", not(target_env = "musl")))] +//! 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 +//! spawn. +//! - Authentic exec errors (such as `ENOEXEC` on a script without a `#!` line) +//! propagate normally and keep the trace complete. +#![cfg(target_os = "linux")] use std::{ - ffi::OsStr, fs::{self, Permissions}, - os::unix::{ffi::OsStrExt as _, fs::PermissionsExt as _}, - path::{Path, PathBuf}, - process::Command, + mem::offset_of, + os::unix::fs::PermissionsExt as _, + process::Stdio, }; -use allocator_api2::alloc::Global; -use fspy_seccomp_unotify::payload::SeccompPayload; -use fspy_shared::ipc::{ - IpcStr, - channel::{Receiver, RecordsLost, channel}, +use fspy::TrackingIncomplete; +use linux_raw_sys::{ + errno::EPERM, + prctl::PR_SET_NO_NEW_PRIVS, + ptrace::{ + BPF_ABS, BPF_JEQ, BPF_JMP, BPF_K, BPF_LD, BPF_RET, BPF_W, SECCOMP_RET_ALLOW, + SECCOMP_RET_DATA, SECCOMP_RET_ERRNO, SECCOMP_SET_MODE_FILTER, seccomp_data, sock_filter, + sock_fprog, + }, }; -use fspy_shared_unix::payload::{Payload, encode_payload}; +use syscalls::Sysno; +use test_log::test; +use tokio::io::AsyncReadExt as _; +use tokio_util::sync::CancellationToken; +use vt_subprocess_test::command_for_fn; -use crate::test_utils::test_bin_path; - -mod test_utils; - -/// The preload cdylib, built as a dependency of this crate. -const PRELOAD_CDYLIB: &str = env!("CARGO_CDYLIB_FILE_FSPY_PRELOAD_UNIX"); - -/// Clears `command`'s environment and preloads fspy into it with a seccomp -/// payload whose install always fails. Returns the channel the preload -/// reports to. -fn preload_with_failing_seccomp(command: &mut Command) -> Receiver { - let receiver = channel(1 << 30, Global).unwrap(); - { - let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); - let payload = Payload { - ipc_channel_conf: receiver.conf(), - preload_path, - seccomp_payload: SeccompPayload::unreachable( - b"/nonexistent/fspy-unreachable-supervisor".to_vec(), - ), - }; - let bump = bumpalo::Bump::new(); - let encoded = encode_payload(payload, &bump); - command - .env_clear() - .env("LD_PRELOAD", PRELOAD_CDYLIB) - .env("FSPY_PAYLOAD", OsStr::from_bytes(encoded.encoded_string.as_ref())); - } - receiver -} +/// An authentic exec error (`ENOEXEC` for a script without a `#!` line) keeps +/// its errno and leaves the trace complete so `/bin/sh` runs the script itself, +/// as it does without tracking. +#[test(tokio::test)] +async fn exec_errors_are_not_reported_as_lost() { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + let script = dir.path().join("fspy-script-without-shebang"); + fs::write(&script, "exit 0\n").expect("failed to write the script"); + fs::set_permissions(&script, Permissions::from_mode(0o755)) + .expect("failed to set permissions on the script"); -/// A static binary exec'd from a traced process needs the preload's inline -/// seccomp install. When that install fails (here: the payload's empty -/// filter, which the kernel refuses), the binary must still run — untracked -/// — and the channel must report the loss. -#[test] -fn static_binary_runs_untracked_when_injection_fails() { - let mut command = Command::new("/bin/sh"); - let receiver = preload_with_failing_seccomp(&mut command); - let output = command - .arg("-c") - .arg(format!("exec {} stat /hello", test_bin_path().display())) - .output() - .expect("failed to spawn the shell"); + let mut command = fspy::Command::new("/bin/sh"); + command.arg("-c").arg(script.as_os_str()).stdin(Stdio::null()); + let tracked = command.spawn(CancellationToken::new()).await.expect("failed to spawn /bin/sh"); + let termination = tracked.wait_handle.await.expect("failed to wait for /bin/sh"); + assert!(termination.status.success(), "the script without a shebang did not run"); assert!( - output.status.success(), - "the static binary did not run: {}", - String::from_utf8_lossy(&output.stderr) + termination.path_accesses.is_ok(), + "an authentic exec error was reported as an untracked exec" ); - - let Err(RecordsLost) = receiver.close() else { - panic!("the channel did not report the untracked exec"); - }; } -/// The untracked fallback must replay the interposed call as it was made, -/// not as `execve`. GNU `env` runs its command through `execvp`, so a bare -/// program name found only on `PATH` still runs when injection fails; -/// forwarding it to `execve` would fail with `ENOENT` instead. +/// 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. #[test] -fn execvp_fallback_keeps_path_search() { - let test_bin = test_bin_path(); - let mut command = Command::new("/usr/bin/env"); - let receiver = preload_with_failing_seccomp(&mut command); - let output = command - .arg(test_bin.file_name().unwrap()) - .arg("stat") - .arg("/hello") - .env("PATH", test_bin.parent().unwrap()) - .current_dir("/") - .output() - .expect("failed to spawn env"); - assert!( - output.status.success(), - "the execvp fallback lost its PATH search: {}", - String::from_utf8_lossy(&output.stderr) - ); - - let Err(RecordsLost) = receiver.close() else { - panic!("the channel did not report the untracked exec"); - }; -} +fn seccomp_blocked_sandbox_falls_back_to_untracked() { + let cmd = command_for_fn!((), |()| { + #[expect( + clippy::cast_possible_truncation, + reason = "cBPF opcodes and offsets fit in u16/u32" + )] + let filter = [ + sock_filter { + code: (BPF_LD | BPF_W | BPF_ABS) as u16, + jt: 0, + jf: 0, + k: offset_of!(seccomp_data, nr) as u32, + }, + sock_filter { + code: (BPF_JMP | BPF_JEQ | BPF_K) as u16, + jt: 0, + jf: 1, + k: Sysno::seccomp as u32, + }, + sock_filter { + code: (BPF_RET | BPF_K) as u16, + jt: 0, + jf: 0, + k: SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA), + }, + sock_filter { code: (BPF_RET | BPF_K) as u16, jt: 0, jf: 0, k: SECCOMP_RET_ALLOW }, + ]; + let prog = sock_fprog { len: 4, filter: filter.as_ptr().cast_mut() }; + // SAFETY: installs a valid 4-instruction seccomp filter on this test subprocess. + unsafe { + syscalls::syscall!(Sysno::prctl, PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0).unwrap(); + syscalls::syscall!(Sysno::seccomp, SECCOMP_SET_MODE_FILTER, 0, &raw const prog) + .unwrap(); + } -/// Only a failed seccomp install takes the untracked path. An exec that -/// fails the way the real exec would, here `ENOEXEC` for a script without a -/// `#!` line, keeps its errno and leaves the trace complete. `sh` then runs -/// the script itself, as it does without tracking. -#[test] -fn exec_errors_are_not_reported_as_lost() { - let script = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("fspy-script-without-shebang"); - fs::write(&script, "exit 0\n").expect("failed to write the script"); - fs::set_permissions(&script, Permissions::from_mode(0o755)) - .expect("failed to set permissions on the script"); + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + rt.block_on(async { + let mut command = fspy::Command::new("/bin/echo"); + command.arg("sandbox-ok").stdout(Stdio::piped()).stdin(Stdio::null()); + let mut tracked = command + .spawn(CancellationToken::new()) + .await + .expect("sandboxed spawn should fall back untracked"); + let mut stdout = Vec::new(); + tracked.stdout.take().unwrap().read_to_end(&mut stdout).await.unwrap(); + 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))); + }); + }); - let mut command = Command::new("/bin/sh"); - let receiver = preload_with_failing_seccomp(&mut command); - let output = - command.arg("-c").arg(script.as_os_str()).output().expect("failed to spawn the shell"); + let output = std::process::Command::from(cmd).output().expect("failed to run sandbox test"); assert!( output.status.success(), - "the script without a shebang did not run: {}", - String::from_utf8_lossy(&output.stderr) + "sandboxed subprocess failed: stdout={}, stderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), ); - - assert!(receiver.close().is_ok(), "an authentic exec error was reported as an untracked exec"); } diff --git a/crates/fspy_benchmark/README.md b/crates/fspy_benchmark/README.md index 7d722b214..61183a9bf 100644 --- a/crates/fspy_benchmark/README.md +++ b/crates/fspy_benchmark/README.md @@ -5,7 +5,7 @@ Measures what fspy costs a process it tracks, and whether a change to fspy moved - `launch`: the wall clock of a tracked launch that opens nothing. This is the cost of starting a process under tracking: injection, session setup, and teardown. - `access`: how long a batch of opens takes, timed by two threads that each open their own path. This is the cost of interception itself, under the concurrency a tracked process normally has. -Linux measures a dynamically linked target (`LD_PRELOAD`) and a `x86_64-unknown-linux-musl` target (seccomp user notification). macOS measures `DYLD_INSERT_LIBRARIES`. Windows measures Detours injection. +Linux measures both a dynamically linked target and a static `x86_64-unknown-linux-musl` target through the freestanding ELF/`SIGSYS` tracker. macOS measures `DYLD_INSERT_LIBRARIES`. Windows measures Detours injection. Run the overhead report locally with: diff --git a/crates/fspy_client_unix/Cargo.toml b/crates/fspy_client_unix/Cargo.toml deleted file mode 100644 index c0b9da26a..000000000 --- a/crates/fspy_client_unix/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "fspy_client_unix" -edition = "2024" -license.workspace = true -publish = false - -[target.'cfg(all(unix, not(target_env = "musl")))'.dependencies] -allocator-api2 = { workspace = true, features = ["alloc"] } -anyhow = { workspace = true } -bstr = { workspace = true, features = ["alloc", "std"] } -fspy_shared = { workspace = true } -fspy_shared_unix = { workspace = true } -libc = { workspace = true } -nix = { workspace = true, features = ["fs"] } -fspy_nostd = { workspace = true } -fspy_nostd_alloc = { workspace = true } - -[target.'cfg(all(target_os = "linux", not(target_env = "musl")))'.dependencies] -itoa = { workspace = true } - -[lints] -workspace = true - -[lib] -doctest = false -test = false diff --git a/crates/fspy_client_unix/README.md b/crates/fspy_client_unix/README.md deleted file mode 100644 index 6839cc9f2..000000000 --- a/crates/fspy_client_unix/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# fspy_client_unix - -The Unix client that resolves and reports file accesses to the fspy supervisor. - -The preload library owns interception-specific initialization and re-entry -guards. This crate owns the reusable client, path conversion, and exec -transformation so another Unix injection mechanism can provide its own runtime -integration around the same client. diff --git a/crates/fspy_client_unix/src/convert.rs b/crates/fspy_client_unix/src/convert.rs deleted file mode 100644 index 6b3e72c93..000000000 --- a/crates/fspy_client_unix/src/convert.rs +++ /dev/null @@ -1,239 +0,0 @@ -use std::ffi::CStr; - -use allocator_api2::{alloc::Allocator, vec::Vec}; -use bstr::ByteSlice; -use fspy_nostd::{BorrowedFd, CWD}; -use fspy_shared::ipc::AccessMode; -use libc::{c_char, c_int}; - -#[cfg(target_os = "linux")] -fn get_fd_path(allocator: A, fd: BorrowedFd<'_>) -> nix::Result>> { - if fd.as_raw_fd() == CWD.as_raw_fd() { - let path = fspy_nostd_alloc::fs::getcwd(allocator) - .map_err(|errno| nix::errno::Errno::from_raw(errno.raw_os_error()))? - .into_units(); - return Ok(Some(path)); - } - let mut path = [0; PROC_FD_PATH_CAPACITY]; - let path = proc_fd_path(fd.as_raw_fd(), &mut path); - match fspy_nostd_alloc::fs::readlinkat(allocator, CWD, path) { - Ok(path) => Ok(Some(path)), - Err(fspy_nostd::Error::BADF | fspy_nostd::Error::NOENT) => Ok(None), - Err(errno) => Err(nix::errno::Errno::from_raw(errno.raw_os_error())), - } -} - -#[cfg(target_os = "linux")] -pub const PROC_FD_PATH_CAPACITY: usize = - b"/proc/self/fd/".len() + ::MAX_STR_LEN + 1; - -/// Formats `/proc/self/fd/{fd}` into `buf`, without allocating. -#[cfg(target_os = "linux")] -pub fn proc_fd_path( - fd: c_int, - buf: &mut [u8; PROC_FD_PATH_CAPACITY], -) -> fspy_nostd::CStr<'_, fspy_nostd::Thin> { - const PREFIX: &[u8] = b"/proc/self/fd/"; - - let mut formatted = itoa::Buffer::new(); - let fd = formatted.format(fd).as_bytes(); - - buf[..PREFIX.len()].copy_from_slice(PREFIX); - let end = PREFIX.len() + fd.len(); - buf[PREFIX.len()..end].copy_from_slice(fd); - buf[end] = 0; - - // SAFETY: the initialized prefix ends in NUL and lives as long as `buf`. - unsafe { fspy_nostd::CStr::from_ptr(buf.as_ptr().cast()) } -} - -#[cfg(target_os = "macos")] -fn get_fd_path(allocator: A, fd: BorrowedFd<'_>) -> nix::Result>> { - if fd.as_raw_fd() == CWD.as_raw_fd() { - let path = fspy_nostd_alloc::fs::getcwd(allocator) - .map_err(|errno| nix::errno::Errno::from_raw(errno.raw_os_error()))? - .into_units(); - return Ok(Some(path)); - } - - match fspy_nostd_alloc::fs::fcntl_getpath(allocator, fd) { - Ok(path) => { - // `F_GETPATH` does not return a length. Count at this caller before - // converting its allocation into the returned path. - Ok(Some(path.count().into_units())) - } - Err(fspy_nostd::Error::BADF | fspy_nostd::Error::NOENT) => Ok(None), - Err(errno) => Err(nix::errno::Errno::from_raw(errno.raw_os_error())), - } -} - -pub trait ToAbsolutePath { - /// Resolves this argument to an absolute path allocated in `allocator`, - /// or borrowed from the argument itself when it is already absolute. - /// - /// The result is a C string so that callers forwarding it to an exec — - /// which needs a terminator — cannot be handed unterminated bytes; - /// [`as_units`] gives the path without the NUL. - /// - /// [`as_units`]: fspy_nostd::CStr::as_units - /// - /// # Errors - /// - /// Returns the error reported while resolving a descriptor or the current - /// working directory. - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a; -} - -impl ToAbsolutePath for BorrowedFd<'_> { - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a, - { - let Some(mut path) = get_fd_path(allocator, self)? else { - return Ok(None); - }; - path.push(0); - // SAFETY: a resolved descriptor path carries no interior NUL, and - // exactly one was appended above. The storage stays in `allocator` - // until it is dropped, which for a per-call arena ends the call. - Ok(Some(unsafe { fspy_nostd::CStr::from_units_with_nul_unchecked(path.leak()) })) - } -} - -impl ToAbsolutePath for Option { - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a, - { - self.map_or(Ok(None), |path| path.to_absolute_path(allocator)) - } -} - -/// A pathname resolved against a directory descriptor, as in `openat`. -/// -/// The descriptor is `None` when the caller passed `-1`. The kernel ignores -/// it for an absolute pathname and fails a relative one with `EBADF`. -pub struct PathAt<'fd, 'path>( - pub Option>, - pub fspy_nostd::CStr<'path, fspy_nostd::Thin>, -); - -impl PathAt<'_, '_> { - /// Borrows raw directory-descriptor and pathname arguments. - /// - /// # Safety - /// - /// `fd` must be `-1` or remain valid while the returned value is used, - /// and `path` must point to a valid NUL-terminated string. - #[must_use] - pub const unsafe fn borrow_raw(fd: c_int, path: *const c_char) -> Self { - // SAFETY: both invariants are upheld by the caller. - Self(unsafe { BorrowedFd::try_borrow_raw(fd) }, unsafe { - fspy_nostd::CStr::from_ptr(path.cast()) - }) - } -} - -impl ToAbsolutePath for PathAt<'_, '_> { - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a, - { - let counted = self.1.count(); - let pathname = counted.as_units(); - - if pathname.starts_with(b"/") { - // Already absolute, and already NUL-terminated by the caller. - Ok(Some(counted)) - } else { - // A relative pathname at `-1` accesses nothing: the call fails. - let Some(dirfd) = self.0 else { - return Ok(None); - }; - let Some(mut base) = get_fd_path(allocator, dirfd)? else { - return Ok(None); - }; - if !pathname.is_empty() { - if !base.ends_with(b"/") { - base.push(b'/'); - } - base.extend_from_slice(pathname); - } - base.push(0); - // SAFETY: neither the directory nor the pathname carries an - // interior NUL — both come from C strings or the kernel — and - // exactly one was appended above. The storage stays in - // `allocator` until it is dropped. - Ok(Some(unsafe { fspy_nostd::CStr::from_units_with_nul_unchecked(base.leak()) })) - } - } -} - -impl ToAbsolutePath for fspy_nostd::CStr<'_, fspy_nostd::Thin> { - fn to_absolute_path<'a, A: Allocator>( - self, - allocator: &'a A, - ) -> nix::Result>> - where - Self: 'a, - { - PathAt(Some(CWD), self).to_absolute_path(allocator) - } -} - -pub trait ToAccessMode { - /// Converts the intercepted operation's mode into an access mode. - /// - /// # Safety - /// - /// Implementations backed by raw process pointers require those pointers - /// to remain valid for the conversion. - unsafe fn to_access_mode(self) -> AccessMode; -} - -impl ToAccessMode for AccessMode { - unsafe fn to_access_mode(self) -> AccessMode { - self - } -} - -pub struct OpenFlags(pub c_int); -impl ToAccessMode for OpenFlags { - unsafe fn to_access_mode(self) -> AccessMode { - match self.0 & libc::O_ACCMODE { - libc::O_RDWR => AccessMode::ReadWrite, - libc::O_WRONLY => AccessMode::Write, - _ => AccessMode::Read, - } - } -} - -pub struct ModeStr(pub *const c_char); -impl ToAccessMode for ModeStr { - unsafe fn to_access_mode(self) -> AccessMode { - // SAFETY: self.0 is a non-null pointer to a valid null-terminated C - // string, as guaranteed by the libc calling convention. - let mode_str = unsafe { CStr::from_ptr(self.0) }.to_bytes().as_bstr(); - let has_read = mode_str.contains(&b'r'); - let has_write = mode_str.contains(&b'w') || mode_str.contains(&b'a'); - match (has_read, has_write) { - (false, true) => AccessMode::Write, - (true, true) => AccessMode::ReadWrite, - _ => AccessMode::Read, - } - } -} diff --git a/crates/fspy_client_unix/src/lib.rs b/crates/fspy_client_unix/src/lib.rs deleted file mode 100644 index d51c90f10..000000000 --- a/crates/fspy_client_unix/src/lib.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Reusable Unix client for reporting file accesses to the fspy supervisor. - -// Compile as an empty crate on non-Unix targets and on musl, matching the -// current preload client. Musl support will be enabled as its dependencies are -// made usable before libc initialization. -#![cfg(all(unix, not(target_env = "musl")))] - -pub mod convert; -pub mod raw_exec; - -use std::{ffi::OsStr, fmt::Debug, os::unix::ffi::OsStrExt as _, path::Path}; - -use allocator_api2::alloc::Allocator; -use convert::{ToAbsolutePath, ToAccessMode}; -use fspy_shared::ipc::{AccessMode, channel::Sender}; -use fspy_shared_unix::{ - exec::ExecResolveConfig, - payload::{EncodedPayload, decode_payload_from_env}, - spawn::{PreExec, handle_exec}, -}; -use raw_exec::RawExec; - -pub struct Client<'a> { - encoded_payload: EncodedPayload<'a>, - ipc_sender: Option, -} - -// Seals the view-only design: the client holds views of leaked memory and -// the sender, never an allocator. A retained allocator handle is -// interior-mutable and would fail this assertion. (`Sender`'s own manual -// `Send`/`Sync` impls are the one audited exception the check trusts.) -const _: () = { - const fn assert_send_sync() {} - assert_send_sync::>(); -}; - -impl Debug for Client<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Client").finish() - } -} - -impl<'a> Client<'a> { - /// Constructs a client from the encoded payload in the process - /// environment, leaking the payload's storage into `allocator`. - /// - /// The sender's temporary path decode also comes from `allocator` and - /// drops before this returns; a bump allocator gets that space back, - /// since the block is its most recent allocation. `A: 'a` bounds the - /// client's lifetime — a `'static` allocator yields a `Client<'static>` - /// with no further ceremony — and the client never retains the - /// allocator itself (see the `Send + Sync` assertion above). - /// - /// # Panics - /// - /// Panics when the payload is missing, malformed, or cannot be decoded, - /// and when the channel is there but cannot be attached to (see - /// [`ChannelConf::sender`](fspy_shared::ipc::channel::ChannelConf::sender)). - pub fn from_env( - envs: impl Iterator, - allocator: impl Allocator + Clone + 'a, - ) -> Self { - let encoded_payload = decode_payload_from_env(envs, allocator.clone()).unwrap(); - - // `None` when the channel is already over, which happens when this - // process starts after the root target exited. Nothing is said - // about it: a preload library writing to the traced process's - // stderr corrupts whatever that process is printing. - let ipc_sender = encoded_payload.payload.ipc_channel_conf.sender(allocator); - - Self { encoded_payload, ipc_sender } - } - - fn send(&self, mode: AccessMode, path: &Path) { - let Some(ipc_sender) = &self.ipc_sender else { - return; - }; - let path_bytes = path.as_os_str().as_bytes(); - if path_bytes.starts_with(b"/dev/") - || (cfg!(target_os = "linux") - && (path_bytes.starts_with(b"/proc/") || path_bytes.starts_with(b"/sys/"))) - { - return; - } - // The interception proceeds whether or not the record could be - // sent — a preload library can never panic its host process. - ipc_sender.send(&mode.with_path(path.into())); - } - - /// Marks the run's trace incomplete, so the receiver treats it as - /// untracked and the runner does not cache it. Call it before the - /// process does something that tracking cannot record, such as an exec - /// that continues untracked because [`PreExec::run`] failed. It does - /// nothing when this client has no channel sender. - pub fn report_loss(&self) { - if let Some(ipc_sender) = &self.ipc_sender { - ipc_sender.report_loss(); - } - } - - /// Resolves and reports an exec, returning the transformed arguments to - /// forward and what to run before forwarding them. - /// - /// # Safety - /// - /// `raw_exec` must contain the valid C strings and pointer arrays required - /// by [`RawExec::to_exec`]. The returned `RawExec` points into - /// `allocator`, and must not be used after `allocator` is dropped. - /// - /// # Errors - /// - /// Returns errors from exec resolution or platform preparation. - pub unsafe fn handle_exec( - &self, - config: ExecResolveConfig, - raw_exec: RawExec, - allocator: &A, - ) -> nix::Result<(RawExec, Option)> { - // SAFETY: raw_exec contains valid pointers to C strings and - // null-terminated arrays, as provided by the caller. - let mut exec = unsafe { raw_exec.to_exec(allocator) }; - let pre_exec = handle_exec(&mut exec, config, &self.encoded_payload, |path| { - self.send(AccessMode::Read, path); - })?; - Ok((RawExec::from_exec(exec), pre_exec)) - } - - /// Resolves and reports one intercepted file access. - /// - /// # Safety - /// - /// `path` and `mode` must satisfy their implementation-specific raw - /// pointer and descriptor contracts for the duration of this call. - /// - /// # Errors - /// - /// Returns errors from path resolution or shared-memory serialization. - pub unsafe fn try_handle_open( - &self, - path: impl ToAbsolutePath, - mode: impl ToAccessMode, - allocator: impl Allocator, - ) -> anyhow::Result<()> { - // SAFETY: mode contains a valid pointer (if ModeStr) or a plain value, - // as provided by the caller. - let mode = unsafe { mode.to_access_mode() }; - let Some(abs_path) = path.to_absolute_path(&allocator)? else { - return Ok(()); - }; - self.send(mode, Path::new(OsStr::from_bytes(abs_path.as_units()))); - Ok(()) - } -} diff --git a/crates/fspy_client_unix/src/raw_exec.rs b/crates/fspy_client_unix/src/raw_exec.rs deleted file mode 100644 index d7397c6f0..000000000 --- a/crates/fspy_client_unix/src/raw_exec.rs +++ /dev/null @@ -1,122 +0,0 @@ -use std::{ffi::CStr, ptr::null}; - -use allocator_api2::{alloc::Allocator, vec::Vec}; -use fspy_shared_unix::exec::{Exec, to_vec_in}; - -#[derive(Clone, Copy)] -pub struct RawExec { - pub prog: *const libc::c_char, - pub argv: *const *const libc::c_char, - pub envp: *const *const libc::c_char, -} - -impl RawExec { - unsafe fn collect_c_str_array( - strs: *const *const libc::c_char, - allocator: A, - mut map_fn: impl FnMut(&[u8]) -> T, - ) -> Vec { - let mut count = 0usize; - let mut cur_str = strs; - // SAFETY: cur_str points into a valid null-terminated array of C - // string pointers (argv/envp convention). - while !(unsafe { *cur_str }).is_null() { - count += 1; - // SAFETY: advancing within the bounds of the null-terminated - // pointer array. - cur_str = unsafe { cur_str.add(1) }; - } - - let mut str_vec = Vec::with_capacity_in(count, allocator); - for i in 0..count { - // SAFETY: i < count, so strs.add(i) is within the bounds of the - // pointer array. - let cur_str = unsafe { strs.add(i) }; - // SAFETY: *cur_str is a non-null pointer to a valid - // null-terminated C string, verified by the counting loop above. - str_vec.push(map_fn(unsafe { CStr::from_ptr(*cur_str) }.to_bytes())); - } - str_vec - } - - /// NUL-terminates `s` and leaks it into its allocator. - fn into_c_str(mut s: Vec) -> *const libc::c_char { - s.push(0); - s.leak().as_ptr().cast() - } - - /// Builds a NULL-terminated array of C strings, leaked into the strings' - /// allocator. - fn into_c_str_array( - strs: Vec, A>, - ) -> *const *const libc::c_char { - let mut ptrs = Vec::with_capacity_in(strs.len() + 1, strs.allocator().clone()); - ptrs.extend(strs.into_iter().map(Self::into_c_str)); - ptrs.push(null()); - ptrs.leak().as_ptr() - } - - /// Copies the raw exec arguments into `allocator`. - /// - /// # Safety - /// - /// `prog` must point to a valid C string. `argv` and `envp` must each - /// point to a readable, null-terminated array of valid C string pointers. - pub unsafe fn to_exec(self, allocator: A) -> Exec { - // SAFETY: self.prog is a non-null pointer to a valid null-terminated C - // string, as guaranteed by the libc exec calling convention. - let program = to_vec_in(unsafe { CStr::from_ptr(self.prog) }.to_bytes(), allocator.clone()); - - // SAFETY: self.argv is a valid null-terminated array of C string - // pointers, as guaranteed by the libc exec calling convention. - let args = unsafe { - Self::collect_c_str_array(self.argv, allocator.clone(), |arg| { - to_vec_in(arg, allocator.clone()) - }) - }; - - // SAFETY: self.envp is a valid null-terminated array of C string - // pointers, as guaranteed by the libc exec calling convention. - let envs = unsafe { - Self::collect_c_str_array(self.envp, allocator.clone(), |env| { - env.iter().position(|b| *b == b'=').map_or_else( - || (to_vec_in(env, allocator.clone()), None), - |eq_pos| { - ( - to_vec_in(&env[..eq_pos], allocator.clone()), - Some(to_vec_in(&env[(eq_pos + 1)..], allocator.clone())), - ) - }, - ) - }) - }; - - Exec { program, args, envs } - } - - /// Builds the C strings and pointer arrays for `cmd` in its allocator. - /// - /// They are leaked there rather than freed, so the pointers stay valid - /// until the allocator itself goes away. In the preload that is the - /// interception's per-call bump: exec runs in the child of `fork()` in - /// multithreaded programs, where libc malloc's lock may be held by a - /// thread that no longer exists, and the bump hands everything back - /// when the call ends. - pub fn from_exec(cmd: Exec) -> Self { - let mut envs = Vec::with_capacity_in(cmd.envs.len(), cmd.allocator().clone()); - for (name, value) in cmd.envs { - let mut env = name; - if let Some(value) = value { - env.push(b'='); - env.extend_from_slice(&value); - } - envs.push(env); - } - - Self { - prog: Self::into_c_str(cmd.program), - argv: Self::into_c_str_array(cmd.args), - envp: Self::into_c_str_array(envs), - } - } -} diff --git a/crates/fspy_preload_linux/Cargo.toml b/crates/fspy_preload_linux/Cargo.toml new file mode 100644 index 000000000..4507add47 --- /dev/null +++ b/crates/fspy_preload_linux/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "fspy_preload_linux" +version = "0.0.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +rust-version.workspace = true + +[target.'cfg(target_os = "none")'.dependencies] +allocator-api2 = { workspace = true, features = ["alloc"] } +bstr = { workspace = true } +fspy_elf_loader = { path = "../fspy_elf_loader" } +fspy_nostd = { workspace = true } +fspy_nostd_alloc = { workspace = true } +fspy_shared = { workspace = true } +fspy_shared_unix = { workspace = true } +linux-raw-sys = { workspace = true, features = ["general", "no_std"] } +syscalls = { workspace = true } + +[[bin]] +name = "fspy_preload_linux" +path = "src/main.rs" +test = false +bench = false + +[lints] +workspace = true diff --git a/crates/fspy_preload_linux/README.md b/crates/fspy_preload_linux/README.md new file mode 100644 index 000000000..dad416613 --- /dev/null +++ b/crates/fspy_preload_linux/README.md @@ -0,0 +1,25 @@ +# `fspy_preload_linux` + +Freestanding Linux ELF loader and `SIGSYS` syscall-tracking runtime for `fspy`. + +## Overview + +`fspy_preload_linux` is built as a fixed-address, `no_std`, `no_main` ELF64 +executable targeting `x86_64-unknown-none` and `aarch64-unknown-none-softfloat`. +Instead of injecting a libc-bound `LD_PRELOAD` shared library or relying on +`seccomp_unotify`, `fspy` spawns `fspy_preload_linux`, which: + +1. Decodes `__FSPY_BOOTSTRAP` from the initial Linux stack environment and + attaches to the shared-memory IPC channel. +2. Resolves (when invoked as `Target::Unresolved`) or opens the target ELF64 + executable, strips `__FSPY_BOOTSTRAP`, and enters the target via + `fspy_elf_loader::exec_elf` with its `SIGSYS` syscall interceptor installed. +3. Intercepts tracked filesystem syscalls and `execve`/`execveat` in-process + inside the `SIGSYS` handler, reporting accessed paths to the IPC channel and + chaining child `execve`/`execveat` calls through `fspy_preload_linux` while + reusing the existing seccomp-BPF filter. + +Because the runtime is completely freestanding and intercepts syscalls directly +via seccomp `SECCOMP_RET_TRAP`, it tracks dynamic glibc binaries, musl binaries, +static binaries, and custom-runtime binaries (such as Go, Bun, and Deno) +uniformly without `LD_PRELOAD`. diff --git a/crates/fspy_preload_linux/build.rs b/crates/fspy_preload_linux/build.rs new file mode 100644 index 000000000..3ef51502e --- /dev/null +++ b/crates/fspy_preload_linux/build.rs @@ -0,0 +1,7 @@ +fn main() { + if let Ok(link_args) = std::env::var("DEP_FSPY_ELF_LOADER_LINK_ARGS") { + for argument in link_args.split_whitespace() { + println!("cargo::rustc-link-arg={argument}"); + } + } +} diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs new file mode 100644 index 000000000..51ddd7815 --- /dev/null +++ b/crates/fspy_preload_linux/src/main.rs @@ -0,0 +1,718 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +#[cfg(not(target_os = "none"))] +const fn main() {} + +#[cfg(target_os = "none")] +mod runtime { + use core::{ + alloc::Layout, + cell::UnsafeCell, + ffi::c_void, + mem::size_of, + ptr::{self, NonNull}, + sync::atomic::{AtomicI32, AtomicPtr, Ordering}, + }; + + use allocator_api2::{alloc::Allocator, vec::Vec}; + use bstr::BStr; + use fspy_elf_loader::{Syscall, SyscallAction, SyscallInterceptor}; + use fspy_nostd::{ + BorrowedFd, CStr, CWD, Error, OwnedFd, RawFd, Result, Thin, env::InitialStack, + fs::fcntl_dupfd, + }; + use fspy_nostd_alloc::{ + PageAllocator, PageBump, + fs::{fd_path, resolve_path_at}, + page_bump, pooled_bump, + }; + use fspy_shared::ipc::{ + AccessMode, IpcPath, IpcStr, + channel::{ChannelConf, Sender}, + }; + use fspy_shared_unix::{ + Exec, RawExec, + linux::{ + BOOTSTRAP_ENV_NAME, Bootstrap, ExecAtFlags, Target, encode_bootstrap, + ensure_bootstrap_env, resolve_exec, + }, + }; + use linux_raw_sys::general::{ + AT_EMPTY_PATH, O_ACCMODE, O_RDWR, O_WRONLY, SIG_SETMASK, open_how, + }; + use syscalls::Sysno; + + fspy_nostd::main!(run); + fspy_nostd::no_global_alloc!(); + + /// Linux 6.14+ `execveat(2)` flag that checks executability without replacing + /// the process image. + const AT_EXECVE_CHECK: u32 = 0x10000; + + struct SyncCell(UnsafeCell); + + // SAFETY: `STARTUP_BUMP` and `RUNTIME` are initialized once in the fresh, + // single-threaded launcher process before `exec_elf` arms seccomp and enters + // the target; after that `RUNTIME` is strictly read-only. + unsafe impl Sync for SyncCell {} + + struct Runtime { + ipc_channel_conf: ChannelConf<'static>, + preload_path: &'static IpcStr, + sender: Option, + } + + /// Scratch memory for one `execve` re-routed through the launcher: the + /// arena holding the rewritten `argv`/`envp`, and any descriptor kept open + /// for the new image. + /// + /// A successful exec in a `CLONE_VM` child (`vfork` / `posix_spawn`) + /// leaves the node in its parent's memory, so such nodes are pushed onto + /// [`PARKED_EXEC_SCRATCH`] with `active_tid` registered through + /// `set_tid_address`. The kernel clears it once the child execs or exits, + /// and a later exec trap frees the node. + struct ExecScratch { + next: AtomicPtr, + active_tid: AtomicI32, + parked: bool, + arena: UnsafeCell>, + duped_fd: UnsafeCell, + } + + // SAFETY: `arena` and `duped_fd` are mutated only by the exec'ing thread + // before `active_tid` becomes `0` (`Release`), and dropped by a reclaimer + // only after it observes `0` (`Acquire`) on a node it detached from + // `PARKED_EXEC_SCRATCH`. + unsafe impl Sync for ExecScratch {} + + static STARTUP_BUMP: SyncCell = SyncCell(UnsafeCell::new(page_bump())); + static RUNTIME: SyncCell> = SyncCell(UnsafeCell::new(None)); + static PARKED_EXEC_SCRATCH: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + + #[cfg(target_arch = "x86_64")] + const TRACKED_SYSCALLS: &[Sysno] = &[ + Sysno::open, + Sysno::openat, + Sysno::openat2, + Sysno::getdents, + Sysno::getdents64, + Sysno::stat, + Sysno::lstat, + Sysno::newfstatat, + Sysno::statx, + Sysno::access, + Sysno::faccessat, + Sysno::faccessat2, + Sysno::mkdir, + Sysno::mkdirat, + Sysno::rename, + Sysno::renameat, + Sysno::renameat2, + Sysno::link, + Sysno::linkat, + Sysno::symlink, + Sysno::symlinkat, + Sysno::execve, + Sysno::execveat, + ]; + + #[cfg(target_arch = "aarch64")] + const TRACKED_SYSCALLS: &[Sysno] = &[ + Sysno::openat, + Sysno::openat2, + Sysno::getdents64, + Sysno::fstatat, + Sysno::statx, + Sysno::faccessat, + Sysno::faccessat2, + Sysno::mkdirat, + Sysno::renameat, + Sysno::renameat2, + Sysno::linkat, + Sysno::symlinkat, + Sysno::execve, + Sysno::execveat, + ]; + + static INTERCEPTOR: SyscallInterceptor = + SyscallInterceptor { syscalls: TRACKED_SYSCALLS, handle: handle_syscall }; + + #[inline] + fn runtime() -> &'static Runtime { + // SAFETY: `RUNTIME` is initialized once during single-threaded startup + // before any `SIGSYS` handler or helper calls `runtime()`. + unsafe { (*RUNTIME.0.get()).as_ref() }.expect("runtime not initialized") + } + + #[expect(clippy::needless_pass_by_value, reason = "signature required by fspy_nostd::main!")] + fn run(stack: InitialStack<'_>) -> ! { + // SAFETY: `run` executes once in a fresh single-threaded process. + let bump: &'static PageBump = unsafe { &*STARTUP_BUMP.0.get() }; + let bootstrap = Bootstrap::from_env(stack.envs(), bump); + let sender = bootstrap.ipc_channel_conf.sender(bump); + + // SAFETY: single-threaded startup before arming seccomp. + unsafe { + *RUNTIME.0.get() = Some(Runtime { + ipc_channel_conf: bootstrap.ipc_channel_conf, + preload_path: bootstrap.preload_path, + sender, + }); + } + + let filtered_envs = stack.envs().iter().copied().filter(|&entry| !is_bootstrap_env(entry)); + + match bootstrap.target { + Target::Unresolved { path, error_pipe_fd } => { + let mut exec_args = Vec::with_capacity_in(stack.args().len(), bump); + for arg in stack.args() { + exec_args.push(copy_bytes(arg.count().as_units(), bump)); + } + let mut exec = Exec { + program: copy_bytes(path.as_bytes(), bump), + args: exec_args, + envs: Vec::new_in(bump), + }; + + let resolved = resolve_exec(&mut exec, Some(CWD), ExecAtFlags::empty(), |p| { + send_path(AccessMode::Read, p); + }) + .and_then(|resolved| { + fspy_elf_loader::validate_exec(resolved.file.as_fd())?; + Ok(resolved) + }); + + let resolved = match resolved { + Ok(resolved) => resolved, + Err(err) => { + write_error_pipe(error_pipe_fd, err.raw_os_error()); + exit_group(127); + } + }; + + write_error_pipe(error_pipe_fd, 0); + // Close the error pipe before entering the target so it never + // leaks an open descriptor into the child process. + if error_pipe_fd >= 0 { + // SAFETY: the parent opened `error_pipe_fd` exclusively for + // this startup handshake and transferred ownership to us. + drop(unsafe { OwnedFd::from_raw_fd(error_pipe_fd) }); + } + + let execfn = leak_cstr(&resolved.execfn, bump); + let mut argv = Vec::with_capacity_in(exec.args.len(), bump); + for arg in &exec.args { + argv.push(leak_cstr(arg, bump)); + } + + // SAFETY: fresh single-threaded freestanding launcher; `exec_elf` + // copies strings onto the new stack before abandoning ours. + unsafe { + fspy_elf_loader::exec_elf( + resolved.file, + execfn, + argv.into_iter(), + filtered_envs, + stack.auxv(), + Some(INTERCEPTOR), + ) + } + } + Target::ResolvedFd { fd, execfn, sigmask } => { + let execfn_cstr = + execfn.to_os_c_string_in(bump).expect("resolved execfn contains NUL"); + // SAFETY: parent duped `fd` specifically for this handoff. + let file = unsafe { OwnedFd::from_raw_fd(fd) }; + + restore_sigmask(sigmask); + + // SAFETY: fresh single-threaded freestanding launcher; `exec_elf` + // copies strings onto the new stack before abandoning ours. + unsafe { + fspy_elf_loader::exec_elf( + file, + execfn_cstr.as_c_str().as_thin(), + stack.args().iter().copied(), + filtered_envs, + stack.auxv(), + Some(INTERCEPTOR), + ) + } + } + } + } + + fn is_bootstrap_env(entry: CStr<'_, Thin>) -> bool { + let bytes = entry.count().as_units(); + bytes + .strip_prefix(BOOTSTRAP_ENV_NAME.as_bytes()) + .is_some_and(|rest| rest.is_empty() || rest.starts_with(b"=")) + } + + fn copy_bytes(bytes: &[u8], allocator: A) -> Vec { + let mut out = Vec::with_capacity_in(bytes.len(), allocator); + out.extend_from_slice(bytes); + out + } + + fn leak_cstr<'a, A: Allocator + 'a>(bytes: &[u8], allocator: A) -> CStr<'a, Thin> { + let mut owned = Vec::with_capacity_in(bytes.len() + 1, allocator); + owned.extend_from_slice(bytes); + owned.push(0); + let leaked: &'a [u8] = owned.leak(); + // SAFETY: `leaked` ends with a NUL byte and lives for `'a`. + unsafe { CStr::::from_ptr(leaked.as_ptr()) } + } + + fn write_error_pipe(fd: RawFd, code: i32) { + if fd < 0 { + return; + } + // SAFETY: `fd` is the parent-provided non-negative pipe descriptor. + let borrowed = unsafe { BorrowedFd::borrow_raw(fd) }; + let bytes = code.to_ne_bytes(); + let mut written = 0usize; + while written < bytes.len() { + match fspy_nostd::io::write(borrowed, &bytes[written..]) { + Ok(0) => break, + Ok(n) => written += n, + Err(Error::INTR) => {} + Err(_) => break, + } + } + } + + fn restore_sigmask(sigmask: u64) { + // SAFETY: `sigmask` is a valid stack-local 64-bit Linux `sigset_t`. + // Executing from inside the launcher's `PF_X` allowlist bypasses the + // inherited seccomp filter, and `exec_elf`'s `sigsys::install` will + // subsequently record and unblock `SIGSYS` if it was set in `sigmask`. + let _ = unsafe { + syscalls::syscall!( + Sysno::rt_sigprocmask, + SIG_SETMASK, + &raw const sigmask, + 0usize, + size_of::() + ) + }; + } + + fn exit_group(code: i32) -> ! { + // SAFETY: `exit_group` terminates the process immediately and never returns. + let _ = unsafe { syscalls::syscall!(Sysno::exit_group, code) }; + loop { + core::hint::spin_loop(); + } + } + + fn send_path(mode: AccessMode, path: &BStr) { + let bytes: &[u8] = path.as_ref(); + if bytes.starts_with(b"/dev/") + || bytes.starts_with(b"/proc/") + || bytes.starts_with(b"/sys/") + { + return; + } + if let Some(sender) = runtime().sender.as_ref() { + sender.send(&mode.with_path(IpcPath::from_bytes(bytes))); + } + } + + #[expect( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + reason = "Linux file descriptors are 32-bit signed integers" + )] + const fn arg_i32(raw: usize) -> i32 { + raw as i32 + } + + #[expect(clippy::cast_possible_truncation, reason = "Linux flags live in low 32 bits")] + const fn arg_u32(raw: usize) -> u32 { + raw as u32 + } + + const fn open_mode(flags: u32) -> AccessMode { + match flags & O_ACCMODE { + O_RDWR => AccessMode::ReadWrite, + O_WRONLY => AccessMode::Write, + _ => AccessMode::Read, + } + } + + /// Reports a path-based syscall to the IPC channel. `path_ptr` is the + /// trapped syscall's own argument, which `fspy_elf_loader` assumes valid. + fn report_path_at( + dirfd: Option>, + path_ptr: usize, + mode: AccessMode, + allow_empty_path: bool, + ) { + if path_ptr == 0 { + if allow_empty_path && let Some(fd) = dirfd { + report_fd(fd, mode); + } + return; + } + // SAFETY: `path_ptr` is the trapped syscall's path argument. + let Ok(c_path) = (unsafe { fspy_elf_loader::user_cstr(path_ptr) }) else { + return; + }; + let raw = c_path.count().as_units(); + if raw.is_empty() { + if allow_empty_path && let Some(fd) = dirfd { + report_fd(fd, mode); + } + return; + } + if raw.starts_with(b"/") { + send_path(mode, BStr::new(raw)); + return; + } + let arena = pooled_bump(); + if let Ok(Some(resolved)) = resolve_path_at(&arena, dirfd, c_path) { + send_path(mode, BStr::new(resolved.as_units())); + } + } + + fn report_fd(fd: BorrowedFd<'_>, mode: AccessMode) { + let arena = pooled_bump(); + if let Ok(Some(resolved)) = fd_path(&arena, fd) { + send_path(mode, BStr::new(resolved.as_units())); + } + } + + /// `SIGSYS` interceptor callback invoked by `fspy_elf_loader`. + /// + /// # Safety + /// + /// `call` holds the live (and `/proc/*/exe`-rewritten) arguments of a + /// trapped syscall listed in [`TRACKED_SYSCALLS`]. + unsafe fn handle_syscall(call: &Syscall) -> Result { + // SAFETY: `dirfd` arguments come directly from the trapped syscall; `-1` + // maps to `None` and invalid fds return `Ok(None)` from `fd_path`. + let borrow_dirfd = |raw: usize| unsafe { BorrowedFd::try_borrow_raw(arg_i32(raw)) }; + + match call.sysno { + Sysno::execve => handle_exec( + Some(CWD), + call.args[0], + call.args[1], + call.args[2], + ExecAtFlags::empty(), + call.sigmask(), + call.is_shared_vm_child(), + ), + Sysno::execveat => { + let raw_flags = arg_u32(call.args[4]); + // Linux 6.14+ `AT_EXECVE_CHECK` validates executability without + // replacing the process image; record the path lookup like + // `faccessat2` and let the kernel answer directly. + if (raw_flags & AT_EXECVE_CHECK) != 0 { + let empty_ok = (raw_flags & AT_EMPTY_PATH) != 0; + report_path_at( + borrow_dirfd(call.args[0]), + call.args[1], + AccessMode::Read, + empty_ok, + ); + return Ok(SyscallAction::Replay); + } + let Some(flags) = ExecAtFlags::from_bits(raw_flags) else { + return Err(Error::INVAL); + }; + handle_exec( + borrow_dirfd(call.args[0]), + call.args[1], + call.args[2], + call.args[3], + flags, + call.sigmask(), + call.is_shared_vm_child(), + ) + } + _ => { + handle_fs_syscall(call); + Ok(SyscallAction::Replay) + } + } + } + + /// Reports a tracked filesystem syscall to the IPC channel. + fn handle_fs_syscall(call: &Syscall) { + // SAFETY: `dirfd` arguments come directly from the trapped syscall; `-1` + // maps to `None` and invalid fds return `Ok(None)` from `fd_path`. + let dirfd = |idx: usize| unsafe { BorrowedFd::try_borrow_raw(arg_i32(call.args[idx])) }; + let a = call.args; + + match call.sysno { + #[cfg(target_arch = "x86_64")] + Sysno::open => report_path_at(Some(CWD), a[0], open_mode(arg_u32(a[1])), false), + Sysno::openat => report_path_at(dirfd(0), a[1], open_mode(arg_u32(a[2])), false), + Sysno::openat2 => report_openat2(dirfd(0), a[1], a[2], a[3]), + #[cfg(target_arch = "x86_64")] + Sysno::getdents => { + if let Some(fd) = dirfd(0) { + report_fd(fd, AccessMode::ReadDir); + } + } + Sysno::getdents64 => { + if let Some(fd) = dirfd(0) { + report_fd(fd, AccessMode::ReadDir); + } + } + #[cfg(target_arch = "x86_64")] + Sysno::stat | Sysno::lstat | Sysno::access => { + report_path_at(Some(CWD), a[0], AccessMode::Read, false); + } + #[cfg(target_arch = "x86_64")] + Sysno::newfstatat => { + let empty_ok = (arg_u32(a[3]) & AT_EMPTY_PATH) != 0; + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); + } + #[cfg(target_arch = "aarch64")] + Sysno::fstatat => { + let empty_ok = (arg_u32(a[3]) & AT_EMPTY_PATH) != 0; + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); + } + Sysno::statx => { + let empty_ok = (arg_u32(a[2]) & AT_EMPTY_PATH) != 0; + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); + } + Sysno::faccessat => { + report_path_at(dirfd(0), a[1], AccessMode::Read, false); + } + Sysno::faccessat2 => { + let empty_ok = (arg_u32(a[3]) & AT_EMPTY_PATH) != 0; + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); + } + #[cfg(target_arch = "x86_64")] + Sysno::mkdir => report_path_at(Some(CWD), a[0], AccessMode::Mkdir, false), + Sysno::mkdirat => report_path_at(dirfd(0), a[1], AccessMode::Mkdir, false), + #[cfg(target_arch = "x86_64")] + Sysno::rename => report_path_at(Some(CWD), a[1], AccessMode::RenameTarget, false), + Sysno::renameat | Sysno::renameat2 => { + report_path_at(dirfd(2), a[3], AccessMode::RenameTarget, false); + } + #[cfg(target_arch = "x86_64")] + Sysno::link | Sysno::symlink => { + report_path_at(Some(CWD), a[1], AccessMode::Write, false); + } + Sysno::linkat => report_path_at(dirfd(2), a[3], AccessMode::Write, false), + Sysno::symlinkat => report_path_at(dirfd(1), a[2], AccessMode::Write, false), + _ => {} + } + } + + fn report_openat2(dirfd: Option>, path_ptr: usize, how_ptr: usize, size: usize) { + if how_ptr == 0 || size < size_of::() { + return; + } + // SAFETY: `open_how` is a `#[repr(C)]` struct of `u64` fields valid for + // any bit pattern, and `how_ptr` is the trapped syscall's argument. + let Ok(how) = (unsafe { fspy_elf_loader::copy_user_value::(how_ptr) }) else { + return; + }; + #[expect( + clippy::cast_possible_truncation, + reason = "O_ACCMODE bits live in low 32 bits of open_how.flags" + )] + let mode = open_mode(how.flags as u32); + report_path_at(dirfd, path_ptr, mode, false); + } + + #[inline] + fn set_tid_address(addr: *const AtomicI32) { + // SAFETY: `addr` is either null or points to a live `AtomicI32` that + // remains mapped while the calling `CLONE_VM` child is attached to the + // current `mm_struct`. + let _ = unsafe { syscalls::raw::syscall1(Sysno::set_tid_address as usize, addr.addr()) }; + } + + unsafe fn push_parked_exec_scratch(node: *mut ExecScratch) { + let mut head = PARKED_EXEC_SCRATCH.load(Ordering::Acquire); + loop { + // SAFETY: Caller owns `node` exclusively until CAS publishes it. + unsafe { (*node).next.store(head, Ordering::Relaxed) }; + match PARKED_EXEC_SCRATCH.compare_exchange_weak( + head, + node, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return, + Err(actual) => head = actual, + } + } + } + + /// Drops `node`'s arena and returns its page to the allocator. + /// + /// # Safety + /// + /// `node` must be a live `ExecScratch` that nothing else references. + unsafe fn free_exec_scratch(node: *mut ExecScratch) { + // SAFETY: forwarded from the caller contract. + unsafe { + ptr::drop_in_place(node); + PageAllocator + .deallocate(NonNull::new_unchecked(node).cast(), Layout::new::()); + } + } + + /// Frees parked `CLONE_VM` exec scratch whose child has exec'd or exited, + /// keeping parent memory bounded across any number of `vfork` / + /// `posix_spawn` children. + fn reclaim_exec_scratch() { + if PARKED_EXEC_SCRATCH.load(Ordering::Acquire).is_null() { + return; + } + let mut cur = PARKED_EXEC_SCRATCH.swap(ptr::null_mut(), Ordering::AcqRel); + while !cur.is_null() { + // SAFETY: `swap(null)` transferred exclusive ownership of this chain. + let next = unsafe { (*cur).next.load(Ordering::Relaxed) }; + // SAFETY: `cur` is a live node of the detached chain. + if unsafe { (*cur).active_tid.load(Ordering::Acquire) } == 0 { + // SAFETY: The child left this memory (or failure cleanup + // released the node), so nothing references `cur`. Its + // `duped_fd` belonged to the child's descriptor table. + unsafe { free_exec_scratch(cur) }; + } else { + // SAFETY: `cur` is still in use by its child; park it again. + unsafe { push_parked_exec_scratch(cur) }; + } + cur = next; + } + } + + /// Failure cleanup invoked by `fspy_elf_loader` when `SYS_execve` returns + /// an error. + unsafe fn cleanup_exec_scratch(raw: *mut c_void) { + let node = raw.cast::(); + // SAFETY: `node` is the scratch of this failed exec, still owned by + // the calling thread, and `duped_fd` is open in its descriptor table. + unsafe { + let fd = *(*node).duped_fd.get(); + *(*node).duped_fd.get() = -1; + if fd >= 0 { + drop(OwnedFd::from_raw_fd(fd)); + } + if (*node).parked { + // Already published: release its arena and let a later + // reclaim free the node. + set_tid_address(ptr::null()); + *(*node).arena.get() = None; + (*node).active_tid.store(0, Ordering::Release); + } else { + free_exec_scratch(node); + } + } + } + + /// Resolves, validates, and prepares an `execve` / `execveat` call through + /// `fspy_preload_linux`, returning [`SyscallAction::Execve`] so + /// `fspy_elf_loader` releases the private `SIGSYS` stack before executing + /// the replacement `SYS_execve`. + fn handle_exec( + dirfd: Option>, + prog_ptr: usize, + argv_ptr: usize, + envp_ptr: usize, + flags: ExecAtFlags, + sigmask: u64, + is_shared_vm_child: bool, + ) -> Result { + reclaim_exec_scratch(); + + let mem = PageAllocator.allocate(Layout::new::()).map_err(|_| Error::NOMEM)?; + let node = mem.cast::().as_ptr(); + // SAFETY: `node` is freshly page-allocated for an `ExecScratch`. + unsafe { + node.write(ExecScratch { + next: AtomicPtr::new(ptr::null_mut()), + active_tid: AtomicI32::new(0), + parked: false, + arena: UnsafeCell::new(Some(page_bump())), + duped_fd: UnsafeCell::new(-1), + }); + } + // SAFETY: `arena` was just set and lives until the node is freed. + let arena: &'static PageBump = unsafe { (*(*node).arena.get()).as_ref().unwrap() }; + let (raw_out, duped_fd) = + match prepare_exec_in(dirfd, prog_ptr, argv_ptr, envp_ptr, flags, sigmask, arena) { + Ok(prepared) => prepared, + Err(err) => { + // SAFETY: the node was never published. + unsafe { free_exec_scratch(node) }; + return Err(err); + } + }; + // SAFETY: the node is owned by this thread until published below. + unsafe { + *(*node).duped_fd.get() = duped_fd; + if is_shared_vm_child { + (*node).parked = true; + (*node).active_tid.store(1, Ordering::Release); + push_parked_exec_scratch(node); + set_tid_address(&raw const (*node).active_tid); + } + } + Ok(SyscallAction::Execve { + prog: raw_out.prog.cast(), + argv: raw_out.argv.cast(), + envp: raw_out.envp.cast(), + cleanup: Some((cleanup_exec_scratch, node.cast())), + }) + } + + fn prepare_exec_in( + dirfd: Option>, + prog_ptr: usize, + argv_ptr: usize, + envp_ptr: usize, + flags: ExecAtFlags, + sigmask: u64, + arena: &'static PageBump, + ) -> Result<(RawExec, RawFd)> { + let raw = RawExec { + prog: ptr::with_exposed_provenance(prog_ptr), + argv: ptr::with_exposed_provenance(argv_ptr), + envp: ptr::with_exposed_provenance(envp_ptr), + }; + // SAFETY: the pointers are the trapped syscall's own `execve` arguments. + let mut exec = unsafe { raw.to_exec(arena) }?; + let resolved = resolve_exec(&mut exec, dirfd, flags, |p| send_path(AccessMode::Read, p))?; + fspy_elf_loader::validate_exec(resolved.file.as_fd())?; + + // Hand the validated descriptor itself to the new image instead of a + // pathname to reopen: the file may be replaced or unlinked meanwhile, + // and `/proc/self/fd/N` targets close with `FD_CLOEXEC` on exec. Keep + // `duped_fd` open across `SYS_execve` (`fcntl_dupfd` clears + // `FD_CLOEXEC`). If `prepare_exec_in` fails below, `OwnedFd` closes it + // automatically; once handed back as a raw fd, `cleanup_*` closes it on + // `SYS_execve` failure while a successful exec transfers it to the child. + let duped_fd = fcntl_dupfd(resolved.file.as_fd(), 3)?; + + let rt = runtime(); + let target = Target::ResolvedFd { + fd: duped_fd.as_raw_fd(), + execfn: IpcStr::from_bytes(&resolved.execfn), + sigmask, + }; + let bootstrap = Bootstrap { + ipc_channel_conf: rt.ipc_channel_conf, + preload_path: rt.preload_path, + target, + }; + let encoded = encode_bootstrap(&bootstrap, arena); + ensure_bootstrap_env(&mut exec.envs, encoded)?; + + exec.program = copy_bytes(rt.preload_path.as_bytes(), arena); + let raw_out = RawExec::from_exec(exec); + let duped_raw = duped_fd.as_raw_fd(); + core::mem::forget(duped_fd); + Ok((raw_out, duped_raw)) + } +} diff --git a/crates/fspy_client_unix/.clippy.toml b/crates/fspy_preload_macos/.clippy.toml similarity index 100% rename from crates/fspy_client_unix/.clippy.toml rename to crates/fspy_preload_macos/.clippy.toml diff --git a/crates/fspy_preload_unix/Cargo.toml b/crates/fspy_preload_macos/Cargo.toml similarity index 54% rename from crates/fspy_preload_unix/Cargo.toml rename to crates/fspy_preload_macos/Cargo.toml index 8c9a1dc66..505f64240 100644 --- a/crates/fspy_preload_unix/Cargo.toml +++ b/crates/fspy_preload_macos/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "fspy_preload_unix" +name = "fspy_preload_macos" edition = "2024" license.workspace = true publish = false @@ -7,20 +7,16 @@ publish = false [lib] crate-type = ["cdylib"] -[target.'cfg(unix)'.dependencies] +[target.'cfg(target_os = "macos")'.dependencies] +allocator-api2 = { workspace = true, features = ["alloc"] } +bstr = { workspace = true } ctor = { workspace = true } -fspy_client_unix = { workspace = true } +fspy_nostd = { workspace = true } +fspy_nostd_alloc = { workspace = true } fspy_shared = { workspace = true } fspy_shared_unix = { workspace = true } libc = { workspace = true } -nix = { workspace = true, features = ["signal", "fs", "socket", "mman", "time"] } -fspy_nostd = { workspace = true } -allocator-api2 = { workspace = true } -fspy_nostd_alloc = { workspace = true } static_cell = { workspace = true } -[target.'cfg(target_os = "linux")'.dependencies] -syscalls = { workspace = true } - [lints] workspace = true diff --git a/crates/fspy_preload_macos/README.md b/crates/fspy_preload_macos/README.md new file mode 100644 index 000000000..64fe600a8 --- /dev/null +++ b/crates/fspy_preload_macos/README.md @@ -0,0 +1,4 @@ +## fspy_preload_macos + +Dynamic library (`cdylib`) injected into traced macOS processes via +`DYLD_INSERT_LIBRARIES` using dyld's `__DATA,__interpose` section. diff --git a/crates/fspy_preload_macos/src/client.rs b/crates/fspy_preload_macos/src/client.rs new file mode 100644 index 000000000..b17a6c77d --- /dev/null +++ b/crates/fspy_preload_macos/src/client.rs @@ -0,0 +1,177 @@ +use std::sync::OnceLock; + +use allocator_api2::alloc::Allocator; +use bstr::BStr; +use fspy_nostd::{BorrowedFd, CStr, CWD, Error, Result, Thin}; +use fspy_nostd_alloc::fs::{fd_path, resolve_path_at}; +use fspy_shared::ipc::{AccessMode, IpcPath, channel::Sender}; +use fspy_shared_unix::{RawExec, macos::EncodedPayload}; +use libc::{c_char, c_int}; + +use crate::which; + +pub struct Client<'a> { + encoded_payload: EncodedPayload<'a>, + ipc_sender: Option, +} + +const _: () = { + const fn assert_send_sync() {} + assert_send_sync::>(); +}; + +#[cfg(not(test))] +impl<'a> Client<'a> { + fn from_env( + envs: impl Iterator, + allocator: impl Allocator + Clone + 'a, + ) -> Self { + let encoded_payload = EncodedPayload::from_env(envs, allocator.clone()); + let ipc_sender = encoded_payload.ipc_channel_conf().sender(allocator); + Self { encoded_payload, ipc_sender } + } +} + +impl Client<'_> { + pub fn send_path(&self, mode: AccessMode, path: &BStr) { + let Some(ipc_sender) = &self.ipc_sender else { + return; + }; + let bytes: &[u8] = path.as_ref(); + if bytes.starts_with(b"/dev/") { + return; + } + ipc_sender.send(&mode.with_path(IpcPath::from_bytes(bytes))); + } + + /// Resolves and prepares an exec call, optionally searching `PATH` first. + /// + /// # Safety + /// + /// `raw_exec` must contain valid pointers satisfying [`RawExec::to_exec`]. + /// The returned [`RawExec`] borrows from `allocator`. + /// + /// # Errors + /// + /// Returns OS-compatible `errno` values from `PATH` lookup or exec + /// preparation. + pub unsafe fn handle_exec( + &self, + search_path: bool, + raw_exec: RawExec, + allocator: &A, + ) -> Result { + // SAFETY: caller upholds `RawExec::to_exec`'s pointer contract. + let mut exec = unsafe { raw_exec.to_exec(allocator) }?; + if search_path { + exec.program = which::resolve_in_path(&exec.program, allocator, |candidate| { + self.send_path(AccessMode::Read, candidate); + })?; + } + self.encoded_payload.prepare_exec(&mut exec, |path| { + self.send_path(AccessMode::Read, path); + })?; + Ok(RawExec::from_exec(exec)) + } +} + +static CLIENT: OnceLock> = OnceLock::new(); + +pub fn global_client() -> Option<&'static Client<'static>> { + CLIENT.get() +} + +pub fn set_errno(error: Error) { + // SAFETY: `__error()` returns a non-null pointer to thread-local `errno`. + unsafe { *::libc::__error() = error.raw_os_error() }; +} + +pub const fn open_flags_mode(flags: c_int) -> AccessMode { + match flags & ::libc::O_ACCMODE { + ::libc::O_RDWR => AccessMode::ReadWrite, + ::libc::O_WRONLY => AccessMode::Write, + _ => AccessMode::Read, + } +} + +/// Decodes a `fopen`/`freopen` mode string into an [`AccessMode`]. +/// +/// # Safety +/// +/// `mode` must be a valid NUL-terminated C string. +pub unsafe fn mode_str_to_access_mode(mode: *const c_char) -> AccessMode { + // SAFETY: caller guarantees `mode` points to a valid NUL-terminated string. + let mode_bytes = unsafe { CStr::::from_ptr(mode.cast()) }.count().as_units(); + let has_read = mode_bytes.contains(&b'r'); + let has_write = mode_bytes.contains(&b'w') || mode_bytes.contains(&b'a'); + match (has_read, has_write) { + (false, true) => AccessMode::Write, + (true, true) => AccessMode::ReadWrite, + _ => AccessMode::Read, + } +} + +/// Reports a path relative to `CWD`. +/// +/// # Safety +/// +/// `path` must point to a valid NUL-terminated C string. +pub unsafe fn handle_open_path(path: *const c_char, mode: AccessMode) { + // SAFETY: `CWD` is permanent and `path` is guaranteed valid by the caller. + unsafe { handle_open_at(CWD.as_raw_fd(), path, mode) }; +} + +/// Reports a path relative to `dirfd` (or ignored when `path` is absolute). +/// +/// # Safety +/// +/// `dirfd` must be `-1` or an open descriptor, and `path` must point to a valid +/// NUL-terminated C string. +pub unsafe fn handle_open_at(dirfd: c_int, path: *const c_char, mode: AccessMode) { + let Some(client) = global_client() else { + return; + }; + if path.is_null() { + return; + } + let arena = fspy_nostd_alloc::pooled_bump(); + // SAFETY: `dirfd` is `-1` or open, and `path` is a non-null C string. + let dirfd = unsafe { BorrowedFd::try_borrow_raw(dirfd) }; + // SAFETY: non-null `path` is NUL-terminated for the duration of this call. + let c_path = unsafe { CStr::::from_ptr(path.cast()) }; + if let Ok(Some(resolved)) = resolve_path_at(&arena, dirfd, c_path) { + client.send_path(mode, BStr::new(resolved.as_units())); + } +} + +/// Reports an access on an open descriptor (such as `fdopendir`). +/// +/// # Safety +/// +/// `fd` must be `-1` or an open descriptor. +pub unsafe fn handle_open_fd(fd: c_int, mode: AccessMode) { + let Some(client) = global_client() else { + return; + }; + // SAFETY: `fd` is `-1` or an open descriptor. + let Some(fd) = (unsafe { BorrowedFd::try_borrow_raw(fd) }) else { + return; + }; + let arena = fspy_nostd_alloc::pooled_bump(); + if let Ok(Some(resolved)) = fd_path(&arena, fd) { + client.send_path(mode, BStr::new(resolved.as_units())); + } +} + +#[cfg(not(test))] +#[ctor::ctor(unsafe)] +fn init_client() { + // SAFETY: the ctor only reads the process environment while constructing + // the client and does not retain borrowed environment views. + let current = unsafe { fspy_nostd::env::current() }.unwrap(); + static BUMP: static_cell::StaticCell = + static_cell::StaticCell::new(); + let bump: &'static fspy_nostd_alloc::PageBump = BUMP.init(fspy_nostd_alloc::page_bump()); + let client = Client::from_env(current.envs(), bump); + assert!(CLIENT.set(client).is_ok(), "client already initialized"); +} diff --git a/crates/fspy_preload_unix/src/interceptions/access.rs b/crates/fspy_preload_macos/src/interceptions/access.rs similarity index 52% rename from crates/fspy_preload_unix/src/interceptions/access.rs rename to crates/fspy_preload_macos/src/interceptions/access.rs index db220a314..69fd8e7b7 100644 --- a/crates/fspy_preload_unix/src/interceptions/access.rs +++ b/crates/fspy_preload_macos/src/interceptions/access.rs @@ -2,17 +2,15 @@ use fspy_shared::ipc::AccessMode; use libc::{c_char, c_int}; use crate::{ - client::{convert::PathAt, handle_open}, + client::{handle_open_at, handle_open_path}, macros::intercept, }; intercept!(access(64): unsafe extern "C" fn(pathname: *const c_char, mode: c_int) -> c_int); unsafe extern "C" fn access(pathname: *const c_char, mode: c_int) -> c_int { - // SAFETY: pathname is a valid C string pointer provided by the caller of the interposed function - unsafe { - handle_open(fspy_nostd::CStr::from_ptr(pathname.cast()), AccessMode::Read); - } - // SAFETY: calling the original libc access() with the same arguments forwarded from the interposed function + // SAFETY: pathname is a valid C string pointer provided by the caller. + unsafe { handle_open_path(pathname, AccessMode::Read) }; + // SAFETY: calling the original libc access() with forwarded arguments. unsafe { access::original()(pathname, mode) } } @@ -23,10 +21,8 @@ unsafe extern "C" fn faccessat( mode: c_int, flags: c_int, ) -> c_int { - // SAFETY: dirfd is -1 or a valid file descriptor, and pathname is a valid C string, provided by the caller of the interposed function - unsafe { - handle_open(PathAt::borrow_raw(dirfd, pathname), AccessMode::Read); - } - // SAFETY: calling the original libc faccessat() with the same arguments forwarded from the interposed function + // 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. unsafe { faccessat::original()(dirfd, pathname, mode, flags) } } diff --git a/crates/fspy_preload_macos/src/interceptions/dirent.rs b/crates/fspy_preload_macos/src/interceptions/dirent.rs new file mode 100644 index 000000000..5d8c9d175 --- /dev/null +++ b/crates/fspy_preload_macos/src/interceptions/dirent.rs @@ -0,0 +1,85 @@ +use fspy_shared::ipc::AccessMode; +use libc::{DIR, c_char, c_int, c_long, c_void}; + +use crate::{ + client::{handle_open_fd, handle_open_path}, + macros::intercept, +}; + +intercept!(scandir(64): unsafe extern "C" fn( + dirname: *const c_char, + namelist: *mut c_void, + select: *const c_void, + compar: *const c_void, +) -> c_int); +unsafe extern "C" fn scandir( + dirname: *const c_char, + namelist: *mut c_void, + select: *const c_void, + compar: *const c_void, +) -> c_int { + // SAFETY: dirname is a valid C string pointer provided by the caller. + unsafe { handle_open_path(dirname, AccessMode::ReadDir) }; + // SAFETY: calling the original libc scandir() with forwarded arguments. + unsafe { scandir::original()(dirname, namelist, select, compar) } +} + +intercept!(scandir_b: unsafe extern "C" fn( + dirname: *const c_char, + namelist: *mut c_void, + select: *const c_void, + compar: *const c_void, +) -> c_int); +unsafe extern "C" fn scandir_b( + dirname: *const c_char, + namelist: *mut c_void, + select: *const c_void, + compar: *const c_void, +) -> c_int { + // SAFETY: dirname is a valid C string pointer provided by the caller. + unsafe { handle_open_path(dirname, AccessMode::ReadDir) }; + // SAFETY: calling the original libc scandir_b() with forwarded arguments. + unsafe { scandir_b::original()(dirname, namelist, select, compar) } +} + +intercept!(__getdirentries64: unsafe extern "C" fn(c_int, *mut u8, usize, *mut i64) -> isize); +unsafe extern "C" fn __getdirentries64( + fd: c_int, + buf: *mut u8, + buf_len: usize, + basep: *mut i64, +) -> isize { + // SAFETY: fd is -1 or a valid file descriptor provided by the caller. + unsafe { handle_open_fd(fd, AccessMode::ReadDir) }; + // SAFETY: calling the original libc __getdirentries64() with forwarded arguments. + unsafe { __getdirentries64::original()(fd, buf, buf_len, basep) } +} + +intercept!(getdirentries(64): unsafe extern "C" fn(fd: c_int, buf: *mut c_char, nbytes: c_int, basep: *mut c_long) -> c_int); +unsafe extern "C" fn getdirentries( + fd: c_int, + buf: *mut c_char, + nbytes: c_int, + basep: *mut c_long, +) -> c_int { + // SAFETY: fd is -1 or a valid file descriptor provided by the caller. + unsafe { handle_open_fd(fd, AccessMode::ReadDir) }; + // SAFETY: calling the original libc getdirentries() with forwarded arguments. + unsafe { getdirentries::original()(fd, buf, nbytes, basep) } +} + +intercept!(fdopendir(64): unsafe extern "C" fn(fd: c_int) -> *mut DIR); +unsafe extern "C" fn fdopendir(fd: c_int) -> *mut DIR { + // SAFETY: fd is -1 or a valid file descriptor provided by the caller. + unsafe { handle_open_fd(fd, AccessMode::ReadDir) }; + // SAFETY: calling the original libc fdopendir() with forwarded arguments. + unsafe { fdopendir::original()(fd) } +} + +intercept!(opendir(64): unsafe extern "C" fn(*const c_char) -> *mut DIR); +unsafe extern "C" fn opendir(dir_name: *const c_char) -> *mut DIR { + // SAFETY: dir_name is a valid C string pointer provided by the caller. + unsafe { handle_open_path(dir_name, AccessMode::ReadDir) }; + // SAFETY: calling the original libc opendir() with forwarded arguments. + unsafe { opendir::original()(dir_name) } +} diff --git a/crates/fspy_preload_unix/src/interceptions/dyld.rs b/crates/fspy_preload_macos/src/interceptions/dyld.rs similarity index 100% rename from crates/fspy_preload_unix/src/interceptions/dyld.rs rename to crates/fspy_preload_macos/src/interceptions/dyld.rs diff --git a/crates/fspy_preload_unix/src/interceptions/mod.rs b/crates/fspy_preload_macos/src/interceptions/mod.rs similarity index 51% rename from crates/fspy_preload_unix/src/interceptions/mod.rs rename to crates/fspy_preload_macos/src/interceptions/mod.rs index 389462e18..019f9c098 100644 --- a/crates/fspy_preload_unix/src/interceptions/mod.rs +++ b/crates/fspy_preload_macos/src/interceptions/mod.rs @@ -1,11 +1,7 @@ mod access; mod dirent; -#[cfg(target_os = "macos")] mod dyld; mod namespace; mod open; mod spawn; mod stat; - -#[cfg(target_os = "linux")] -mod linux_syscall; diff --git a/crates/fspy_preload_macos/src/interceptions/namespace.rs b/crates/fspy_preload_macos/src/interceptions/namespace.rs new file mode 100644 index 000000000..de445bbc5 --- /dev/null +++ b/crates/fspy_preload_macos/src/interceptions/namespace.rs @@ -0,0 +1,116 @@ +//! Calls that make an entry at a path without opening it: mkdir, symlink, +//! and rename and hard link, which put an existing file or folder at a new +//! path. + +use fspy_shared::ipc::AccessMode; +use libc::{c_char, c_int, mode_t}; + +use crate::{ + client::{handle_open_at, handle_open_path}, + macros::intercept, +}; + +intercept!(mkdir: unsafe extern "C" fn(path: *const c_char, mode: mode_t) -> c_int); +unsafe extern "C" fn mkdir(path: *const c_char, mode: mode_t) -> c_int { + // SAFETY: path is a valid C string pointer provided by the caller. + unsafe { handle_open_path(path, AccessMode::Mkdir) }; + // SAFETY: calling the original libc mkdir() with forwarded arguments. + unsafe { mkdir::original()(path, mode) } +} + +intercept!(mkdirat: unsafe extern "C" fn(dirfd: c_int, path: *const c_char, mode: mode_t) -> c_int); +unsafe extern "C" fn mkdirat(dirfd: c_int, path: *const c_char, mode: mode_t) -> c_int { + // SAFETY: dirfd is -1 or valid, and path is a valid C string. + unsafe { handle_open_at(dirfd, path, AccessMode::Mkdir) }; + // SAFETY: calling the original libc mkdirat() with forwarded arguments. + unsafe { mkdirat::original()(dirfd, path, mode) } +} + +intercept!(rename: unsafe extern "C" fn(old: *const c_char, new: *const c_char) -> c_int); +unsafe extern "C" fn rename(old: *const c_char, new: *const c_char) -> c_int { + // SAFETY: new is a valid C string pointer provided by the caller. + unsafe { handle_open_path(new, AccessMode::RenameTarget) }; + // SAFETY: calling the original libc rename() with forwarded arguments. + unsafe { rename::original()(old, new) } +} + +intercept!(renameat: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char) -> c_int); +unsafe extern "C" fn renameat( + olddirfd: c_int, + old: *const c_char, + newdirfd: c_int, + new: *const c_char, +) -> c_int { + // SAFETY: newdirfd is -1 or valid, and new is a valid C string. + unsafe { handle_open_at(newdirfd, new, AccessMode::RenameTarget) }; + // SAFETY: calling the original libc renameat() with forwarded arguments. + unsafe { renameat::original()(olddirfd, old, newdirfd, new) } +} + +intercept!(renamex_np: unsafe extern "C" fn(old: *const c_char, new: *const c_char, flags: libc::c_uint) -> c_int); +unsafe extern "C" fn renamex_np( + old: *const c_char, + new: *const c_char, + flags: libc::c_uint, +) -> c_int { + // SAFETY: new is a valid C string pointer provided by the caller. + unsafe { handle_open_path(new, AccessMode::RenameTarget) }; + // SAFETY: calling the original libc renamex_np() with forwarded arguments. + unsafe { renamex_np::original()(old, new, flags) } +} + +intercept!(renameatx_np: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char, flags: libc::c_uint) -> c_int); +unsafe extern "C" fn renameatx_np( + olddirfd: c_int, + old: *const c_char, + newdirfd: c_int, + new: *const c_char, + flags: libc::c_uint, +) -> c_int { + // SAFETY: newdirfd is -1 or valid, and new is a valid C string. + unsafe { handle_open_at(newdirfd, new, AccessMode::RenameTarget) }; + // SAFETY: calling the original libc renameatx_np() with forwarded arguments. + unsafe { renameatx_np::original()(olddirfd, old, newdirfd, new, flags) } +} + +intercept!(link: unsafe extern "C" fn(old: *const c_char, new: *const c_char) -> c_int); +unsafe extern "C" fn link(old: *const c_char, new: *const c_char) -> c_int { + // SAFETY: new is a valid C string pointer provided by the caller. + unsafe { handle_open_path(new, AccessMode::Write) }; + // SAFETY: calling the original libc link() with forwarded arguments. + unsafe { link::original()(old, new) } +} + +intercept!(linkat: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char, flags: c_int) -> c_int); +unsafe extern "C" fn linkat( + olddirfd: c_int, + old: *const c_char, + newdirfd: c_int, + new: *const c_char, + flags: c_int, +) -> c_int { + // SAFETY: newdirfd is -1 or valid, and new is a valid C string. + unsafe { handle_open_at(newdirfd, new, AccessMode::Write) }; + // SAFETY: calling the original libc linkat() with forwarded arguments. + unsafe { linkat::original()(olddirfd, old, newdirfd, new, flags) } +} + +intercept!(symlink: unsafe extern "C" fn(target: *const c_char, link: *const c_char) -> c_int); +unsafe extern "C" fn symlink(target: *const c_char, link: *const c_char) -> c_int { + // SAFETY: link is a valid C string pointer provided by the caller. + unsafe { handle_open_path(link, AccessMode::Write) }; + // SAFETY: calling the original libc symlink() with forwarded arguments. + unsafe { symlink::original()(target, link) } +} + +intercept!(symlinkat: unsafe extern "C" fn(target: *const c_char, newdirfd: c_int, link: *const c_char) -> c_int); +unsafe extern "C" fn symlinkat( + target: *const c_char, + newdirfd: c_int, + link: *const c_char, +) -> c_int { + // SAFETY: newdirfd is -1 or valid, and link is a valid C string. + unsafe { handle_open_at(newdirfd, link, AccessMode::Write) }; + // SAFETY: calling the original libc symlinkat() with forwarded arguments. + unsafe { symlinkat::original()(target, newdirfd, link) } +} diff --git a/crates/fspy_preload_unix/src/interceptions/open.rs b/crates/fspy_preload_macos/src/interceptions/open.rs similarity index 50% rename from crates/fspy_preload_unix/src/interceptions/open.rs rename to crates/fspy_preload_macos/src/interceptions/open.rs index cb8ac5f3b..1f3fe60f6 100644 --- a/crates/fspy_preload_unix/src/interceptions/open.rs +++ b/crates/fspy_preload_macos/src/interceptions/open.rs @@ -1,41 +1,29 @@ use libc::FILE; use crate::{ - client::{ - convert::{ModeStr, OpenFlags, PathAt}, - handle_open, - }, + client::{handle_open_at, handle_open_path, mode_str_to_access_mode, open_flags_mode}, libc::{c_char, c_int}, macros::intercept, }; const fn has_mode_arg(o_flags: c_int) -> bool { - if o_flags & libc::O_CREAT != 0 { - return true; - } - #[cfg(target_os = "linux")] - if o_flags & libc::O_TMPFILE != 0 { - return true; - } - false + o_flags & libc::O_CREAT != 0 } -#[cfg(not(target_os = "macos"))] -type Mode = libc::mode_t; -#[cfg(target_os = "macos")] // https://github.com/tailhook/openat/issues/21#issuecomment-535914957 +// https://github.com/tailhook/openat/issues/21#issuecomment-535914957 type Mode = c_int; intercept!(open(64): unsafe extern "C" fn(*const c_char, c_int, args: ...) -> c_int); unsafe extern "C" fn open(path: *const c_char, flags: c_int, mut args: ...) -> c_int { - // SAFETY: path is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(path.cast()), OpenFlags(flags)) }; + // SAFETY: path is a valid C string pointer provided by the caller. + unsafe { handle_open_path(path, open_flags_mode(flags)) }; if has_mode_arg(flags) { - // SAFETY: when O_CREAT or O_TMPFILE is set, a mode_t argument is required by the open() contract + // SAFETY: O_CREAT requires a mode argument. let mode: Mode = unsafe { args.next_arg() }; - // SAFETY: calling the original libc open() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc open() with forwarded arguments. unsafe { open::original()(path, flags, mode) } } else { - // SAFETY: calling the original libc open() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc open() with forwarded arguments. unsafe { open::original()(path, flags) } } } @@ -47,65 +35,59 @@ unsafe extern "C" fn openat( flags: c_int, mut args: ... ) -> c_int { - // SAFETY: dirfd is -1 or a valid file descriptor, and path is a valid C string, provided by the caller of the interposed function - unsafe { handle_open(PathAt::borrow_raw(dirfd, path), OpenFlags(flags)) }; - + // SAFETY: dirfd is -1 or valid, and path is a valid C string. + unsafe { handle_open_at(dirfd, path, open_flags_mode(flags)) }; if has_mode_arg(flags) { - // https://github.com/tailhook/openat/issues/21#issuecomment-535914957 - // SAFETY: when O_CREAT or O_TMPFILE is set, a mode_t argument is required by the openat() contract + // SAFETY: O_CREAT requires a mode argument. let mode: Mode = unsafe { args.next_arg() }; - // SAFETY: calling the original libc openat() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc openat() with forwarded arguments. unsafe { openat::original()(dirfd, path, flags, mode) } } else { - // SAFETY: calling the original libc openat() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc openat() with forwarded arguments. unsafe { openat::original()(dirfd, path, flags) } } } -#[cfg(target_os = "macos")] intercept!(open_nocancel: unsafe extern "C" fn(*const c_char, c_int, ...) -> c_int); -#[cfg(target_os = "macos")] unsafe extern "C" fn open_nocancel(path: *const c_char, flags: c_int, mut args: ...) -> c_int { - // SAFETY: path is a valid C string pointer provided by the caller of open$NOCANCEL - unsafe { handle_open(fspy_nostd::CStr::from_ptr(path.cast()), OpenFlags(flags)) }; + // SAFETY: path is a valid C string pointer provided by the caller. + unsafe { handle_open_path(path, open_flags_mode(flags)) }; if has_mode_arg(flags) { - // SAFETY: O_CREAT requires a mode argument, matching the open$NOCANCEL contract + // SAFETY: O_CREAT requires a mode argument. let mode: Mode = unsafe { args.next_arg() }; - // SAFETY: calling the original libc open$NOCANCEL() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc open$NOCANCEL() with forwarded arguments. unsafe { open_nocancel::original()(path, flags, mode) } } else { - // SAFETY: calling the original libc open$NOCANCEL() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc open$NOCANCEL() with forwarded arguments. unsafe { open_nocancel::original()(path, flags) } } } -#[cfg(target_os = "macos")] intercept!(openat_nocancel: unsafe extern "C" fn(c_int, *const c_char, c_int, ...) -> c_int); -#[cfg(target_os = "macos")] unsafe extern "C" fn openat_nocancel( dirfd: c_int, path: *const c_char, flags: c_int, mut args: ... ) -> c_int { - // SAFETY: dirfd is -1 or a valid file descriptor, and path is a valid C string, provided by the caller of openat$NOCANCEL - unsafe { handle_open(PathAt::borrow_raw(dirfd, path), OpenFlags(flags)) }; + // SAFETY: dirfd is -1 or valid, and path is a valid C string. + unsafe { handle_open_at(dirfd, path, open_flags_mode(flags)) }; if has_mode_arg(flags) { - // SAFETY: O_CREAT requires a mode argument, matching the openat$NOCANCEL contract + // SAFETY: O_CREAT requires a mode argument. let mode: Mode = unsafe { args.next_arg() }; - // SAFETY: calling the original libc openat$NOCANCEL() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc openat$NOCANCEL() with forwarded arguments. unsafe { openat_nocancel::original()(dirfd, path, flags, mode) } } else { - // SAFETY: calling the original libc openat$NOCANCEL() with the same arguments forwarded from the interposed function + // SAFETY: calling the original libc openat$NOCANCEL() with forwarded arguments. unsafe { openat_nocancel::original()(dirfd, path, flags) } } } intercept!(fopen(64): unsafe extern "C" fn(path: *const c_char, mode: *const c_char) -> *mut FILE); unsafe extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> *mut libc::FILE { - // SAFETY: path and mode are valid C string pointers provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(path.cast()), ModeStr(mode)) }; - // SAFETY: calling the original libc fopen() with the same arguments forwarded from the interposed function + // SAFETY: path and mode are valid C string pointers provided by the caller. + unsafe { handle_open_path(path, mode_str_to_access_mode(mode)) }; + // SAFETY: calling the original libc fopen() with forwarded arguments. unsafe { fopen::original()(path, mode) } } @@ -115,8 +97,8 @@ unsafe extern "C" fn freopen( mode: *const c_char, stream: *mut FILE, ) -> *mut FILE { - // SAFETY: path and mode are valid C string pointers provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(path.cast()), ModeStr(mode)) }; - // SAFETY: calling the original libc freopen() with the same arguments forwarded from the interposed function + // SAFETY: path and mode are valid C string pointers provided by the caller. + unsafe { handle_open_path(path, mode_str_to_access_mode(mode)) }; + // SAFETY: calling the original libc freopen() with forwarded arguments. unsafe { freopen::original()(path, mode, stream) } } diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs b/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs new file mode 100644 index 000000000..aef0ba972 --- /dev/null +++ b/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs @@ -0,0 +1,140 @@ +use std::{ffi::VaList, ptr::null}; + +use allocator_api2::{alloc::Allocator, vec::Vec}; +use fspy_shared_unix::RawExec; +use libc::{c_char, c_int}; + +use crate::{ + client::{global_client, set_errno}, + macros::intercept, +}; + +unsafe fn environ() -> *const *const c_char { + // SAFETY: `_NSGetEnviron()` always returns a valid pointer to the process's `environ`. + unsafe { *(libc::_NSGetEnviron().cast()) } +} + +/// Collects `arg` and the variadic arguments after it into a NULL-terminated +/// argv array in `allocator` (never touching libc malloc). +/// +/// # Safety +/// +/// Unless `arg` is NULL, `va` must hold `*const c_char` arguments up to a +/// NULL pointer. +unsafe fn collect_argv( + allocator: A, + mut arg: *const c_char, + va: &mut VaList<'_>, +) -> Vec<*const c_char, A> { + let mut argv = Vec::new_in(allocator); + while !arg.is_null() { + argv.push(arg); + // SAFETY: caller guarantees arguments continue up to a NULL pointer. + arg = unsafe { va.next_arg() }; + } + argv.push(null()); + argv +} + +fn handle_exec( + allocator: impl Allocator, + search_path: bool, + prog: *const c_char, + argv: *const *const c_char, + envp: *const *const c_char, +) -> c_int { + let client = + global_client().expect("exec unexpectedly called before client initialized in ctor"); + // SAFETY: prog, argv, and envp are forwarded from the interposed exec call. + let raw_command = match unsafe { + client.handle_exec(search_path, RawExec { prog, argv, envp }, &allocator) + } { + Ok(raw) => raw, + Err(err) => { + set_errno(err); + return -1; + } + }; + // SAFETY: `raw_command` points into `allocator`, which outlives this call. + unsafe { execve::original()(raw_command.prog, raw_command.argv, raw_command.envp) } +} + +intercept!(execve(64): unsafe extern "C" fn( + prog: *const c_char, + argv: *const *const c_char, + envp: *const *const c_char, +) -> c_int); +unsafe extern "C" fn execve( + prog: *const c_char, + argv: *const *const c_char, + envp: *const *const c_char, +) -> c_int { + handle_exec(fspy_nostd_alloc::pooled_bump(), false, prog, argv, envp) +} + +intercept!(execl(64): unsafe extern "C" fn(path: *const c_char, arg0: *const c_char, ...) -> c_int); +unsafe extern "C" fn execl(path: *const c_char, arg: *const c_char, mut valist: ...) -> c_int { + #[expect( + clippy::no_effect_underscore_binding, + reason = "suppresses unused warning on *::original" + )] + let _unused = execl::original; + let arena = fspy_nostd_alloc::pooled_bump(); + // SAFETY: valist holds execl's NULL-terminated argument list after arg. + let (argv, envp) = unsafe { (collect_argv(&arena, arg, &mut valist), environ()) }; + handle_exec(&arena, false, path, argv.as_ptr(), envp) +} + +intercept!(execlp(64): unsafe extern "C" fn(path: *const c_char, arg0: *const c_char, ...) -> c_int); +unsafe extern "C" fn execlp(path: *const c_char, arg: *const c_char, mut valist: ...) -> c_int { + #[expect( + clippy::no_effect_underscore_binding, + reason = "suppresses unused warning on *::original" + )] + let _unused = execlp::original; + let arena = fspy_nostd_alloc::pooled_bump(); + // SAFETY: valist holds execlp's NULL-terminated argument list after arg. + let (argv, envp) = unsafe { (collect_argv(&arena, arg, &mut valist), environ()) }; + handle_exec(&arena, true, path, argv.as_ptr(), envp) +} + +intercept!(execle(64): unsafe extern "C" fn(path: *const c_char, arg0: *const c_char, ...) -> c_int); +unsafe extern "C" fn execle(path: *const c_char, arg: *const c_char, mut valist: ...) -> c_int { + #[expect( + clippy::no_effect_underscore_binding, + reason = "suppresses unused warning on *::original" + )] + let _unused = execle::original; + let arena = fspy_nostd_alloc::pooled_bump(); + // SAFETY: valist holds execle's NULL-terminated argument list followed by envp. + let (argv, envp) = unsafe { + let argv = collect_argv(&arena, arg, &mut valist); + (argv, valist.next_arg::<*const *const c_char>()) + }; + handle_exec(&arena, false, path, argv.as_ptr(), envp) +} + +intercept!(execv(64): unsafe extern "C" fn(path: *const c_char, argv: *const *const c_char) -> c_int); +unsafe extern "C" fn execv(path: *const c_char, argv: *const *const c_char) -> c_int { + #[expect( + clippy::no_effect_underscore_binding, + reason = "suppresses unused warning on *::original" + )] + let _unused = execv::original; + // SAFETY: `environ()` returns the valid process environment pointer. + handle_exec(fspy_nostd_alloc::pooled_bump(), false, path, argv, unsafe { environ() }) +} + +intercept!(execvp(64): unsafe extern "C" fn( + prog: *const c_char, + argv: *const *const c_char, +) -> c_int); +unsafe extern "C" fn execvp(prog: *const c_char, argv: *const *const c_char) -> c_int { + #[expect( + clippy::no_effect_underscore_binding, + reason = "suppresses unused warning on *::original" + )] + let _unused = execvp::original; + // SAFETY: `environ()` returns the valid process environment pointer. + handle_exec(fspy_nostd_alloc::pooled_bump(), true, prog, argv, unsafe { environ() }) +} diff --git a/crates/fspy_preload_unix/src/interceptions/spawn/mod.rs b/crates/fspy_preload_macos/src/interceptions/spawn/mod.rs similarity index 100% rename from crates/fspy_preload_unix/src/interceptions/spawn/mod.rs rename to crates/fspy_preload_macos/src/interceptions/spawn/mod.rs diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs new file mode 100644 index 000000000..96fb71b2a --- /dev/null +++ b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs @@ -0,0 +1,104 @@ +use fspy_shared_unix::RawExec; +use libc::{c_char, c_int}; + +use crate::{client::global_client, macros::intercept}; + +type PosixSpawnFn = unsafe extern "C" fn( + pid: *mut libc::pid_t, + prog: *const c_char, + file_actions: *const libc::posix_spawn_file_actions_t, + attrp: *const libc::posix_spawnattr_t, + argv: *const *mut c_char, + envp: *const *mut c_char, +) -> c_int; + +#[expect( + clippy::too_many_arguments, + reason = "mirrors the posix_spawn(3) signature which requires all these parameters" +)] +unsafe fn handle_posix_spawn( + search_path: bool, + original: PosixSpawnFn, + pid: *mut libc::pid_t, + file: *const c_char, + file_actions: *const libc::posix_spawn_file_actions_t, + attrp: *const libc::posix_spawnattr_t, + argv: *const *mut c_char, + envp: *const *mut c_char, +) -> c_int { + let client = global_client() + .expect("posix_spawn(p) unexpectedly called before client initialized in ctor"); + + let arena = fspy_nostd_alloc::pooled_bump(); + // SAFETY: file, argv, and envp are valid pointers forwarded from posix_spawn(p). + let raw_command = match unsafe { + client.handle_exec( + search_path, + RawExec { prog: file, argv: argv.cast(), envp: envp.cast() }, + &arena, + ) + } { + Ok(raw) => raw, + Err(err) => return err.raw_os_error(), + }; + // SAFETY: caller's pointers are forwarded unchanged, and `raw_command`'s + // strings and arrays live in `arena`, which outlives this call. + unsafe { + original( + pid, + raw_command.prog, + file_actions, + attrp, + raw_command.argv.cast(), + raw_command.envp.cast(), + ) + } +} + +intercept!(posix_spawnp(64): PosixSpawnFn); +unsafe extern "C" fn posix_spawnp( + pid: *mut libc::pid_t, + file: *const c_char, + file_actions: *const libc::posix_spawn_file_actions_t, + attrp: *const libc::posix_spawnattr_t, + argv: *const *mut c_char, + envp: *const *mut c_char, +) -> c_int { + // SAFETY: all arguments are valid pointers forwarded from posix_spawnp. + unsafe { + handle_posix_spawn( + true, + posix_spawnp::original(), + pid, + file, + file_actions, + attrp, + argv, + envp, + ) + } +} + +intercept!(posix_spawn(64): PosixSpawnFn); +unsafe extern "C" fn posix_spawn( + pid: *mut libc::pid_t, + file: *const c_char, + file_actions: *const libc::posix_spawn_file_actions_t, + attrp: *const libc::posix_spawnattr_t, + argv: *const *mut c_char, + envp: *const *mut c_char, +) -> c_int { + // SAFETY: all arguments are valid pointers forwarded from posix_spawn. + unsafe { + handle_posix_spawn( + false, + posix_spawn::original(), + pid, + file, + file_actions, + attrp, + argv, + envp, + ) + } +} diff --git a/crates/fspy_preload_macos/src/interceptions/stat.rs b/crates/fspy_preload_macos/src/interceptions/stat.rs new file mode 100644 index 000000000..318e8acc1 --- /dev/null +++ b/crates/fspy_preload_macos/src/interceptions/stat.rs @@ -0,0 +1,36 @@ +use fspy_shared::ipc::AccessMode; +use libc::{c_char, c_int, stat as stat_struct}; + +use crate::{ + client::{handle_open_at, handle_open_path}, + macros::intercept, +}; + +intercept!(stat(64): unsafe extern "C" fn(path: *const c_char, buf: *mut stat_struct) -> c_int); +unsafe extern "C" fn stat(path: *const c_char, buf: *mut stat_struct) -> c_int { + // SAFETY: path is a valid C string pointer provided by the caller. + unsafe { handle_open_path(path, AccessMode::Read) }; + // SAFETY: calling the original libc stat() with forwarded arguments. + unsafe { stat::original()(path, buf) } +} + +intercept!(lstat(64): unsafe extern "C" fn(path: *const c_char, buf: *mut stat_struct) -> c_int); +unsafe extern "C" fn lstat(path: *const c_char, buf: *mut stat_struct) -> c_int { + // SAFETY: path is a valid C string pointer provided by the caller. + unsafe { handle_open_path(path, AccessMode::Read) }; + // SAFETY: calling the original libc lstat() with forwarded arguments. + unsafe { lstat::original()(path, buf) } +} + +intercept!(fstatat(64): unsafe extern "C" fn(dirfd: c_int, pathname: *const c_char, buf: *mut stat_struct, flags: c_int) -> c_int); +unsafe extern "C" fn fstatat( + dirfd: c_int, + pathname: *const c_char, + buf: *mut stat_struct, + flags: c_int, +) -> c_int { + // 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 fstatat() with forwarded arguments. + unsafe { fstatat::original()(dirfd, pathname, buf, flags) } +} diff --git a/crates/fspy_preload_macos/src/lib.rs b/crates/fspy_preload_macos/src/lib.rs new file mode 100644 index 000000000..dbde26fea --- /dev/null +++ b/crates/fspy_preload_macos/src/lib.rs @@ -0,0 +1,7 @@ +#![cfg(target_os = "macos")] + +mod client; +mod interceptions; +mod libc; +mod macros; +mod which; diff --git a/crates/fspy_preload_unix/src/libc.rs b/crates/fspy_preload_macos/src/libc.rs similarity index 84% rename from crates/fspy_preload_unix/src/libc.rs rename to crates/fspy_preload_macos/src/libc.rs index 55f5ac544..cdf1b91d0 100644 --- a/crates/fspy_preload_unix/src/libc.rs +++ b/crates/fspy_preload_macos/src/libc.rs @@ -2,7 +2,6 @@ pub use libc::*; /// The leading fields of `mach_header` from ``, which /// `libc` deprecates in favor of the `mach2` crate. -#[cfg(target_os = "macos")] #[repr(C)] pub struct mach_header { pub magic: u32, @@ -15,7 +14,7 @@ unsafe extern "C" { // On macOS x86_64, directory functions use $INODE64 symbol suffix for 64-bit inode support. // On arm64, 64-bit inodes are the only option so no suffix is needed. // https://github.com/apple-open-source-mirror/Libc/blob/5e566be7a7047360adfb35ffc44c6a019a854bea/include/dirent.h#L198 - #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), link_name = "scandir$INODE64")] + #[cfg_attr(target_arch = "x86_64", link_name = "scandir$INODE64")] pub unsafe fn scandir( dirname: *const c_char, namelist: *mut c_void, @@ -23,7 +22,6 @@ unsafe extern "C" { compar: *const c_void, ) -> c_int; - #[cfg(target_os = "macos")] #[cfg_attr(target_arch = "x86_64", link_name = "scandir_b$INODE64")] pub unsafe fn scandir_b( dirname: *const c_char, @@ -39,15 +37,12 @@ unsafe extern "C" { basep: *mut c_long, ) -> c_int; - #[cfg(target_os = "macos")] #[link_name = "open$NOCANCEL"] pub unsafe fn open_nocancel(path: *const c_char, flags: c_int, ...) -> c_int; - #[cfg(target_os = "macos")] #[link_name = "openat$NOCANCEL"] pub unsafe fn openat_nocancel(dirfd: c_int, path: *const c_char, flags: c_int, ...) -> c_int; - #[cfg(target_os = "macos")] pub unsafe fn __getdirentries64( fd: c_int, buf: *mut u8, @@ -57,12 +52,9 @@ unsafe extern "C" { // Declared here because `libc` deprecates its dyld bindings in favor of // the `mach2` crate. - #[cfg(target_os = "macos")] pub unsafe fn _dyld_get_image_header(image_index: u32) -> *const mach_header; - #[cfg(target_os = "macos")] pub unsafe fn _dyld_get_image_vmaddr_slide(image_index: u32) -> intptr_t; - #[cfg(target_os = "macos")] pub unsafe fn _dyld_get_image_name(image_index: u32) -> *const c_char; } diff --git a/crates/fspy_preload_unix/src/macros/macos.rs b/crates/fspy_preload_macos/src/macros/macos.rs similarity index 100% rename from crates/fspy_preload_unix/src/macros/macos.rs rename to crates/fspy_preload_macos/src/macros/macos.rs diff --git a/crates/fspy_preload_macos/src/macros/mod.rs b/crates/fspy_preload_macos/src/macros/mod.rs new file mode 100644 index 000000000..9bc84109a --- /dev/null +++ b/crates/fspy_preload_macos/src/macros/mod.rs @@ -0,0 +1,7 @@ +mod macos; + +#[expect( + clippy::redundant_pub_crate, + reason = "macro_rules! macros cannot be `pub`, only `pub(crate)` at most" +)] +pub(crate) use macos::*; diff --git a/crates/fspy_preload_macos/src/which.rs b/crates/fspy_preload_macos/src/which.rs new file mode 100644 index 000000000..38c2d8c5f --- /dev/null +++ b/crates/fspy_preload_macos/src/which.rs @@ -0,0 +1,85 @@ +//! No-malloc `PATH` lookup for `execvp`, `execlp`, and `posix_spawnp`. + +use allocator_api2::{alloc::Allocator, vec::Vec}; +use bstr::BStr; +use fspy_nostd::{ + CStr, CWD, Error, Result, Thin, + fs::{AccessFlags, faccessat}, +}; +use fspy_nostd_alloc::fs::resolve_path_at; + +const NAME_MAX: usize = 255; +const DEFAULT_PATH: &[u8] = b"/usr/local/bin:/bin:/usr/bin"; + +fn getenv_path() -> &'static [u8] { + // SAFETY: `c"PATH"` is a static NUL-terminated C string. + let value = unsafe { ::libc::getenv(c"PATH".as_ptr()) }; + if value.is_null() { + DEFAULT_PATH + } else { + // SAFETY: `getenv` returns a pointer to a NUL-terminated env value. + unsafe { CStr::::from_ptr(value.cast()) }.count().as_units() + } +} + +/// Resolves `file` against `PATH` using `allocator` (no libc malloc). +/// +/// Calls `on_path_read` with the absolute path of every candidate checked. +/// +/// # Errors +/// +/// Returns `ENOENT`, `EACCES`, `ENOTDIR`, or `ENAMETOOLONG`, matching POSIX +/// `execvp` / musl `execvp`. +pub fn resolve_in_path( + file: &[u8], + allocator: A, + mut on_path_read: impl FnMut(&BStr), +) -> Result> { + if file.is_empty() { + return Err(Error::NOENT); + } + if file.contains(&b'/') { + let mut out = Vec::with_capacity_in(file.len(), allocator); + out.extend_from_slice(file); + return Ok(out); + } + if file.len() > NAME_MAX { + return Err(Error::NAMETOOLONG); + } + + let path_env = getenv_path(); + let mut seen_eacces = false; + let mut last_err = Error::NOENT; + let mut candidate = Vec::new_in(allocator.clone()); + + for dir in path_env.split(|&ch| ch == b':') { + candidate.clear(); + candidate.extend_from_slice(dir); + if !dir.is_empty() { + candidate.push(b'/'); + } + candidate.extend_from_slice(file); + candidate.push(0); + + let c_candidate = CStr::from_units_with_nul(&candidate).ok_or(Error::NOENT)?; + if let Ok(Some(abs)) = resolve_path_at(&allocator, Some(CWD), c_candidate.as_thin()) { + on_path_read(BStr::new(abs.as_units())); + } + + match faccessat(CWD, c_candidate.as_thin(), AccessFlags::X_OK) { + Ok(()) => { + candidate.pop(); // strip trailing NUL + return Ok(candidate); + } + Err(err @ (Error::ACCES | Error::NOENT | Error::NOTDIR)) => { + if err == Error::ACCES { + seen_eacces = true; + } + last_err = err; + } + Err(other) => return Err(other), + } + } + + Err(if seen_eacces { Error::ACCES } else { last_err }) +} diff --git a/crates/fspy_preload_unix/.clippy.toml b/crates/fspy_preload_unix/.clippy.toml deleted file mode 120000 index c7929b369..000000000 --- a/crates/fspy_preload_unix/.clippy.toml +++ /dev/null @@ -1 +0,0 @@ -../../.non-vite.clippy.toml \ No newline at end of file diff --git a/crates/fspy_preload_unix/README.md b/crates/fspy_preload_unix/README.md deleted file mode 100644 index d0e9644c8..000000000 --- a/crates/fspy_preload_unix/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## fspy_preload_unix - -The shared library injected by `DYLD_INSERT_LIBRARIES` on macOS and `LD_PRELOAD` on Linux to intercept file system calls. - -This crates only contains code the shared library itself. The injection process is done in `fspy` crate. diff --git a/crates/fspy_preload_unix/src/client.rs b/crates/fspy_preload_unix/src/client.rs deleted file mode 100644 index 9f250d8c3..000000000 --- a/crates/fspy_preload_unix/src/client.rs +++ /dev/null @@ -1,44 +0,0 @@ -use std::sync::OnceLock; - -use convert::{ToAbsolutePath, ToAccessMode}; -pub use fspy_client_unix::{Client, convert, raw_exec}; - -static CLIENT: OnceLock> = OnceLock::new(); - -pub fn global_client() -> Option<&'static Client<'static>> { - CLIENT.get() -} - -// The handler needs no re-entry guard: on Linux everything it calls is a -// raw syscall — nothing binds through the PLT, where LD_PRELOAD would -// resolve to our own interposers — and on macOS dyld never applies -// `__interpose` tuples to the interposing image's own bindings, the same -// exemption every `original()` forward relies on. Keep the handler free of -// bindable libc calls on Linux: a call that binds to an interposer here -// recurses until the traced process overflows its stack. -pub unsafe fn handle_open(path: impl ToAbsolutePath, mode: impl ToAccessMode) { - if let Some(client) = global_client() { - let allocator = fspy_nostd_alloc::pooled_bump(); - // SAFETY: path and mode contain valid pointers/values forwarded - // from the interposed function's caller. - unsafe { client.try_handle_open(path, mode, allocator) }.unwrap(); - } -} - -#[cfg(not(test))] -#[ctor::ctor(unsafe)] -fn init_client() { - // SAFETY: the ctor only reads the process environment while constructing - // the client and does not retain borrowed environment views. - let current = unsafe { fspy_nostd::env::current() }.unwrap(); - // The attach's storage: one page-backed bump housed in a static, so - // its borrow is 'static by construction and the client comes out as - // Client<'static> with no lifetime promotion anywhere. The bump is not - // Sync, so this handle cannot be stored globally by any safe code, and - // the Send/Sync assertion on Client proves the client keeps no handle. - static BUMP: static_cell::StaticCell = - static_cell::StaticCell::new(); - let bump: &'static fspy_nostd_alloc::PageBump = BUMP.init(fspy_nostd_alloc::page_bump()); - let client = Client::from_env(current.envs(), bump); - CLIENT.set(client).unwrap(); -} diff --git a/crates/fspy_preload_unix/src/interceptions/dirent.rs b/crates/fspy_preload_unix/src/interceptions/dirent.rs deleted file mode 100644 index 048f8f447..000000000 --- a/crates/fspy_preload_unix/src/interceptions/dirent.rs +++ /dev/null @@ -1,88 +0,0 @@ -use fspy_nostd::BorrowedFd; -use fspy_shared::ipc::AccessMode; -use libc::{DIR, c_char, c_int, c_long, c_void}; - -use crate::{client::handle_open, macros::intercept}; - -intercept!(scandir(64): unsafe extern "C" fn ( - dirname: *const c_char, - namelist: *mut c_void, - select: *const c_void, - compar: *const c_void, -) -> c_int); -unsafe extern "C" fn scandir( - dirname: *const c_char, - namelist: *mut c_void, - select: *const c_void, - compar: *const c_void, -) -> c_int { - // SAFETY: dirname is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(dirname.cast()), AccessMode::ReadDir) } - // SAFETY: calling the original libc scandir() with the same arguments forwarded from the interposed function - unsafe { scandir::original()(dirname, namelist, select, compar) } -} - -#[cfg(target_os = "macos")] -mod macos_only { - use super::{AccessMode, BorrowedFd, c_char, c_int, c_void, handle_open, intercept}; - - intercept!(scandir_b: unsafe extern "C" fn ( - dirname: *const c_char, - namelist: *mut c_void, - select: *const c_void, - compar: *const c_void, - ) -> c_int); - unsafe extern "C" fn scandir_b( - dirname: *const c_char, - namelist: *mut c_void, - select: *const c_void, - compar: *const c_void, - ) -> c_int { - // SAFETY: dirname is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(dirname.cast()), AccessMode::ReadDir) }; - // SAFETY: calling the original libc scandir_b() with the same arguments forwarded from the interposed function - unsafe { scandir_b::original()(dirname, namelist, select, compar) } - } - - intercept!(__getdirentries64: unsafe extern "C" fn(c_int, *mut u8, usize, *mut i64) -> isize); - unsafe extern "C" fn __getdirentries64( - fd: c_int, - buf: *mut u8, - buf_len: usize, - basep: *mut i64, - ) -> isize { - // SAFETY: fd is -1 or a valid file descriptor provided by the caller of __getdirentries64 - unsafe { handle_open(BorrowedFd::try_borrow_raw(fd), AccessMode::ReadDir) }; - // SAFETY: calling the original libc __getdirentries64() with the same arguments forwarded from the interposed function - unsafe { __getdirentries64::original()(fd, buf, buf_len, basep) } - } -} - -intercept!(getdirentries(64): unsafe extern "C" fn (fd: c_int, buf: *mut c_char, nbytes: c_int, basep: *mut c_long) -> c_int); -unsafe extern "C" fn getdirentries( - fd: c_int, - buf: *mut c_char, - nbytes: c_int, - basep: *mut c_long, -) -> c_int { - // SAFETY: fd is -1 or a valid file descriptor provided by the caller of the interposed function - unsafe { handle_open(BorrowedFd::try_borrow_raw(fd), AccessMode::ReadDir) }; - // SAFETY: calling the original libc getdirentries() with the same arguments forwarded from the interposed function - unsafe { getdirentries::original()(fd, buf, nbytes, basep) } -} - -intercept!(fdopendir(64): unsafe extern "C" fn (fd: c_int) -> *mut DIR); -unsafe extern "C" fn fdopendir(fd: c_int) -> *mut DIR { - // SAFETY: fd is -1 or a valid file descriptor provided by the caller of the interposed function - unsafe { handle_open(BorrowedFd::try_borrow_raw(fd), AccessMode::ReadDir) }; - // SAFETY: calling the original libc fdopendir() with the same arguments forwarded from the interposed function - unsafe { fdopendir::original()(fd) } -} - -intercept!(opendir(64): unsafe extern "C" fn (*const c_char) -> *mut DIR); -unsafe extern "C" fn opendir(dir_name: *const c_char) -> *mut DIR { - // SAFETY: dir_name is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(dir_name.cast()), AccessMode::ReadDir) }; - // SAFETY: calling the original libc opendir() with the same arguments forwarded from the interposed function - unsafe { opendir::original()(dir_name) } -} diff --git a/crates/fspy_preload_unix/src/interceptions/linux_syscall.rs b/crates/fspy_preload_unix/src/interceptions/linux_syscall.rs deleted file mode 100644 index f351ca1fa..000000000 --- a/crates/fspy_preload_unix/src/interceptions/linux_syscall.rs +++ /dev/null @@ -1,95 +0,0 @@ -use fspy_nostd::BorrowedFd; -use fspy_shared::ipc::AccessMode; -use libc::{c_char, c_int, c_long}; - -use crate::{ - client::{convert::PathAt, handle_open}, - macros::intercept, -}; - -intercept!(syscall(64): unsafe extern "C" fn(c_long, args: ...) -> c_long); -unsafe extern "C" fn syscall(syscall_no: c_long, mut args: ...) -> c_long { - // https://github.com/bminor/glibc/blob/efc8642051e6c4fe5165e8986c1338ba2c180de6/sysdeps/unix/sysv/linux/syscall.c#L23 - // SAFETY: extracting variadic arguments matching the syscall ABI; the caller passes at least 6 c_long arguments - let a0 = unsafe { args.next_arg::() }; - // SAFETY: extracting variadic arguments matching the syscall ABI - let a1 = unsafe { args.next_arg::() }; - // SAFETY: extracting variadic arguments matching the syscall ABI - let a2 = unsafe { args.next_arg::() }; - // SAFETY: extracting variadic arguments matching the syscall ABI - let a3 = unsafe { args.next_arg::() }; - // SAFETY: extracting variadic arguments matching the syscall ABI - let a4 = unsafe { args.next_arg::() }; - // SAFETY: extracting variadic arguments matching the syscall ABI - let a5 = unsafe { args.next_arg::() }; - - if syscall_no == libc::SYS_statx { - // C-style conversions are expected for the variadic syscall arguments. - #[expect( - clippy::cast_possible_truncation, - reason = "C-style conversion from c_long syscall arguments to c_int" - )] - let dirfd = a0 as c_int; - let pathname = a1 as *const c_char; - #[expect( - clippy::cast_possible_truncation, - reason = "C-style conversion from c_long syscall arguments to c_int" - )] - let flags = a2 as c_int; - if pathname.is_null() { - if flags & libc::AT_EMPTY_PATH != 0 { - // SAFETY: dirfd is -1 or a valid file descriptor provided by the statx syscall caller. - unsafe { handle_open(BorrowedFd::try_borrow_raw(dirfd), AccessMode::Read) }; - } - } else { - // SAFETY: dirfd is -1 or a valid file descriptor, and pathname is a non-null C string pointer, provided by the statx syscall caller. - unsafe { - handle_open(PathAt::borrow_raw(dirfd, pathname), AccessMode::Read); - }; - } - } - // Do not resolve libc's syscall through LazyLock: concurrent first calls - // wait through futex, which calls this interposer again before the lock - // is initialized. Forward directly to the kernel instead. - #[expect( - clippy::cast_sign_loss, - clippy::cast_possible_truncation, - reason = "c_long and usize have the same width on supported Linux targets; preserve their bit patterns" - )] - // SAFETY: forward the syscall number and arguments supplied by the caller. - let result = unsafe { - syscalls::raw::syscall6( - syscall_no as usize, - a0 as usize, - a1 as usize, - a2 as usize, - a3 as usize, - a4 as usize, - a5 as usize, - ) - }; - match syscalls::Errno::from_ret(result) { - #[expect(clippy::cast_possible_wrap, reason = "preserve the syscall result's bit pattern")] - Ok(value) => value as c_long, - Err(errno) => { - // SAFETY: __errno_location returns this thread's errno storage. - unsafe { *libc::__errno_location() = errno.into_raw() }; - -1 - } - } -} - -#[cfg(test)] -mod tests { - use super::syscall; - - #[test] - fn error_sets_errno() { - // SAFETY: close rejects an invalid descriptor without accessing memory. - unsafe { - *libc::__errno_location() = 0; - assert_eq!(syscall(libc::SYS_close, -1_i64, 0_i64, 0_i64, 0_i64, 0_i64, 0_i64), -1); - assert_eq!(*libc::__errno_location(), libc::EBADF); - } - } -} diff --git a/crates/fspy_preload_unix/src/interceptions/namespace.rs b/crates/fspy_preload_unix/src/interceptions/namespace.rs deleted file mode 100644 index 7f33c7404..000000000 --- a/crates/fspy_preload_unix/src/interceptions/namespace.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! Calls that make an entry at a path without opening it: mkdir, symlink, -//! and rename and hard link, which put an existing file or folder at a new -//! path. The path is recorded before the call, so a failed call is recorded -//! too: as a mkdir for a mkdir, whose folder may be there already; as a -//! rename target for a rename, which may move a whole folder; and as a write -//! for a symlink, and for a hard link, always to a file. The source of a -//! rename needs no record, and neither does the target of a symlink, which -//! is stored as text, not accessed. - -use fspy_shared::ipc::AccessMode; -use libc::{c_char, c_int, mode_t}; - -use crate::{ - client::{convert::PathAt, handle_open}, - macros::intercept, -}; - -intercept!(mkdir: unsafe extern "C" fn(path: *const c_char, mode: mode_t) -> c_int); -unsafe extern "C" fn mkdir(path: *const c_char, mode: mode_t) -> c_int { - // SAFETY: path is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(path.cast()), AccessMode::Mkdir) }; - // SAFETY: calling the original libc mkdir() with the same arguments forwarded from the interposed function - unsafe { mkdir::original()(path, mode) } -} - -intercept!(mkdirat: unsafe extern "C" fn(dirfd: c_int, path: *const c_char, mode: mode_t) -> c_int); -unsafe extern "C" fn mkdirat(dirfd: c_int, path: *const c_char, mode: mode_t) -> c_int { - // SAFETY: dirfd is -1 or a valid file descriptor, and path is a valid C string, provided by the caller of the interposed function - unsafe { handle_open(PathAt::borrow_raw(dirfd, path), AccessMode::Mkdir) }; - // SAFETY: calling the original libc mkdirat() with the same arguments forwarded from the interposed function - unsafe { mkdirat::original()(dirfd, path, mode) } -} - -intercept!(rename: unsafe extern "C" fn(old: *const c_char, new: *const c_char) -> c_int); -unsafe extern "C" fn rename(old: *const c_char, new: *const c_char) -> c_int { - // SAFETY: new is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(new.cast()), AccessMode::RenameTarget) }; - // SAFETY: calling the original libc rename() with the same arguments forwarded from the interposed function - unsafe { rename::original()(old, new) } -} - -intercept!(renameat: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char) -> c_int); -unsafe extern "C" fn renameat( - olddirfd: c_int, - old: *const c_char, - newdirfd: c_int, - new: *const c_char, -) -> c_int { - // SAFETY: newdirfd is -1 or a valid file descriptor, and new is a valid C string, provided by the caller of the interposed function - unsafe { handle_open(PathAt::borrow_raw(newdirfd, new), AccessMode::RenameTarget) }; - // SAFETY: calling the original libc renameat() with the same arguments forwarded from the interposed function - unsafe { renameat::original()(olddirfd, old, newdirfd, new) } -} - -#[cfg(target_os = "linux")] -intercept!(renameat2: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char, flags: libc::c_uint) -> c_int); -/// With `RENAME_EXCHANGE` both paths change; only the destination is -/// recorded, as for a plain rename. -#[cfg(target_os = "linux")] -unsafe extern "C" fn renameat2( - olddirfd: c_int, - old: *const c_char, - newdirfd: c_int, - new: *const c_char, - flags: libc::c_uint, -) -> c_int { - let Some(original) = renameat2::try_original() else { - // glibc added renameat2 in 2.28. Callers that look it up at run time - // treat ENOSYS as unsupported, as when the kernel lacks it. - // SAFETY: __errno_location returns the calling thread's errno storage on Linux. - unsafe { *libc::__errno_location() = libc::ENOSYS }; - return -1; - }; - // SAFETY: newdirfd is -1 or a valid file descriptor, and new is a valid C string, provided by the caller of the interposed function - unsafe { handle_open(PathAt::borrow_raw(newdirfd, new), AccessMode::RenameTarget) }; - // SAFETY: calling the original libc renameat2() with the same arguments forwarded from the interposed function - unsafe { original(olddirfd, old, newdirfd, new, flags) } -} - -#[cfg(target_os = "macos")] -intercept!(renamex_np: unsafe extern "C" fn(old: *const c_char, new: *const c_char, flags: libc::c_uint) -> c_int); -#[cfg(target_os = "macos")] -unsafe extern "C" fn renamex_np( - old: *const c_char, - new: *const c_char, - flags: libc::c_uint, -) -> c_int { - // SAFETY: new is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(new.cast()), AccessMode::RenameTarget) }; - // SAFETY: calling the original libc renamex_np() with the same arguments forwarded from the interposed function - unsafe { renamex_np::original()(old, new, flags) } -} - -#[cfg(target_os = "macos")] -intercept!(renameatx_np: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char, flags: libc::c_uint) -> c_int); -#[cfg(target_os = "macos")] -unsafe extern "C" fn renameatx_np( - olddirfd: c_int, - old: *const c_char, - newdirfd: c_int, - new: *const c_char, - flags: libc::c_uint, -) -> c_int { - // SAFETY: newdirfd is -1 or a valid file descriptor, and new is a valid C string, provided by the caller of the interposed function - unsafe { handle_open(PathAt::borrow_raw(newdirfd, new), AccessMode::RenameTarget) }; - // SAFETY: calling the original libc renameatx_np() with the same arguments forwarded from the interposed function - unsafe { renameatx_np::original()(olddirfd, old, newdirfd, new, flags) } -} - -intercept!(link: unsafe extern "C" fn(old: *const c_char, new: *const c_char) -> c_int); -unsafe extern "C" fn link(old: *const c_char, new: *const c_char) -> c_int { - // SAFETY: new is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(new.cast()), AccessMode::Write) }; - // SAFETY: calling the original libc link() with the same arguments forwarded from the interposed function - unsafe { link::original()(old, new) } -} - -intercept!(linkat: unsafe extern "C" fn(olddirfd: c_int, old: *const c_char, newdirfd: c_int, new: *const c_char, flags: c_int) -> c_int); -unsafe extern "C" fn linkat( - olddirfd: c_int, - old: *const c_char, - newdirfd: c_int, - new: *const c_char, - flags: c_int, -) -> c_int { - // SAFETY: newdirfd is -1 or a valid file descriptor, and new is a valid C string, provided by the caller of the interposed function - unsafe { handle_open(PathAt::borrow_raw(newdirfd, new), AccessMode::Write) }; - // SAFETY: calling the original libc linkat() with the same arguments forwarded from the interposed function - unsafe { linkat::original()(olddirfd, old, newdirfd, new, flags) } -} - -intercept!(symlink: unsafe extern "C" fn(target: *const c_char, link: *const c_char) -> c_int); -unsafe extern "C" fn symlink(target: *const c_char, link: *const c_char) -> c_int { - // SAFETY: link is a valid C string pointer provided by the caller of the interposed function - unsafe { handle_open(fspy_nostd::CStr::from_ptr(link.cast()), AccessMode::Write) }; - // SAFETY: calling the original libc symlink() with the same arguments forwarded from the interposed function - unsafe { symlink::original()(target, link) } -} - -intercept!(symlinkat: unsafe extern "C" fn(target: *const c_char, newdirfd: c_int, link: *const c_char) -> c_int); -unsafe extern "C" fn symlinkat( - target: *const c_char, - newdirfd: c_int, - link: *const c_char, -) -> c_int { - // SAFETY: newdirfd is -1 or a valid file descriptor, and link is a valid C string, provided by the caller of the interposed function - unsafe { handle_open(PathAt::borrow_raw(newdirfd, link), AccessMode::Write) }; - // SAFETY: calling the original libc symlinkat() with the same arguments forwarded from the interposed function - unsafe { symlinkat::original()(target, newdirfd, link) } -} diff --git a/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs b/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs deleted file mode 100644 index 745577c1c..000000000 --- a/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs +++ /dev/null @@ -1,334 +0,0 @@ -use std::{ffi::VaList, ptr::null}; - -use allocator_api2::{alloc::Allocator, vec::Vec}; -use fspy_shared_unix::exec::ExecResolveConfig; -use libc::{c_char, c_int}; - -use crate::{ - client::{global_client, raw_exec::RawExec}, - macros::intercept, -}; - -#[cfg(target_os = "macos")] -pub unsafe fn environ() -> *const *const c_char { - // SAFETY: _NSGetEnviron() always returns a valid pointer to the process's environ on macOS - unsafe { *(libc::_NSGetEnviron().cast()) } -} - -#[cfg(target_os = "linux")] -pub unsafe fn environ() -> *const *const c_char { - unsafe extern "C" { - static environ: *const *const c_char; - } - // SAFETY: environ is a valid global pointer to the process environment, as defined by POSIX - unsafe { environ } -} - -/// Collects `arg` and the variadic arguments after it into the -/// NULL-terminated argv array that `execl`, `execlp` and `execle` take as a -/// list. The array lives in `allocator`, not libc's heap: exec may run in -/// the child of `fork()`, where malloc's lock may be held by a thread that -/// no longer exists. `va` is left past the terminator, where `execle` finds -/// `envp`. -/// -/// # Safety -/// -/// Unless `arg` is NULL, `va` must hold `*const c_char` arguments up to a -/// NULL pointer. -unsafe fn collect_argv( - allocator: A, - mut arg: *const c_char, - va: &mut VaList<'_>, -) -> Vec<*const c_char, A> { - let mut argv = Vec::new_in(allocator); - while !arg.is_null() { - argv.push(arg); - // SAFETY: the caller guarantees the arguments continue up to a NULL pointer. - arg = unsafe { va.next_arg() }; - } - argv.push(null()); - argv -} - -/// Resolves, reports, and performs a tracked exec. -/// -/// `untracked` performs the interposed call as the caller made it, through -/// that function's own original: `execvp` keeps its `PATH` search, -/// `execveat` its `dirfd` and flags, `fexecve` its descriptor. It runs when -/// the seccomp filter cannot be installed, so the process still execs, -/// untracked. -fn handle_exec( - allocator: impl Allocator, - config: ExecResolveConfig, - prog: *const libc::c_char, - argv: *const *const libc::c_char, - envp: *const *const libc::c_char, - untracked: impl FnOnce() -> libc::c_int, -) -> libc::c_int { - let client = - global_client().expect("exec unexpectedly called before client initialized in ctor"); - // SAFETY: prog, argv, and envp are valid pointers to C strings/arrays forwarded from the interposed exec function - let handled = unsafe { client.handle_exec(config, RawExec { prog, argv, envp }, &allocator) }; - let (raw_command, pre_exec) = match handled { - Ok(handled) => handled, - Err(errno) => { - errno.set(); - return -1; - } - }; - if let Some(pre_exec) = pre_exec - && pre_exec.run().is_err() - { - // The seccomp filter cannot be installed, for example in a sandbox - // that denies the `seccomp` syscall. Mark the run's trace incomplete - // so it is not cached, then run the interposed call untracked. Its - // envp still carries LD_PRELOAD/FSPY_PAYLOAD, so each generation - // tries tracking again on its own. - client.report_loss(); - return untracked(); - } - // SAFETY: raw_command's strings and arrays live in `allocator`, which outlives the call - unsafe { execve::original()(raw_command.prog, raw_command.argv, raw_command.envp) } -} - -intercept!(execve(64): unsafe extern "C" fn( - prog: *const libc::c_char, - argv: *const *const libc::c_char, - envp: *const *const libc::c_char, -) -> libc::c_int); -unsafe extern "C" fn execve( - prog: *const libc::c_char, - argv: *const *const libc::c_char, - envp: *const *const libc::c_char, -) -> libc::c_int { - handle_exec( - fspy_nostd_alloc::pooled_bump(), - ExecResolveConfig::search_path_disabled(), - prog, - argv, - envp, - // SAFETY: the interposed execve's own arguments. - || unsafe { execve::original()(prog, argv, envp) }, - ) -} - -intercept!(execl(64): unsafe extern "C" fn(path: *const c_char, arg0: *const c_char, ...) -> c_int); -unsafe extern "C" fn execl(path: *const c_char, arg: *const c_char, mut valist: ...) -> c_int { - #[expect( - clippy::no_effect_underscore_binding, - reason = "suppresses unused warning on *::original" - )] - let _unused = execl::original; - let arena = fspy_nostd_alloc::pooled_bump(); - // SAFETY: valist holds execl's NULL-terminated argument list after arg, - // and environ() returns the valid process environment pointer - let (argv, envp) = unsafe { (collect_argv(&arena, arg, &mut valist), environ()) }; - handle_exec( - &arena, - ExecResolveConfig::search_path_disabled(), - path, - argv.as_ptr(), - envp, - // A variadic original cannot be forwarded a collected argv; - // execl is execv over the same argv. - // SAFETY: argv is the NULL-terminated argument list execl was given. - || unsafe { execv::original()(path, argv.as_ptr()) }, - ) -} - -intercept!(execlp(64): unsafe extern "C" fn(path: *const c_char, arg0: *const c_char, ...) -> c_int); -unsafe extern "C" fn execlp(path: *const c_char, arg: *const c_char, mut valist: ...) -> c_int { - #[expect( - clippy::no_effect_underscore_binding, - reason = "suppresses unused warning on *::original" - )] - let _unused = execlp::original; - let arena = fspy_nostd_alloc::pooled_bump(); - // SAFETY: valist holds execlp's NULL-terminated argument list after arg, - // and environ() returns the valid process environment pointer - let (argv, envp) = unsafe { (collect_argv(&arena, arg, &mut valist), environ()) }; - handle_exec( - &arena, - ExecResolveConfig::search_path_enabled(None), - path, - argv.as_ptr(), - envp, - // execlp is execvp over the same argv, PATH search included. - // SAFETY: argv is the NULL-terminated argument list execlp was given. - || unsafe { execvp::original()(path, argv.as_ptr()) }, - ) -} - -intercept!(execle(64): unsafe extern "C" fn(path: *const c_char, arg0: *const c_char, ...) -> c_int); -unsafe extern "C" fn execle(path: *const c_char, arg: *const c_char, mut valist: ...) -> c_int { - #[expect( - clippy::no_effect_underscore_binding, - reason = "suppresses unused warning on *::original" - )] - let _unused = execle::original; - let arena = fspy_nostd_alloc::pooled_bump(); - // SAFETY: valist holds execle's NULL-terminated argument list after arg, - // followed by envp - let (argv, envp) = unsafe { - let argv = collect_argv(&arena, arg, &mut valist); - (argv, valist.next_arg::<*const *const c_char>()) - }; - handle_exec( - &arena, - ExecResolveConfig::search_path_disabled(), - path, - argv.as_ptr(), - envp, - // execle is execve over the same argv and envp. - // SAFETY: argv is the NULL-terminated argument list execle was given, - // and envp is the environment it was given after the list. - || unsafe { execve::original()(path, argv.as_ptr(), envp) }, - ) -} - -intercept!(execv(64): unsafe extern "C" fn(path: *const c_char, argv: *const *const c_char) -> c_int); -unsafe extern "C" fn execv(path: *const c_char, argv: *const *const c_char) -> c_int { - // SAFETY: path, argv are valid pointers forwarded from the interposed function; environ() returns the process environment - unsafe { - handle_exec( - fspy_nostd_alloc::pooled_bump(), - ExecResolveConfig::search_path_disabled(), - path, - argv, - environ(), - || execv::original()(path, argv), - ) - } -} - -intercept!(execvp(64): unsafe extern "C" fn( - prog: *const libc::c_char, - argv: *const *const libc::c_char, -) -> c_int); -unsafe extern "C" fn execvp(prog: *const c_char, argv: *const *const c_char) -> c_int { - handle_exec( - fspy_nostd_alloc::pooled_bump(), - ExecResolveConfig::search_path_enabled(None), - prog, - argv, - // SAFETY: environ() returns the valid process environment pointer - unsafe { environ() }, - // SAFETY: the interposed execvp's own arguments. - || unsafe { execvp::original()(prog, argv) }, - ) -} - -#[cfg(target_os = "linux")] -mod linux_only { - #[expect( - clippy::useless_attribute, - reason = "allow_attributes on use items is flagged as useless but needed here" - )] - #[expect( - clippy::allow_attributes, - reason = "using allow because wildcard_imports may or may not fire depending on build target" - )] - #[allow( - clippy::wildcard_imports, - reason = "macro-generated code requires types from parent scope" - )] - use super::*; - use crate::client::convert::{PROC_FD_PATH_CAPACITY, PathAt, ToAbsolutePath, proc_fd_path}; - - intercept!(execvpe(64): unsafe extern "C" fn( - prog: *const libc::c_char, - argv: *const *const libc::c_char, - envp: *const *const libc::c_char, - ) -> libc::c_int); - unsafe extern "C" fn execvpe( - file: *const c_char, - argv: *const *const libc::c_char, - envp: *const *const libc::c_char, - ) -> c_int { - handle_exec( - fspy_nostd_alloc::pooled_bump(), - ExecResolveConfig::search_path_enabled(None), - file, - argv, - envp, - // SAFETY: the interposed execvpe's own arguments. - || unsafe { execvpe::original()(file, argv, envp) }, - ) - } - intercept!(execveat(64): unsafe extern "C" fn( - dirfd: c_int, - prog: *const libc::c_char, - argv: *const *mut libc::c_char, - envp: *const *mut libc::c_char, - flags: c_int - ) -> libc::c_int); - unsafe extern "C" fn execveat( - dirfd: c_int, - pathname: *const libc::c_char, - argv: *const *mut libc::c_char, - envp: *const *mut libc::c_char, - flags: c_int, // TODO: conform to semantics of flags - ) -> libc::c_int { - // Without `AT_EMPTY_PATH`, an empty pathname fails with `ENOENT` - // before the kernel looks anything up, while resolving it against - // `dirfd` would run whatever `dirfd` refers to. Let the real call - // fail. - // SAFETY: pathname is a valid C string from the interposed execveat call. - if unsafe { *pathname } == 0 && flags & libc::AT_EMPTY_PATH == 0 { - // SAFETY: forwarding the original arguments to the real execveat syscall - return unsafe { execveat::original()(dirfd, pathname, argv, envp, flags) }; - } - let arena = fspy_nostd_alloc::pooled_bump(); - - // SAFETY: dirfd is -1 or a valid file descriptor, and pathname is a valid C string, from the interposed execveat call. - let path = unsafe { PathAt::borrow_raw(dirfd, pathname) }; - let abs_path = match path.to_absolute_path(&arena) { - Ok(None) => { - // SAFETY: forwarding the original arguments to the real execveat syscall - return unsafe { execveat::original()(dirfd, pathname, argv, envp, flags) }; - } - Ok(Some(path)) => path, - Err(errno) => { - errno.set(); - return -1; - } - }; - - // `abs_path` is a C string, so the exec receives a terminated - // pointer by construction rather than by convention. - handle_exec( - &arena, - ExecResolveConfig::search_path_disabled(), - abs_path.as_ptr().cast(), - argv.cast(), - envp.cast(), - // SAFETY: the interposed execveat's own arguments. - || unsafe { execveat::original()(dirfd, pathname, argv, envp, flags) }, - ) - } - - intercept!(fexecve(64): unsafe extern "C" fn( - fd: c_int, - argv: *const *const libc::c_char, - envp: *const *const libc::c_char, - ) -> libc::c_int); - unsafe extern "C" fn fexecve( - fd: c_int, - argv: *const *const libc::c_char, - envp: *const *const libc::c_char, - ) -> libc::c_int { - let mut prog = [0; PROC_FD_PATH_CAPACITY]; - let prog = proc_fd_path(fd, &mut prog); - handle_exec( - fspy_nostd_alloc::pooled_bump(), - ExecResolveConfig::search_path_disabled(), - prog.as_ptr().cast(), - argv, - envp, - // The descriptor itself, not its /proc path: a sandbox without - // /proc can still fexecve. - // SAFETY: the interposed fexecve's own arguments. - || unsafe { fexecve::original()(fd, argv, envp) }, - ) - } -} diff --git a/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs deleted file mode 100644 index b069df335..000000000 --- a/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs +++ /dev/null @@ -1,143 +0,0 @@ -use std::thread; - -use fspy_shared_unix::exec::ExecResolveConfig; -use libc::{c_char, c_int}; - -use crate::{ - client::{global_client, raw_exec::RawExec}, - macros::intercept, -}; - -type PosixSpawnFn = unsafe extern "C" fn( - pid: *mut libc::pid_t, - prog: *const c_char, - file_actions: *const libc::posix_spawn_file_actions_t, - attrp: *const libc::posix_spawnattr_t, - argv: *const *mut c_char, - envp: *const *mut c_char, -) -> libc::c_int; - -#[expect( - clippy::too_many_arguments, - reason = "mirrors the posix_spawn(3) signature which requires all these parameters" -)] -unsafe fn handle_posix_spawn( - config: ExecResolveConfig, - original: PosixSpawnFn, - pid: *mut libc::pid_t, - file: *const c_char, - file_actions: *const libc::posix_spawn_file_actions_t, - attrp: *const libc::posix_spawnattr_t, - argv: *const *mut c_char, - envp: *const *mut c_char, -) -> c_int { - struct AssertSend(T); - #[expect( - clippy::non_send_fields_in_send_ty, - reason = "the closure captures raw pointers that are valid for the duration of the thread::scope call, so sending them to the scoped thread is safe" - )] - // SAFETY: the raw pointers captured inside T are valid for the duration of the thread::scope call, so sending them to the scoped thread is safe - unsafe impl Send for AssertSend {} - - let client = global_client() - .expect("posix_spawn(p) unexpectedly called before client initialized in ctor"); - - let arena = fspy_nostd_alloc::pooled_bump(); - // SAFETY: file, argv, and envp are valid pointers forwarded from the interposed posix_spawn(p) function - let handled = unsafe { - client.handle_exec( - config, - RawExec { prog: file, argv: argv.cast(), envp: envp.cast() }, - &arena, - ) - }; - let (raw_command, pre_exec) = match handled { - Ok(handled) => handled, - Err(errno) => return errno as _, - }; - let call_original = move || { - // SAFETY: the caller's pointers are forwarded unchanged, and raw_command's - // strings and arrays live in `arena`, which outlives the call - unsafe { - original( - pid, - raw_command.prog, - file_actions, - attrp, - raw_command.argv.cast(), - raw_command.envp.cast(), - ) - } - }; - let Some(pre_exec) = pre_exec else { - return call_original(); - }; - thread::scope(move |s| { - let call_original = AssertSend(call_original); - s.spawn(move || { - let call_original = call_original; - pre_exec.run()?; - - nix::Result::Ok((call_original.0)()) - }) - .join() - .unwrap() - }) - .unwrap_or_else(|_| { - // The seccomp filter cannot be installed, so the spawn never - // happened. Mark the run's trace incomplete so it is not cached, - // then spawn untracked with the caller's own arguments. - client.report_loss(); - // SAFETY: all arguments are the interposed posix_spawn(p) function's - // own valid arguments. - unsafe { original(pid, file, file_actions, attrp, argv, envp) } - }) -} - -intercept!(posix_spawnp(64): PosixSpawnFn); -unsafe extern "C" fn posix_spawnp( - pid: *mut libc::pid_t, - file: *const c_char, - file_actions: *const libc::posix_spawn_file_actions_t, - attrp: *const libc::posix_spawnattr_t, - argv: *const *mut c_char, - envp: *const *mut c_char, -) -> libc::c_int { - // SAFETY: all arguments are valid pointers forwarded from the interposed posix_spawnp function - unsafe { - handle_posix_spawn( - ExecResolveConfig::search_path_enabled(None), - posix_spawnp::original(), - pid, - file, - file_actions, - attrp, - argv, - envp, - ) - } -} - -intercept!(posix_spawn(64): PosixSpawnFn); -unsafe extern "C" fn posix_spawn( - pid: *mut libc::pid_t, - file: *const c_char, - file_actions: *const libc::posix_spawn_file_actions_t, - attrp: *const libc::posix_spawnattr_t, - argv: *const *mut c_char, - envp: *const *mut c_char, -) -> libc::c_int { - // SAFETY: all arguments are valid pointers forwarded from the interposed posix_spawn function - unsafe { - handle_posix_spawn( - ExecResolveConfig::search_path_disabled(), - posix_spawn::original(), - pid, - file, - file_actions, - attrp, - argv, - envp, - ) - } -} diff --git a/crates/fspy_preload_unix/src/interceptions/stat.rs b/crates/fspy_preload_unix/src/interceptions/stat.rs deleted file mode 100644 index a386de6b5..000000000 --- a/crates/fspy_preload_unix/src/interceptions/stat.rs +++ /dev/null @@ -1,82 +0,0 @@ -#[cfg(target_os = "linux")] -use fspy_nostd::BorrowedFd; -use fspy_shared::ipc::AccessMode; -use libc::{c_char, c_int, stat as stat_struct}; - -use crate::{ - client::{convert::PathAt, handle_open}, - macros::intercept, -}; - -intercept!(stat(64): unsafe extern "C" fn(path: *const c_char, buf: *mut stat_struct) -> c_int); -unsafe extern "C" fn stat(path: *const c_char, buf: *mut stat_struct) -> c_int { - // SAFETY: path is a valid C string pointer provided by the caller of the interposed function - unsafe { - handle_open(fspy_nostd::CStr::from_ptr(path.cast()), AccessMode::Read); - } - // SAFETY: calling the original libc stat() with the same arguments forwarded from the interposed function - unsafe { stat::original()(path, buf) } -} - -intercept!(lstat(64): unsafe extern "C" fn(path: *const c_char, buf: *mut stat_struct) -> c_int); -unsafe extern "C" fn lstat(path: *const c_char, buf: *mut stat_struct) -> c_int { - // TODO: add accessmode ReadNoFollow - // SAFETY: path is a valid C string pointer provided by the caller of the interposed function - unsafe { - handle_open(fspy_nostd::CStr::from_ptr(path.cast()), AccessMode::Read); - } - // SAFETY: calling the original libc lstat() with the same arguments forwarded from the interposed function - unsafe { lstat::original()(path, buf) } -} - -intercept!(fstatat(64): unsafe extern "C" fn(dirfd: c_int, pathname: *const c_char, buf: *mut stat_struct, flags: c_int) -> c_int); -unsafe extern "C" fn fstatat( - dirfd: c_int, - pathname: *const c_char, - buf: *mut stat_struct, - flags: c_int, -) -> c_int { - // SAFETY: dirfd is -1 or a valid file descriptor, and pathname is a valid C string, provided by the caller of the interposed function - unsafe { - handle_open(PathAt::borrow_raw(dirfd, pathname), AccessMode::Read); - } - // SAFETY: calling the original libc fstatat() with the same arguments forwarded from the interposed function - unsafe { fstatat::original()(dirfd, pathname, buf, flags) } -} - -#[cfg(target_os = "linux")] -intercept!(statx: unsafe extern "C" fn( - dirfd: c_int, - pathname: *const c_char, - flags: c_int, - mask: libc::c_uint, - statxbuf: *mut libc::statx, -) -> c_int); -#[cfg(target_os = "linux")] -unsafe extern "C" fn statx( - dirfd: c_int, - pathname: *const c_char, - flags: c_int, - mask: libc::c_uint, - statxbuf: *mut libc::statx, -) -> c_int { - let Some(original) = statx::try_original() else { - // Rust's standard library interprets ENOSYS from its statx availability - // probe as unsupported and falls back to stat64. - // SAFETY: __errno_location returns the calling thread's errno storage on Linux. - unsafe { *libc::__errno_location() = libc::ENOSYS }; - return -1; - }; - - if pathname.is_null() { - if flags & libc::AT_EMPTY_PATH != 0 { - // SAFETY: dirfd is -1 or a valid file descriptor provided by the statx caller. - unsafe { handle_open(BorrowedFd::try_borrow_raw(dirfd), AccessMode::Read) }; - } - } else { - // SAFETY: dirfd is -1 or a valid file descriptor, and pathname is a non-null C string pointer, provided by the statx caller. - unsafe { handle_open(PathAt::borrow_raw(dirfd, pathname), AccessMode::Read) }; - } - // SAFETY: calling the original libc statx() with the same arguments forwarded from the interposed function - unsafe { original(dirfd, pathname, flags, mask, statxbuf) } -} diff --git a/crates/fspy_preload_unix/src/lib.rs b/crates/fspy_preload_unix/src/lib.rs deleted file mode 100644 index 6c4e10b3e..000000000 --- a/crates/fspy_preload_unix/src/lib.rs +++ /dev/null @@ -1,11 +0,0 @@ -// Compile as an empty crate on non-unix targets and on musl (where seccomp -// alone handles access tracking). - -#[cfg(all(unix, not(target_env = "musl")))] -mod client; -#[cfg(all(unix, not(target_env = "musl")))] -mod interceptions; -#[cfg(all(unix, not(target_env = "musl")))] -mod libc; -#[cfg(all(unix, not(target_env = "musl")))] -mod macros; diff --git a/crates/fspy_preload_unix/src/macros/linux.rs b/crates/fspy_preload_unix/src/macros/linux.rs deleted file mode 100644 index 20cca08c8..000000000 --- a/crates/fspy_preload_unix/src/macros/linux.rs +++ /dev/null @@ -1,133 +0,0 @@ -macro_rules! intercept { - ($name: ident (64): $fn_sig: ty) => { - $crate::macros::intercept_inner! { - $name: $fn_sig; - - #[cfg(test)] - #[test] - fn symbol_64_exists() { - ::core::assert!($crate::macros::symbol_exists(::core::stringify!($name))); - } - } - #[cfg(not(test))] // Don't interpose on the test binary - #[expect( - clippy::allow_attributes, - reason = "runtime symbol lint applies only to compiler-known libc symbols" - )] - const _: () = { - #[allow( - invalid_runtime_symbol_definitions, - reason = "naked assembly trampoline forwards the original ABI without a Rust signature" - )] - #[unsafe(naked)] - #[unsafe(export_name = ::core::concat!(::core::stringify!($name), 64))] - pub unsafe extern "C" fn interpose_fn() { - #[cfg(target_arch = "aarch64")] - ::core::arch::naked_asm!("b {}", sym $name); - #[cfg(target_arch = "x86_64")] - ::core::arch::naked_asm!("jmp {}", sym $name); - } - }; - }; - ($name: ident: $fn_sig: ty) => { - $crate::macros::intercept_inner! { - $name: $fn_sig; - - #[cfg(test)] - #[test] - fn symbol_64_does_not_exist() { - ::core::assert_eq!( - $crate::macros::symbol_exists(::core::concat!(::core::stringify!($name), 64)), - false, - ); - } - } - }; -} - -pub(crate) use intercept; - -#[cfg(test)] -#[doc(hidden)] -pub fn symbol_exists(name: &str) -> bool { - use std::ffi::CString; - - let name = CString::new(name).unwrap(); - // SAFETY: dlsym with RTLD_DEFAULT searches for the symbol in the default shared object search order - !unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast()) }.is_null() -} - -macro_rules! intercept_inner { - ($name: ident: $fn_sig: ty; $test_fn: item) => { - const _: $fn_sig = $name; - const _: $fn_sig = $crate::libc::$name; - - #[cfg(not(test))] // Don't interpose on the test binary - #[expect( - clippy::allow_attributes, - reason = "runtime symbol lint applies only to compiler-known libc symbols" - )] - const _: () = { - #[allow( - invalid_runtime_symbol_definitions, - reason = "naked assembly trampoline forwards the original ABI without a Rust signature" - )] - #[unsafe(naked)] - #[unsafe(export_name = ::core::stringify!($name))] - pub unsafe extern "C" fn interpose_fn() { - #[cfg(target_arch = "aarch64")] - ::core::arch::naked_asm!("b {}", sym $name); - #[cfg(target_arch = "x86_64")] - ::core::arch::naked_asm!("jmp {}", sym $name); - } - }; - mod $name { - #[expect(clippy::allow_attributes, reason = "using allow because unused_imports may or may not fire depending on macro expansion")] - #[allow(unused_imports, reason = "glob import brings types into scope for macro-generated code")] - use super::*; - #[expect( - clippy::allow_attributes, - reason = "using allow because dead_code only fires for optional original symbols" - )] - #[allow( - dead_code, - reason = "not every interposer forwards to its generated original function" - )] - pub unsafe fn original() -> $fn_sig { - try_original().unwrap_or_else(|| { - panic!(::core::concat!( - "original symbol not found: ", - ::core::stringify!($name) - )) - }) - } - pub fn try_original() -> ::core::option::Option<$fn_sig> { - static LAZY: std::sync::LazyLock<::core::option::Option<$fn_sig>> = - std::sync::LazyLock::new(|| { - // SAFETY: dlsym with RTLD_NEXT returns the next symbol in the dynamic - // linking order. A non-null pointer has the signature checked by the - // macro invocation. - let symbol = unsafe { - ::libc::dlsym( - ::libc::RTLD_NEXT, - ::core::concat!(::core::stringify!($name), "\0").as_ptr().cast(), - ) - }; - if symbol.is_null() { - ::core::option::Option::None - } else { - // SAFETY: the symbol name and function signature are paired by the - // macro invocation, and null was checked above. - ::core::option::Option::Some(unsafe { - ::core::mem::transmute::<*mut ::libc::c_void, $fn_sig>(symbol) - }) - } - }); - *LAZY - } - $test_fn - } - }; -} - -pub(crate) use intercept_inner; diff --git a/crates/fspy_preload_unix/src/macros/mod.rs b/crates/fspy_preload_unix/src/macros/mod.rs deleted file mode 100644 index 5b3fa805f..000000000 --- a/crates/fspy_preload_unix/src/macros/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -#[cfg(target_os = "macos")] -#[path = "./macos.rs"] -mod os_impl; - -#[cfg(target_os = "linux")] -#[path = "./linux.rs"] -mod os_impl; - -#[expect( - clippy::redundant_pub_crate, - reason = "macro_rules! macros cannot be `pub`, only `pub(crate)` at most" -)] -pub(crate) use os_impl::*; diff --git a/crates/fspy_seccomp_unotify/.clippy.toml b/crates/fspy_seccomp_unotify/.clippy.toml deleted file mode 120000 index c7929b369..000000000 --- a/crates/fspy_seccomp_unotify/.clippy.toml +++ /dev/null @@ -1 +0,0 @@ -../../.non-vite.clippy.toml \ No newline at end of file diff --git a/crates/fspy_seccomp_unotify/Cargo.toml b/crates/fspy_seccomp_unotify/Cargo.toml deleted file mode 100644 index 6437f3c3e..000000000 --- a/crates/fspy_seccomp_unotify/Cargo.toml +++ /dev/null @@ -1,40 +0,0 @@ -[package] -name = "fspy_seccomp_unotify" -version = "0.1.0" -edition = "2024" -license.workspace = true -publish = false - -[target.'cfg(target_os = "linux")'.dependencies] -wincode = { workspace = true, features = ["derive"] } -libc = { workspace = true } -nix = { workspace = true, features = ["process", "fs", "poll", "socket", "uio"] } -passfd = { workspace = true, default-features = false, optional = true } -seccompiler = { workspace = true } -syscalls = { workspace = true, features = ["std"] } -tokio = { workspace = true, features = ["net", "process", "io-util", "rt", "sync"] } -tracing = { workspace = true } -tempfile = { workspace = true } -futures-util = { workspace = true } - -[target.'cfg(target_os = "linux")'.dev-dependencies] -assertables = { workspace = true } -futures-util = { workspace = true } -nix = { workspace = true, features = ["fs"] } -test-log = { workspace = true, features = ["trace"] } -tokio = { workspace = true, features = ["macros", "time"] } - -[features] -supervisor = ["dep:passfd", "passfd/async"] -target = ["dep:passfd"] - -[lints] -workspace = true - -[lib] -test = false -doctest = false - -[[test]] -name = "arg_types" -required-features = ["supervisor", "target"] diff --git a/crates/fspy_seccomp_unotify/README.md b/crates/fspy_seccomp_unotify/README.md deleted file mode 100644 index c55f5ba7f..000000000 --- a/crates/fspy_seccomp_unotify/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# fspy_seccomp_unotify - -Safe bindings for `seccomp_unotify` used by `fspy` to intercept direct syscalls on Linux. - -- `src/supervisor` is gated by feature `supervisor`. It contains code that needs to run in the supervisor process(the process that uses `fspy` to track child processes). -- `src/target` is gated by feature `target`. It contains code that needs to run in target processes(child processes tracked by `fspy`). diff --git a/crates/fspy_seccomp_unotify/src/bindings/alloc.rs b/crates/fspy_seccomp_unotify/src/bindings/alloc.rs deleted file mode 100644 index 024287dea..000000000 --- a/crates/fspy_seccomp_unotify/src/bindings/alloc.rs +++ /dev/null @@ -1,106 +0,0 @@ -use std::{ - alloc::{self, Layout}, - cmp::max, - ops::Deref, - ptr::NonNull, - sync::LazyLock, -}; - -use super::get_notif_sizes; - -#[derive(Debug)] -struct BufSizes { - req_layout: Layout, - resp_layout: Layout, -} - -static BUF_SIZES: LazyLock = LazyLock::new(|| { - const MAX_ALIGN: usize = align_of::(); - - let sizes = get_notif_sizes().unwrap(); - BufSizes { - req_layout: Layout::from_size_align( - max(sizes.seccomp_notif.into(), size_of::()), - MAX_ALIGN, - ) - .unwrap(), - resp_layout: Layout::from_size_align( - max(sizes.seccomp_notif_resp.into(), size_of::()), - MAX_ALIGN, - ) - .unwrap(), - } -}); - -pub struct Alloced { - ptr: NonNull, - layout: Layout, -} - -impl Alloced { - /// Allocates a zero-initialized buffer with the given layout. - /// - /// # Safety - /// The `layout` must have a size large enough to hold a value of type `T` and - /// must have proper alignment for `T`. - pub(crate) unsafe fn alloc(layout: Layout) -> Self { - // SAFETY: layout is non-zero-sized (guaranteed by caller) and properly aligned - let ptr = unsafe { alloc::alloc_zeroed(layout) }; - - let ptr = NonNull::new(ptr).unwrap(); - Self { ptr: ptr.cast(), layout } - } - - pub(crate) const fn zeroed(&mut self) -> &mut T { - // SAFETY: `self.ptr` was allocated with `self.layout.size()` bytes, - // so writing that many zero bytes is within bounds - unsafe { self.ptr.cast::().write_bytes(0, self.layout.size()) }; - // SAFETY: the pointer is valid, properly aligned, and the buffer has just - // been zero-initialized, which is valid for the kernel structs used here - unsafe { self.ptr.as_mut() } - } -} - -impl Deref for Alloced { - type Target = T; - - fn deref(&self) -> &Self::Target { - // SAFETY: the pointer is valid and properly aligned, allocated in `alloc()` - unsafe { self.ptr.as_ref() } - } -} - -impl Drop for Alloced { - fn drop(&mut self) { - // SAFETY: `self.ptr` was allocated with `alloc::alloc_zeroed` using `self.layout`, - // so it is safe to deallocate with the same layout - unsafe { - alloc::dealloc(self.ptr.as_ptr().cast(), self.layout); - } - } -} - -// SAFETY: `Alloced` owns a heap allocation and does not use thread-local storage. -// It is safe to send across threads when `T` itself is `Send + Sync`. -unsafe impl Send for Alloced {} -// SAFETY: `Alloced` only provides shared access via `Deref`, which is safe -// when `T` is `Send + Sync`. -unsafe impl Sync for Alloced {} - -/// Allocates a zero-initialized buffer for a `seccomp_notif` struct, sized to at least -/// what the kernel requires. -#[must_use] -pub fn alloc_seccomp_notif() -> Alloced { - // SAFETY: `BUF_SIZES.req_layout` is computed from `get_notif_sizes()` and - // `size_of::()`, guaranteeing sufficient size and alignment - unsafe { Alloced::alloc(BUF_SIZES.req_layout) } -} - -/// Allocates a zero-initialized buffer for a `seccomp_notif_resp` struct, sized to at least -/// what the kernel requires. -#[must_use] -pub fn alloc_seccomp_notif_resp() -> Alloced { - // SAFETY: `BUF_SIZES.resp_layout` is computed from `get_notif_sizes()` and - // `size_of::()`, guaranteeing sufficient size and alignment - unsafe { Alloced::alloc(BUF_SIZES.resp_layout) } -} diff --git a/crates/fspy_seccomp_unotify/src/bindings/mod.rs b/crates/fspy_seccomp_unotify/src/bindings/mod.rs deleted file mode 100644 index b6461a4f4..000000000 --- a/crates/fspy_seccomp_unotify/src/bindings/mod.rs +++ /dev/null @@ -1,87 +0,0 @@ -#[cfg(feature = "supervisor")] -pub mod alloc; - -#[cfg(feature = "supervisor")] -use alloc::Alloced; -use std::os::raw::c_int; - -use libc::syscall; - -/// # Safety -/// The `args` pointer must be valid for the given `operation`, or null if the operation -/// does not require arguments. -unsafe fn seccomp( - operation: libc::c_uint, - flags: libc::c_uint, - args: *mut libc::c_void, -) -> nix::Result { - // SAFETY: caller guarantees `args` is valid for the given seccomp operation - let ret = unsafe { syscall(libc::SYS_seccomp, operation, flags, args) }; - if ret < 0 { - return Err(nix::Error::last()); - } - Ok(c_int::try_from(ret).unwrap()) -} - -#[cfg(feature = "supervisor")] -fn get_notif_sizes() -> nix::Result { - use std::mem::zeroed; - // SAFETY: `seccomp_notif_sizes` is a plain data struct safe to zero-initialize - let mut sizes = unsafe { zeroed::() }; - // SAFETY: `sizes` is a valid mutable pointer to a `seccomp_notif_sizes` struct, - // which is the expected argument for `SECCOMP_GET_NOTIF_SIZES` - unsafe { seccomp(libc::SECCOMP_GET_NOTIF_SIZES, 0, (&raw mut sizes).cast()) }?; - Ok(sizes) -} - -/// Receives a seccomp notification from the given file descriptor into the provided buffer. -/// -/// # Errors -/// Returns an error if the ioctl call fails (e.g., the fd is invalid or the kernel -/// returns an error). -#[cfg(feature = "supervisor")] -pub fn notif_recv( - fd: std::os::fd::BorrowedFd<'_>, - notif_buf: &mut Alloced, -) -> nix::Result<()> { - use std::os::fd::AsRawFd; - const SECCOMP_IOCTL_NOTIF_RECV: libc::Ioctl = 3_226_476_800u64 as libc::Ioctl; - // SAFETY: `notif_buf.zeroed()` returns a valid mutable pointer to a zeroed - // `seccomp_notif` buffer with sufficient size for the kernel's notification struct - let ret = unsafe { - libc::ioctl(fd.as_raw_fd(), SECCOMP_IOCTL_NOTIF_RECV, (&raw mut *notif_buf.zeroed())) - }; - if ret < 0 { - return Err(nix::Error::last()); - } - Ok(()) -} - -/// Installs a seccomp user notification filter and returns the notification file descriptor. -/// -/// # Errors -/// Returns an error if the seccomp syscall fails (e.g., invalid filter program or -/// insufficient privileges). -#[cfg(feature = "target")] -pub fn install_unotify_filter(prog: &[libc::sock_filter]) -> nix::Result { - use std::os::fd::FromRawFd; - let mut filter = libc::sock_fprog { - len: prog.len().try_into().unwrap(), - filter: prog.as_ptr().cast_mut().cast(), - }; - - // SAFETY: `filter` is a valid `sock_fprog` pointing to the BPF program slice, - // and `SECCOMP_FILTER_FLAG_NEW_LISTENER` requests a notification fd - #[expect(clippy::cast_possible_truncation, reason = "flag value fits in u32")] - let fd = unsafe { - seccomp( - libc::SECCOMP_SET_MODE_FILTER, - libc::SECCOMP_FILTER_FLAG_NEW_LISTENER as _, - (&raw mut filter).cast(), - ) - }?; - - // SAFETY: the seccomp syscall with `SECCOMP_FILTER_FLAG_NEW_LISTENER` returns - // a valid, owned file descriptor on success - Ok(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) }) -} diff --git a/crates/fspy_seccomp_unotify/src/lib.rs b/crates/fspy_seccomp_unotify/src/lib.rs deleted file mode 100644 index a70b0a816..000000000 --- a/crates/fspy_seccomp_unotify/src/lib.rs +++ /dev/null @@ -1,10 +0,0 @@ -#![cfg(target_os = "linux")] - -#[cfg(any(feature = "supervisor", feature = "target"))] -mod bindings; -pub mod payload; -#[cfg(feature = "target")] -pub mod target; - -#[cfg(feature = "supervisor")] -pub mod supervisor; diff --git a/crates/fspy_seccomp_unotify/src/payload/filter.rs b/crates/fspy_seccomp_unotify/src/payload/filter.rs deleted file mode 100644 index 5852aa7dc..000000000 --- a/crates/fspy_seccomp_unotify/src/payload/filter.rs +++ /dev/null @@ -1,28 +0,0 @@ -use wincode::{SchemaRead, SchemaWrite}; - -#[derive(Debug, SchemaWrite, SchemaRead, Clone, Copy)] -pub struct CodableSockFilter { - code: u16, - jt: u8, - jf: u8, - k: u32, -} - -#[cfg(feature = "supervisor")] -impl From for CodableSockFilter { - fn from(c_filter: seccompiler::sock_filter) -> Self { - let seccompiler::sock_filter { code, jt, jf, k } = c_filter; - Self { code, jt, jf, k } - } -} - -#[cfg(feature = "target")] -impl From for libc::sock_filter { - fn from(filter: CodableSockFilter) -> Self { - let CodableSockFilter { code, jt, jf, k } = filter; - Self { code, jt, jf, k } - } -} - -#[derive(SchemaWrite, SchemaRead, Debug, Clone)] -pub struct Filter(pub(crate) Vec); diff --git a/crates/fspy_seccomp_unotify/src/payload/mod.rs b/crates/fspy_seccomp_unotify/src/payload/mod.rs deleted file mode 100644 index c4bd5342c..000000000 --- a/crates/fspy_seccomp_unotify/src/payload/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -mod filter; -pub use filter::Filter; -use wincode::{SchemaRead, SchemaWrite}; - -#[derive(Debug, SchemaWrite, SchemaRead, Clone)] -pub struct SeccompPayload { - pub(crate) ipc_path: Vec, - pub(crate) filter: Filter, -} - -impl SeccompPayload { - /// Builds a payload whose installation is guaranteed to fail: the filter - /// is empty (the kernel refuses it) and nothing listens on `ipc_path`. - /// - /// Test support for the untracked-exec fallback: integration tests in - /// dependent crates use it to exercise a failing [`crate::target`] - /// install without a restricted sandbox. - #[doc(hidden)] - #[must_use] - pub const fn unreachable(ipc_path: Vec) -> Self { - Self { ipc_path, filter: Filter(Vec::new()) } - } -} diff --git a/crates/fspy_seccomp_unotify/src/supervisor/handler/arg.rs b/crates/fspy_seccomp_unotify/src/supervisor/handler/arg.rs deleted file mode 100644 index fa9dc305d..000000000 --- a/crates/fspy_seccomp_unotify/src/supervisor/handler/arg.rs +++ /dev/null @@ -1,229 +0,0 @@ -use std::{ - ffi::{OsString, c_int}, - io::{self, IoSliceMut, Read}, - marker::PhantomData, - mem::MaybeUninit, - os::{fd::RawFd, raw::c_void}, -}; - -use libc::{pid_t, seccomp_notif}; -use nix::sys::uio::{RemoteIoVec, process_vm_readv}; - -pub trait FromSyscallArg: Sized { - /// Converts a raw syscall argument into this type. - /// - /// # Errors - /// Returns an error if the argument value cannot be interpreted as this type. - fn from_syscall_arg(arg: u64) -> io::Result; -} -/// Represents the caller of a syscall. Needed to read memory from the caller's address space. -#[derive(Debug, Clone, Copy)] -pub struct Caller<'a> { - pid: pid_t, - _marker: std::marker::PhantomData<&'a ()>, -} - -impl<'a> Caller<'a> { - /// Creates a `Caller` for the given pid with a local lifetime. - #[doc(hidden)] // only exposed for `impl_handler` macro - pub fn with_pid) -> R>(pid: pid_t, f: F) -> R { - f(Self { pid, _marker: std::marker::PhantomData }) - } - - #[must_use] - pub const fn read_vm(self, starting_addr: usize) -> ProcessVmReader<'a> { - ProcessVmReader { caller: self, current_addr: starting_addr } - } -} - -pub struct ProcessVmReader<'a> { - caller: Caller<'a>, - current_addr: usize, -} - -impl io::Read for ProcessVmReader<'_> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - let buf_len = buf.len(); - let read_len = process_vm_readv( - nix::unistd::Pid::from_raw(self.caller.pid), - &mut [IoSliceMut::new(buf)], - &[RemoteIoVec { base: self.current_addr, len: buf_len }], - )?; - self.current_addr = self - .current_addr - .checked_add(read_len) - .ok_or_else(|| io::Error::other("address overflow while reading remote process"))?; - Ok(read_len) - } -} - -#[derive(Debug, Clone, Copy)] -pub struct CStrPtr { - remote_ptr: usize, -} - -impl CStrPtr { - // Reads the C string from the remote process into the provided buffer. - // Returns: - /// - `Ok(Some(n))` if a null-terminator was found at position n of the buffer, - /// - `Ok(None)` if the buffer was filled without encountering a null-terminator. - /// - `Err(UnexpectedEof)` if Eof was reached without encountering a null-terminator. - /// - `Err(other_err)` on other errors from reading the remote process memory. - /// - /// # Errors - /// Returns an error if reading from the remote process memory fails. - pub fn read(self, caller: Caller<'_>, buf: &mut [u8]) -> io::Result> { - let mut reader = caller.read_vm(self.remote_ptr); - let mut pos = 0; - while let Some((_, unfilled)) = buf.split_at_mut_checked(pos) { - if unfilled.is_empty() { - break; - } - let read_bytes = reader.read(unfilled)?; - if read_bytes == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "reached EOF while reading C string from remote process", - )); - } - if let Some(null_pos) = unfilled[..read_bytes].iter().position(|&b| b == 0) { - return Ok(Some(pos + null_pos)); - } - pos += read_bytes; - } - Ok(None) - } -} - -impl FromSyscallArg for CStrPtr { - #[expect(clippy::cast_possible_truncation, reason = "syscall arg represents a pointer address")] - fn from_syscall_arg(arg: u64) -> io::Result { - Ok(Self { remote_ptr: arg as usize }) - } -} - -pub struct Ptr { - remote_ptr: *mut c_void, - _marker: PhantomData, -} -impl FromSyscallArg for Ptr { - fn from_syscall_arg(arg: u64) -> io::Result { - Ok(Self { remote_ptr: arg as *mut c_void, _marker: PhantomData }) - } -} -impl Ptr { - /// Reads the value of type T from the remote process memory. - /// - /// # Safety - /// The remote pointer must be valid and point to a value of type T in the remote process memory. - /// - /// # Errors - /// Returns an error if reading from the remote process memory fails. - pub unsafe fn read(&self, caller: Caller<'_>) -> io::Result { - let mut reader = caller.read_vm(self.remote_ptr as usize); - let mut buf = MaybeUninit::::zeroed(); - // SAFETY: `MaybeUninit` has the same layout as `T`, so casting to a - // byte slice of `size_of::()` bytes is valid for writing into - let buf_slice = unsafe { - std::slice::from_raw_parts_mut(buf.as_mut_ptr().cast::(), std::mem::size_of::()) - }; - reader.read_exact(buf_slice)?; - // SAFETY: all bytes of `buf` have been initialized by `read_exact`, - // and the caller guarantees the remote pointer points to a valid `T` - Ok(unsafe { buf.assume_init() }) - } -} - -#[derive(Debug)] -pub struct Ignored(()); -impl FromSyscallArg for Ignored { - fn from_syscall_arg(_arg: u64) -> io::Result { - Ok(Self(())) - } -} - -#[derive(Debug)] -pub struct Fd { - fd: RawFd, -} - -impl Fd { - #[must_use] - pub const fn cwd() -> Self { - Self { fd: libc::AT_FDCWD } - } -} - -impl FromSyscallArg for Fd { - fn from_syscall_arg(arg: u64) -> io::Result { - Ok(Self { fd: arg as RawFd }) - } -} - -impl Fd { - // TODO: allocate in arena - /// Returns the filesystem path associated with this file descriptor. - /// - /// # Errors - /// Returns an error if the `/proc` readlink fails (e.g., the process has exited). - pub fn get_path(self, caller: Caller<'_>) -> nix::Result { - nix::fcntl::readlink( - if self.fd == libc::AT_FDCWD { - format!("/proc/{}/cwd", caller.pid) - } else { - format!("/proc/{}/fd/{}", caller.pid, self.fd) - } - .as_str(), - ) - } -} - -impl FromSyscallArg for c_int { - #[expect(clippy::cast_possible_truncation, reason = "syscall arg represents a c_int value")] - fn from_syscall_arg(arg: u64) -> io::Result { - Ok(arg as Self) - } -} - -pub trait FromNotify: Sized { - /// Parses syscall arguments from a seccomp notification. - /// - /// # Errors - /// Returns an error if any argument cannot be parsed. - fn from_notify(notif: &seccomp_notif) -> io::Result; -} - -impl FromNotify for (T,) { - fn from_notify(notif: &seccomp_notif) -> io::Result { - Ok((T::from_syscall_arg(notif.data.args[0])?,)) - } -} - -impl FromNotify for (T1, T2) { - fn from_notify(notif: &seccomp_notif) -> io::Result { - Ok((T1::from_syscall_arg(notif.data.args[0])?, T2::from_syscall_arg(notif.data.args[1])?)) - } -} - -impl FromNotify for (T1, T2, T3) { - fn from_notify(notif: &seccomp_notif) -> io::Result { - Ok(( - T1::from_syscall_arg(notif.data.args[0])?, - T2::from_syscall_arg(notif.data.args[1])?, - T3::from_syscall_arg(notif.data.args[2])?, - )) - } -} - -impl FromNotify - for (T1, T2, T3, T4) -{ - fn from_notify(notif: &seccomp_notif) -> io::Result { - Ok(( - T1::from_syscall_arg(notif.data.args[0])?, - T2::from_syscall_arg(notif.data.args[1])?, - T3::from_syscall_arg(notif.data.args[2])?, - T4::from_syscall_arg(notif.data.args[3])?, - )) - } -} diff --git a/crates/fspy_seccomp_unotify/src/supervisor/handler/mod.rs b/crates/fspy_seccomp_unotify/src/supervisor/handler/mod.rs deleted file mode 100644 index 312e0c062..000000000 --- a/crates/fspy_seccomp_unotify/src/supervisor/handler/mod.rs +++ /dev/null @@ -1,49 +0,0 @@ -pub mod arg; - -use std::io; - -use libc::seccomp_notif; - -#[expect(clippy::module_name_repetitions, reason = "clearer as a standalone export")] -pub trait SeccompNotifyHandler { - fn syscalls() -> &'static [syscalls::Sysno]; - /// Handles a seccomp notification for an intercepted syscall. - /// - /// # Errors - /// Returns an error if the handler fails to process the notification. - fn handle_notify(&mut self, notify: &seccomp_notif) -> io::Result<()>; -} - -#[doc(hidden)] // Re-export for use in the macro -pub use syscalls::Sysno; - -#[macro_export] -macro_rules! impl_handler { - ($type:ty: $( - $(#[$attr:meta])? - $syscall:ident, - )* ) => { - - impl $crate::supervisor::handler::SeccompNotifyHandler for $type { - fn syscalls() -> &'static [$crate::supervisor::handler::Sysno] { - &[ $( - $(#[$attr])? - $crate::supervisor::handler::Sysno::$syscall - ),* ] - } - fn handle_notify(&mut self, notify: &::libc::seccomp_notif) -> ::std::io::Result<()> { - $crate::supervisor::handler::arg::Caller::with_pid(notify.pid as _, |caller| { - // The cast names its type: with `as _`, any `PartialEq for c_int` impl in - // the dependency graph, such as serde_json's, makes the comparison ambiguous. - $( - $(#[$attr])? - if notify.data.nr == $crate::supervisor::handler::Sysno::$syscall as ::libc::c_int { - return self.$syscall(caller, $crate::supervisor::handler::arg::FromNotify::from_notify(notify)?) - } - )* - Ok(()) - }) - } - } - }; -} diff --git a/crates/fspy_seccomp_unotify/src/supervisor/listener.rs b/crates/fspy_seccomp_unotify/src/supervisor/listener.rs deleted file mode 100644 index 487768d60..000000000 --- a/crates/fspy_seccomp_unotify/src/supervisor/listener.rs +++ /dev/null @@ -1,99 +0,0 @@ -use std::{ - io, - os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd}, -}; - -use libc::{seccomp_notif, seccomp_notif_resp}; -use tokio::io::unix::AsyncFd; -use tracing::trace; - -use crate::bindings::{ - alloc::{Alloced, alloc_seccomp_notif}, - notif_recv, -}; - -pub struct NotifyListener { - async_fd: AsyncFd, - notif_buf: Alloced, -} - -impl TryFrom for NotifyListener { - type Error = io::Error; - - fn try_from(value: OwnedFd) -> Result { - // SAFETY: `value` is an owned fd. `AsyncFd` stores it until the - // `AsyncFd` is dropped, and nothing replaces or closes the descriptor - // while it is registered. - let async_fd = unsafe { AsyncFd::register(value)? }; - Ok(Self { async_fd, notif_buf: alloc_seccomp_notif() }) - } -} -impl AsFd for NotifyListener { - fn as_fd(&self) -> BorrowedFd<'_> { - self.async_fd.as_fd() - } -} - -const SECCOMP_IOCTL_NOTIF_SEND: libc::Ioctl = 3_222_806_785u64 as libc::Ioctl; - -impl NotifyListener { - /// Sends a `SECCOMP_USER_NOTIF_FLAG_CONTINUE` response for the given request ID. - /// - /// # Errors - /// Returns an error if the ioctl call fails, except for `ENOENT` which is - /// silently ignored (indicates the target process's syscall was interrupted). - pub fn send_continue( - &self, - req_id: u64, - buf: &mut Alloced, - ) -> io::Result<()> { - let resp = buf.zeroed(); - resp.id = req_id; - #[expect(clippy::cast_possible_truncation, reason = "flag constant fits in u32")] - { - resp.flags = libc::SECCOMP_USER_NOTIF_FLAG_CONTINUE as u32; - } - - // SAFETY: `resp` is a valid mutable pointer to a zeroed and populated - // `seccomp_notif_resp` buffer, and the fd is a valid seccomp notify fd - let ret = unsafe { - libc::ioctl(self.async_fd.as_raw_fd(), SECCOMP_IOCTL_NOTIF_SEND, &raw mut *resp) - }; - if ret < 0 { - let err = nix::Error::last(); - // ignore error if target process's syscall was interrupted - if err == nix::Error::ENOENT { - return Ok(()); - } - return Err(err.into()); - } - Ok(()) - } - - /// Waits for and returns the next seccomp notification, or `None` if the fd is closed. - /// - /// # Errors - /// Returns an error if waiting on or reading from the notification fd fails. - pub async fn next(&mut self) -> io::Result> { - loop { - let mut ready_guard = self.async_fd.readable().await?; - let ready = ready_guard.ready(); - trace!("notify fd readable: {:?}", ready); - if ready.is_read_closed() || ready.is_write_closed() { - return Ok(None); - } - - if !ready.is_readable() { - continue; - } - // TODO: check why this call solves the issue that `is_read_closed || is_write_closed` is never true. - ready_guard.clear_ready(); - - match notif_recv(ready_guard.get_inner().as_fd(), &mut self.notif_buf) { - Ok(()) => return Ok(Some(&self.notif_buf)), - Err(nix::Error::EINTR | nix::Error::EWOULDBLOCK | nix::Error::ENOENT) => {} - Err(other_error) => return Err(other_error.into()), - } - } - } -} diff --git a/crates/fspy_seccomp_unotify/src/supervisor/mod.rs b/crates/fspy_seccomp_unotify/src/supervisor/mod.rs deleted file mode 100644 index db270dff5..000000000 --- a/crates/fspy_seccomp_unotify/src/supervisor/mod.rs +++ /dev/null @@ -1,135 +0,0 @@ -pub mod handler; -mod listener; - -use std::{ - convert::Infallible, - io::{self}, - os::{ - fd::{FromRawFd, OwnedFd}, - unix::ffi::OsStrExt, - }, -}; - -use futures_util::{ - future::{Either, select}, - pin_mut, -}; -pub use handler::SeccompNotifyHandler; -use listener::NotifyListener; -use passfd::tokio::FdPassingExt; -use seccompiler::{BpfProgram, SeccompAction, SeccompFilter}; -use tokio::{ - net::UnixListener, - sync::oneshot, - task::{JoinHandle, JoinSet}, -}; -use tracing::{Level, span}; - -use crate::{ - bindings::alloc::alloc_seccomp_notif_resp, - payload::{Filter, SeccompPayload}, -}; - -pub struct Supervisor { - payload: SeccompPayload, - cancel_tx: oneshot::Sender, - handling_loop_task: JoinHandle>>, -} - -impl Supervisor { - #[must_use] - pub const fn payload(&self) -> &SeccompPayload { - &self.payload - } - - /// Stops the supervisor and returns all handler instances. - /// - /// # Panics - /// Panics if the handling loop task has panicked. - /// - /// # Errors - /// Returns an error if any of the spawned handler tasks failed with an I/O error. - pub async fn stop(self) -> io::Result> { - drop(self.cancel_tx); - self.handling_loop_task.await.expect("handling loop task panicked") - } -} - -/// Creates a new supervisor that listens for seccomp user notifications. -/// -/// `new_handler` creates the handler for each notification fd a target -/// process sends. -/// -/// # Panics -/// Panics if the seccomp filter cannot be compiled or the target architecture is unsupported. -/// -/// # Errors -/// Returns an error if the temporary IPC socket cannot be created. -pub fn supervise(mut new_handler: F) -> io::Result> -where - H: SeccompNotifyHandler + Send + 'static, - F: FnMut() -> H + Send + 'static, -{ - let notify_listener = tempfile::Builder::new() - .prefix("fspy_seccomp_notify") - .make(|path| UnixListener::bind(path))?; - - let seccomp_filter = SeccompFilter::new( - H::syscalls().iter().map(|sysno| (sysno.id().into(), vec![])).collect(), - SeccompAction::Allow, - SeccompAction::UserNotif, - std::env::consts::ARCH.try_into().unwrap(), - ) - .unwrap(); - - let bpf_filter = - Filter(BpfProgram::try_from(seccomp_filter).unwrap().into_iter().map(Into::into).collect()); - - let payload = SeccompPayload { - ipc_path: notify_listener.path().as_os_str().as_bytes().to_vec(), - filter: bpf_filter, - }; - - // The oneshot channel is used to cancel the accept loop. - // The sender doesn't need to actually send anything. Drop is enough. - let (cancel_tx, mut cancel_rx) = oneshot::channel::(); - - let handling_loop = async move { - let mut join_set: JoinSet> = JoinSet::new(); - - loop { - let accept_future = notify_listener.as_file().accept(); - pin_mut!(accept_future); - let (incoming_stream, _) = match select(&mut cancel_rx, accept_future).await { - Either::Left((Err(_), _)) => break, - Either::Right((incoming, _)) => incoming?, - }; - let notify_fd = incoming_stream.recv_fd().await?; - // SAFETY: `recv_fd` returns a valid file descriptor received via - // Unix domain socket fd passing - let notify_fd = unsafe { OwnedFd::from_raw_fd(notify_fd) }; - let mut listener = NotifyListener::try_from(notify_fd)?; - - let mut handler = new_handler(); - let mut resp_buf = alloc_seccomp_notif_resp(); - - join_set.spawn(async move { - while let Some(notify) = listener.next().await? { - let _span = span!(Level::TRACE, "notify loop tick"); - // Errors on the supervisor side could be caused by a target process aborting. - // It shouldn't break the syscall handling loop as there might be target processes. - let _handle_result = handler.handle_notify(notify); - let req_id = notify.id; - listener.send_continue(req_id, &mut resp_buf)?; - } - io::Result::Ok(handler) - }); - } - let mut handlers = Vec::::new(); - while let Some(handler) = join_set.join_next().await.transpose()? { - handlers.push(handler?); - } - Ok(handlers) - }; - Ok(Supervisor { payload, cancel_tx, handling_loop_task: tokio::spawn(handling_loop) }) -} diff --git a/crates/fspy_seccomp_unotify/src/target.rs b/crates/fspy_seccomp_unotify/src/target.rs deleted file mode 100644 index 5406f7961..000000000 --- a/crates/fspy_seccomp_unotify/src/target.rs +++ /dev/null @@ -1,33 +0,0 @@ -use std::{ - ffi::OsStr, - os::{ - fd::AsRawFd, - unix::{ffi::OsStrExt, net::UnixStream}, - }, -}; - -use libc::sock_filter; -use nix::sys::prctl::set_no_new_privs; -use passfd::FdPassingExt; - -use crate::{bindings::install_unotify_filter, payload::SeccompPayload}; - -/// Installs the seccomp user notification filter and sends the notification fd -/// to the supervisor via the IPC socket. -/// -/// # Errors -/// Returns an error if setting no-new-privs fails, the filter cannot be installed, -/// or the IPC socket communication fails. -pub fn install_target(payload: &SeccompPayload) -> nix::Result<()> { - set_no_new_privs()?; - let sock_filters = - payload.filter.0.iter().copied().map(sock_filter::from).collect::>(); - let notify_fd = install_unotify_filter(&sock_filters)?; - let ipc_path = OsStr::from_bytes(&payload.ipc_path); - let ipc_unix_stream = UnixStream::connect(ipc_path) - .map_err(|err| nix::Error::try_from(err).unwrap_or(nix::Error::UnknownErrno))?; - ipc_unix_stream - .send_fd(notify_fd.as_raw_fd()) - .map_err(|err| nix::Error::try_from(err).unwrap_or(nix::Error::UnknownErrno))?; - Ok(()) -} diff --git a/crates/fspy_seccomp_unotify/tests/arg_types.rs b/crates/fspy_seccomp_unotify/tests/arg_types.rs deleted file mode 100644 index 7f7c72185..000000000 --- a/crates/fspy_seccomp_unotify/tests/arg_types.rs +++ /dev/null @@ -1,144 +0,0 @@ -#![cfg(target_os = "linux")] -use std::{ - env::{current_dir, set_current_dir}, - error::Error, - ffi::{CString, OsString}, - io, - os::unix::ffi::OsStringExt, - time::Duration, -}; - -use assertables::assert_contains; -use fspy_seccomp_unotify::{ - impl_handler, - supervisor::{ - handler::arg::{CStrPtr, Caller, Fd}, - supervise, - }, - target::install_target, -}; -use nix::{ - fcntl::{AT_FDCWD, OFlag, openat}, - sys::stat::Mode, -}; -use test_log::test; -use tokio::{process::Command, task::spawn_blocking, time::timeout}; -use tracing::{Level, span, trace}; - -#[derive(Debug, PartialEq, Eq, Clone)] -enum Syscall { - Openat { at_dir: OsString, path: Option }, -} - -#[derive(Default, Clone, Debug)] -struct SyscallRecorder(Vec); -impl SyscallRecorder { - fn openat(&mut self, caller: Caller<'_>, (fd, path): (Fd, CStrPtr)) -> io::Result<()> { - let at_dir = fd.get_path(caller)?; - let mut buf = vec![0u8; 40000]; - let path = path - .read(caller, &mut buf)? - .map(|null_pos| OsString::from_vec(buf[..null_pos].to_vec())); - self.0.push(Syscall::Openat { at_dir, path }); - Ok(()) - } -} - -impl_handler!(SyscallRecorder: openat,); - -async fn run_in_pre_exec( - mut f: impl FnMut() -> io::Result<()> + Send + Sync + 'static, -) -> Result, Box> { - Ok(timeout(Duration::from_secs(5), async move { - let mut cmd = Command::new("/bin/echo"); - let supervisor = supervise(SyscallRecorder::default)?; - - let payload = supervisor.payload().clone(); - - // SAFETY: `pre_exec` closure runs in the forked child process before exec. - // It installs the seccomp filter and runs the user-provided closure, both of - // which are safe in a pre-exec context (no async, no locks held). - unsafe { - cmd.pre_exec(move || { - install_target(&payload)?; - f()?; - Ok(()) - }); - } - let child_fut = spawn_blocking(move || { - let _span = span!(Level::TRACE, "spawn test child process"); - cmd.spawn() - }); - - let exit_status = child_fut.await.unwrap()?.wait().await?; - trace!("test child process exited with status: {:?}", exit_status); - - trace!("waiting for handler to finish and test child process to exit"); - - assert!(exit_status.success()); - - let recorders = supervisor.stop().await?; - trace!("{} recorders awaited", recorders.len()); - - let syscalls = recorders.into_iter().flat_map(|recorder| recorder.0); - io::Result::Ok(syscalls.collect()) - }) - .await??) -} - -#[test(tokio::test)] -async fn fd_and_path() -> Result<(), Box> { - let syscalls = run_in_pre_exec(|| { - set_current_dir("/")?; - let home_fd = openat(AT_FDCWD, c"/home", OFlag::O_PATH, Mode::empty())?; - let _ = openat(home_fd, c"open_at_home", OFlag::O_RDONLY, Mode::empty()); - let _ = openat(AT_FDCWD, c"openat_cwd", OFlag::O_RDONLY, Mode::empty()); - Ok(()) - }) - .await?; - assert_contains!(syscalls, &Syscall::Openat { at_dir: "/".into(), path: Some("/home".into()) }); - assert_contains!( - syscalls, - &Syscall::Openat { at_dir: "/home".into(), path: Some("open_at_home".into()) } - ); - assert_contains!( - syscalls, - &Syscall::Openat { at_dir: "/".into(), path: Some("openat_cwd".into()) } - ); - Ok(()) -} - -#[tokio::test] -async fn path_long() -> Result<(), Box> { - let long_path = b"a".repeat(30000); - let long_path_cstr = CString::new(long_path.as_slice()).unwrap(); - let syscalls = run_in_pre_exec(move || { - let _ = openat(AT_FDCWD, long_path_cstr.as_c_str(), OFlag::O_RDONLY, Mode::empty()); - Ok(()) - }) - .await?; - assert_contains!( - syscalls, - &Syscall::Openat { - at_dir: current_dir().unwrap().into(), - path: Some(OsString::from_vec(long_path)), - } - ); - Ok(()) -} - -#[tokio::test] -async fn path_overflow() -> Result<(), Box> { - let long_path = b"a".repeat(40000); - let long_path_cstr = CString::new(long_path.as_slice()).unwrap(); - let syscalls = run_in_pre_exec(move || { - let _ = openat(AT_FDCWD, long_path_cstr.as_c_str(), OFlag::O_RDONLY, Mode::empty()); - Ok(()) - }) - .await?; - assert_contains!( - syscalls, - &Syscall::Openat { at_dir: current_dir().unwrap().into(), path: None } - ); - Ok(()) -} diff --git a/crates/fspy_shared_unix/Cargo.toml b/crates/fspy_shared_unix/Cargo.toml index 3d5988ed1..eed797e87 100644 --- a/crates/fspy_shared_unix/Cargo.toml +++ b/crates/fspy_shared_unix/Cargo.toml @@ -5,27 +5,25 @@ edition.workspace = true license.workspace = true publish = false -[target.'cfg(unix)'.dependencies] +[target.'cfg(any(unix, target_os = "none"))'.dependencies] allocator-api2 = { workspace = true, features = ["alloc"] } -anyhow = { workspace = true } base64 = { workspace = true } -wincode = { workspace = true, features = ["derive"] } -bstr = { workspace = true, features = ["alloc", "std"] } -fspy_shared = { workspace = true } -nix = { workspace = true, features = ["fs"] } +bstr = { workspace = true } fspy_nostd = { workspace = true } fspy_nostd_alloc = { workspace = true } +fspy_shared = { workspace = true } +wincode = { workspace = true, features = ["derive"] } -[dev-dependencies] - -[target.'cfg(target_os = "linux")'.dependencies] -elf = { workspace = true } -fspy_seccomp_unotify = { workspace = true, features = ["target"] } -memmap2 = { workspace = true } +[target.'cfg(any(target_os = "linux", target_os = "none"))'.dependencies] +bitflags = { workspace = true } +linux-raw-sys = { workspace = true, features = ["general", "no_std"] } [target.'cfg(target_os = "macos")'.dependencies] phf = { workspace = true, features = ["macros"] } +[dev-dependencies] +tempfile = { workspace = true } + [lints] workspace = true diff --git a/crates/fspy_shared_unix/README.md b/crates/fspy_shared_unix/README.md index 241514631..879071828 100644 --- a/crates/fspy_shared_unix/README.md +++ b/crates/fspy_shared_unix/README.md @@ -1,3 +1,4 @@ # fspy_shared_unix -Common code shared by `fspy` (run in the supervisor process) and `fspy_preload_unix` (run in target processes, macOS/Linux only). +`no_std` Unix exec-resolution and payload/bootstrap serialization shared by +`fspy`, `fspy_preload_linux`, and `fspy_preload_macos`. diff --git a/crates/fspy_shared_unix/src/codec.rs b/crates/fspy_shared_unix/src/codec.rs new file mode 100644 index 000000000..dbec633eb --- /dev/null +++ b/crates/fspy_shared_unix/src/codec.rs @@ -0,0 +1,52 @@ +use allocator_api2::{alloc::Allocator, vec::Vec}; +use base64::{Engine as _, prelude::BASE64_STANDARD_NO_PAD}; +use wincode::{SchemaRead, SchemaWrite, config::DefaultConfig}; + +/// Serializes `value` with wincode and base64-encodes it without padding, +/// leaking the encoded UTF-8 string into `allocator`. +/// +/// The intermediate binary buffer is dropped before returning. +#[must_use] +pub fn encode_b64<'a, T, A>(value: &T, allocator: A) -> &'a str +where + T: SchemaWrite, + A: Allocator + Clone + 'a, +{ + let serialized_size = usize::try_from( + wincode::serialized_size(value).expect("payload cannot report its serialized size"), + ) + .expect("serialized payload size exceeds usize"); + let mut buffer = Vec::with_capacity_in(serialized_size, allocator.clone()); + buffer.resize(serialized_size, 0); + let mut writer: &mut [u8] = &mut buffer; + wincode::serialize_into(&mut writer, value).expect("payload serialization failed"); + assert!(writer.is_empty(), "payload wrote fewer bytes than the size it reported"); + + let encoded_len = + base64::encoded_len(serialized_size, false).expect("encoded payload length exceeds usize"); + let mut encoded = Vec::with_capacity_in(encoded_len, allocator); + encoded.resize(encoded_len, 0); + let written = + BASE64_STANDARD_NO_PAD.encode_slice(&buffer, &mut encoded).expect("base64 encoding failed"); + encoded.truncate(written); + drop(buffer); + + let leaked: &'a [u8] = encoded.leak(); + core::str::from_utf8(leaked).expect("base64 output is valid UTF-8") +} + +/// Base64-decodes `encoded` into `allocator` and deserializes `T` borrowing +/// from the leaked decoded bytes. +pub fn decode_b64<'a, T, A>(encoded: &[u8], allocator: A) -> Option +where + T: SchemaRead<'a, DefaultConfig, Dst = T>, + A: Allocator + 'a, +{ + let decoded_len_estimate = base64::decoded_len_estimate(encoded.len()); + let mut buffer = Vec::with_capacity_in(decoded_len_estimate, allocator); + buffer.resize(decoded_len_estimate, 0); + let decoded_len = BASE64_STANDARD_NO_PAD.decode_slice(encoded, &mut buffer).ok()?; + buffer.truncate(decoded_len); + let leaked: &'a [u8] = buffer.leak(); + wincode::deserialize_exact(leaked).ok() +} diff --git a/crates/fspy_shared_unix/src/elf.rs b/crates/fspy_shared_unix/src/elf.rs deleted file mode 100644 index 7dde8637c..000000000 --- a/crates/fspy_shared_unix/src/elf.rs +++ /dev/null @@ -1,63 +0,0 @@ -use std::{ - ffi::{CStr, OsStr}, - os::unix::ffi::OsStrExt as _, - path::Path, -}; - -use bstr::BStr; -use elf::{ElfBytes, abi::PT_INTERP, endian::AnyEndian}; - -/// Checks whether the given ELF executable is dynamically linked to libc. -/// -/// # Errors -/// -/// Returns `ENOEXEC` if the binary cannot be parsed as a valid ELF file. -pub fn is_dynamically_linked_to_libc(executable: impl AsRef<[u8]>) -> nix::Result { - let executable = executable.as_ref(); - let Some(interp) = get_interp(executable)? else { - return Ok(false); - }; - let Some(interp_filename) = Path::new(OsStr::from_bytes(interp)).file_name() else { - return Ok(false); - }; - let interp_filename = interp_filename.as_bytes(); - Ok(interp_filename.starts_with(b"ld-") || interp_filename.starts_with(b"ld.")) -} - -fn get_interp(executable: &[u8]) -> nix::Result> { - let elf = - ElfBytes::<'_, AnyEndian>::minimal_parse(executable).map_err(|_| nix::Error::ENOEXEC)?; - let Some(headers) = elf.segments() else { - return Ok(None); - }; - - let Some(interp_header) = headers.into_iter().find(|header| header.p_type == PT_INTERP) else { - return Ok(None); - }; - let Ok(interp) = elf.segment_data(&interp_header) else { - return Err(nix::Error::ENOEXEC); - }; - - let interp = CStr::from_bytes_until_nul(interp).map_or(interp, CStr::to_bytes); - Ok(Some(BStr::new(interp))) -} - -#[cfg(test)] -mod tests { - use std::fs::read; - - use super::*; - #[test] - fn dynamic_executable() { - assert!(is_dynamically_linked_to_libc(read("/bin/sh").unwrap()).unwrap()); - } - #[test] - fn static_executable() { - let cat = read("/bin/cat").unwrap(); - let ld_so_path = get_interp(&cat).unwrap().unwrap(); - - assert!( - !is_dynamically_linked_to_libc(read(OsStr::from_bytes(ld_so_path)).unwrap()).unwrap() - ); - } -} diff --git a/crates/fspy_shared_unix/src/exec/mod.rs b/crates/fspy_shared_unix/src/exec/mod.rs deleted file mode 100644 index bcc3fc819..000000000 --- a/crates/fspy_shared_unix/src/exec/mod.rs +++ /dev/null @@ -1,326 +0,0 @@ -mod shebang; -mod which; - -use std::{ - ffi::{CStr, OsStr}, - iter::once, - mem::replace, - os::unix::ffi::OsStrExt, - path::Path, -}; - -use allocator_api2::{alloc::Allocator, vec::Vec}; -use bstr::{BStr, ByteSlice}; -use nix::unistd::{AccessFlags, access}; -use shebang::{ParseShebangOptions, parse_shebang}; - -use crate::open_exec::open_executable; - -#[derive(Debug, Clone)] -pub struct SearchPath<'a> { - /// Custom search path to use (like execvP), overrides PATH if Some - pub custom_path: Option<&'a BStr>, -} - -/// Configuration for exec resolution behavior -#[derive(Debug, Clone)] -pub struct ExecResolveConfig<'a> { - /// If Some and the program doesn't contains `/`, - /// search the program in PATH (like execvp, execvpe, execlp) instead of finding it in current directory - pub search_path: Option>, - /// Options for parsing shebangs (all exec variants handle shebangs) - pub shebang_options: ParseShebangOptions, -} - -impl<'a> ExecResolveConfig<'a> { - /// Configuration for execve - no PATH search, direct execution - #[must_use] - pub fn search_path_disabled() -> Self { - Self { search_path: None, shebang_options: ParseShebangOptions::default() } - } - - /// execlp/execvp/execvP/execvpe - /// `custom_path` allows a customized path to be searched like in execvP (macOS extension) - #[must_use] - pub fn search_path_enabled(custom_path: Option<&'a BStr>) -> Self { - Self { - search_path: Some(SearchPath { custom_path }), - shebang_options: ParseShebangOptions::default(), - } - } -} - -/// An environment entry: (name, value). value is None when the entry in -/// environ doesn't contain a `=` character. -pub type Env = (Vec, Option>); - -/// An exec call's program, arguments and environment. -/// -/// The strings live in `A`, so the preload can keep them in the -/// interception's bump rather than libc's heap: exec may run in the child of -/// `fork()`, where malloc's lock may be held by a thread that no longer -/// exists. -/// Copies `bytes` into a `Vec` in `allocator`. -pub fn to_vec_in(bytes: &[u8], allocator: A) -> Vec { - let mut vec = Vec::with_capacity_in(bytes.len(), allocator); - vec.extend_from_slice(bytes); - vec -} - -#[derive(Debug)] -pub struct Exec { - pub program: Vec, - pub args: Vec, A>, - pub envs: Vec, A>, -} - -fn getenv(name: &CStr) -> Option<&'static CStr> { - // SAFETY: `getenv` is a C standard library function, called with a valid pointer from `CStr::as_ptr`. - let value = unsafe { nix::libc::getenv(name.as_ptr().cast()) }; - if value.is_null() { - None - } else { - // SAFETY: `value` is non-null (checked above) and points to a null-terminated string owned - // by the environment, as guaranteed by the C `getenv` contract. - Some(unsafe { CStr::from_ptr(value) }) - } -} - -fn peek_executable(path: &Path, buf: &mut [u8]) -> nix::Result { - let fd = open_executable(path)?; - let mut total_read_size = 0; - loop { - let read_size = nix::unistd::read(&fd, &mut buf[total_read_size..])?; - if read_size == 0 { - break; - } - total_read_size += read_size; - } - Ok(total_read_size) -} - -impl Exec { - /// The allocator the strings live in. - pub fn allocator(&self) -> &A { - self.args.allocator() - } - - /// Resolve the program path according to exec family semantics - /// - /// This method replicates the behavior of execve/execvp/execvP/execvpe for program resolution, - /// including PATH searching and shebang handling. - /// - /// # Returns - /// - /// * `Ok(())` if resolution succeeds and `self` is updated with resolved paths - /// * `Err(nix::Error)` with appropriate errno, like the exec function would return - /// - /// # Errors - /// - /// Returns an error if: - /// - The program is empty, or is not found in PATH (`ENOENT`) - /// - The program file cannot be accessed or read (`EACCES`, `EISDIR`, `EIO`) - /// - Shebang parsing fails due to I/O errors (`EIO`) - pub fn resolve( - &mut self, - mut on_path_read: impl FnMut(&Path), - config: ExecResolveConfig, - ) -> nix::Result<()> { - // execve and libc's PATH search both fail an empty program with - // ENOENT before looking anything up, so nothing is read. - if self.program.is_empty() { - return Err(nix::Error::ENOENT); - } - if let Some(search_path) = config.search_path { - let path = search_path.custom_path.unwrap_or_else(|| { - getenv(c"PATH").map_or_else( - || { - // https://github.com/kraj/musl/blob/1b06420abdf46f7d06ab4067e7c51b8b63731852/src/process/execvp.c#L21 - b"/usr/local/bin:/bin:/usr/bin".as_bstr() - }, - |path| path.to_bytes().as_bstr(), - ) - }); - self.program = which::which( - self.program.as_bstr(), - path, - |path| { - on_path_read(Path::new(OsStr::from_bytes(path))); - access(OsStr::from_bytes(path), AccessFlags::X_OK) - }, - self.allocator().clone(), - )?; - } - - self.parse_shebang(on_path_read, config.shebang_options)?; - - Ok(()) - } - - fn parse_shebang( - &mut self, - mut on_path_read: impl FnMut(&Path), - options: ParseShebangOptions, - ) -> nix::Result<()> { - if let Some(shebang) = parse_shebang( - |path, buf| { - on_path_read(path); - peek_executable(path, buf) - }, - Path::new(OsStr::from_bytes(&self.program)), - options, - self.allocator().clone(), - )? { - self.args[0].clone_from(&shebang.interpreter); - let old_program = replace(&mut self.program, shebang.interpreter); - self.args.splice(1..1, shebang.arguments.into_iter().chain(once(old_program))); - } - Ok(()) - } -} - -/// Ensures an environment variable is set to the specified value -/// -/// If the variable doesn't exist, it is added. If it exists with the same value, -/// no change is made. If it exists with a different value, an error is returned. -/// -/// # Errors -/// -/// Returns `Err(nix::Error::EINVAL)` if the environment variable already exists with a different value. -pub fn ensure_env( - envs: &mut Vec, A>, - name: impl AsRef, - value: impl AsRef, -) -> nix::Result<()> { - let name = name.as_ref(); - let value = value.as_ref(); - let existing_value = - envs.iter().find_map(|(n, v)| if n.as_bstr() == name { v.as_ref() } else { None }); - if let Some(existing_value) = existing_value { - return if existing_value.as_bstr() == value { Ok(()) } else { Err(nix::Error::EINVAL) }; - } - let allocator = envs.allocator().clone(); - envs.push((to_vec_in(name, allocator.clone()), Some(to_vec_in(value, allocator)))); - Ok(()) -} - -/// Ensures `value` is the trailing colon-separated entry of env var `name`. -/// -/// Used for `LD_PRELOAD` / `DYLD_INSERT_LIBRARIES`, which the dynamic loader -/// treats as colon-separated lists. Appending (rather than overwriting) -/// preserves any user-provided preload, and appending to the *end* keeps -/// fspy's shim as the last interposer so a user preload that short-circuits -/// a call (returning without forwarding to libc) stays invisible to fspy — -/// mirroring what the OS actually did. -/// -/// - Absent: inserts `(name, value)`. -/// - Present with `value` already as the last colon-separated entry: no -/// change (idempotent across nested execs within the preloaded shim). -/// - Present otherwise: rewrites to `{existing}:{value}`. If `existing` is -/// empty, sets to `value` alone to avoid a leading `:` (which glibc's -/// `ld.so` interprets as the current directory). -pub fn append_path_env( - envs: &mut Vec, A>, - name: impl AsRef, - value: impl AsRef, -) { - let name = name.as_ref(); - let value = value.as_ref(); - let allocator = envs.allocator().clone(); - if let Some(entry) = envs.iter_mut().find(|(n, _)| n.as_bstr() == name) { - let existing: &[u8] = entry.1.as_deref().unwrap_or_default(); - let value_bytes: &[u8] = value.as_ref(); - let already_last = existing == value_bytes - || (existing.len() > value_bytes.len() - && existing.ends_with(value_bytes) - && existing[existing.len() - value_bytes.len() - 1] == b':'); - if already_last { - return; - } - let mut new_value = - Vec::with_capacity_in(existing.len() + 1 + value_bytes.len(), allocator); - if !existing.is_empty() { - new_value.extend_from_slice(existing); - new_value.push(b':'); - } - new_value.extend_from_slice(value_bytes); - entry.1 = Some(new_value); - } else { - envs.push((to_vec_in(name, allocator.clone()), Some(to_vec_in(value, allocator)))); - } -} - -#[cfg(test)] -mod tests { - use allocator_api2::{alloc::Global, vec::Vec}; - - use super::{append_path_env, to_vec_in}; - - type Envs = Vec<(Vec, Option>)>; - - fn env(envs: &Envs, name: &[u8]) -> Option> { - envs.iter().find(|(n, _)| n == name).and_then(|(_, v)| v.as_ref().map(|v| v.to_vec())) - } - - /// (case, envs before the call, appended `LD_PRELOAD` value, expected value) - type AppendCase<'a> = (&'a str, &'a [(&'a str, Option<&'a str>)], &'a str, &'a [u8]); - - #[test] - fn appends_value_to_the_env_list() { - let cases: &[AppendCase<'_>] = &[ - ("inserts when absent", &[], "/a.so", b"/a.so"), - ("noop when equal", &[("LD_PRELOAD", Some("/a.so"))], "/a.so", b"/a.so"), - ( - "noop when value is last entry", - &[("LD_PRELOAD", Some("/user.so:/a.so"))], - "/a.so", - b"/user.so:/a.so", - ), - ( - "appends with colon when present and different", - &[("LD_PRELOAD", Some("/user.so"))], - "/a.so", - b"/user.so:/a.so", - ), - ( - "sets without leading colon when existing is empty", - &[("LD_PRELOAD", Some(""))], - "/a.so", - b"/a.so", - ), - // `lib/a.so` ends with `/a.so` as bytes, but the preceding byte is - // `b` not `:`, so it must NOT be treated as already-present. - ( - "does not false match prefix without preceding colon", - &[("LD_PRELOAD", Some("/lib/a.so"))], - "a.so", - b"/lib/a.so:a.so", - ), - // An env var present in the list but with `None` value (name without - // `=`) should be rewritten to `Some(value)`. - ("inserts when present with none value", &[("LD_PRELOAD", None)], "/a.so", b"/a.so"), - ]; - for &(case, existing, value, expected) in cases { - let mut envs: Envs = existing - .iter() - .map(|&(name, value)| { - ( - to_vec_in(name.as_bytes(), Global), - value.map(|v| to_vec_in(v.as_bytes(), Global)), - ) - }) - .collect(); - append_path_env(&mut envs, "LD_PRELOAD", value); - assert_eq!(env(&envs, b"LD_PRELOAD"), Some(expected.to_vec()), "{case}"); - } - } - - #[test] - fn idempotent_on_repeat() { - let mut envs = Envs::new(); - append_path_env(&mut envs, "LD_PRELOAD", "/a.so"); - append_path_env(&mut envs, "LD_PRELOAD", "/a.so"); - append_path_env(&mut envs, "LD_PRELOAD", "/a.so"); - assert_eq!(env(&envs, b"LD_PRELOAD"), Some(b"/a.so".to_vec())); - } -} diff --git a/crates/fspy_shared_unix/src/exec/shebang.rs b/crates/fspy_shared_unix/src/exec/shebang.rs deleted file mode 100644 index 7b65d698d..000000000 --- a/crates/fspy_shared_unix/src/exec/shebang.rs +++ /dev/null @@ -1,402 +0,0 @@ -use std::path::Path; - -use allocator_api2::{alloc::Allocator, vec::Vec}; -use bstr::ByteSlice; - -use super::to_vec_in; - -#[derive(Debug, Clone)] -pub struct Shebang { - pub interpreter: Vec, - pub arguments: Vec, A>, -} - -const fn is_whitespace(c: u8) -> bool { - c == b' ' || c == b'\t' -} - -#[derive(Clone, Copy, Debug)] -pub struct ParseShebangOptions { - pub split_arguments: bool, // TODO: recursive - /// How many bytes of the file the kernel reads to find the shebang line. - pub max_line_len: usize, - /// Whether the line must end within `max_line_len` bytes. - /// - /// macOS refuses a script whose line doesn't end. Linux accepts it as - /// long as the interpreter path is followed by a space or tab, so only - /// the arguments can have been cut off. - pub require_line_end: bool, - /// Whether `#` ends the line like a newline does, as on macOS (`IS_EOL` - /// in XNU's `exec_shell_imgact`). - pub hash_ends_line: bool, -} - -/// Size of the buffer the macOS kernel reads the shebang line into (`IMG_SHSIZE`). -const MACOS_MAX_LINE_LEN: usize = 512; -/// Size of the buffer the Linux kernel reads the shebang line into (`BINPRM_BUF_SIZE`). -const LINUX_MAX_LINE_LEN: usize = 256; - -impl ParseShebangOptions { - #[must_use] - pub const fn macos() -> Self { - Self { - split_arguments: true, - max_line_len: MACOS_MAX_LINE_LEN, - require_line_end: true, - hash_ends_line: true, - } - } - - #[must_use] - pub const fn linux() -> Self { - Self { - split_arguments: false, - max_line_len: LINUX_MAX_LINE_LEN, - require_line_end: false, - hash_ends_line: false, - } - } -} - -impl Default for ParseShebangOptions { - fn default() -> Self { - if cfg!(target_vendor = "apple") { Self::macos() } else { Self::linux() } - } -} - -/// Parses the shebang line of the executable at `path` the way the kernel -/// does, copying the interpreter and arguments into `allocator`. -/// -/// Returns `ENOEXEC` where the kernel would refuse the script instead of -/// running a truncated interpreter path. -/// -/// # Panics -/// -/// Panics if `options.max_line_len` is larger than 512. -pub fn parse_shebang( - mut peek_executable: impl FnMut(&Path, &mut [u8]) -> nix::Result, - path: &Path, - options: ParseShebangOptions, - allocator: A, -) -> Result>, nix::Error> { - let mut buf = [0u8; MACOS_MAX_LINE_LEN]; - let buf = &mut buf[..options.max_line_len]; - - let total_read_size = peek_executable(path, buf)?; - let buf = &buf[..total_read_size]; - - let Some(line) = buf.strip_prefix(b"#!") else { - return Ok(None); - }; - - let line_ends: &[u8] = if options.hash_ends_line { b"\n#" } else { b"\n" }; - let line = if let Some(line_end) = line.find_byteset(line_ends) { - &line[..line_end] - } else if options.require_line_end { - return Err(nix::Error::ENOEXEC); - } else if total_read_size < options.max_line_len { - // The whole file fits in the buffer, so nothing was cut off. - line - } else { - // https://github.com/torvalds/linux/blob/v6.12/fs/binfmt_script.c - // The interpreter path must be followed by a space or tab, or it may be - // cut off. Like the kernel, look for one in the whole buffer but keep - // its last byte as a terminator. - if !line.iter().skip_while(|ch| is_whitespace(**ch)).any(|ch| is_whitespace(*ch)) { - return Err(nix::Error::ENOEXEC); - } - &line[..line.len() - 1] - }; - - let line = line.trim_ascii(); - let interpreter = line.split(|ch| is_whitespace(*ch)).next().unwrap_or_default(); - if interpreter.is_empty() { - return Err(nix::Error::ENOEXEC); - } - let arguments_buf = line[interpreter.len()..].trim_ascii_start().as_bstr(); - - let mut arguments = Vec::new_in(allocator.clone()); - if options.split_arguments { - arguments.extend(arguments_buf.split(|ch| is_whitespace(*ch)).filter_map(|arg| { - let arg = arg.trim_ascii(); - if arg.is_empty() { None } else { Some(to_vec_in(arg, allocator.clone())) } - })); - } else if !arguments_buf.is_empty() { - arguments.push(to_vec_in(arguments_buf, allocator.clone())); - } - - Ok(Some(Shebang { interpreter: to_vec_in(interpreter, allocator), arguments })) -} - -// #[derive(Debug)] -// pub struct RecursiveParseOpts { -// pub recursion_limit: usize, -// pub split_arguments: bool, -// } - -// impl Default for RecursiveParseOpts { -// fn default() -> Self { -// Self { -// recursion_limit: 4, // BINPRM_MAX_RECURSION -// split_arguments: false, -// } -// } -// } - -// fn parse_shebang_recursive_impl( -// buf: &mut [u8], -// reader: R, -// mut get_reader: impl FnMut(&OsStr) -> io::Result, -// mut on_shebang: impl FnMut(shebang<'_>) -> io::Result<()>, -// ) -> io::Result<()> { -// let Some(mut shebang) = parse_shebang(buf, reader)? else { -// return Ok(()); -// }; -// on_shebang(shebang)?; -// loop { -// let reader = get_reader(&shebang.interpreter)?; -// let Some(cur_shebang) = parse_shebang(buf, reader)? else { -// break Ok(()); -// }; -// on_shebang(cur_shebang)?; -// shebang = cur_shebang; -// } -// } - -// pub fn parse_shebang_recursive< -// const PEEK_CAP: usize, -// R: Read, -// O: FnMut(&OsStr) -> io::Result, -// C: FnMut(&OsStr) -> io::Result<()>, -// >( -// opts: RecursiveParseOpts, -// reader: R, -// open: O, -// mut on_arg_reverse: C, -// ) -> io::Result<()> { -// let mut peek_buf = [0u8; PEEK_CAP]; -// let mut recursive_count = 0; -// parse_shebang_recursive_impl(&mut peek_buf, reader, open, |shebang| { -// if recursive_count > opts.recursion_limit { -// return Err(io::Error::from_raw_os_error(libc::ELOOP)); -// } -// if opts.split_arguments { -// for arg in shebang.arguments.split().rev() { -// on_arg_reverse(arg)?; -// } -// } else { -// on_arg_reverse(shebang.arguments.as_one())?; -// } -// on_arg_reverse(shebang.interpreter)?; -// recursive_count += 1; -// Ok(()) -// })?; -// Ok(()) -// } - -// #[cfg(test)] -// mod tests { -// use std::os::unix::ffi::OsStrExt; - -// use super::*; - -// #[test] -// fn shebang_basic() { -// let mut buf = [0u8; PEEK_SIZE]; -// let shebang = parse_shebang(&mut buf, "#!/bin/sh a b\n".as_bytes()) -// .unwrap() -// .unwrap(); -// assert_eq!(shebang.interpreter.as_bytes(), b"/bin/sh"); -// assert_eq!(shebang.arguments.as_one().as_bytes(), b"a b"); -// assert_eq!( -// shebang -// .arguments -// .split() -// .map(OsStrExt::as_bytes) -// .collect::>(), -// vec![b"a", b"b"] -// ); -// } - -// #[test] -// fn shebang_trimming_spaces() { -// let mut buf = [0u8; PEEK_SIZE]; -// let shebang = parse_shebang(&mut buf, "#! /bin/sh a \n".as_bytes()) -// .unwrap() -// .unwrap(); -// assert_eq!(shebang.interpreter, b"/bin/sh"); -// assert_eq!(shebang.arguments.as_one().as_bytes(), b"a"); -// assert_eq!( -// shebang -// .arguments -// .split() -// .map(OsStrExt::as_bytes) -// .collect::>(), -// vec![b"a"] -// ); -// } - -// #[test] -// fn shebang_split_arguments() { -// let mut buf = [0u8; PEEK_SIZE]; -// let shebang = parse_shebang(&mut buf, "#! /bin/sh a b\tc \n".as_bytes()) -// .unwrap() -// .unwrap(); -// assert_eq!(shebang.interpreter, b"/bin/sh"); -// assert_eq!( -// shebang -// .arguments -// .split() -// .map(OsStrExt::as_bytes) -// .collect::>(), -// &[b"a", b"b", b"c"] -// ); -// } -// #[test] -// fn shebang_recursive_basic() { -// let mut args = Vec::::new(); -// parse_shebang_recursive::( -// RecursiveParseOpts { -// split_arguments: true, -// ..RecursiveParseOpts::default() -// }, -// "#!/bin/B bparam".as_bytes(), -// |path| { -// Ok(match path.as_bytes() { -// b"/bin/B" => "#! /bin/A aparam1 aparam2".as_bytes(), -// b"/bin/A" => "not a shebang script".as_bytes(), -// _ => unreachable!("Unexpected path: {}", path.display()), -// }) -// }, -// |arg| { -// args.push(str::from_utf8(arg.as_bytes()).unwrap().to_owned()); -// Ok(()) -// }, -// ) -// .unwrap(); -// args.reverse(); -// assert_eq!( -// args, -// vec!["/bin/A", "aparam1", "aparam2", "/bin/B", "bparam"] -// ); -// } -// } - -#[cfg(test)] -mod tests { - use std::path::Path; - - use allocator_api2::alloc::Global; - - use super::*; - - fn parse(content: &[u8], options: ParseShebangOptions) -> nix::Result>> { - parse_shebang( - |_, buf| { - let len = content.len().min(buf.len()); - buf[..len].copy_from_slice(&content[..len]); - Ok(len) - }, - Path::new("/script"), - options, - Global, - ) - } - - fn script_with_interpreter_len(len: usize) -> (std::vec::Vec, std::vec::Vec) { - let interpreter = [b"/".as_slice(), &vec![b'x'; len - 1]].concat(); - let script = [b"#!".as_slice(), &interpreter, b"\necho hi\n"].concat(); - (script, interpreter) - } - - #[test] - fn keeps_interpreter_paths_longer_than_128_bytes() { - for options in [ParseShebangOptions::macos(), ParseShebangOptions::linux()] { - let (script, interpreter) = script_with_interpreter_len(200); - let shebang = parse(&script, options).unwrap().unwrap(); - assert_eq!(shebang.interpreter, interpreter.as_slice()); - } - } - - #[test] - fn macos_accepts_line_up_to_512_bytes() { - // "#!" + 509 bytes + "\n" is exactly 512 bytes. - let (script, interpreter) = script_with_interpreter_len(509); - let shebang = parse(&script, ParseShebangOptions::macos()).unwrap().unwrap(); - assert_eq!(shebang.interpreter, interpreter.as_slice()); - - let (script, _) = script_with_interpreter_len(510); - assert_eq!(parse(&script, ParseShebangOptions::macos()).unwrap_err(), nix::Error::ENOEXEC); - } - - #[test] - fn macos_requires_newline() { - let result = parse(b"#!/bin/sh", ParseShebangOptions::macos()); - assert_eq!(result.unwrap_err(), nix::Error::ENOEXEC); - } - - #[test] - fn macos_ends_line_at_hash() { - // The `#` is past the first 128 bytes and no newline follows within 512. - let script = - [b"#!/bin/sh -e ".as_slice(), &[b' '; 200], b"# comment", &[b'x'; 400]].concat(); - let shebang = parse(&script, ParseShebangOptions::macos()).unwrap().unwrap(); - assert_eq!(shebang.interpreter, b"/bin/sh"); - assert_eq!(shebang.arguments, [b"-e"]); - } - - #[test] - fn linux_accepts_line_up_to_256_bytes() { - // "#!" + 253 bytes + "\n" is exactly 256 bytes. - let (script, interpreter) = script_with_interpreter_len(253); - let shebang = parse(&script, ParseShebangOptions::linux()).unwrap().unwrap(); - assert_eq!(shebang.interpreter, interpreter.as_slice()); - - let (script, _) = script_with_interpreter_len(254); - assert_eq!(parse(&script, ParseShebangOptions::linux()).unwrap_err(), nix::Error::ENOEXEC); - } - - #[test] - fn linux_accepts_missing_newline_at_end_of_file() { - let shebang = parse(b"#!/bin/sh -e", ParseShebangOptions::linux()).unwrap().unwrap(); - assert_eq!(shebang.interpreter, b"/bin/sh"); - assert_eq!(shebang.arguments, [b"-e"]); - } - - #[test] - fn linux_accepts_space_in_last_byte() { - // "#!" + 253 bytes + " " fills the 256-byte buffer without a newline. - let interpreter = [b"/".as_slice(), &[b'x'; 252]].concat(); - let script = [b"#!".as_slice(), &interpreter, b" ", &[b'a'; 100]].concat(); - let shebang = parse(&script, ParseShebangOptions::linux()).unwrap().unwrap(); - assert_eq!(shebang.interpreter, interpreter.as_slice()); - assert!(shebang.arguments.is_empty()); - } - - #[test] - fn linux_refuses_truncated_interpreter() { - let (script, _) = script_with_interpreter_len(300); - assert_eq!(parse(&script, ParseShebangOptions::linux()).unwrap_err(), nix::Error::ENOEXEC); - } - - #[test] - fn linux_truncates_long_arguments() { - let script = [b"#!/bin/sh ".as_slice(), &[b'a'; 300], b"\n"].concat(); - let shebang = parse(&script, ParseShebangOptions::linux()).unwrap().unwrap(); - assert_eq!(shebang.interpreter, b"/bin/sh"); - // 256-byte buffer, minus "#!/bin/sh " and the reserved last byte. - assert_eq!(shebang.arguments, [[b'a'; 256 - 10 - 1]]); - } - - #[test] - fn missing_interpreter_is_an_error() { - for options in [ParseShebangOptions::macos(), ParseShebangOptions::linux()] { - assert_eq!(parse(b"#! \n", options).unwrap_err(), nix::Error::ENOEXEC); - } - } - - #[test] - fn not_a_script() { - assert!(parse(b"\x7fELF", ParseShebangOptions::default()).unwrap().is_none()); - } -} diff --git a/crates/fspy_shared_unix/src/exec/which.rs b/crates/fspy_shared_unix/src/exec/which.rs deleted file mode 100644 index 9f15f0725..000000000 --- a/crates/fspy_shared_unix/src/exec/which.rs +++ /dev/null @@ -1,135 +0,0 @@ -use allocator_api2::{alloc::Allocator, vec::Vec}; -use bstr::{BStr, ByteSlice}; - -use super::to_vec_in; - -const NAME_MAX: usize = 255; - -/// Search the executable in PATH, returning its path in `allocator`. -/// -/// Referenced musl Implementation: -/// -/// Difference from musl: -/// - Instead of actually calling execve, use `access_executable` to check if the file is executable, and return the found executable. -/// - The path limit (`PATH_MAX`) is not checked. -/// - PATH is passed as parameter instead of using the real environment variable. -pub fn which( - file: &BStr, - path: &BStr, - mut access_executable: impl FnMut(&BStr) -> nix::Result<()>, - allocator: A, -) -> nix::Result> { - use nix::Error; - // 1. If file is empty, return ENOENT - if file.is_empty() { - return Err(Error::ENOENT); - } - // 2. If file contains '/', return it directly - if file.contains(&b'/') { - return Ok(to_vec_in(file, allocator)); - } - // 3. If file is too long, return ENAMETOOLONG - if file.len() > NAME_MAX { - return Err(Error::ENAMETOOLONG); - } - // 4. Search PATH, building each candidate in the same buffer - let mut seen_eacces = false; - let mut last_err = Error::ENOENT; - let mut candidate = Vec::new_in(allocator); - for p in path.split(|ch| *ch == b':') { - candidate.clear(); - candidate.extend_from_slice(p); - // join with '/' if path is not empty - if !p.is_empty() { - candidate.push(b'/'); - } - candidate.extend_from_slice(file); - match access_executable(candidate.as_bstr()) { - Ok(()) => return Ok(candidate), - Err(err @ (Error::EACCES | Error::ENOENT | Error::ENOTDIR)) => { - if err == Error::EACCES { - seen_eacces = true; - } - last_err = err; - } - Err(other_err) => return Err(other_err), - } - } - Err(if seen_eacces { Error::EACCES } else { last_err }) -} - -#[cfg(test)] -mod tests { - use allocator_api2::alloc::Global; - use bstr::B; - - use super::*; - - fn mock_access<'a>( - allowed: &'a [&'a str], - fail_eacces: &'a [&'a str], - fail_enotdir: &'a [&'a str], - ) -> impl FnMut(&BStr) -> nix::Result<()> + 'a { - move |path| { - let s = std::str::from_utf8(path).unwrap(); - if allowed.contains(&s) { - Ok(()) - } else if fail_eacces.contains(&s) { - Err(nix::Error::EACCES) - } else if fail_enotdir.contains(&s) { - Err(nix::Error::ENOTDIR) - } else { - Err(nix::Error::ENOENT) - } - } - } - - /// (case, file, PATH, executable paths, EACCES paths, ENOTDIR paths, - /// the executable found or the error); any other path fails with ENOENT. - type WhichCase<'a> = ( - &'a str, - &'a [u8], - &'a str, - &'a [&'a str], - &'a [&'a str], - &'a [&'a str], - Result<&'a str, nix::Error>, - ); - - #[test] - fn test_which() { - let long_name = vec![b'a'; NAME_MAX + 1]; - let cases: &[WhichCase<'_>] = &[ - ("found", b"foo", "/bin:/usr/bin", &["/bin/foo"], &[], &[], Ok("/bin/foo")), - ("not found", b"foo", "/bin:/usr/bin", &[], &[], &[], Err(nix::Error::ENOENT)), - ( - "eacces", - b"foo", - "/bin:/usr/bin", - &[], - &["/bin/foo", "/usr/bin/foo"], - &[], - Err(nix::Error::EACCES), - ), - ("enotdir", b"foo", "/usr/bin:/bin", &[], &[], &["/bin/foo"], Err(nix::Error::ENOTDIR)), - ("slash in file", b"/usr/bin/foo", "", &["/usr/bin/foo"], &[], &[], Ok("/usr/bin/foo")), - ("empty file", b"", "/bin:/usr/bin", &[], &[], &[], Err(nix::Error::ENOENT)), - ( - "file too long", - &long_name, - "/bin:/usr/bin", - &[], - &[], - &[], - Err(nix::Error::ENAMETOOLONG), - ), - ("empty path entry", b"foo", ":/bin", &["foo"], &[], &[], Ok("foo")), - ]; - for &(case, file, path, executable, fail_eacces, fail_enotdir, expected) in cases { - let access = mock_access(executable, fail_eacces, fail_enotdir); - let res = which(B(file).as_bstr(), B(path).as_bstr(), access, Global) - .map(|found| found.as_bstr().to_owned()); - assert_eq!(res, expected.map(|found| B(found).as_bstr().to_owned()), "{case}"); - } - } -} diff --git a/crates/fspy_shared_unix/src/lib.rs b/crates/fspy_shared_unix/src/lib.rs index 5437a3efc..ec2f6719a 100644 --- a/crates/fspy_shared_unix/src/lib.rs +++ b/crates/fspy_shared_unix/src/lib.rs @@ -1,12 +1,11 @@ -#![cfg(unix)] +#![cfg(any(unix, target_os = "none"))] +#![cfg_attr(not(test), no_std)] -pub mod exec; -pub(crate) mod open_exec; -pub mod payload; -pub mod spawn; +mod codec; +#[cfg(any(target_os = "linux", target_os = "none"))] +pub mod linux; +#[cfg(target_os = "macos")] +pub mod macos; +mod nostd_exec; -#[cfg(target_os = "linux")] -mod elf; - -#[cfg(target_os = "linux")] // exposed for verifying static executables in fspy tests -pub use elf::is_dynamically_linked_to_libc; +pub use nostd_exec::{Env, Exec, RawExec}; diff --git a/crates/fspy_shared_unix/src/linux.rs b/crates/fspy_shared_unix/src/linux.rs new file mode 100644 index 000000000..865a782a3 --- /dev/null +++ b/crates/fspy_shared_unix/src/linux.rs @@ -0,0 +1,499 @@ +//! Linux exec resolution and bootstrap serialization shared between `fspy` and +//! `fspy_preload_linux`. + +use allocator_api2::{alloc::Allocator, vec::Vec}; +use bitflags::bitflags; +use bstr::BStr; +use fspy_nostd::{ + BorrowedFd, CStr, CWD, Error, OwnedFd, RawFd, Result, Thin, + fs::{ + AccessFlags, Mode, OFlags, faccessat, fcntl_dupfd_cloexec, fcntl_is_cloexec, fstat, openat, + }, +}; +use fspy_nostd_alloc::{ + CString, + fs::{fd_path, resolve_path_at}, +}; +use fspy_shared::ipc::{IpcStr, channel::ChannelConf}; +use wincode::{SchemaRead, SchemaWrite}; + +use crate::{ + codec::{decode_b64, encode_b64}, + nostd_exec::{ + Exec, + open::{open_executable, pread_header}, + shebang::{ + LINUX_MAX_LINE_LEN, LINUX_MAX_RECURSION, ParseShebangOptions, apply_shebang, + parse_shebang_bytes, + }, + to_vec_in, + }, +}; + +/// Environment variable carrying the base64-encoded [`Bootstrap`]. +/// +/// Passed from `fspy` (or a parent `fspy_preload_linux` process) into a fresh +/// `fspy_preload_linux` image, and stripped before entering the target. +pub const BOOTSTRAP_ENV_NAME: &str = "__FSPY_BOOTSTRAP"; + +bitflags! { + /// Flags accepted by Linux `execveat(2)` and [`resolve_exec`]. + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub struct ExecAtFlags: u32 { + /// Execute the file referred to by `dirfd` when `exec.program` is empty. + const EMPTY_PATH = linux_raw_sys::general::AT_EMPTY_PATH; + /// Refuse to follow a trailing symbolic link on the initial lookup. + const SYMLINK_NOFOLLOW = linux_raw_sys::general::AT_SYMLINK_NOFOLLOW; + } +} + +/// Output of [`resolve_exec`]: the open final binary descriptor and the +/// original execution name for `AT_EXECFN`. +pub struct ResolvedExec { + pub file: OwnedFd, + pub execfn: Vec, +} + +/// What the freshly exec'd `fspy_preload_linux` binary should load and run. +#[derive(Debug, SchemaWrite, SchemaRead)] +pub enum Target<'a> { + /// Initial spawn from `fspy`: `fspy_preload_linux` performs [`resolve_exec`] + /// and ELF validation itself, reporting the result errno (or `0`) over + /// `error_pipe_fd`. + Unresolved { path: &'a IpcStr, error_pipe_fd: RawFd }, + /// Child `execve`/`execveat` handed off as the already-validated open + /// descriptor, so the new image loads the exact file the call resolved. + /// `sigmask` is the calling thread's virtualized signal mask prior to exec. + ResolvedFd { fd: RawFd, execfn: &'a IpcStr, sigmask: u64 }, +} + +/// Bootstrap configuration passed into `fspy_preload_linux` via +/// [`BOOTSTRAP_ENV_NAME`]. +#[derive(Debug, SchemaWrite, SchemaRead)] +pub struct Bootstrap<'a> { + pub ipc_channel_conf: ChannelConf<'a>, + pub preload_path: &'a IpcStr, + pub target: Target<'a>, +} + +// Seals the view-only design: every borrowed field points into leaked storage. +const _: () = { + const fn assert_send_sync() {} + assert_send_sync::>(); +}; + +/// Serializes `bootstrap` into its unpadded base64 representation, leaked into +/// `allocator`. +/// +/// # Panics +/// +/// Panics if serialization or base64 encoding fails, which cannot happen for a +/// valid [`Bootstrap`]. +#[must_use] +pub fn encode_bootstrap<'a, A: Allocator + Clone + 'a>( + bootstrap: &Bootstrap<'_>, + allocator: A, +) -> &'a str { + encode_b64(bootstrap, allocator) +} + +impl<'a> Bootstrap<'a> { + /// Decodes the [`Bootstrap`] stored in [`BOOTSTRAP_ENV_NAME`] from `envs`, + /// leaking decoded backing bytes into `allocator`. + /// + /// # Panics + /// + /// Panics when [`BOOTSTRAP_ENV_NAME`] is missing, malformed base64, or + /// fails deserialization. + #[must_use] + pub fn from_env(envs: &[CStr<'_, Thin>], allocator: A) -> Self { + let prefix = BOOTSTRAP_ENV_NAME.as_bytes(); + let encoded = envs + .iter() + .find_map(|entry| { + let bytes = entry.count().as_units(); + bytes.strip_prefix(prefix).and_then(|rest| rest.strip_prefix(b"=")) + }) + .expect("environment variable '__FSPY_BOOTSTRAP' not found"); + + decode_b64(encoded, allocator).expect("invalid '__FSPY_BOOTSTRAP' payload") + } +} + +/// Ensures [`BOOTSTRAP_ENV_NAME`] is set to `encoded` on `envs`. +/// +/// # Errors +/// +/// Returns [`Error::INVAL`] if [`BOOTSTRAP_ENV_NAME`] is already present with a +/// different value. +pub fn ensure_bootstrap_env( + envs: &mut Vec, A>, + encoded: &str, +) -> Result<()> { + crate::nostd_exec::ensure_env(envs, BOOTSTRAP_ENV_NAME.as_bytes(), encoded.as_bytes()) +} + +/// Resolves a Linux `execve`/`execveat` target through optional `AT_EMPTY_PATH` +/// handling and recursive `#!` shebang expansion, reporting every read path via +/// `on_path_read`. +/// +/// On success, `exec.program` and `exec.args` reflect the final binary, and +/// [`ResolvedExec::file`] holds an open `O_CLOEXEC` descriptor to that binary +/// ready for ELF validation or loading. +/// +/// # Errors +/// +/// Returns Linux-compatible `errno` values: +/// - [`Error::NOENT`] for an empty pathname without [`ExecAtFlags::EMPTY_PATH`], +/// missing files, or `FD_CLOEXEC` script descriptors under `AT_EMPTY_PATH`. +/// - [`Error::BADF`] for an invalid or missing `dirfd`. +/// - [`Error::ACCES`] for non-regular files or files lacking execute permission. +/// - [`Error::LOOP`] for `AT_SYMLINK_NOFOLLOW` on a symlink or exceeding +/// `LINUX_MAX_RECURSION` (`5`) `#!` hops. +/// - [`Error::NOEXEC`] for malformed `#!` lines. +/// - [`Error::NOMEM`] if allocation fails. +pub fn resolve_exec( + exec: &mut Exec, + dirfd: Option>, + flags: ExecAtFlags, + mut on_path_read: impl FnMut(&BStr), +) -> Result> { + let allocator = exec.allocator().clone(); + let mut peek_buf = [0u8; LINUX_MAX_LINE_LEN]; + + let (execfn, mut depth, mut cur_dirfd, mut cur_nofollow) = if exec.program.is_empty() { + if !flags.contains(ExecAtFlags::EMPTY_PATH) { + return Err(Error::NOENT); + } + match resolve_empty_path(exec, dirfd, &mut peek_buf, &mut on_path_read)? { + EmptyPathStep::Resolved(resolved) => return Ok(resolved), + EmptyPathStep::Shebang { execfn } => (execfn, 1usize, Some(CWD), false), + } + } else { + let execfn = to_vec_in(&exec.program, allocator.clone()); + (execfn, 0usize, dirfd, flags.contains(ExecAtFlags::SYMLINK_NOFOLLOW)) + }; + + loop { + if exec.program.is_empty() { + return Err(Error::NOENT); + } + let is_abs = exec.program.starts_with(b"/"); + let c_path = bytes_to_cstring(&exec.program, allocator.clone())?; + + // Resolve absolute path for `on_path_read` and final-hop normalization. + // Tolerate `getcwd` failures (e.g. deleted cwd) so relative execs can + // still fall back to fd-backed handoff, matching kernel behavior. + let abs_path = + resolve_path_at(&allocator, cur_dirfd, c_path.as_c_str().as_thin()).ok().flatten(); + if let Some(resolved) = abs_path { + on_path_read(BStr::new(resolved.as_units())); + } + + let open_dirfd = if is_abs { CWD } else { cur_dirfd.ok_or(Error::BADF)? }; + let file = open_executable(open_dirfd, c_path.as_c_str().as_thin(), cur_nofollow)?; + let n = pread_header(file.as_fd(), &mut peek_buf)?; + + if let Some(shebang) = + parse_shebang_bytes(&peek_buf[..n], ParseShebangOptions::linux(), allocator.clone())? + { + depth += 1; + if depth > LINUX_MAX_RECURSION { + return Err(Error::LOOP); + } + drop(file); + + // Preserve relative path as `script_arg` when relative to CWD (matching + // kernel `execve`), or substitute the resolved path for non-CWD `dirfd`. + let script_arg = + if is_abs || cur_dirfd.is_some_and(|d| d.as_raw_fd() == CWD.as_raw_fd()) { + to_vec_in(&exec.program, allocator.clone()) + } else if let Some(resolved) = abs_path { + to_vec_in(resolved.as_units(), allocator.clone()) + } else { + to_vec_in(&exec.program, allocator.clone()) + }; + + apply_shebang(exec, shebang, script_arg); + cur_dirfd = Some(CWD); + cur_nofollow = false; + continue; + } + + return Ok(ResolvedExec { file, execfn }); + } +} + +enum EmptyPathStep { + Resolved(ResolvedExec), + Shebang { execfn: Vec }, +} + +fn resolve_empty_path( + exec: &mut Exec, + dirfd: Option>, + peek_buf: &mut [u8; LINUX_MAX_LINE_LEN], + on_path_read: &mut impl FnMut(&BStr), +) -> Result> { + let allocator = exec.allocator().clone(); + let Some(fd) = dirfd else { + return Err(Error::BADF); + }; + if !fstat(fd)?.is_regular_file() { + return Err(Error::ACCES); + } + let raw_fd = u32::try_from(fd.as_raw_fd()).map_err(|_| Error::BADF)?; + let mut proc_buf = [0u8; 32]; + let proc_fd = format_proc_self_fd(&mut proc_buf, raw_fd); + faccessat(CWD, proc_fd, AccessFlags::X_OK)?; + + let resolved_fd_path = fd_path(allocator.clone(), fd)?; + if let Some(ref p) = resolved_fd_path { + on_path_read(BStr::new(p.as_units())); + } + + let (file, n) = match pread_header(fd, peek_buf) { + Ok(n) => (fcntl_dupfd_cloexec(fd, 0)?, n), + Err(Error::BADF) => { + // `fd` may have been opened with `O_PATH`; reopen read-only via `/proc/self/fd`. + let reopened = openat( + CWD, + proc_fd, + OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NONBLOCK, + Mode::empty(), + )?; + let n = pread_header(reopened.as_fd(), peek_buf)?; + (reopened, n) + } + Err(err) => return Err(err), + }; + + let execfn = resolved_fd_path.map_or_else( + || format_dev_fd(raw_fd, allocator.clone()), + fspy_nostd_alloc::CString::into_units, + ); + + let Some(shebang) = + parse_shebang_bytes(&peek_buf[..n], ParseShebangOptions::linux(), allocator.clone())? + else { + return Ok(EmptyPathStep::Resolved(ResolvedExec { file, execfn })); + }; + + drop(file); + // Matches Linux `binfmt_script`: an `FD_CLOEXEC` script fd cannot be + // passed to the interpreter as `/dev/fd/`. + if fcntl_is_cloexec(fd)? { + return Err(Error::NOENT); + } + let script_arg = format_dev_fd(raw_fd, allocator); + apply_shebang(exec, shebang, script_arg); + Ok(EmptyPathStep::Shebang { execfn }) +} + +/// Checks whether a non-CWD `dirfd` refers to an unlinked directory whose +/// `/proc/self/fd/` symlink ends with ` (deleted)`, making its path +/// unopenable in the child `fspy_preload_linux` process. +fn bytes_to_cstring( + bytes: &[u8], + allocator: A, +) -> Result> { + let mut owned = Vec::new_in(allocator); + owned.try_reserve_exact(bytes.len() + 1).map_err(|_| Error::NOMEM)?; + owned.extend_from_slice(bytes); + owned.push(0); + CString::from_vec_with_nul(owned).ok_or(Error::NOENT) +} + +fn format_proc_self_fd(buf: &mut [u8; 32], fd: u32) -> CStr<'_, Thin> { + format_fd_with_prefix(buf, b"/proc/self/fd/", fd) +} + +fn format_fd_with_prefix<'a>(buf: &'a mut [u8; 32], prefix: &[u8], mut fd: u32) -> CStr<'a, Thin> { + let mut digits = [0u8; 10]; + let mut count = 0; + loop { + digits[count] = b'0' + (fd % 10) as u8; + count += 1; + fd /= 10; + if fd == 0 { + break; + } + } + let mut len = prefix.len(); + buf[..len].copy_from_slice(prefix); + for i in (0..count).rev() { + buf[len] = digits[i]; + len += 1; + } + buf[len] = 0; + // SAFETY: `buf` begins with a NUL-terminated ASCII string for lifetime `'a`. + unsafe { CStr::from_ptr(buf.as_ptr()) } +} + +fn format_dev_fd(fd: u32, allocator: A) -> Vec { + let mut buf = [0u8; 32]; + let cstr = format_fd_with_prefix(&mut buf, b"/dev/fd/", fd); + to_vec_in(cstr.count().as_units(), allocator) +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use std::{ + fs::{self, File, Permissions}, + os::unix::{ + ffi::OsStrExt as _, + fs::{PermissionsExt as _, symlink}, + io::AsRawFd as _, + }, + path::Path, + }; + + use allocator_api2::alloc::Global; + use fspy_shared::ipc::channel::channel; + + use super::*; + + fn write_exec(path: &Path, content: &[u8]) { + fs::write(path, content).unwrap(); + fs::set_permissions(path, Permissions::from_mode(0o755)).unwrap(); + } + + fn make_exec(prog: &[u8], args: &[&[u8]]) -> Exec { + let mut a = Vec::new_in(Global); + for arg in args { + a.push(to_vec_in(arg, Global)); + } + Exec { program: to_vec_in(prog, Global), args: a, envs: Vec::new_in(Global) } + } + + #[test] + fn bootstrap_round_trips_all_target_variants() { + let receiver = channel(1 << 30, Global).unwrap(); + let preload = IpcStr::from_bytes(b"/tmp/fspy_preload"); + let target_path = IpcStr::from_bytes(b"/usr/bin/env"); + let execfn = IpcStr::from_bytes(b"env"); + + let cases = [ + Target::Unresolved { path: target_path, error_pipe_fd: 7 }, + Target::ResolvedFd { fd: 9, execfn, sigmask: 0x5678 }, + ]; + + for target in cases { + let bump = fspy_nostd_alloc::pooled_bump(); + let bootstrap = + Bootstrap { ipc_channel_conf: receiver.conf(), preload_path: preload, target }; + let encoded = encode_bootstrap(&bootstrap, &bump); + + let mut env_bytes = std::vec::Vec::new(); + env_bytes.extend_from_slice(BOOTSTRAP_ENV_NAME.as_bytes()); + env_bytes.push(b'='); + env_bytes.extend_from_slice(encoded.as_bytes()); + env_bytes.push(0); + let other = b"PATH=/usr/bin\0"; + // SAFETY: both slices are NUL-terminated for the duration of `from_env`. + let envs = unsafe { + [CStr::::from_ptr(other.as_ptr()), CStr::::from_ptr(env_bytes.as_ptr())] + }; + + let decoded = Bootstrap::from_env(&envs, &bump); + assert_eq!(decoded.preload_path.as_bytes(), b"/tmp/fspy_preload"); + match (&bootstrap.target, &decoded.target) { + ( + Target::Unresolved { path: p1, error_pipe_fd: f1 }, + Target::Unresolved { path: p2, error_pipe_fd: f2 }, + ) => { + assert_eq!(p1.as_bytes(), p2.as_bytes()); + assert_eq!(f1, f2); + } + ( + Target::ResolvedFd { fd: f1, execfn: e1, sigmask: m1 }, + Target::ResolvedFd { fd: f2, execfn: e2, sigmask: m2 }, + ) => { + assert_eq!(f1, f2); + assert_eq!(e1.as_bytes(), e2.as_bytes()); + assert_eq!(m1, m2); + } + _ => panic!("mismatched target variant"), + } + } + } + + #[test] + fn resolve_exec_handles_chained_shebangs_and_loop_limit() { + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("bin"); + write_exec(&bin, b"\x7fELFnot-a-script"); + + // Chain of 5 shebangs -> bin (allowed: depth 5 <= LINUX_MAX_RECURSION). + let s5 = dir.path().join("s5"); + let s4 = dir.path().join("s4"); + let s3 = dir.path().join("s3"); + let s2 = dir.path().join("s2"); + let s1 = dir.path().join("s1"); + let s0 = dir.path().join("s0"); + write_exec(&s5, format!("#!{} a5\n", bin.display()).as_bytes()); + write_exec(&s4, format!("#!{} a4\n", s5.display()).as_bytes()); + write_exec(&s3, format!("#!{} a3\n", s4.display()).as_bytes()); + write_exec(&s2, format!("#!{} a2\n", s3.display()).as_bytes()); + write_exec(&s1, format!("#!{} a1\n", s2.display()).as_bytes()); + write_exec(&s0, format!("#!{} a0\n", s1.display()).as_bytes()); + + let mut seen = std::vec::Vec::new(); + let mut exec = make_exec(s1.as_os_str().as_bytes(), &[b"orig0", b"user"]); + let resolved = + resolve_exec(&mut exec, Some(CWD), ExecAtFlags::empty(), |p| seen.push(p.to_vec())) + .unwrap(); + assert_eq!(resolved.execfn.as_slice(), s1.as_os_str().as_bytes()); + assert_eq!(exec.program.as_slice(), bin.as_os_str().as_bytes()); + assert_eq!(seen.len(), 6); + + // Chain of 6 shebangs exceeds LINUX_MAX_RECURSION -> ELOOP. + let mut exec = make_exec(s0.as_os_str().as_bytes(), &[b"orig0"]); + let err = resolve_exec(&mut exec, Some(CWD), ExecAtFlags::empty(), |_| {}).err().unwrap(); + assert_eq!(err, Error::LOOP); + } + + #[test] + fn resolve_exec_handles_empty_path_and_nofollow() { + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("bin"); + write_exec(&bin, b"\x7fELFdummy"); + let link = dir.path().join("link"); + symlink(&bin, &link).unwrap(); + + // Empty path without EMPTY_PATH -> ENOENT without reading anything. + let mut reads = 0usize; + let mut exec = make_exec(b"", &[]); + assert_eq!( + resolve_exec(&mut exec, Some(CWD), ExecAtFlags::empty(), |_| reads += 1).err(), + Some(Error::NOENT) + ); + assert_eq!(reads, 0); + + // SYMLINK_NOFOLLOW on symlink -> ELOOP. + let mut exec = make_exec(link.as_os_str().as_bytes(), &[b"link"]); + assert_eq!( + resolve_exec(&mut exec, Some(CWD), ExecAtFlags::SYMLINK_NOFOLLOW, |_| {}).err(), + Some(Error::LOOP) + ); + + // AT_EMPTY_PATH on open executable fd resolves. + let file = File::open(&bin).unwrap(); + // SAFETY: `file` remains open for the call. + let fd = unsafe { BorrowedFd::borrow_raw(file.as_raw_fd()) }; + let mut exec = make_exec(b"", &[b"bin"]); + assert!(resolve_exec(&mut exec, Some(fd), ExecAtFlags::EMPTY_PATH, |_| {}).is_ok()); + + // AT_EMPTY_PATH on CLOEXEC shebang script -> ENOENT. + let script = dir.path().join("script.sh"); + write_exec(&script, format!("#!{}\n", bin.display()).as_bytes()); + let script_file = File::open(&script).unwrap(); // Rust opens with O_CLOEXEC. + // SAFETY: `script_file` remains open for the call. + let script_fd = unsafe { BorrowedFd::borrow_raw(script_file.as_raw_fd()) }; + let mut exec = make_exec(b"", &[]); + assert_eq!( + resolve_exec(&mut exec, Some(script_fd), ExecAtFlags::EMPTY_PATH, |_| {}).err(), + Some(Error::NOENT) + ); + } +} diff --git a/crates/fspy_shared_unix/src/macos.rs b/crates/fspy_shared_unix/src/macos.rs new file mode 100644 index 000000000..73cf5fb71 --- /dev/null +++ b/crates/fspy_shared_unix/src/macos.rs @@ -0,0 +1,306 @@ +//! macOS payload serialization and exec preparation shared between `fspy` and +//! `fspy_preload_macos`. + +use allocator_api2::{alloc::Allocator, vec::Vec}; +use bstr::BStr; +use fspy_nostd::{CWD, Error, Result}; +use fspy_nostd_alloc::CString; +use fspy_shared::ipc::{IpcStr, channel::ChannelConf}; +use phf::{Set, phf_set}; +use wincode::{SchemaRead, SchemaWrite}; + +use crate::{ + codec::{decode_b64, encode_b64}, + nostd_exec::{ + Exec, append_path_env, ensure_env, + open::{absolute_relative, open_executable, pread_header}, + shebang::{ + MACOS_MAX_LINE_LEN, MACOS_MAX_RECURSION, ParseShebangOptions, apply_shebang, + parse_shebang_bytes, + }, + to_vec_in, + }, +}; + +const PAYLOAD_ENV_NAME: &str = "FSPY_PAYLOAD"; +const DYLD_INSERT_LIBRARIES: &[u8] = b"DYLD_INSERT_LIBRARIES"; + +/// Configuration transferred from `fspy` to `fspy_preload_macos` via the +/// process environment. +#[derive(Debug, SchemaWrite, SchemaRead)] +pub struct Payload<'a> { + pub ipc_channel_conf: ChannelConf<'a>, + pub preload_path: &'a IpcStr, + pub bash_path: &'a IpcStr, + pub coreutils_path: &'a IpcStr, +} + +/// An opaque encoded macOS payload ready to inspect or forward to children. +pub struct EncodedPayload<'a> { + payload: Payload<'a>, + encoded_string: &'a str, +} + +// Seals the view-only design: every field borrows leaked bytes. +const _: () = { + const fn assert_send_sync() {} + assert_send_sync::>(); +}; + +impl<'a> EncodedPayload<'a> { + /// Encodes `payload` into its unpadded base64 form, leaking the encoded + /// string into `allocator`. + /// + /// # Panics + /// + /// Panics if serialization or base64 encoding fails. + #[must_use] + pub fn encode(payload: Payload<'a>, allocator: A) -> Self { + let encoded_string = encode_b64(&payload, allocator); + Self { payload, encoded_string } + } + + /// Decodes the macOS payload from an iterator over environment entries, + /// leaking its backing bytes into `allocator`. + /// + /// Copies the encoded value out of the environment before decoding so it + /// never borrows mutable `environ` storage. + /// + /// # Panics + /// + /// Panics when `FSPY_PAYLOAD` is missing, malformed base64, or fails + /// deserialization. + #[must_use] + pub fn from_env( + mut envs: impl Iterator, + allocator: A, + ) -> Self { + let encoded_string: &'a str = envs + .find_map(|(name, value)| { + if AsRef::<[u8]>::as_ref(name) == PAYLOAD_ENV_NAME.as_bytes() { + value.map(|value| { + let copied = to_vec_in(value.as_units(), allocator.clone()); + let leaked: &'a [u8] = copied.leak(); + core::str::from_utf8(leaked).expect("FSPY_PAYLOAD is not valid UTF-8") + }) + } else { + None + } + }) + .expect("environment variable 'FSPY_PAYLOAD' not found"); + + let payload = decode_b64(encoded_string.as_bytes(), allocator) + .expect("invalid 'FSPY_PAYLOAD' payload"); + Self { payload, encoded_string } + } + + /// Returns the shared-memory IPC channel configuration. + #[must_use] + pub const fn ipc_channel_conf(&self) -> ChannelConf<'a> { + self.payload.ipc_channel_conf + } + + /// Resolves shebangs, reports every read path, swaps SIP-protected + /// `/bin`/`/usr/bin` utilities for bundled equivalents, and configures + /// `DYLD_INSERT_LIBRARIES` + `FSPY_PAYLOAD` on `exec`. + /// + /// # Errors + /// + /// Returns OS-compatible `errno` values on empty program (`ENOENT`), + /// inaccessible or non-regular executables (`ENOENT`/`EACCES`), malformed + /// or nested shebangs (`ENOEXEC`), or conflicting `FSPY_PAYLOAD` values + /// (`EINVAL`). + pub fn prepare_exec( + &self, + exec: &mut Exec, + mut on_path_read: impl FnMut(&BStr), + ) -> Result<()> { + if exec.program.is_empty() { + return Err(Error::NOENT); + } + + let allocator = exec.allocator().clone(); + let mut peek_buf = [0u8; MACOS_MAX_LINE_LEN]; + let mut depth = 0usize; + + loop { + if exec.program.is_empty() { + return Err(Error::NOENT); + } + if exec.program.starts_with(b"/") { + on_path_read(BStr::new(&exec.program)); + } else { + let abs = absolute_relative(&exec.program, allocator.clone())?; + on_path_read(BStr::new(&abs)); + } + + let c_path = bytes_to_cstring(&exec.program, allocator.clone())?; + let file = open_executable(CWD, c_path.as_c_str().as_thin(), false)?; + let n = pread_header(file.as_fd(), &mut peek_buf)?; + drop(file); + + if let Some(shebang) = parse_shebang_bytes( + &peek_buf[..n], + ParseShebangOptions::macos(), + allocator.clone(), + )? { + depth += 1; + if depth > MACOS_MAX_RECURSION { + return Err(Error::NOEXEC); + } + let script_arg = to_vec_in(&exec.program, allocator.clone()); + apply_shebang(exec, shebang, script_arg); + continue; + } + break; + } + + if !exec.program.starts_with(b"/") { + exec.program = absolute_relative(&exec.program, allocator.clone())?; + } + + let injectable = match sip_bin_file_name(&exec.program) { + Some(file_name) => { + if matches!(file_name, b"sh" | b"bash") { + exec.program = to_vec_in(self.payload.bash_path.as_bytes(), allocator); + true + } else if COREUTILS_FUNCTIONS_FOR_TEST.contains(file_name) { + exec.program = to_vec_in(self.payload.coreutils_path.as_bytes(), allocator); + true + } else { + false + } + } + _ => true, + }; + + if injectable { + append_path_env( + &mut exec.envs, + DYLD_INSERT_LIBRARIES, + self.payload.preload_path.as_bytes(), + ); + ensure_env( + &mut exec.envs, + PAYLOAD_ENV_NAME.as_bytes(), + self.encoded_string.as_bytes(), + )?; + } else { + exec.envs.retain(|(name, _)| { + name.as_slice() != DYLD_INSERT_LIBRARIES + && name.as_slice() != PAYLOAD_ENV_NAME.as_bytes() + }); + } + + Ok(()) + } +} + +fn bytes_to_cstring( + bytes: &[u8], + allocator: A, +) -> Result> { + let mut owned = Vec::new_in(allocator); + owned.try_reserve_exact(bytes.len() + 1).map_err(|_| Error::NOMEM)?; + owned.extend_from_slice(bytes); + owned.push(0); + CString::from_vec_with_nul(owned).ok_or(Error::NOENT) +} + +/// Returns the file name of an absolute `path` directly inside `/bin` or +/// `/usr/bin`. Like `Path::parent`, empty and `.` components are ignored, +/// while `..` is kept as written. +fn sip_bin_file_name(path: &[u8]) -> Option<&[u8]> { + let rest = path.strip_prefix(b"/")?; + let mut parts: [&[u8]; 3] = [&[]; 3]; + let mut count = 0; + for part in rest.split(|&b| b == b'/').filter(|part| !matches!(*part, b"" | b".")) { + *parts.get_mut(count)? = part; + count += 1; + } + match parts[..count] { + [b"bin", file_name] | [b"usr", b"bin", file_name] => Some(file_name), + _ => None, + } +} + +#[doc(hidden)] +pub static COREUTILS_FUNCTIONS_FOR_TEST: Set<&'static [u8]> = phf_set! { + b"[", b"arch", b"b2sum", b"base32", b"base64", b"basename", b"basenc", b"cat", + b"chgrp", b"chmod", b"chown", b"chroot", b"cksum", b"comm", b"cp", b"csplit", + b"cut", b"date", b"dd", b"df", b"dir", b"dircolors", b"dirname", b"du", b"echo", + b"env", b"expand", b"expr", b"factor", b"false", b"fmt", b"fold", b"groups", + b"hashsum", b"head", b"hostid", b"hostname", b"id", b"install", b"join", b"kill", + b"link", b"ln", b"logname", b"ls", b"md5sum", b"mkdir", b"mkfifo", b"mknod", + b"mktemp", b"more", b"mv", b"nice", b"nl", b"nohup", b"nproc", b"numfmt", b"od", + b"paste", b"pathchk", b"pinky", b"pr", b"printenv", b"printf", b"ptx", b"pwd", + b"readlink", b"realpath", b"rm", b"rmdir", b"seq", b"sha1sum", b"sha224sum", + b"sha256sum", b"sha384sum", b"sha512sum", b"shred", b"shuf", b"sleep", b"sort", + b"split", b"stat", b"stdbuf", b"stty", b"sum", b"sync", b"tac", b"tail", b"tee", + b"test", b"timeout", b"touch", b"tr", b"true", b"truncate", b"tsort", b"tty", + b"uname", b"unexpand", b"uniq", b"unlink", b"uptime", b"users", b"vdir", b"wc", + b"who", b"whoami", b"yes" +}; + +#[cfg(test)] +mod tests { + use super::sip_bin_file_name; + + #[test] + fn finds_files_directly_in_sip_bin_dirs() { + for (path, expected) in [ + (&b"/bin/sh"[..], Some(&b"sh"[..])), + (b"/usr/bin/cat", Some(b"cat")), + (b"/bin//sh", Some(b"sh")), + (b"/bin/./sh", Some(b"sh")), + (b"/./usr/bin/./cat/", Some(b"cat")), + (b"/bin/../bin/sh", None), + (b"/usr/local/bin/sh", None), + (b"/foo", None), + (b"/", None), + (b"bin/sh", None), + ] { + assert_eq!(sip_bin_file_name(path), expected, "{}", path.escape_ascii()); + } + } + + #[cfg(target_os = "macos")] + #[test] + fn nested_shebang_returns_enoexec_matching_xnu() { + use std::{ + fs::{self, Permissions}, + os::unix::{ffi::OsStrExt as _, fs::PermissionsExt as _}, + }; + + use allocator_api2::alloc::Global; + use fspy_shared::ipc::{IpcStr, channel::channel}; + + use super::{EncodedPayload, Payload}; + use crate::nostd_exec::{Exec, to_vec_in}; + + let dir = tempfile::tempdir().unwrap(); + let inner = dir.path().join("inner.sh"); + let outer = dir.path().join("outer.sh"); + fs::write(&inner, b"#!/bin/sh\necho inner\n").unwrap(); + fs::set_permissions(&inner, Permissions::from_mode(0o755)).unwrap(); + fs::write(&outer, format!("#!{}\n", inner.display())).unwrap(); + fs::set_permissions(&outer, Permissions::from_mode(0o755)).unwrap(); + + let receiver = channel(1 << 30, Global).unwrap(); + let payload = EncodedPayload::encode( + Payload { + ipc_channel_conf: receiver.conf(), + preload_path: IpcStr::from_bytes(b"/tmp/preload.dylib"), + bash_path: IpcStr::from_bytes(b"/tmp/bash"), + coreutils_path: IpcStr::from_bytes(b"/tmp/coreutils"), + }, + Global, + ); + let mut exec = Exec { + program: to_vec_in(outer.as_os_str().as_bytes(), Global), + args: allocator_api2::vec::Vec::new_in(Global), + envs: allocator_api2::vec::Vec::new_in(Global), + }; + assert_eq!(payload.prepare_exec(&mut exec, |_| {}).unwrap_err(), fspy_nostd::Error::NOEXEC); + } +} diff --git a/crates/fspy_shared_unix/src/nostd_exec/mod.rs b/crates/fspy_shared_unix/src/nostd_exec/mod.rs new file mode 100644 index 000000000..c7b546837 --- /dev/null +++ b/crates/fspy_shared_unix/src/nostd_exec/mod.rs @@ -0,0 +1,290 @@ +pub mod open; +pub mod shebang; + +use core::{ffi::c_char, ptr::null}; + +use allocator_api2::{alloc::Allocator, vec::Vec}; +use bstr::ByteSlice as _; +use fspy_nostd::{CStr, Error, Result, Thin}; + +/// An environment entry: `(name, value)`. `value` is `None` when the entry in +/// `environ` does not contain a `=` byte. +pub type Env = (Vec, Option>); + +/// Copies `bytes` into a `Vec` in `allocator`. +pub fn to_vec_in(bytes: &[u8], allocator: A) -> Vec { + let mut vec = Vec::with_capacity_in(bytes.len(), allocator); + vec.extend_from_slice(bytes); + vec +} + +/// An exec call's program, arguments, and environment. +/// +/// The strings live in `A`, so preloads and signal handlers can keep them in a +/// per-call bump allocator rather than libc's heap: exec may run in the child +/// of `fork()` or inside a `SIGSYS` handler, where malloc is unsafe. +#[derive(Debug)] +pub struct Exec { + pub program: Vec, + pub args: Vec, A>, + pub envs: Vec, A>, +} + +impl Exec { + /// Returns the allocator the strings live in. + #[must_use] + pub fn allocator(&self) -> &A { + self.args.allocator() + } +} + +/// Raw C pointers for an `execve`-family invocation. +#[derive(Clone, Copy)] +pub struct RawExec { + pub prog: *const c_char, + pub argv: *const *const c_char, + pub envp: *const *const c_char, +} + +impl RawExec { + unsafe fn collect_c_str_array( + strs: *const *const c_char, + allocator: A, + mut map_fn: impl FnMut(&[u8]) -> T, + ) -> Result> { + if strs.is_null() { + return Ok(Vec::new_in(allocator)); + } + + let mut count = 0usize; + let mut cur_str = strs; + // SAFETY: `cur_str` points into a valid NULL-terminated array of C + // string pointers (the `argv`/`envp` convention). + while !(unsafe { *cur_str }).is_null() { + count += 1; + // SAFETY: advancing within the bounds of the NULL-terminated array. + cur_str = unsafe { cur_str.add(1) }; + } + + let mut str_vec = Vec::new_in(allocator); + str_vec.try_reserve_exact(count).map_err(|_| Error::NOMEM)?; + for i in 0..count { + // SAFETY: `i < count`, so `strs.add(i)` is within the pointer array. + let entry_ptr = unsafe { *strs.add(i) }; + // SAFETY: `entry_ptr` is non-null (verified by the counting loop) and + // points to a valid NUL-terminated C string. + let bytes = unsafe { CStr::::from_ptr(entry_ptr.cast()) }.count().as_units(); + str_vec.push(map_fn(bytes)); + } + Ok(str_vec) + } + + /// NUL-terminates `s` and leaks it into its allocator. + fn into_c_str(mut s: Vec) -> *const c_char { + s.push(0); + s.leak().as_ptr().cast() + } + + /// Builds a NULL-terminated array of C strings, leaked into the strings' + /// allocator. + fn into_c_str_array(strs: Vec, A>) -> *const *const c_char { + let mut ptrs = Vec::with_capacity_in(strs.len() + 1, strs.allocator().clone()); + ptrs.extend(strs.into_iter().map(Self::into_c_str)); + ptrs.push(null()); + ptrs.leak().as_ptr() + } + + /// Copies the raw exec arguments into `allocator`. + /// + /// Returns [`Error::FAULT`] when `prog` is null. Null `argv` or `envp` + /// arrays are treated as empty, matching Linux `execve` semantics. + /// + /// # Errors + /// + /// Returns [`Error::FAULT`] if `prog` is null, or [`Error::NOMEM`] if + /// storage cannot be allocated. + /// + /// # Safety + /// + /// When non-null, `prog` must point to a valid NUL-terminated C string, and + /// `argv` and `envp` must each point to a readable, NULL-terminated array + /// of valid C string pointers. + pub unsafe fn to_exec(self, allocator: A) -> Result> { + if self.prog.is_null() { + return Err(Error::FAULT); + } + + // SAFETY: `self.prog` is non-null and points to a valid NUL-terminated + // C string, as required by the caller. + let prog_bytes = unsafe { CStr::::from_ptr(self.prog.cast()) }.count().as_units(); + let program = to_vec_in(prog_bytes, allocator.clone()); + + // SAFETY: `self.argv` is null or a valid NULL-terminated array of C + // string pointers. + let args = unsafe { + Self::collect_c_str_array(self.argv, allocator.clone(), |arg| { + to_vec_in(arg, allocator.clone()) + }) + }?; + + // SAFETY: `self.envp` is null or a valid NULL-terminated array of C + // string pointers. + let envs = unsafe { + Self::collect_c_str_array(self.envp, allocator.clone(), |env| { + env.iter().position(|b| *b == b'=').map_or_else( + || (to_vec_in(env, allocator.clone()), None), + |eq_pos| { + ( + to_vec_in(&env[..eq_pos], allocator.clone()), + Some(to_vec_in(&env[(eq_pos + 1)..], allocator.clone())), + ) + }, + ) + }) + }?; + + Ok(Exec { program, args, envs }) + } + + /// Builds the C strings and pointer arrays for `cmd` in its allocator. + /// + /// They are leaked there rather than freed, so the pointers stay valid + /// until the allocator itself goes away (typically a per-call bump). + #[must_use] + pub fn from_exec(cmd: Exec) -> Self { + let mut envs = Vec::with_capacity_in(cmd.envs.len(), cmd.allocator().clone()); + for (name, value) in cmd.envs { + let mut env = name; + if let Some(value) = value { + env.push(b'='); + env.extend_from_slice(&value); + } + envs.push(env); + } + + Self { + prog: Self::into_c_str(cmd.program), + argv: Self::into_c_str_array(cmd.args), + envp: Self::into_c_str_array(envs), + } + } +} + +/// Ensures an environment variable is set to `value`. +/// +/// If absent, it is inserted. If present with the same value, no change is +/// made. If present with a different value (or without `=`), returns +/// [`Error::INVAL`]. +/// +/// # Errors +/// +/// Returns [`Error::INVAL`] when `name` already exists with a different value. +pub fn ensure_env( + envs: &mut Vec, A>, + name: &[u8], + value: &[u8], +) -> Result<()> { + if let Some((_, existing_value)) = envs.iter().find(|(n, _)| n.as_bstr() == name) { + return match existing_value.as_deref() { + Some(existing) if existing == value => Ok(()), + _ => Err(Error::INVAL), + }; + } + let allocator = envs.allocator().clone(); + envs.push((to_vec_in(name, allocator.clone()), Some(to_vec_in(value, allocator)))); + Ok(()) +} + +/// Ensures `value` is the trailing colon-separated entry of env var `name`. +#[cfg_attr( + not(any(target_os = "macos", test)), + expect(dead_code, reason = "used by macOS DYLD_INSERT_LIBRARIES injection") +)] +pub fn append_path_env(envs: &mut Vec, A>, name: &[u8], value: &[u8]) { + let allocator = envs.allocator().clone(); + if let Some(entry) = envs.iter_mut().find(|(n, _)| n.as_bstr() == name) { + let existing: &[u8] = entry.1.as_deref().unwrap_or_default(); + let already_last = existing == value + || (existing.len() > value.len() + && existing.ends_with(value) + && existing[existing.len() - value.len() - 1] == b':'); + if already_last { + return; + } + let mut new_value = Vec::with_capacity_in(existing.len() + 1 + value.len(), allocator); + if !existing.is_empty() { + new_value.extend_from_slice(existing); + new_value.push(b':'); + } + new_value.extend_from_slice(value); + entry.1 = Some(new_value); + } else { + envs.push((to_vec_in(name, allocator.clone()), Some(to_vec_in(value, allocator)))); + } +} + +#[cfg(test)] +mod tests { + use core::ptr; + + use allocator_api2::alloc::Global; + + use super::*; + + #[test] + fn raw_exec_rejects_null_prog_and_accepts_null_argv_envp() { + let raw_null = RawExec { prog: ptr::null(), argv: ptr::null(), envp: ptr::null() }; + // SAFETY: `to_exec` explicitly checks for null `prog`, `argv`, and `envp`. + assert_eq!(unsafe { raw_null.to_exec(Global) }.unwrap_err(), Error::FAULT); + + let raw_empty = + RawExec { prog: c"/bin/true".as_ptr(), argv: ptr::null(), envp: ptr::null() }; + // SAFETY: `prog` is a valid static C string and `argv`/`envp` are null. + let exec = unsafe { raw_empty.to_exec(Global) }.unwrap(); + assert_eq!(exec.program.as_slice(), b"/bin/true"); + assert!(exec.args.is_empty()); + assert!(exec.envs.is_empty()); + } + + #[test] + fn raw_exec_round_trips_program_args_and_envs() { + let bump = fspy_nostd_alloc::pooled_bump(); + let mut args = Vec::new_in(&bump); + args.push(to_vec_in(b"prog", &bump)); + args.push(to_vec_in(b"--flag", &bump)); + let mut envs = Vec::new_in(&bump); + envs.push((to_vec_in(b"K", &bump), Some(to_vec_in(b"V=1", &bump)))); + envs.push((to_vec_in(b"BARE", &bump), None)); + let exec = Exec { program: to_vec_in(b"/usr/bin/prog", &bump), args, envs }; + + let raw = RawExec::from_exec(exec); + // SAFETY: `raw` points into `bump`, which stays alive for this call. + let back = unsafe { raw.to_exec(Global) }.unwrap(); + assert_eq!(back.program.as_slice(), b"/usr/bin/prog"); + assert_eq!(back.args.len(), 2); + assert_eq!(back.args[0].as_slice(), b"prog"); + assert_eq!(back.args[1].as_slice(), b"--flag"); + assert_eq!(back.envs.len(), 2); + assert_eq!(back.envs[0].0.as_slice(), b"K"); + assert_eq!(back.envs[0].1.as_deref(), Some(b"V=1".as_slice())); + assert_eq!(back.envs[1].0.as_slice(), b"BARE"); + assert_eq!(back.envs[1].1, None); + } + + #[test] + fn append_path_env_preserves_order_and_is_idempotent() { + let mut envs: Vec, Global> = Vec::new_in(Global); + append_path_env(&mut envs, b"DYLD_INSERT_LIBRARIES", b"/a.dylib"); + assert_eq!(envs[0].1.as_deref(), Some(b"/a.dylib".as_slice())); + + append_path_env(&mut envs, b"DYLD_INSERT_LIBRARIES", b"/a.dylib"); + assert_eq!(envs[0].1.as_deref(), Some(b"/a.dylib".as_slice())); + + envs[0].1 = Some(to_vec_in(b"/user.dylib", Global)); + append_path_env(&mut envs, b"DYLD_INSERT_LIBRARIES", b"/a.dylib"); + assert_eq!(envs[0].1.as_deref(), Some(b"/user.dylib:/a.dylib".as_slice())); + + append_path_env(&mut envs, b"DYLD_INSERT_LIBRARIES", b"/a.dylib"); + assert_eq!(envs[0].1.as_deref(), Some(b"/user.dylib:/a.dylib".as_slice())); + } +} diff --git a/crates/fspy_shared_unix/src/nostd_exec/open.rs b/crates/fspy_shared_unix/src/nostd_exec/open.rs new file mode 100644 index 000000000..da9b4666a --- /dev/null +++ b/crates/fspy_shared_unix/src/nostd_exec/open.rs @@ -0,0 +1,92 @@ +use allocator_api2::{alloc::Allocator, vec::Vec}; +use fspy_nostd::{ + BorrowedFd, CStr, Error, OwnedFd, Result, Thin, + fs::{AccessFlags, Mode, OFlags, faccessat, fstat, openat}, + io::pread, +}; + +/// Opens an executable regular file relative to `dirfd` and checks `X_OK`. +/// +/// Opens with `O_RDONLY | O_CLOEXEC | O_NONBLOCK` (plus `O_NOFOLLOW` when +/// `nofollow` is `true`) so FIFOs do not block and symlinks fail with `ELOOP` +/// under `AT_SYMLINK_NOFOLLOW`. Non-regular files (such as directories or +/// FIFOs) are rejected with `EACCES`, matching kernel `execve`. +pub fn open_executable( + dirfd: BorrowedFd<'_>, + path: CStr<'_, Thin>, + nofollow: bool, +) -> Result { + let mut flags = OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NONBLOCK; + if nofollow { + flags |= OFlags::NOFOLLOW; + } + let fd = openat(dirfd, path, flags, Mode::empty())?; + if !fstat(fd.as_fd())?.is_regular_file() { + return Err(Error::ACCES); + } + faccessat(dirfd, path, AccessFlags::X_OK)?; + Ok(fd) +} + +/// Reads up to `buf.len()` bytes starting at offset 0 of `fd` without mutating +/// the descriptor's file offset. +pub fn pread_header(fd: BorrowedFd<'_>, buf: &mut [u8]) -> Result { + let mut total = 0usize; + while total < buf.len() { + match pread(fd, &mut buf[total..], total as u64) { + Ok(0) => break, + Ok(n) => total += n, + Err(Error::INTR) => {} + Err(err) => return Err(err), + } + } + Ok(total) +} + +/// Makes a relative `path` absolute against the current working directory, +/// matching `std::path::absolute` without touching `std` or libc malloc. +#[cfg_attr( + not(any(target_os = "macos", test)), + expect(dead_code, reason = "used by macOS path normalization and unit tests") +)] +pub fn absolute_relative(path: &[u8], allocator: A) -> Result> { + debug_assert!(!path.starts_with(b"/")); + if path.is_empty() { + return Err(Error::INVAL); + } + let mut abs = fspy_nostd_alloc::fs::getcwd(allocator)?.into_units(); + for segment in path.split(|&b| b == b'/') { + if segment.is_empty() || segment == b"." { + continue; + } + if abs.last() != Some(&b'/') { + abs.push(b'/'); + } + abs.extend_from_slice(segment); + } + if path.ends_with(b"/") && abs.last() != Some(&b'/') { + abs.push(b'/'); + } + Ok(abs) +} + +#[cfg(test)] +mod tests { + use std::{os::unix::ffi::OsStrExt as _, path::Path}; + + use allocator_api2::alloc::Global; + + use super::absolute_relative; + + #[test] + fn absolute_relative_matches_std() { + for path in ["foo", "./foo", "foo/./bar", "foo//bar", "../foo", "foo/", ".", "./", ""] { + let std_path = Path::new(path); + assert_eq!( + absolute_relative(path.as_bytes(), Global).ok().as_deref(), + std::path::absolute(std_path).ok().as_ref().map(|p| p.as_os_str().as_bytes()), + "{path}" + ); + } + } +} diff --git a/crates/fspy_shared_unix/src/nostd_exec/shebang.rs b/crates/fspy_shared_unix/src/nostd_exec/shebang.rs new file mode 100644 index 000000000..0c31856cf --- /dev/null +++ b/crates/fspy_shared_unix/src/nostd_exec/shebang.rs @@ -0,0 +1,276 @@ +use allocator_api2::{alloc::Allocator, vec::Vec}; +use bstr::ByteSlice as _; +use fspy_nostd::{Error, Result}; + +use super::{Exec, to_vec_in}; + +/// Maximum shebang recursion depth on Linux (`exec_binprm` allows 5 nested +/// `#!` hops and returns `ELOOP` on the 6th). +#[cfg_attr( + not(any(target_os = "linux", target_os = "none")), + expect(dead_code, reason = "used on Linux") +)] +pub const LINUX_MAX_RECURSION: usize = 5; + +/// Maximum shebang recursion depth on macOS (XNU allows 1 `#!` hop and +/// rejects a nested `#!` interpreter with `ENOEXEC`). +#[cfg_attr(not(target_os = "macos"), expect(dead_code, reason = "used on macOS"))] +pub const MACOS_MAX_RECURSION: usize = 1; + +/// Size of the buffer the macOS kernel reads the shebang line into (`IMG_SHSIZE`). +#[cfg_attr( + not(any(target_os = "macos", test)), + expect(dead_code, reason = "used on macOS and in cross-platform unit tests") +)] +pub const MACOS_MAX_LINE_LEN: usize = 512; + +/// Size of the buffer the Linux kernel reads the shebang line into (`BINPRM_BUF_SIZE`). +#[cfg_attr( + not(any(target_os = "linux", target_os = "none", test)), + expect(dead_code, reason = "used on Linux and in cross-platform unit tests") +)] +pub const LINUX_MAX_LINE_LEN: usize = 256; + +#[derive(Debug, Clone)] +pub struct Shebang { + pub interpreter: Vec, + pub arguments: Vec, A>, +} + +const fn is_whitespace(c: u8) -> bool { + c == b' ' || c == b'\t' +} + +const fn trim_sp_tab_start(mut bytes: &[u8]) -> &[u8] { + while let Some((&first, rest)) = bytes.split_first() { + if is_whitespace(first) { + bytes = rest; + } else { + break; + } + } + bytes +} + +const fn trim_sp_tab(mut bytes: &[u8]) -> &[u8] { + bytes = trim_sp_tab_start(bytes); + while let Some((&last, rest)) = bytes.split_last() { + if is_whitespace(last) { + bytes = rest; + } else { + break; + } + } + bytes +} + +#[derive(Clone, Copy, Debug)] +pub struct ParseShebangOptions { + pub split_arguments: bool, + /// How many bytes of the file the kernel reads to find the shebang line. + pub max_line_len: usize, + /// Whether the line must end within `max_line_len` bytes. + pub require_line_end: bool, + /// Whether `#` ends the line like a newline does (XNU `IS_EOL`). + pub hash_ends_line: bool, +} + +impl ParseShebangOptions { + #[cfg_attr( + not(any(target_os = "macos", test)), + expect(dead_code, reason = "used on macOS and in cross-platform unit tests") + )] + #[must_use] + pub const fn macos() -> Self { + Self { + split_arguments: true, + max_line_len: MACOS_MAX_LINE_LEN, + require_line_end: true, + hash_ends_line: true, + } + } + + #[cfg_attr( + not(any(target_os = "linux", target_os = "none", test)), + expect(dead_code, reason = "used on Linux and in cross-platform unit tests") + )] + #[must_use] + pub const fn linux() -> Self { + Self { + split_arguments: false, + max_line_len: LINUX_MAX_LINE_LEN, + require_line_end: false, + hash_ends_line: false, + } + } +} + +/// Parses the shebang line from an already-peeked file prefix (`buf.len() <= +/// options.max_line_len`), copying the interpreter and arguments into +/// `allocator`. +/// +/// Returns [`Error::NOEXEC`] where the kernel would refuse the script instead +/// of running a truncated interpreter path. +pub fn parse_shebang_bytes( + buf: &[u8], + options: ParseShebangOptions, + allocator: A, +) -> Result>> { + let Some(line) = buf.strip_prefix(b"#!") else { + return Ok(None); + }; + + let line_ends: &[u8] = if options.hash_ends_line { b"\n#\0" } else { b"\n\0" }; + let line = if let Some(line_end) = line.find_byteset(line_ends) { + &line[..line_end] + } else if options.require_line_end { + return Err(Error::NOEXEC); + } else if buf.len() < options.max_line_len { + // The whole file fits in the buffer, so nothing was cut off. + line + } else { + // https://github.com/torvalds/linux/blob/v6.12/fs/binfmt_script.c + // The interpreter path must be followed by a space or tab, or it may be + // cut off. Like the kernel, look for one in the whole buffer but keep + // its last byte as a terminator. + if !line.iter().skip_while(|ch| is_whitespace(**ch)).any(|ch| is_whitespace(*ch)) { + return Err(Error::NOEXEC); + } + &line[..line.len() - 1] + }; + + let line = trim_sp_tab(line); + let interpreter = line.split(|ch| is_whitespace(*ch)).next().unwrap_or_default(); + if interpreter.is_empty() { + return Err(Error::NOEXEC); + } + let arguments_buf = trim_sp_tab_start(&line[interpreter.len()..]).as_bstr(); + + let mut arguments = Vec::new_in(allocator.clone()); + if options.split_arguments { + arguments.extend(arguments_buf.split(|ch| is_whitespace(*ch)).filter_map(|arg| { + let arg = trim_sp_tab(arg); + if arg.is_empty() { None } else { Some(to_vec_in(arg, allocator.clone())) } + })); + } else if !arguments_buf.is_empty() { + arguments.push(to_vec_in(arguments_buf, allocator.clone())); + } + + Ok(Some(Shebang { interpreter: to_vec_in(interpreter, allocator), arguments })) +} + +/// Rewrites `exec` for a parsed `#!` hop, inserting `shebang.interpreter`, +/// `shebang.arguments`, and `script_arg` at the front of `exec.args`. +/// +/// Safely handles an empty `exec.args` without panicking. +pub fn apply_shebang( + exec: &mut Exec, + shebang: Shebang, + script_arg: Vec, +) { + let allocator = exec.allocator().clone(); + let tail_len = exec.args.len().saturating_sub(1); + let mut new_args = Vec::with_capacity_in(2 + shebang.arguments.len() + tail_len, allocator); + new_args.push(shebang.interpreter.clone()); + new_args.extend(shebang.arguments); + new_args.push(script_arg); + let old_args = core::mem::replace(&mut exec.args, new_args); + exec.args.extend(old_args.into_iter().skip(1)); + exec.program = shebang.interpreter; +} + +#[cfg(test)] +mod tests { + use allocator_api2::alloc::Global; + + use super::*; + + fn parse(content: &[u8], options: ParseShebangOptions) -> Result>> { + let len = content.len().min(options.max_line_len); + parse_shebang_bytes(&content[..len], options, Global) + } + + fn script_with_interpreter_len(len: usize) -> (std::vec::Vec, std::vec::Vec) { + let interpreter = [b"/".as_slice(), &vec![b'x'; len - 1]].concat(); + let script = [b"#!".as_slice(), &interpreter, b"\necho hi\n"].concat(); + (script, interpreter) + } + + #[test] + fn keeps_interpreter_paths_longer_than_128_bytes() { + for options in [ParseShebangOptions::macos(), ParseShebangOptions::linux()] { + let (script, interpreter) = script_with_interpreter_len(200); + let shebang = parse(&script, options).unwrap().unwrap(); + assert_eq!(shebang.interpreter, interpreter.as_slice()); + } + } + + #[test] + fn macos_and_linux_line_limits_and_delimiters() { + let (script, interpreter) = script_with_interpreter_len(509); + assert_eq!( + parse(&script, ParseShebangOptions::macos()).unwrap().unwrap().interpreter, + interpreter.as_slice() + ); + let (script, _) = script_with_interpreter_len(510); + assert_eq!(parse(&script, ParseShebangOptions::macos()).unwrap_err(), Error::NOEXEC); + assert_eq!(parse(b"#!/bin/sh", ParseShebangOptions::macos()).unwrap_err(), Error::NOEXEC); + + let (script, interpreter) = script_with_interpreter_len(253); + assert_eq!( + parse(&script, ParseShebangOptions::linux()).unwrap().unwrap().interpreter, + interpreter.as_slice() + ); + let (script, _) = script_with_interpreter_len(254); + assert_eq!(parse(&script, ParseShebangOptions::linux()).unwrap_err(), Error::NOEXEC); + assert_eq!( + parse(b"#!/bin/sh -e", ParseShebangOptions::linux()).unwrap().unwrap().arguments, + [b"-e"] + ); + assert_eq!(parse(b"#! \n", ParseShebangOptions::linux()).unwrap_err(), Error::NOEXEC); + assert!(parse(b"\x7fELF", ParseShebangOptions::linux()).unwrap().is_none()); + + // Linux & XNU stop at NUL and only trim space/tab (NOT `\r`). + let crlf = parse(b"#!/bin/sh\r\n", ParseShebangOptions::linux()).unwrap().unwrap(); + assert_eq!(crlf.interpreter.as_slice(), b"/bin/sh\r"); + let crlf_arg = parse(b"#!/bin/sh -e\r\n", ParseShebangOptions::linux()).unwrap().unwrap(); + assert_eq!(crlf_arg.interpreter.as_slice(), b"/bin/sh"); + assert_eq!(crlf_arg.arguments[0].as_slice(), b"-e\r"); + let nul = parse(b"#!/bin/sh\0ignored\n", ParseShebangOptions::linux()).unwrap().unwrap(); + assert_eq!(nul.interpreter.as_slice(), b"/bin/sh"); + } + + #[test] + fn apply_shebang_handles_empty_and_non_empty_args() { + let shebang = Shebang { + interpreter: to_vec_in(b"/bin/sh", Global), + arguments: { + let mut v = Vec::new_in(Global); + v.push(to_vec_in(b"-e", Global)); + v + }, + }; + let mut exec = Exec { + program: to_vec_in(b"/tmp/s.sh", Global), + args: Vec::new_in(Global), + envs: Vec::new_in(Global), + }; + apply_shebang(&mut exec, shebang.clone(), to_vec_in(b"/tmp/s.sh", Global)); + assert_eq!(exec.program.as_slice(), b"/bin/sh"); + assert_eq!( + exec.args.iter().map(Vec::as_slice).collect::>(), + vec![b"/bin/sh".as_slice(), b"-e", b"/tmp/s.sh"] + ); + + let mut args = Vec::new_in(Global); + args.push(to_vec_in(b"orig0", Global)); + args.push(to_vec_in(b"a1", Global)); + let mut exec = + Exec { program: to_vec_in(b"/tmp/s.sh", Global), args, envs: Vec::new_in(Global) }; + apply_shebang(&mut exec, shebang, to_vec_in(b"/tmp/s.sh", Global)); + assert_eq!( + exec.args.iter().map(Vec::as_slice).collect::>(), + vec![b"/bin/sh".as_slice(), b"-e", b"/tmp/s.sh", b"a1"] + ); + } +} diff --git a/crates/fspy_shared_unix/src/open_exec.rs b/crates/fspy_shared_unix/src/open_exec.rs deleted file mode 100644 index 24c5e6770..000000000 --- a/crates/fspy_shared_unix/src/open_exec.rs +++ /dev/null @@ -1,13 +0,0 @@ -use std::{os::fd::OwnedFd, path::Path}; - -use nix::{ - fcntl::{OFlag, open}, - sys::stat::Mode, - unistd::{AccessFlags, access}, -}; - -pub fn open_executable(path: impl AsRef) -> nix::Result { - let path = path.as_ref(); - access(path, AccessFlags::X_OK)?; - open(path, OFlag::O_RDONLY | OFlag::O_CLOEXEC, Mode::empty()) -} diff --git a/crates/fspy_shared_unix/src/payload.rs b/crates/fspy_shared_unix/src/payload.rs deleted file mode 100644 index 8276ba5ee..000000000 --- a/crates/fspy_shared_unix/src/payload.rs +++ /dev/null @@ -1,141 +0,0 @@ -use allocator_api2::alloc::Allocator; -use base64::{Engine as _, prelude::BASE64_STANDARD_NO_PAD}; -use bstr::BStr; -#[cfg(not(target_env = "musl"))] -use fspy_shared::ipc::IpcStr; -#[cfg(not(target_env = "musl"))] -use fspy_shared::ipc::channel::ChannelConf; -use wincode::{SchemaRead, SchemaWrite}; - -/// The payload as it travels between processes. -/// -/// A payload is a view: every path in it borrows from storage its producer -/// owns — the supervisor's session state, or the storage a -/// [`decode_payload_from_env`] caller supplies — so serializing one, and -/// deserializing one in the preload, allocates nothing for the borrowed -/// fields. -#[derive(Debug, SchemaWrite, SchemaRead)] -pub struct Payload<'a> { - #[cfg(not(target_env = "musl"))] - pub ipc_channel_conf: ChannelConf<'a>, - #[cfg(target_env = "musl")] - pub ipc_channel_conf: core::marker::PhantomData<&'a ()>, - - #[cfg(not(target_env = "musl"))] - pub preload_path: &'a IpcStr, - - #[cfg(target_os = "macos")] - pub artifacts: Artifacts<'a>, - - #[cfg(target_os = "linux")] - #[cfg_attr( - not(target_env = "musl"), - expect(clippy::struct_field_names, reason = "descriptive field name for clarity") - )] - pub seccomp_payload: fspy_seccomp_unotify::payload::SeccompPayload, -} - -#[cfg(target_os = "macos")] -#[derive(Debug, SchemaWrite, SchemaRead, Clone, Copy)] -pub struct Artifacts<'a> { - pub bash_path: &'a IpcStr, - pub coreutils_path: &'a IpcStr, -} - -pub(crate) const PAYLOAD_ENV_NAME: &str = "FSPY_PAYLOAD"; - -/// A payload together with its encoded form, for handing to child processes. -/// -/// Like [`Payload`], this is strictly a view: it lives as long as the -/// storage [`decode_payload_from_env`] allocated into. -pub struct EncodedPayload<'a> { - pub payload: Payload<'a>, - pub encoded_string: &'a BStr, -} - -// Seals the view-only design: every field is an inert borrow of leaked -// bytes. A retained allocator handle is interior-mutable and would fail -// this assertion. -const _: () = { - const fn assert_send_sync() {} - assert_send_sync::>(); -}; - -/// Encodes the payload into its base64 environment form and assembles the -/// [`EncodedPayload`] that travels to child processes. -/// -/// The serialization buffer is transient; the encoded string is leaked -/// into `allocator`, and `A: 'a` bounds the result's lifetime just as in -/// [`decode_payload_from_env`]. -/// -/// # Panics -/// -/// Panics if serialization fails, which should never happen for valid -/// [`Payload`] structs. -#[must_use] -pub fn encode_payload<'a, A: Allocator + Clone + 'a>( - payload: Payload<'a>, - allocator: A, -) -> EncodedPayload<'a> { - let serialized_size = usize::try_from(wincode::serialized_size(&payload).unwrap()) - .expect("serialized size exceeds usize"); - let mut buffer = allocator_api2::vec::Vec::with_capacity_in(serialized_size, allocator.clone()); - buffer.resize(serialized_size, 0); - let mut writer: &mut [u8] = &mut buffer; - wincode::serialize_into(&mut writer, &payload).unwrap(); - assert!(writer.is_empty(), "the payload wrote fewer bytes than the size it reported"); - - let encoded_len = - base64::encoded_len(serialized_size, false).expect("encoded payload length exceeds usize"); - let mut encoded = allocator_api2::vec::Vec::with_capacity_in(encoded_len, allocator); - encoded.resize(encoded_len, 0); - let written = BASE64_STANDARD_NO_PAD.encode_slice(&buffer, &mut encoded).unwrap(); - encoded.truncate(written); - EncodedPayload { payload, encoded_string: BStr::new(encoded.leak()) } -} - -/// Decodes the fspy payload from an iterator over environment entries. -/// -/// The returned payload borrows allocations that are leaked into -/// `allocator` and never individually freed. `A: 'a` bounds the payload's -/// lifetime: a borrowed bump yields a payload that dies with the borrow, -/// and a `'static` allocator yields a `'static` payload outright. -/// -/// The payload never borrows the process environment itself: the -/// environment is not stable storage (any `setenv` may move or rewrite it), -/// so the encoded value is copied out before it is used. -/// -/// # Errors -/// -/// Returns an error if the payload environment variable is missing, base64 -/// decoding fails, or deserialization fails. -pub fn decode_payload_from_env<'a, A: Allocator + Clone + 'a>( - mut envs: impl Iterator, - allocator: A, -) -> anyhow::Result> { - let Some(encoded_string) = envs.find_map(|(name, value)| { - if AsRef::<[u8]>::as_ref(name) == PAYLOAD_ENV_NAME.as_bytes() { - value.map(|value| { - let mut encoded = allocator_api2::vec::Vec::with_capacity_in( - value.as_units().len(), - allocator.clone(), - ); - encoded.extend_from_slice(value.as_units()); - BStr::new(encoded.leak()) - }) - } else { - None - } - }) else { - anyhow::bail!("Environment variable '{PAYLOAD_ENV_NAME}' not found"); - }; - - let decoded_len_estimate = base64::decoded_len_estimate(encoded_string.len()); - let mut buffer = allocator_api2::vec::Vec::with_capacity_in(decoded_len_estimate, allocator); - buffer.resize(decoded_len_estimate, 0); - let decoded_len = BASE64_STANDARD_NO_PAD.decode_slice(encoded_string, &mut buffer)?; - buffer.truncate(decoded_len); - let payload: Payload<'a> = wincode::deserialize_exact(buffer.leak())?; - - Ok(EncodedPayload { payload, encoded_string }) -} diff --git a/crates/fspy_shared_unix/src/spawn/linux/mod.rs b/crates/fspy_shared_unix/src/spawn/linux/mod.rs deleted file mode 100644 index bf610151b..000000000 --- a/crates/fspy_shared_unix/src/spawn/linux/mod.rs +++ /dev/null @@ -1,66 +0,0 @@ -#[cfg(not(target_env = "musl"))] -use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _, path::Path}; - -use allocator_api2::alloc::Allocator; -use fspy_seccomp_unotify::{payload::SeccompPayload, target::install_target}; -#[cfg(not(target_env = "musl"))] -use memmap2::Mmap; - -#[cfg(not(target_env = "musl"))] -use crate::{ - elf, - exec::{append_path_env, ensure_env}, - open_exec::open_executable, -}; -use crate::{ - exec::Exec, - payload::{EncodedPayload, PAYLOAD_ENV_NAME}, -}; - -const LD_PRELOAD: &str = "LD_PRELOAD"; - -pub struct PreExec(SeccompPayload); -impl PreExec { - /// Installs the seccomp unotify filter for the current process. - /// - /// # Errors - /// - /// Returns an error if the seccomp filter installation fails. - pub fn run(&self) -> nix::Result<()> { - install_target(&self.0) - } -} - -pub fn handle_exec( - command: &mut Exec, - encoded_payload: &EncodedPayload, -) -> nix::Result> { - // On musl targets, LD_PRELOAD is not available (cdylib not supported). - // Always use seccomp-based tracking instead. - #[cfg(not(target_env = "musl"))] - { - let executable_fd = open_executable(Path::new(OsStr::from_bytes(&command.program)))?; - // SAFETY: The file descriptor is valid and we only read from the mapping. - let executable_mmap = unsafe { Mmap::map(&executable_fd) }.map_err(|io_error| { - nix::Error::try_from(io_error).unwrap_or(nix::Error::UnknownErrno) - })?; - if elf::is_dynamically_linked_to_libc(executable_mmap)? { - // Append (don't overwrite) so a user-provided LD_PRELOAD keeps - // working. fspy's shim goes last so user preloads that - // short-circuit a libc call stay invisible to fspy — what the - // OS actually executed is what we want to record. - append_path_env( - &mut command.envs, - LD_PRELOAD, - encoded_payload.payload.preload_path.as_os_str().as_bytes(), - ); - ensure_env(&mut command.envs, PAYLOAD_ENV_NAME, encoded_payload.encoded_string)?; - return Ok(None); - } - } - - command - .envs - .retain(|(name, _)| name != LD_PRELOAD.as_bytes() && name != PAYLOAD_ENV_NAME.as_bytes()); - Ok(Some(PreExec(encoded_payload.payload.seccomp_payload.clone()))) -} diff --git a/crates/fspy_shared_unix/src/spawn/macos.rs b/crates/fspy_shared_unix/src/spawn/macos.rs deleted file mode 100644 index 214ac9774..000000000 --- a/crates/fspy_shared_unix/src/spawn/macos.rs +++ /dev/null @@ -1,99 +0,0 @@ -use std::{convert::Infallible, ffi::OsStr, os::unix::ffi::OsStrExt, path::Path}; - -use allocator_api2::alloc::Allocator; -use phf::{Set, phf_set}; - -use super::absolute; -use crate::{ - exec::{Exec, append_path_env, ensure_env, to_vec_in}, - payload::{EncodedPayload, PAYLOAD_ENV_NAME}, -}; - -pub struct PreExec(Infallible); -impl PreExec { - /// Runs pre-exec operations - /// - /// # Errors - /// - /// This function never returns an error as the type is `Infallible` - pub const fn run(&self) -> nix::Result<()> { - match self.0 {} - } -} - -pub fn handle_exec( - command: &mut Exec, - encoded_payload: &EncodedPayload, -) -> nix::Result> { - const DYLD_INSERT_LIBRARIES: &[u8] = b"DYLD_INSERT_LIBRARIES"; - - if command.program.first() != Some(&b'/') { - command.program = - absolute(Path::new(OsStr::from_bytes(&command.program)), command.allocator().clone()) - .expect("Failed to get absolute path"); - } - - let program_path = Path::new(OsStr::from_bytes(&command.program)); - - let injectable = if let (Some(parent), Some(file_name)) = - (program_path.parent(), program_path.file_name()) - { - if matches!(parent.as_os_str().as_bytes(), b"/bin" | b"/usr/bin") { - let artifacts = &encoded_payload.payload.artifacts; - if matches!(file_name.as_bytes(), b"sh" | b"bash") { - command.program = to_vec_in( - artifacts.bash_path.as_os_str().as_bytes(), - command.allocator().clone(), - ); - true - } else if COREUTILS_FUNCTIONS.contains(file_name.as_bytes()) { - command.program = to_vec_in( - artifacts.coreutils_path.as_os_str().as_bytes(), - command.allocator().clone(), - ); - true - } else { - false - } - } else { - true - } - } else { - true - }; - - if injectable { - // Append (don't overwrite) so a user-provided DYLD_INSERT_LIBRARIES - // keeps working. fspy's shim goes last so user preloads that - // short-circuit a libc call stay invisible to fspy — what the OS - // actually executed is what we want to record. - append_path_env( - &mut command.envs, - DYLD_INSERT_LIBRARIES, - encoded_payload.payload.preload_path.as_os_str().as_bytes(), - ); - ensure_env(&mut command.envs, PAYLOAD_ENV_NAME, encoded_payload.encoded_string)?; - } else { - command.envs.retain(|(name, _)| { - name != DYLD_INSERT_LIBRARIES && name != PAYLOAD_ENV_NAME.as_bytes() - }); - } - Ok(None) -} - -pub static COREUTILS_FUNCTIONS: Set<&'static [u8]> = phf_set! { - b"[", b"arch", b"b2sum", b"base32", b"base64", b"basename", b"basenc", b"cat", - b"chgrp", b"chmod", b"chown", b"chroot", b"cksum", b"comm", b"cp", b"csplit", - b"cut", b"date", b"dd", b"df", b"dir", b"dircolors", b"dirname", b"du", b"echo", - b"env", b"expand", b"expr", b"factor", b"false", b"fmt", b"fold", b"groups", - b"hashsum", b"head", b"hostid", b"hostname", b"id", b"install", b"join", b"kill", - b"link", b"ln", b"logname", b"ls", b"md5sum", b"mkdir", b"mkfifo", b"mknod", - b"mktemp", b"more", b"mv", b"nice", b"nl", b"nohup", b"nproc", b"numfmt", b"od", - b"paste", b"pathchk", b"pinky", b"pr", b"printenv", b"printf", b"ptx", b"pwd", - b"readlink", b"realpath", b"rm", b"rmdir", b"seq", b"sha1sum", b"sha224sum", - b"sha256sum", b"sha384sum", b"sha512sum", b"shred", b"shuf", b"sleep", b"sort", - b"split", b"stat", b"stdbuf", b"stty", b"sum", b"sync", b"tac", b"tail", b"tee", - b"test", b"timeout", b"touch", b"tr", b"true", b"truncate", b"tsort", b"tty", - b"uname", b"unexpand", b"uniq", b"unlink", b"uptime", b"users", b"vdir", b"wc", - b"who", b"whoami", b"yes" -}; diff --git a/crates/fspy_shared_unix/src/spawn/mod.rs b/crates/fspy_shared_unix/src/spawn/mod.rs deleted file mode 100644 index 34b2be0eb..000000000 --- a/crates/fspy_shared_unix/src/spawn/mod.rs +++ /dev/null @@ -1,122 +0,0 @@ -#[cfg(target_os = "linux")] -#[path = "./linux/mod.rs"] -mod os_specific; - -#[cfg(target_os = "macos")] -#[path = "./macos.rs"] -mod os_specific; - -use std::{ - ffi::OsStr, - os::unix::ffi::OsStrExt, - path::{Component, Path}, -}; - -use allocator_api2::{alloc::Allocator, vec::Vec}; -#[doc(hidden)] -#[cfg(target_os = "macos")] -pub use os_specific::COREUTILS_FUNCTIONS as COREUTILS_FUNCTIONS_FOR_TEST; -pub use os_specific::PreExec; - -use crate::{ - exec::{Exec, ExecResolveConfig}, - payload::EncodedPayload, -}; - -/// Makes the relative `path` absolute against the current directory, as -/// [`std::path::absolute`] does, but in `allocator` rather than libc's heap: -/// exec may run in the child of `fork()`, where malloc's lock may be held by -/// a thread that no longer exists. -/// -/// Ported from std's Unix implementation, for relative paths only: -/// , -/// with the empty-path check from its public wrapper: -/// . -/// Unlike `env::current_dir`, which grows its buffer, the current directory -/// must fit in `PATH_MAX`. -/// -/// # Errors -/// -/// Like [`std::path::absolute`], fails for an empty path, with `EINVAL`, and -/// with the error from getting the current directory. -pub(crate) fn absolute(path: &Path, allocator: A) -> nix::Result> { - debug_assert!(path.is_relative()); - if path.as_os_str().is_empty() { - return Err(nix::Error::EINVAL); - } - let mut absolute = fspy_nostd_alloc::fs::getcwd(allocator) - .map_err(|errno| nix::Error::from_raw(errno.raw_os_error()))? - .into_units(); - // A relative path's only `.` component is a leading one, which - // `std::path::absolute` drops. - for component in path.components().filter(|component| *component != Component::CurDir) { - if absolute.last() != Some(&b'/') { - absolute.push(b'/'); - } - absolute.extend_from_slice(component.as_os_str().as_bytes()); - } - // Like `std::path::absolute`, keep a trailing slash. - if path.as_os_str().as_bytes().ends_with(b"/") && absolute.last() != Some(&b'/') { - absolute.push(b'/'); - } - Ok(absolute) -} - -/// Handles exec command resolution and injection -/// -/// Resolves the program path and prepares the command for execution with -/// appropriate environment variables and hooks. -/// -/// # Errors -/// -/// Returns an error if: -/// - Program resolution fails (see [`Exec::resolve`] error variants, such as `ENOENT` (file not found) or `EACCES` (permission denied)) -/// - Environment variable operations fail (e.g., `ensure_env` may return `EINVAL` if an existing value conflicts) -/// - Platform-specific errors from `os_specific::handle_exec` -/// -/// # Panics -/// -/// Panics if the current working directory cannot be determined when converting a relative path to absolute. -pub fn handle_exec( - command: &mut Exec, - config: ExecResolveConfig, - encoded_payload: &EncodedPayload, - mut on_path_read: impl FnMut(&Path), -) -> nix::Result> { - let allocator = command.allocator().clone(); - let mut on_path_read = |path: &Path| { - if path.is_absolute() { - on_path_read(path); - } else { - let path = absolute(path, &allocator).expect("Failed to get cwd"); - on_path_read(Path::new(OsStr::from_bytes(&path))); - } - }; - - command.resolve(&mut on_path_read, config)?; - on_path_read(Path::new(OsStr::from_bytes(&command.program))); - - os_specific::handle_exec(command, encoded_payload) -} - -#[cfg(test)] -mod tests { - use std::{os::unix::ffi::OsStrExt, path::Path}; - - use allocator_api2::alloc::Global; - - use super::absolute; - - #[test] - fn absolute_matches_std() { - for path in ["foo", "./foo", "foo/./bar", "foo//bar", "../foo", "foo/", ".", "./", ""] { - let path = Path::new(path); - assert_eq!( - absolute(path, Global).ok().as_deref(), - std::path::absolute(path).ok().as_ref().map(|path| path.as_os_str().as_bytes()), - "{}", - path.display(), - ); - } - } -} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/.gitattributes b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/.gitattributes new file mode 100644 index 000000000..cbdcbbc25 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/.gitattributes @@ -0,0 +1 @@ +*.js text eol=lf diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/biome.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/biome.json new file mode 100644 index 000000000..c303f0979 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/biome.json @@ -0,0 +1,13 @@ +{ + "linter": { + "enabled": true + }, + "formatter": { + "enabled": true + }, + "javascript": { + "formatter": { + "quoteStyle": "single" + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/package.json new file mode 100644 index 000000000..cfaf0daad --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/package.json @@ -0,0 +1,4 @@ +{ + "name": "biome-cache", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/snapshots.toml new file mode 100644 index 000000000..56dd03e0e --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/snapshots.toml @@ -0,0 +1,33 @@ +[[e2e]] +name = "biome_cache" +comment = """ +`biome check` checks and lints `src/index.js`. Editing `src/index.js` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "check", + ], comment = "first run: cache miss", redact = { 'in \d+(\.\d+)?[µu]s' = 'in ' } }, + { argv = [ + "vt", + "run", + "--cache", + "check", + ], comment = "second run: cache hit", redact = { 'in \d+(\.\d+)?[µu]s' = 'in ' } }, + [ + "vtt", + "replace-file-content", + "src/index.js", + "initial-biome", + "edited-biome", + ], + { argv = [ + "vt", + "run", + "--cache", + "check", + ], comment = "third run: cache miss after editing src/index.js", redact = { 'in \d+(\.\d+)?[µu]s' = 'in ' } }, +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/snapshots/biome_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/snapshots/biome_cache.md new file mode 100644 index 000000000..75287b0ca --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/snapshots/biome_cache.md @@ -0,0 +1,38 @@ +# biome_cache + +`biome check` checks and lints `src/index.js`. Editing `src/index.js` invalidates the cache. + +## `vt run --cache check` + +first run: cache miss + +``` +$ biome check src/index.js +Checked 1 file in . No fixes applied. +``` + +## `vt run --cache check` + +second run: cache hit + +``` +$ biome check src/index.js ◉ cache hit, replaying +Checked 1 file in . No fixes applied. + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/index.js initial-biome edited-biome` + +``` +``` + +## `vt run --cache check` + +third run: cache miss after editing src/index.js + +``` +$ biome check src/index.js ○ cache miss: 'src/index.js' modified, executing +Checked 1 file in . No fixes applied. +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/src/index.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/src/index.js new file mode 100644 index 000000000..8f4678760 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/src/index.js @@ -0,0 +1 @@ +export const value = 'initial-biome'; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/vite-task.json new file mode 100644 index 000000000..6cd168a58 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "check": { + "command": "biome check src/index.js", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/package.json new file mode 100644 index 000000000..6df99db04 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/package.json @@ -0,0 +1,4 @@ +{ + "name": "bun-build-cache", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/scripts/compile-and-run.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/scripts/compile-and-run.js new file mode 100644 index 000000000..ecbbbdb5f --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/scripts/compile-and-run.js @@ -0,0 +1,29 @@ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bun-compile-test-')); +try { + const exePath = path.join(tmpDir, process.platform === 'win32' ? 'app.exe' : 'app'); + const compile = spawnSync( + process.execPath, + ['build', '--compile', 'src/cli.js', '--outfile', exePath], + { + encoding: 'utf8', + }, + ); + if (compile.status !== 0) { + process.stderr.write(compile.stdout + compile.stderr); + process.exit(compile.status ?? 1); + } + const run = spawnSync(exePath, ['src/data.txt', 'dist/out.txt'], { + encoding: 'utf8', + }); + if (run.status !== 0) { + process.stderr.write(run.stdout + run.stderr); + process.exit(run.status ?? 1); + } +} finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots.toml new file mode 100644 index 000000000..8aed2234b --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots.toml @@ -0,0 +1,89 @@ +[[e2e]] +name = "bun_build_bundle" +comment = """ +`bun build` bundles `src/index.js` and `src/dep.js` into `dist/bundle.js`. Editing `src/dep.js` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "bundle", + ], comment = "first run: cache miss", redact = { 'bundle\.js\s+\d+(\.\d+)?\s*\w+' = 'bundle.js ' } }, + [ + "vtt", + "grep-file", + "dist/bundle.js", + "initial-bun", + ], + { argv = [ + "vt", + "run", + "--cache", + "bundle", + ], comment = "second run: cache hit", redact = { 'bundle\.js\s+\d+(\.\d+)?\s*\w+' = 'bundle.js ' } }, + [ + "vtt", + "replace-file-content", + "src/dep.js", + "initial-bun", + "edited-bun", + ], + { argv = [ + "vt", + "run", + "--cache", + "bundle", + ], comment = "third run: cache miss after editing src/dep.js", redact = { 'bundle\.js\s+\d+(\.\d+)?\s*\w+' = 'bundle.js ' } }, + [ + "vtt", + "grep-file", + "dist/bundle.js", + "edited-bun", + ], +] + +[[e2e]] +name = "bun_build_compile" +comment = """ +`bun build --compile` builds a standalone executable and runs it to read `src/data.txt` and write `dist/out.txt`. Editing `src/data.txt` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "compile-and-run", + ], comment = "first run: cache miss" }, + [ + "vtt", + "print-file", + "dist/out.txt", + ], + { argv = [ + "vt", + "run", + "--cache", + "compile-and-run", + ], comment = "second run: cache hit" }, + [ + "vtt", + "replace-file-content", + "src/data.txt", + "initial-compiled", + "edited-compiled", + ], + { argv = [ + "vt", + "run", + "--cache", + "compile-and-run", + ], comment = "third run: cache miss after editing src/data.txt" }, + [ + "vtt", + "print-file", + "dist/out.txt", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots/bun_build_bundle.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots/bun_build_bundle.md new file mode 100644 index 000000000..f653016c6 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots/bun_build_bundle.md @@ -0,0 +1,57 @@ +# bun_build_bundle + +`bun build` bundles `src/index.js` and `src/dep.js` into `dist/bundle.js`. Editing `src/dep.js` invalidates the cache. + +## `vt run --cache bundle` + +first run: cache miss + +``` +$ bun build src/index.js --outfile dist/bundle.js +Bundled 2 modules in + + bundle.js (entry point) +``` + +## `vtt grep-file dist/bundle.js initial-bun` + +``` +dist/bundle.js: found "initial-bun" +``` + +## `vt run --cache bundle` + +second run: cache hit + +``` +$ bun build src/index.js --outfile dist/bundle.js ◉ cache hit, replaying +Bundled 2 modules in + + bundle.js (entry point) + + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/dep.js initial-bun edited-bun` + +``` +``` + +## `vt run --cache bundle` + +third run: cache miss after editing src/dep.js + +``` +$ bun build src/index.js --outfile dist/bundle.js ○ cache miss: 'src/dep.js' modified, executing +Bundled 2 modules in + + bundle.js (entry point) +``` + +## `vtt grep-file dist/bundle.js edited-bun` + +``` +dist/bundle.js: found "edited-bun" +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots/bun_build_compile.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots/bun_build_compile.md new file mode 100644 index 000000000..8440ba41a --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots/bun_build_compile.md @@ -0,0 +1,47 @@ +# bun_build_compile + +`bun build --compile` builds a standalone executable and runs it to read `src/data.txt` and write `dist/out.txt`. Editing `src/data.txt` invalidates the cache. + +## `vt run --cache compile-and-run` + +first run: cache miss + +``` +$ bun run scripts/compile-and-run.js +``` + +## `vtt print-file dist/out.txt` + +``` +bun-compiled:initial-compiled +``` + +## `vt run --cache compile-and-run` + +second run: cache hit + +``` +$ bun run scripts/compile-and-run.js ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/data.txt initial-compiled edited-compiled` + +``` +``` + +## `vt run --cache compile-and-run` + +third run: cache miss after editing src/data.txt + +``` +$ bun run scripts/compile-and-run.js ○ cache miss: 'src/data.txt' modified, executing +``` + +## `vtt print-file dist/out.txt` + +``` +bun-compiled:edited-compiled +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/cli.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/cli.js new file mode 100644 index 000000000..71ddcb714 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/cli.js @@ -0,0 +1,7 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +const [input, output] = process.argv.slice(2); +const content = fs.readFileSync(input, 'utf8').trim(); +fs.mkdirSync(path.dirname(output), { recursive: true }); +fs.writeFileSync(output, `bun-compiled:${content}\n`); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/data.txt b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/data.txt new file mode 100644 index 000000000..31b0fc97d --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/data.txt @@ -0,0 +1 @@ +initial-compiled diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/dep.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/dep.js new file mode 100644 index 000000000..29672a974 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/dep.js @@ -0,0 +1 @@ +export const message = 'initial-bun'; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/index.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/index.js new file mode 100644 index 000000000..2c67a0597 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/index.js @@ -0,0 +1,3 @@ +import { message } from './dep.js'; + +console.log(message); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/vite-task.json new file mode 100644 index 000000000..9e7bda425 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/vite-task.json @@ -0,0 +1,12 @@ +{ + "tasks": { + "bundle": { + "command": "bun build src/index.js --outfile dist/bundle.js", + "cache": true + }, + "compile-and-run": { + "command": "bun run scripts/compile-and-run.js", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/package.json new file mode 100644 index 000000000..1a80ad589 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/package.json @@ -0,0 +1,5 @@ +{ + "name": "deno-run-cache", + "private": true, + "type": "module" +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/snapshots.toml new file mode 100644 index 000000000..2ba6af28c --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/snapshots.toml @@ -0,0 +1,63 @@ +[[e2e]] +name = "deno_run_cache" +comment = """ +`deno run --no-remote` spawns a child process via `Deno.execPath()` (exercising `/proc/self/exe` virtualization and recursive exec) and a Web Worker reading a separate input file. Editing either input invalidates the cache. +""" +# Deno does not distribute musl binaries. +cfg = 'not(target_env = "musl")' +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "first run: cache miss" }, + [ + "vtt", + "print-file", + "dist/out.txt", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "second run: cache hit" }, + [ + "vtt", + "replace-file-content", + "src/child-data.txt", + "initial-child", + "edited-child", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "third run: cache miss after editing child process input" }, + [ + "vtt", + "print-file", + "dist/out.txt", + ], + [ + "vtt", + "replace-file-content", + "src/worker-data.txt", + "initial-worker", + "edited-worker", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "fourth run: cache miss after editing Web Worker input" }, + [ + "vtt", + "print-file", + "dist/out.txt", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/snapshots/deno_run_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/snapshots/deno_run_cache.md new file mode 100644 index 000000000..de978b683 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/snapshots/deno_run_cache.md @@ -0,0 +1,66 @@ +# deno_run_cache + +`deno run --no-remote` spawns a child process via `Deno.execPath()` (exercising `/proc/self/exe` virtualization and recursive exec) and a Web Worker reading a separate input file. Editing either input invalidates the cache. + +## `vt run --cache build` + +first run: cache miss + +``` +$ deno run --quiet --no-remote --allow-read --allow-write --allow-run src/main.ts +``` + +## `vtt print-file dist/out.txt` + +``` +child=initial-child;worker=initial-worker +``` + +## `vt run --cache build` + +second run: cache hit + +``` +$ deno run --quiet --no-remote --allow-read --allow-write --allow-run src/main.ts ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/child-data.txt initial-child edited-child` + +``` +``` + +## `vt run --cache build` + +third run: cache miss after editing child process input + +``` +$ deno run --quiet --no-remote --allow-read --allow-write --allow-run src/main.ts ○ cache miss: 'src/child-data.txt' modified, executing +``` + +## `vtt print-file dist/out.txt` + +``` +child=edited-child;worker=initial-worker +``` + +## `vtt replace-file-content src/worker-data.txt initial-worker edited-worker` + +``` +``` + +## `vt run --cache build` + +fourth run: cache miss after editing Web Worker input + +``` +$ deno run --quiet --no-remote --allow-read --allow-write --allow-run src/main.ts ○ cache miss: 'src/worker-data.txt' modified, executing +``` + +## `vtt print-file dist/out.txt` + +``` +child=edited-child;worker=edited-worker +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/child-data.txt b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/child-data.txt new file mode 100644 index 000000000..bfacb8436 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/child-data.txt @@ -0,0 +1 @@ +initial-child diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/child.ts b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/child.ts new file mode 100644 index 000000000..3b58cff55 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/child.ts @@ -0,0 +1,3 @@ +const [input, output] = Deno.args; +const content = Deno.readTextFileSync(input).trim(); +Deno.writeTextFileSync(output, content); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/main.ts b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/main.ts new file mode 100644 index 000000000..c682a4f69 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/main.ts @@ -0,0 +1,35 @@ +// Exercise Deno.execPath() (/proc/self/exe virtualization) by spawning a child +// Deno process directly via Deno.execPath(), plus a Web Worker thread reading a +// second input file — completely offline without downloading denort. +Deno.mkdirSync('dist', { recursive: true }); + +const childOutPath = 'dist/child.txt'; +const child = new Deno.Command(Deno.execPath(), { + args: [ + 'run', + '--quiet', + '--no-remote', + '--allow-read', + '--allow-write', + 'src/child.ts', + 'src/child-data.txt', + childOutPath, + ], + stdout: 'inherit', + stderr: 'inherit', +}); +const status = child.outputSync(); +if (!status.success) { + Deno.exit(status.code || 1); +} +const childValue = Deno.readTextFileSync(childOutPath).trim(); +Deno.removeSync(childOutPath); + +const workerValue = await new Promise((resolve, reject) => { + const worker = new Worker(new URL('./worker.ts', import.meta.url).href, { type: 'module' }); + worker.onmessage = (event: MessageEvent) => resolve(event.data); + worker.onerror = (event) => reject(event.error ?? new Error(event.message)); + worker.postMessage('src/worker-data.txt'); +}); + +Deno.writeTextFileSync('dist/out.txt', `child=${childValue};worker=${workerValue}\n`); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/worker-data.txt b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/worker-data.txt new file mode 100644 index 000000000..e45a0f844 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/worker-data.txt @@ -0,0 +1 @@ +initial-worker diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/worker.ts b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/worker.ts new file mode 100644 index 000000000..bfe2f3232 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/worker.ts @@ -0,0 +1,5 @@ +self.onmessage = (event: MessageEvent) => { + const content = Deno.readTextFileSync(event.data).trim(); + self.postMessage(content); + self.close(); +}; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/vite-task.json new file mode 100644 index 000000000..f43060e85 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "build": { + "command": "deno run --quiet --no-remote --allow-read --allow-write --allow-run src/main.ts", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/build.mjs b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/build.mjs new file mode 100644 index 000000000..aa59aa546 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/build.mjs @@ -0,0 +1,7 @@ +import * as esbuild from 'esbuild'; + +await esbuild.build({ + entryPoints: ['src/index.js'], + bundle: true, + outfile: 'dist/out.js', +}); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/package.json new file mode 100644 index 000000000..4c8fec968 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/package.json @@ -0,0 +1,5 @@ +{ + "name": "esbuild-cache", + "private": true, + "type": "module" +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/snapshots.toml new file mode 100644 index 000000000..ac4863433 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/snapshots.toml @@ -0,0 +1,45 @@ +[[e2e]] +name = "esbuild_cache" +comment = """ +`esbuild` JS API spawns the Go `esbuild` child service to bundle `src/index.js` and `src/dep.js` into `dist/out.js`. Editing `src/dep.js` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "first run: cache miss" }, + [ + "vtt", + "grep-file", + "dist/out.js", + "initial-esbuild", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "second run: cache hit" }, + [ + "vtt", + "replace-file-content", + "src/dep.js", + "initial-esbuild", + "edited-esbuild", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "third run: cache miss after editing src/dep.js" }, + [ + "vtt", + "grep-file", + "dist/out.js", + "edited-esbuild", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/snapshots/esbuild_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/snapshots/esbuild_cache.md new file mode 100644 index 000000000..fa088e8f1 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/snapshots/esbuild_cache.md @@ -0,0 +1,47 @@ +# esbuild_cache + +`esbuild` JS API spawns the Go `esbuild` child service to bundle `src/index.js` and `src/dep.js` into `dist/out.js`. Editing `src/dep.js` invalidates the cache. + +## `vt run --cache build` + +first run: cache miss + +``` +$ node build.mjs +``` + +## `vtt grep-file dist/out.js initial-esbuild` + +``` +dist/out.js: found "initial-esbuild" +``` + +## `vt run --cache build` + +second run: cache hit + +``` +$ node build.mjs ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/dep.js initial-esbuild edited-esbuild` + +``` +``` + +## `vt run --cache build` + +third run: cache miss after editing src/dep.js + +``` +$ node build.mjs ○ cache miss: 'src/dep.js' modified, executing +``` + +## `vtt grep-file dist/out.js edited-esbuild` + +``` +dist/out.js: found "edited-esbuild" +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/src/dep.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/src/dep.js new file mode 100644 index 000000000..73d6255f0 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/src/dep.js @@ -0,0 +1 @@ +export const greeting = 'initial-esbuild'; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/src/index.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/src/index.js new file mode 100644 index 000000000..1a996054f --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/src/index.js @@ -0,0 +1,3 @@ +import { greeting } from './dep.js'; + +console.log(greeting); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/vite-task.json new file mode 100644 index 000000000..f30505855 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "build": { + "command": "node build.mjs", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/package.json new file mode 100644 index 000000000..13442f8ad --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/package.json @@ -0,0 +1,5 @@ +{ + "name": "miniflare-worker-cache", + "private": true, + "type": "module" +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/run.mjs b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/run.mjs new file mode 100644 index 000000000..f34bd3b3a --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/run.mjs @@ -0,0 +1,24 @@ +import fs from 'node:fs'; +import { convertV4MiniflareOptions, Miniflare } from 'miniflare'; + +const mf = new Miniflare( + convertV4MiniflareOptions({ + unsafeDevRegistryPath: '', + unsafeRegisterWorker: false, + host: '127.0.0.1', + port: 0, + modules: [ + { type: 'ESModule', path: 'src/worker.mjs' }, + { type: 'ESModule', path: 'src/data.mjs' }, + ], + compatibilityDate: '2025-01-01', + }), +); +try { + const res = await mf.dispatchFetch('http://localhost/'); + const text = await res.text(); + fs.mkdirSync('dist', { recursive: true }); + fs.writeFileSync('dist/out.txt', `${text}\n`); +} finally { + await mf.dispose(); +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/snapshots.toml new file mode 100644 index 000000000..432f30dbe --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/snapshots.toml @@ -0,0 +1,45 @@ +[[e2e]] +name = "miniflare_worker_cache" +comment = """ +`miniflare` (`workerd`) loads `src/worker.mjs` and its imported module `src/data.mjs`, serves a request, and writes the response to `dist/out.txt`. Editing `src/data.mjs` invalidates the cache. +""" +# workerd does not distribute musl binaries. +cfg = 'not(target_env = "musl")' +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "run", + ], comment = "first run: cache miss" }, + [ + "vtt", + "print-file", + "dist/out.txt", + ], + { argv = [ + "vt", + "run", + "--cache", + "run", + ], comment = "second run: cache hit" }, + [ + "vtt", + "replace-file-content", + "src/data.mjs", + "initial-worker", + "edited-worker", + ], + { argv = [ + "vt", + "run", + "--cache", + "run", + ], comment = "third run: cache miss after editing src/data.mjs" }, + [ + "vtt", + "print-file", + "dist/out.txt", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/snapshots/miniflare_worker_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/snapshots/miniflare_worker_cache.md new file mode 100644 index 000000000..88ce98e35 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/snapshots/miniflare_worker_cache.md @@ -0,0 +1,47 @@ +# miniflare_worker_cache + +`miniflare` (`workerd`) loads `src/worker.mjs` and its imported module `src/data.mjs`, serves a request, and writes the response to `dist/out.txt`. Editing `src/data.mjs` invalidates the cache. + +## `vt run --cache run` + +first run: cache miss + +``` +$ node run.mjs +``` + +## `vtt print-file dist/out.txt` + +``` +worker:initial-worker +``` + +## `vt run --cache run` + +second run: cache hit + +``` +$ node run.mjs ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/data.mjs initial-worker edited-worker` + +``` +``` + +## `vt run --cache run` + +third run: cache miss after editing src/data.mjs + +``` +$ node run.mjs ○ cache miss: 'src/data.mjs' modified, executing +``` + +## `vtt print-file dist/out.txt` + +``` +worker:edited-worker +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/src/data.mjs b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/src/data.mjs new file mode 100644 index 000000000..68fd0c52e --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/src/data.mjs @@ -0,0 +1 @@ +export const payload = 'initial-worker'; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/src/worker.mjs b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/src/worker.mjs new file mode 100644 index 000000000..08dd929d2 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/src/worker.mjs @@ -0,0 +1,7 @@ +import { payload } from './data.mjs'; + +export default { + fetch() { + return new Response(`worker:${payload}`); + }, +}; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/vite-task.json new file mode 100644 index 000000000..0cc3e869e --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "run": { + "command": "node run.mjs", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/.gitattributes b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/.gitattributes new file mode 100644 index 000000000..cbdcbbc25 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/.gitattributes @@ -0,0 +1 @@ +*.js text eol=lf diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/.oxfmtrc.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/.oxfmtrc.json new file mode 100644 index 000000000..544138be4 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/.oxfmtrc.json @@ -0,0 +1,3 @@ +{ + "singleQuote": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/package.json new file mode 100644 index 000000000..1e396e120 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/package.json @@ -0,0 +1,4 @@ +{ + "name": "oxfmt-cache", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/snapshots.toml new file mode 100644 index 000000000..9de55f067 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/snapshots.toml @@ -0,0 +1,33 @@ +[[e2e]] +name = "oxfmt_cache" +comment = """ +`oxfmt --check` formats-checks `src/index.js`. Editing `src/index.js` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "format-check", + ], comment = "first run: cache miss", redact = { 'using \d+ threads?' = 'using threads' } }, + { argv = [ + "vt", + "run", + "--cache", + "format-check", + ], comment = "second run: cache hit", redact = { 'using \d+ threads?' = 'using threads' } }, + [ + "vtt", + "replace-file-content", + "src/index.js", + "initial-oxfmt", + "edited-oxfmt", + ], + { argv = [ + "vt", + "run", + "--cache", + "format-check", + ], comment = "third run: cache miss after editing src/index.js", redact = { 'using \d+ threads?' = 'using threads' } }, +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/snapshots/oxfmt_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/snapshots/oxfmt_cache.md new file mode 100644 index 000000000..1e3a06a35 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/snapshots/oxfmt_cache.md @@ -0,0 +1,47 @@ +# oxfmt_cache + +`oxfmt --check` formats-checks `src/index.js`. Editing `src/index.js` invalidates the cache. + +## `vt run --cache format-check` + +first run: cache miss + +``` +$ oxfmt --check src/index.js +Checking formatting... + +All matched files use the correct format. +Finished in on 1 files using threads. +``` + +## `vt run --cache format-check` + +second run: cache hit + +``` +$ oxfmt --check src/index.js ◉ cache hit, replaying +Checking formatting... + +All matched files use the correct format. +Finished in on 1 files using threads. + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/index.js initial-oxfmt edited-oxfmt` + +``` +``` + +## `vt run --cache format-check` + +third run: cache miss after editing src/index.js + +``` +$ oxfmt --check src/index.js ○ cache miss: 'src/index.js' modified, executing +Checking formatting... + +All matched files use the correct format. +Finished in on 1 files using threads. +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/src/index.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/src/index.js new file mode 100644 index 000000000..68ff54d90 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/src/index.js @@ -0,0 +1 @@ +export const greeting = 'initial-oxfmt'; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/vite-task.json new file mode 100644 index 000000000..99973ef80 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "format-check": { + "command": "oxfmt --check src/index.js", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/package.json new file mode 100644 index 000000000..bd171d4e3 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/package.json @@ -0,0 +1,4 @@ +{ + "name": "pagefind-cache", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/site/index.html b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/site/index.html new file mode 100644 index 000000000..2fc1f9322 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/site/index.html @@ -0,0 +1,9 @@ + + + +

+

initial-pagefind

+

Static search index fixture.

+
+ + diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/snapshots.toml new file mode 100644 index 000000000..dd182e7b3 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/snapshots.toml @@ -0,0 +1,57 @@ +[[e2e]] +name = "pagefind_cache" +comment = """ +`pagefind` (static-PIE ELF64 on Linux x86-64) indexes `site/index.html` into `dist/pagefind/`. Deleting `dist` and re-running restores outputs from cache; editing `site/index.html` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "index", + ], comment = "first run: cache miss" }, + [ + "vtt", + "grep-file", + "dist/pagefind/pagefind-entry.json", + "\"page_count\":1", + ], + [ + "vtt", + "rm", + "-r", + "dist", + ], + { argv = [ + "vt", + "run", + "--cache", + "index", + ], comment = "second run: cache hit restores dist/pagefind" }, + [ + "vtt", + "grep-file", + "dist/pagefind/pagefind-entry.json", + "\"page_count\":1", + ], + [ + "vtt", + "replace-file-content", + "site/index.html", + "initial-pagefind", + "edited-pagefind", + ], + { argv = [ + "vt", + "run", + "--cache", + "index", + ], comment = "third run: cache miss after editing site/index.html" }, + [ + "vtt", + "grep-file", + "dist/pagefind/pagefind-entry.json", + "\"page_count\":1", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/snapshots/pagefind_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/snapshots/pagefind_cache.md new file mode 100644 index 000000000..39fa43ed2 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/snapshots/pagefind_cache.md @@ -0,0 +1,58 @@ +# pagefind_cache + +`pagefind` (static-PIE ELF64 on Linux x86-64) indexes `site/index.html` into `dist/pagefind/`. Deleting `dist` and re-running restores outputs from cache; editing `site/index.html` invalidates the cache. + +## `vt run --cache index` + +first run: cache miss + +``` +$ pagefind --site site --output-path dist/pagefind --silent +``` + +## `vtt grep-file dist/pagefind/pagefind-entry.json '"page_count":1'` + +``` +dist/pagefind/pagefind-entry.json: found "\"page_count\":1" +``` + +## `vtt rm -r dist` + +``` +``` + +## `vt run --cache index` + +second run: cache hit restores dist/pagefind + +``` +$ pagefind --site site --output-path dist/pagefind --silent ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt grep-file dist/pagefind/pagefind-entry.json '"page_count":1'` + +``` +dist/pagefind/pagefind-entry.json: found "\"page_count\":1" +``` + +## `vtt replace-file-content site/index.html initial-pagefind edited-pagefind` + +``` +``` + +## `vt run --cache index` + +third run: cache miss after editing site/index.html + +``` +$ pagefind --site site --output-path dist/pagefind --silent ○ cache miss: 'site/index.html' modified, executing +``` + +## `vtt grep-file dist/pagefind/pagefind-entry.json '"page_count":1'` + +``` +dist/pagefind/pagefind-entry.json: found "\"page_count\":1" +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/vite-task.json new file mode 100644 index 000000000..b2fae1e60 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "index": { + "command": "pagefind --site site --output-path dist/pagefind --silent", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/preexisting_ld_preload/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/preexisting_ld_preload/snapshots.toml index 6d6fa4cbd..135ae05a1 100644 --- a/crates/vt_bin/tests/e2e_snapshots/fixtures/preexisting_ld_preload/snapshots.toml +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/preexisting_ld_preload/snapshots.toml @@ -1,12 +1,10 @@ [[e2e]] name = "preexisting_ld_preload" -# Requires fspy's LD_PRELOAD injection path, which is only active on -# glibc-Linux. On musl fspy uses seccomp-unotify instead and strips -# LD_PRELOAD from spawned children, so the fixture's interposer-chain -# assumptions don't hold. +# Tests user-supplied `LD_PRELOAD` interposition alongside fspy on glibc-Linux +# (`vt_preload_test_lib` is built as a cdylib for glibc). cfg = 'all(target_os = "linux", target_env = "gnu")' comment = """ -Reproduces #340 and verifies that fspy tolerates a user-supplied `LD_PRELOAD` by appending its shim instead of rejecting the spawn. Appending (not prepending) also preserves symbol-interposition order: the user's preload runs first, so short-circuited calls remain invisible to fspy — what the OS actually executed is what fspy records. +Reproduces #340 and verifies that fspy preserves a user-supplied `LD_PRELOAD` untouched. Because Linux tracking runs at the kernel syscall boundary via `fspy_preload_linux` (`SIGSYS`), any call short-circuited in userspace by the user's preload never issues a kernel syscall and remains invisible to fspy — what the OS actually executed is what fspy records. `vt_preload_test_lib` (built as a cdylib artifact dep) intercepts `open`/`openat` and short-circuits any path containing the marker `preload_test_short_circuit`, returning `ENOENT` without forwarding. Every other path is forwarded via `RTLD_NEXT` so fspy still observes the real syscall. diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/preexisting_ld_preload/snapshots/preexisting_ld_preload.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/preexisting_ld_preload/snapshots/preexisting_ld_preload.md index 702482942..ba5b8803d 100644 --- a/crates/vt_bin/tests/e2e_snapshots/fixtures/preexisting_ld_preload/snapshots/preexisting_ld_preload.md +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/preexisting_ld_preload/snapshots/preexisting_ld_preload.md @@ -1,6 +1,6 @@ # preexisting_ld_preload -Reproduces #340 and verifies that fspy tolerates a user-supplied `LD_PRELOAD` by appending its shim instead of rejecting the spawn. Appending (not prepending) also preserves symbol-interposition order: the user's preload runs first, so short-circuited calls remain invisible to fspy — what the OS actually executed is what fspy records. +Reproduces #340 and verifies that fspy preserves a user-supplied `LD_PRELOAD` untouched. Because Linux tracking runs at the kernel syscall boundary via `fspy_preload_linux` (`SIGSYS`), any call short-circuited in userspace by the user's preload never issues a kernel syscall and remains invisible to fspy — what the OS actually executed is what fspy records. `vt_preload_test_lib` (built as a cdylib artifact dep) intercepts `open`/`openat` and short-circuits any path containing the marker `preload_test_short_circuit`, returning `ENOENT` without forwarding. Every other path is forwarded via `RTLD_NEXT` so fspy still observes the real syscall. diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/package.json new file mode 100644 index 000000000..7f05fb65e --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/package.json @@ -0,0 +1,4 @@ +{ + "name": "rspack-build-cache", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/rspack.config.cjs b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/rspack.config.cjs new file mode 100644 index 000000000..a669416d0 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/rspack.config.cjs @@ -0,0 +1,11 @@ +const path = require('node:path'); + +module.exports = { + mode: 'production', + entry: './src/index.js', + output: { + path: path.resolve(__dirname, 'dist'), + filename: 'main.js', + }, + stats: 'errors-only', +}; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/snapshots.toml new file mode 100644 index 000000000..74e08ae90 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/snapshots.toml @@ -0,0 +1,45 @@ +[[e2e]] +name = "rspack_build_cache" +comment = """ +`rspack build` (Rust N-API bundler with `mimalloc` + rayon) bundles `src/index.js` and `src/dep.js` into `dist/main.js`. Editing `src/dep.js` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "first run: cache miss" }, + [ + "vtt", + "grep-file", + "dist/main.js", + "initial-rspack", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "second run: cache hit" }, + [ + "vtt", + "replace-file-content", + "src/dep.js", + "initial-rspack", + "edited-rspack", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "third run: cache miss after editing src/dep.js" }, + [ + "vtt", + "grep-file", + "dist/main.js", + "edited-rspack", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/snapshots/rspack_build_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/snapshots/rspack_build_cache.md new file mode 100644 index 000000000..8e72afbc3 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/snapshots/rspack_build_cache.md @@ -0,0 +1,47 @@ +# rspack_build_cache + +`rspack build` (Rust N-API bundler with `mimalloc` + rayon) bundles `src/index.js` and `src/dep.js` into `dist/main.js`. Editing `src/dep.js` invalidates the cache. + +## `vt run --cache build` + +first run: cache miss + +``` +$ rspack build +``` + +## `vtt grep-file dist/main.js initial-rspack` + +``` +dist/main.js: found "initial-rspack" +``` + +## `vt run --cache build` + +second run: cache hit + +``` +$ rspack build ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/dep.js initial-rspack edited-rspack` + +``` +``` + +## `vt run --cache build` + +third run: cache miss after editing src/dep.js + +``` +$ rspack build ○ cache miss: 'src/dep.js' modified, executing +``` + +## `vtt grep-file dist/main.js edited-rspack` + +``` +dist/main.js: found "edited-rspack" +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/src/dep.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/src/dep.js new file mode 100644 index 000000000..47006360f --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/src/dep.js @@ -0,0 +1 @@ +export const label = 'initial-rspack'; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/src/index.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/src/index.js new file mode 100644 index 000000000..426582990 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/src/index.js @@ -0,0 +1,3 @@ +import { label } from './dep.js'; + +console.log(label); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/vite-task.json new file mode 100644 index 000000000..dd4331d33 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "build": { + "command": "rspack build", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/build.mjs b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/build.mjs new file mode 100644 index 000000000..55cb18962 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/build.mjs @@ -0,0 +1,6 @@ +import fs from 'node:fs'; +import * as sass from 'sass-embedded'; + +const result = sass.compile('src/main.scss'); +fs.mkdirSync('dist', { recursive: true }); +fs.writeFileSync('dist/main.css', `${result.css}\n`); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/package.json new file mode 100644 index 000000000..9e799c949 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/package.json @@ -0,0 +1,5 @@ +{ + "name": "sass-embedded-cache", + "private": true, + "type": "module" +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/snapshots.toml new file mode 100644 index 000000000..f981b42bb --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/snapshots.toml @@ -0,0 +1,47 @@ +[[e2e]] +name = "sass_embedded_cache" +comment = """ +`sass-embedded` (Dart VM AOT binary) compiles `src/main.scss` (which `@use`s `src/_vars.scss`) to `dist/main.css`. Editing `src/_vars.scss` invalidates the cache. +""" +# On macOS, sass-embedded's `dart` binary is signed with Hardened Runtime +# without `com.apple.security.cs.allow-dyld-environment-variables`, so macOS +# strips `DYLD_INSERT_LIBRARIES` and prevents fspy from tracing `dart`. +cfg = 'not(target_os = "macos")' +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "first run: cache miss" }, + [ + "vtt", + "print-file", + "dist/main.css", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "second run: cache hit" }, + [ + "vtt", + "replace-file-content", + "src/_vars.scss", + "#ff0000", + "#0000ff", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "third run: cache miss after editing src/_vars.scss" }, + [ + "vtt", + "print-file", + "dist/main.css", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/snapshots/sass_embedded_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/snapshots/sass_embedded_cache.md new file mode 100644 index 000000000..f5de53077 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/snapshots/sass_embedded_cache.md @@ -0,0 +1,51 @@ +# sass_embedded_cache + +`sass-embedded` (Dart VM AOT binary) compiles `src/main.scss` (which `@use`s `src/_vars.scss`) to `dist/main.css`. Editing `src/_vars.scss` invalidates the cache. + +## `vt run --cache build` + +first run: cache miss + +``` +$ node build.mjs +``` + +## `vtt print-file dist/main.css` + +``` +.box { + color: #ff0000; +} +``` + +## `vt run --cache build` + +second run: cache hit + +``` +$ node build.mjs ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/_vars.scss #ff0000 #0000ff` + +``` +``` + +## `vt run --cache build` + +third run: cache miss after editing src/_vars.scss + +``` +$ node build.mjs ○ cache miss: 'src/_vars.scss' modified, executing +``` + +## `vtt print-file dist/main.css` + +``` +.box { + color: #0000ff; +} +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/src/_vars.scss b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/src/_vars.scss new file mode 100644 index 000000000..edbcb5234 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/src/_vars.scss @@ -0,0 +1 @@ +$color: #ff0000; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/src/main.scss b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/src/main.scss new file mode 100644 index 000000000..f2918ea25 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/src/main.scss @@ -0,0 +1,5 @@ +@use 'vars'; + +.box { + color: vars.$color; +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/vite-task.json new file mode 100644 index 000000000..f30505855 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "build": { + "command": "node build.mjs", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/build.mjs b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/build.mjs new file mode 100644 index 000000000..92ca76b1c --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/build.mjs @@ -0,0 +1,11 @@ +import fs from 'node:fs'; +import sharp from 'sharp'; + +fs.mkdirSync('dist', { recursive: true }); +await sharp('src/icon.svg').resize(8, 8).png().toFile('dist/out.png'); +const { data, info } = await sharp('dist/out.png') + .ensureAlpha() + .raw() + .toBuffer({ resolveWithObject: true }); +const pixel = [data[0], data[1], data[2], data[3]].join(','); +fs.writeFileSync('dist/meta.txt', `${info.width}x${info.height}:${pixel}\n`); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/package.json new file mode 100644 index 000000000..9c4e230f5 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/package.json @@ -0,0 +1,5 @@ +{ + "name": "sharp-image-cache", + "private": true, + "type": "module" +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/snapshots.toml new file mode 100644 index 000000000..e73c4a651 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/snapshots.toml @@ -0,0 +1,43 @@ +[[e2e]] +name = "sharp_image_cache" +comment = """ +`sharp` (`libvips-cpp.so` via `$ORIGIN`) renders `src/icon.svg` to a resized PNG `dist/out.png` and records its decoded dimensions and pixel RGBA in `dist/meta.txt`. Editing `src/icon.svg` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "first run: cache miss" }, + [ + "vtt", + "print-file", + "dist/meta.txt", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "second run: cache hit" }, + [ + "vtt", + "replace-file-content", + "src/icon.svg", + "#ff0000", + "#00ff00", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "third run: cache miss after editing src/icon.svg" }, + [ + "vtt", + "print-file", + "dist/meta.txt", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/snapshots/sharp_image_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/snapshots/sharp_image_cache.md new file mode 100644 index 000000000..bef2df27a --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/snapshots/sharp_image_cache.md @@ -0,0 +1,47 @@ +# sharp_image_cache + +`sharp` (`libvips-cpp.so` via `$ORIGIN`) renders `src/icon.svg` to a resized PNG `dist/out.png` and records its decoded dimensions and pixel RGBA in `dist/meta.txt`. Editing `src/icon.svg` invalidates the cache. + +## `vt run --cache build` + +first run: cache miss + +``` +$ node build.mjs +``` + +## `vtt print-file dist/meta.txt` + +``` +8x8:255,0,0,255 +``` + +## `vt run --cache build` + +second run: cache hit + +``` +$ node build.mjs ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/icon.svg #ff0000 #00ff00` + +``` +``` + +## `vt run --cache build` + +third run: cache miss after editing src/icon.svg + +``` +$ node build.mjs ○ cache miss: 'src/icon.svg' modified, executing +``` + +## `vtt print-file dist/meta.txt` + +``` +8x8:0,255,0,255 +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/src/icon.svg b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/src/icon.svg new file mode 100644 index 000000000..2d4c5cf7f --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/src/icon.svg @@ -0,0 +1 @@ + diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/vite-task.json new file mode 100644 index 000000000..f30505855 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "build": { + "command": "node build.mjs", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/package.json new file mode 100644 index 000000000..587a82b85 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/package.json @@ -0,0 +1,4 @@ +{ + "name": "tailwindcss-v4-cache", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/snapshots.toml new file mode 100644 index 000000000..12554dd32 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/snapshots.toml @@ -0,0 +1,45 @@ +[[e2e]] +name = "tailwindcss_v4_cache" +comment = """ +`@tailwindcss/cli` v4 (Rust `oxide` + `lightningcss` rayon globbing) scans `src/index.html` and compiles `src/input.css` to `dist/output.css`. Editing `src/index.html` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "first run: cache miss", redact = { 'tailwindcss v\d+\.\d+\.\d+' = 'tailwindcss v' } }, + [ + "vtt", + "grep-file", + "dist/output.css", + "text-red-500", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "second run: cache hit", redact = { 'tailwindcss v\d+\.\d+\.\d+' = 'tailwindcss v' } }, + [ + "vtt", + "replace-file-content", + "src/index.html", + "text-red-500", + "text-blue-500", + ], + { argv = [ + "vt", + "run", + "--cache", + "build", + ], comment = "third run: cache miss after editing src/index.html", redact = { 'tailwindcss v\d+\.\d+\.\d+' = 'tailwindcss v' } }, + [ + "vtt", + "grep-file", + "dist/output.css", + "text-blue-500", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/snapshots/tailwindcss_v4_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/snapshots/tailwindcss_v4_cache.md new file mode 100644 index 000000000..b074c85c5 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/snapshots/tailwindcss_v4_cache.md @@ -0,0 +1,56 @@ +# tailwindcss_v4_cache + +`@tailwindcss/cli` v4 (Rust `oxide` + `lightningcss` rayon globbing) scans `src/index.html` and compiles `src/input.css` to `dist/output.css`. Editing `src/index.html` invalidates the cache. + +## `vt run --cache build` + +first run: cache miss + +``` +$ tailwindcss -i src/input.css -o dist/output.css +≈ tailwindcss v + +Done in +``` + +## `vtt grep-file dist/output.css text-red-500` + +``` +dist/output.css: found "text-red-500" +``` + +## `vt run --cache build` + +second run: cache hit + +``` +$ tailwindcss -i src/input.css -o dist/output.css ◉ cache hit, replaying +≈ tailwindcss v + +Done in + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/index.html text-red-500 text-blue-500` + +``` +``` + +## `vt run --cache build` + +third run: cache miss after editing src/index.html + +``` +$ tailwindcss -i src/input.css -o dist/output.css ○ cache miss: 'src/index.html' modified, executing +≈ tailwindcss v + +Done in +``` + +## `vtt grep-file dist/output.css text-blue-500` + +``` +dist/output.css: found "text-blue-500" +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/src/index.html b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/src/index.html new file mode 100644 index 000000000..4ba1bbd9b --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/src/index.html @@ -0,0 +1 @@ +
hello
diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/src/input.css b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/src/input.css new file mode 100644 index 000000000..d4b507858 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/src/input.css @@ -0,0 +1 @@ +@import 'tailwindcss'; diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/vite-task.json new file mode 100644 index 000000000..57c8e62ee --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "build": { + "command": "tailwindcss -i src/input.css -o dist/output.css", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/package.json new file mode 100644 index 000000000..e66866a9a --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/package.json @@ -0,0 +1,5 @@ +{ + "name": "tsx-fork-cache", + "private": true, + "type": "module" +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/snapshots.toml new file mode 100644 index 000000000..2e75dbc16 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/snapshots.toml @@ -0,0 +1,43 @@ +[[e2e]] +name = "tsx_fork_cache" +comment = """ +`tsx` executes `src/parent.ts`, which spawns `src/child.ts` via `child_process.fork()` (inheriting `NODE_CHANNEL_FD` and tsx's `--import` loader). The child reads `src/data.txt` and sends its content over IPC so the parent writes `dist/out.txt`. Editing `src/data.txt` invalidates the cache. +""" +ignore = true +steps = [ + { argv = [ + "vt", + "run", + "--cache", + "run", + ], comment = "first run: cache miss" }, + [ + "vtt", + "print-file", + "dist/out.txt", + ], + { argv = [ + "vt", + "run", + "--cache", + "run", + ], comment = "second run: cache hit" }, + [ + "vtt", + "replace-file-content", + "src/data.txt", + "initial-tsx-ipc", + "edited-tsx-ipc", + ], + { argv = [ + "vt", + "run", + "--cache", + "run", + ], comment = "third run: cache miss after editing src/data.txt" }, + [ + "vtt", + "print-file", + "dist/out.txt", + ], +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/snapshots/tsx_fork_cache.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/snapshots/tsx_fork_cache.md new file mode 100644 index 000000000..4216ec83a --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/snapshots/tsx_fork_cache.md @@ -0,0 +1,47 @@ +# tsx_fork_cache + +`tsx` executes `src/parent.ts`, which spawns `src/child.ts` via `child_process.fork()` (inheriting `NODE_CHANNEL_FD` and tsx's `--import` loader). The child reads `src/data.txt` and sends its content over IPC so the parent writes `dist/out.txt`. Editing `src/data.txt` invalidates the cache. + +## `vt run --cache run` + +first run: cache miss + +``` +$ tsx src/parent.ts +``` + +## `vtt print-file dist/out.txt` + +``` +ipc:initial-tsx-ipc +``` + +## `vt run --cache run` + +second run: cache hit + +``` +$ tsx src/parent.ts ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt replace-file-content src/data.txt initial-tsx-ipc edited-tsx-ipc` + +``` +``` + +## `vt run --cache run` + +third run: cache miss after editing src/data.txt + +``` +$ tsx src/parent.ts ○ cache miss: 'src/data.txt' modified, executing +``` + +## `vtt print-file dist/out.txt` + +``` +ipc:edited-tsx-ipc +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/child.ts b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/child.ts new file mode 100644 index 000000000..5b6d7a696 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/child.ts @@ -0,0 +1,7 @@ +import fs from 'node:fs'; + +const dataPath: string = process.argv[2]!; +const content: string = fs.readFileSync(dataPath, 'utf8').trim(); +process.send?.(content, () => { + process.disconnect(); +}); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/data.txt b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/data.txt new file mode 100644 index 000000000..7873b85aa --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/data.txt @@ -0,0 +1 @@ +initial-tsx-ipc diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/parent.ts b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/parent.ts new file mode 100644 index 000000000..0a6303e39 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/parent.ts @@ -0,0 +1,18 @@ +import { fork } from 'node:child_process'; +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const childPath: string = fileURLToPath(new URL('./child.ts', import.meta.url)); +const child = fork(childPath, ['src/data.txt']); + +let received: string | null = null; +child.on('message', (msg: unknown) => { + received = String(msg); +}); +child.on('exit', (code: number | null) => { + if (code !== 0 || received === null) { + process.exit(1); + } + fs.mkdirSync('dist', { recursive: true }); + fs.writeFileSync('dist/out.txt', `ipc:${received}\n`); +}); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/vite-task.json new file mode 100644 index 000000000..96659f3dc --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "run": { + "command": "tsx src/parent.ts", + "cache": true + } + } +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/vitest_browser_cache/vitest.config.js b/crates/vt_bin/tests/e2e_snapshots/fixtures/vitest_browser_cache/vitest.config.js index 41da653f3..7c6d99014 100644 --- a/crates/vt_bin/tests/e2e_snapshots/fixtures/vitest_browser_cache/vitest.config.js +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/vitest_browser_cache/vitest.config.js @@ -31,7 +31,10 @@ export default defineConfig({ browser: { enabled: true, headless: true, - provider: playwright(), + // Playwright passes `--no-sandbox` by default. Keep Chromium's sandbox + // on, as in a desktop browser, so tracking runs alongside the + // sandboxed renderer's own seccomp filter on Linux. + provider: playwright({ launchOptions: { chromiumSandbox: true } }), instances: [{ browser: 'chromium' }], }, }, diff --git a/crates/vt_materialized_artifact_macros/src/lib.rs b/crates/vt_materialized_artifact_macros/src/lib.rs index 0f7bef0a5..702070486 100644 --- a/crates/vt_materialized_artifact_macros/src/lib.rs +++ b/crates/vt_materialized_artifact_macros/src/lib.rs @@ -38,7 +38,7 @@ use syn::{ /// Construct a `vt_materialized_artifact::Artifact` from an env var holding a /// file path at compile time. /// -/// Usage: `artifact!("fspy_preload", "CARGO_CDYLIB_FILE_FSPY_PRELOAD_UNIX")` +/// Usage: `artifact!("fspy_preload", "CARGO_CDYLIB_FILE_FSPY_PRELOAD_MACOS")` /// where the first argument is the artifact name (used in the materialized /// filename) and the second is the env var holding the file's path: a Cargo /// artifact dependency's `CARGO__FILE_`, or a var the consuming diff --git a/crates/vt_pty_terminal_test_client/Cargo.toml b/crates/vt_pty_terminal_test_client/Cargo.toml index cf39f0983..3cddb56f6 100644 --- a/crates/vt_pty_terminal_test_client/Cargo.toml +++ b/crates/vt_pty_terminal_test_client/Cargo.toml @@ -12,7 +12,7 @@ default = [] testing = ["dep:getrandom", "dep:winapi"] [dependencies] -base64 = { workspace = true } +base64 = { workspace = true, features = ["alloc"] } getrandom = { workspace = true, optional = true } [target.'cfg(windows)'.dependencies] diff --git a/crates/vt_remote_cache/Cargo.toml b/crates/vt_remote_cache/Cargo.toml index bf80338ad..ad726bbb1 100644 --- a/crates/vt_remote_cache/Cargo.toml +++ b/crates/vt_remote_cache/Cargo.toml @@ -8,7 +8,7 @@ publish = false rust-version.workspace = true [dependencies] -base64 = { workspace = true } +base64 = { workspace = true, features = ["alloc"] } bytes = { workspace = true } ciborium = { workspace = true } reqwest = { workspace = true, features = [ diff --git a/crates/vt_subprocess_test/Cargo.toml b/crates/vt_subprocess_test/Cargo.toml index dd3602f45..a74f71de9 100644 --- a/crates/vt_subprocess_test/Cargo.toml +++ b/crates/vt_subprocess_test/Cargo.toml @@ -8,7 +8,7 @@ publish = false rust-version.workspace = true [dependencies] -base64 = { workspace = true } +base64 = { workspace = true, features = ["alloc"] } wincode = { workspace = true } ctor = { workspace = true } fspy = { workspace = true, optional = true } diff --git a/packages/tools/package.json b/packages/tools/package.json index b3d49cbb6..c648aebf2 100644 --- a/packages/tools/package.json +++ b/packages/tools/package.json @@ -10,9 +10,13 @@ }, "dependencies": { "@anthropic-ai/sandbox-runtime": "catalog:", + "@biomejs/biome": "catalog:", "@cloudflare/workers-types": "5.20260911.1", "@openai/codex": "catalog:", "@playwright/browser-chromium": "catalog:", + "@rspack/cli": "catalog:", + "@rspack/core": "catalog:", + "@tailwindcss/cli": "catalog:", "@vitest/browser-playwright": "catalog:", "@voidzero-dev/vite-plus-remote-cache-cloudflare": "github:voidzero-dev/vite-plus-remote-cache-cloudflare#b0c6302efe0345cb2925c06347504c80e4bf0773", "@voidzero-dev/vite-task-client": "workspace:*", @@ -29,12 +33,17 @@ "oxfmt": "catalog:", "oxlint": "catalog:", "oxlint-tsgolint": "catalog:", + "pagefind": "catalog:", "playwright": "catalog:", "pnpm": "catalog:", "postject": "catalog:", "react": "catalog:", "react-dom": "catalog:", + "sass-embedded": "catalog:", + "sharp": "catalog:", + "tailwindcss": "catalog:", "tsdown": "catalog:", + "tsx": "catalog:", "typescript": "7.1.0-dev.20261001.1", "vite": "catalog:", "vitest": "catalog:", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index de5e3ab64..64436fb10 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,12 +9,24 @@ catalogs: '@anthropic-ai/sandbox-runtime': specifier: 0.0.78 version: 0.0.78 + '@biomejs/biome': + specifier: 2.6.9 + version: 2.6.9 '@openai/codex': specifier: 0.160.0 version: 0.160.0 '@playwright/browser-chromium': specifier: 1.63.0 version: 1.63.0 + '@rspack/cli': + specifier: 2.3.4 + version: 2.3.4 + '@rspack/core': + specifier: 2.3.4 + version: 2.3.4 + '@tailwindcss/cli': + specifier: 4.3.5 + version: 4.3.5 '@tsconfig/strictest': specifier: ^2.0.8 version: 2.0.8 @@ -60,6 +72,9 @@ catalogs: oxlint-tsgolint: specifier: ^7.0.0 version: 7.0.2008 + pagefind: + specifier: 1.6.0 + version: 1.6.0 pnpm: specifier: 11.24.0 version: 11.24.0 @@ -72,9 +87,21 @@ catalogs: react-dom: specifier: 19.3.1 version: 19.3.1 + sass-embedded: + specifier: 1.108.2 + version: 1.108.2 + sharp: + specifier: 0.35.5 + version: 0.35.5 + tailwindcss: + specifier: 4.3.5 + version: 4.3.5 tsdown: specifier: 0.23.3 version: 0.23.3 + tsx: + specifier: 4.23.15 + version: 4.23.15 typescript: specifier: ^6.0.3 version: 6.0.3 @@ -106,16 +133,19 @@ importers: version: 6.0.3 vite: specifier: npm:@voidzero-dev/vite-plus-core@1.1.0 - version: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)' + version: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)' vite-plus: specifier: 'catalog:' - version: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(playwright@1.63.0)(typescript@6.0.3)(yaml@2.9.1) + version: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1) packages/tools: dependencies: '@anthropic-ai/sandbox-runtime': specifier: 'catalog:' version: 0.0.78 + '@biomejs/biome': + specifier: 'catalog:' + version: 2.6.9 '@cloudflare/workers-types': specifier: 5.20260911.1 version: 5.20260911.1 @@ -125,9 +155,18 @@ importers: '@playwright/browser-chromium': specifier: 'catalog:' version: 1.63.0 + '@rspack/cli': + specifier: 'catalog:' + version: 2.3.4(@rspack/core@2.3.4) + '@rspack/core': + specifier: 'catalog:' + version: 2.3.4 + '@tailwindcss/cli': + specifier: 'catalog:' + version: 4.3.5 '@vitest/browser-playwright': specifier: 'catalog:' - version: 5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3) + version: 5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3) '@voidzero-dev/vite-plus-remote-cache-cloudflare': specifier: github:voidzero-dev/vite-plus-remote-cache-cloudflare#b0c6302efe0345cb2925c06347504c80e4bf0773 version: https://codeload.github.com/voidzero-dev/vite-plus-remote-cache-cloudflare/tar.gz/b0c6302efe0345cb2925c06347504c80e4bf0773 @@ -136,7 +175,7 @@ importers: version: link:../vite-task-client astro: specifier: 'catalog:' - version: 7.3.8(@types/node@25.0.3)(db0@0.4.2)(esbuild@0.28.1)(yaml@2.9.1) + version: 7.3.8(@types/node@25.0.3)(db0@0.4.2)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1) bun: specifier: 'catalog:' version: 1.4.2 @@ -160,19 +199,22 @@ importers: version: 5.20260911.0-alpha(@types/node@25.0.3) next: specifier: 'catalog:' - version: 15.5.29(@types/node@25.0.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + version: 15.5.29(@types/node@25.0.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(sass@1.108.2) nitro: specifier: 'catalog:' version: 3.0.260903-beta oxfmt: specifier: 'catalog:' - version: 0.73.0(@astrojs/compiler-rs@0.5.2)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) + version: 0.73.0(@astrojs/compiler-rs@0.5.2)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) oxlint: specifier: 'catalog:' - version: 1.95.0(oxlint-tsgolint@7.0.2008)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) + version: 1.95.0(oxlint-tsgolint@7.0.2008)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) oxlint-tsgolint: specifier: 'catalog:' version: 7.0.2008 + pagefind: + specifier: 'catalog:' + version: 1.6.0 playwright: specifier: 1.63.0 version: 1.63.0 @@ -188,18 +230,30 @@ importers: react-dom: specifier: 'catalog:' version: 19.3.1(react@19.3.1) + sass-embedded: + specifier: 'catalog:' + version: 1.108.2 + sharp: + specifier: 'catalog:' + version: 0.35.5(@types/node@25.0.3) + tailwindcss: + specifier: 'catalog:' + version: 4.3.5 tsdown: specifier: 'catalog:' - version: 0.23.3(typescript@7.1.0-dev.20261001.1) + version: 0.23.3(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1) + tsx: + specifier: 'catalog:' + version: 4.23.15 typescript: specifier: 7.1.0-dev.20261001.1 version: 7.1.0-dev.20261001.1 vite: specifier: 8.3.2 - version: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1) + version: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1) vitest: specifier: 'catalog:' - version: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + version: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) wrangler: specifier: 4.131.1 version: 4.131.1(@cloudflare/workers-types@5.20260911.1)(@types/node@25.0.3) @@ -330,6 +384,75 @@ packages: resolution: {integrity: sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==} engines: {node: '>=6.9.0'} + '@biomejs/biome@2.6.9': + resolution: {integrity: sha512-RelCBDzTXu4DBU8c35P4iMrDO80SUjW0OgjDA7CT1z3UcCU5IclWTZ2XnMelI4frQL//xg2K2BQxAhcOKxdPQA==} + engines: {node: '>=14.21.3'} + hasBin: true + + '@biomejs/cli-android-arm64@2.6.9': + resolution: {integrity: sha512-/3Aj5aiG+Iz8yDBJJb/GFDsptr9ONk3n1wZUIERuU+pVXMIslBaOnrTYJI5QVVXZ9jE494myQHiIvFrjQCBYeQ==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [android] + + '@biomejs/cli-android-x64@2.6.9': + resolution: {integrity: sha512-erjbUpD9KJhzTsGHY9oStJ1bSiUJ1ikUXgdr0iOFoIAMiKqW+GdVdEqAlEyqiZA6CBiFqf2fV+g0AVl3hYOuYg==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [android] + + '@biomejs/cli-darwin-arm64@2.6.9': + resolution: {integrity: sha512-fO67s0SF+lKGhNPQ7jUXiz0yXGl/1Qm3XTIn/4Hd2Z2z3ewQMrotWIMVdIPxZAgLJdQtRLBOzgsTRzTl981yWA==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [darwin] + + '@biomejs/cli-darwin-x64@2.6.9': + resolution: {integrity: sha512-RdjT3Z6dLlii0x6EroncTp9jg38FMx2R1aeaaU4BbZ4//3TJ2mA2R39KMIrZYxHdHXcfv9X2V5hwKkXhg08w/g==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [darwin] + + '@biomejs/cli-linux-arm64-musl@2.6.9': + resolution: {integrity: sha512-qoG0R5MhJ8VFozVFZQC42V3qCI1TInDhL/YcPPg0oTzfv3vuh0ZDXj+2nNahq8gboHUMv7MWpGjRDLhpQatJ+A==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-arm64@2.6.9': + resolution: {integrity: sha512-x73OpQSuQLuvNfzXWEjf0mK95NxlJQX4eG/jmuSrGWOz+/jcLUE4N/21yBu3n0X+wa8bJ3NsWNvmNacLnyc2CQ==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-linux-x64-musl@2.6.9': + resolution: {integrity: sha512-o73Sk1hCbGOFOrDlxtpHGIubnLwMXscT32+ujMwUyq9o0f4onxO7OznzkFgcZGbwKy1R3ohroOkqZDXqj1u29g==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-x64@2.6.9': + resolution: {integrity: sha512-uVrqS0HDjRzFlx88ZpfmlZvJ+xIwTU+110vunzrYvZQ5OqXl/1ugMTNvAs61hejH7jh7iequKJwagRVarrYcSQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-win32-arm64@2.6.9': + resolution: {integrity: sha512-4yvNG4nQGJsJA/PTVAt8IBFXvY6hXk4UdjtPlTf4QTMIjH7ysOwBew78bKThkRv1eyRwH2mGLIk4lAZp8tfAdw==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [win32] + + '@biomejs/cli-win32-x64@2.6.9': + resolution: {integrity: sha512-mwarNc4GEg5JknsRaJDyJDFr4kICD7snsGM8yYFOoIHimSU1ekWNbcZ44QDa6/30fUZC9077wbBpXE8fp03aug==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [win32] + '@blazediff/core@1.10.0': resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==} @@ -382,6 +505,9 @@ packages: cpu: [x64] os: [win32] + '@bufbuild/protobuf@2.17.0': + resolution: {integrity: sha512-hcPkSz6D7MiTU/5VBBhK+kxaYDoOdQ6yJRFJ3kS8Nydp+VZXfg1vrpABKPNod8bXMufsVCmiUJVIKFzCzta4uw==} + '@capsizecss/unpack@4.0.1': resolution: {integrity: sha512-CuNiSqg7+e1cO/GjffyMOm5Tt2jUF9CWHHnvQ/UkqvtkGfHdgwEC0wpmq7fkN3gxwpRnrAN0WzO3vREKmNolMQ==} engines: {node: '>=18'} @@ -482,18 +608,27 @@ packages: '@emnapi/core@1.11.3': resolution: {integrity: sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==} + '@emnapi/core@2.0.0-beta.3': + resolution: {integrity: sha512-KA+gOBtbifRATmUa/Gpf5C2B2EJ0r4brHUT3XSgACeHREcuiObXH56xd+B3fFsEFbUT04VBEe6MuZiCtMp0tQg==} + '@emnapi/runtime@1.11.1': resolution: {integrity: sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==} '@emnapi/runtime@1.11.3': resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} + '@emnapi/runtime@2.0.0-beta.3': + resolution: {integrity: sha512-ayb/PyyLzpwRyFVxeC0uoEHu59QlB1iWGcGsOpXQcaB/Dc+uGfBmNmpCHp3HmTT0t8lSsMmg3j7+tdJW/TlHjQ==} + '@emnapi/wasi-threads@1.2.2': resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} '@emnapi/wasi-threads@1.2.3': resolution: {integrity: sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==} + '@emnapi/wasi-threads@2.2.0': + resolution: {integrity: sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==} + '@epic-web/invariant@1.0.0': resolution: {integrity: sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==} @@ -973,6 +1108,12 @@ packages: cpu: [x64] os: [win32] + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + '@jridgewell/resolve-uri@3.1.2': resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} @@ -1718,6 +1859,123 @@ packages: resolution: {integrity: sha512-S0uyoxakDINJ4DPgqxGlEEvrdSMeQb7Z2lKVjxoY2gwsbZbfg2Xr8Klfeo5ZeraHmmdBCELFUHkSe6KEmBpMvg==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + '@pagefind/darwin-arm64@1.6.0': + resolution: {integrity: sha512-611gl64aqN12UcMyKPtZ8+vRWBKlJFSh2JgO8uScxa1Eyjo1dXz9r4wZuRno0yCUE/KN0FauEoKZ3KEwUYHCCg==} + cpu: [arm64] + os: [darwin] + + '@pagefind/darwin-x64@1.6.0': + resolution: {integrity: sha512-rd3ZbtuxyYqjASKZAPuIV7eeQQHJ7VYpoNKKG8CvglaD3g30eT5Nb7XGNLYwVReBsCccpkURwrGwWjSwr8nyQQ==} + cpu: [x64] + os: [darwin] + + '@pagefind/freebsd-x64@1.6.0': + resolution: {integrity: sha512-d+sXqsaThszmPWGVDSRKqIz9GpZcj/bAksNZfg19asSxU0ogNPOMND4kV4giQvOjPFMsltUFf6hQJfoHQ6+hSQ==} + cpu: [x64] + os: [freebsd] + + '@pagefind/linux-arm64@1.6.0': + resolution: {integrity: sha512-SLB2I+XqCZma8NvIGIH8nyKblgKIxw5PmqsVtofWOKxNHhEtOEsddbqU+hsrNcT3EV0faM6UmKDHVIxcPYq29w==} + cpu: [arm64] + os: [linux] + + '@pagefind/linux-x64@1.6.0': + resolution: {integrity: sha512-IbMSx/+Vr/Xk0TTBlLkjgK+rvnbOXGmmb2/MKxQu99AR5DsqQoV3NKEA9PQz2tAhuCZjeD5xJBp4w5N5DHIC7Q==} + cpu: [x64] + os: [linux] + + '@pagefind/windows-arm64@1.6.0': + resolution: {integrity: sha512-wUrniW3REr7VWJHz6xE6F/p/AQgHDFpGZiY9sbWT71KfEijDE5Jnc37V8zc7cilV9h/QkwJGXoEP2+ZLwDmhtw==} + cpu: [arm64] + os: [win32] + + '@pagefind/windows-x64@1.6.0': + resolution: {integrity: sha512-cUA2+yXfbymdJllyMjY5YTBwuOgh0/H53Pn5fYKjDnDjk154Ft4U5RVj3TenWySPL/jG6zJfARUWSlyUyXHlZw==} + cpu: [x64] + os: [win32] + + '@parcel/watcher-android-arm64@2.6.0': + resolution: {integrity: sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [android] + + '@parcel/watcher-darwin-arm64@2.6.0': + resolution: {integrity: sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [darwin] + + '@parcel/watcher-darwin-x64@2.6.0': + resolution: {integrity: sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [darwin] + + '@parcel/watcher-freebsd-x64@2.6.0': + resolution: {integrity: sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [freebsd] + + '@parcel/watcher-linux-arm-glibc@2.6.0': + resolution: {integrity: sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==} + engines: {node: '>= 10.0.0'} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@parcel/watcher-linux-arm-musl@2.6.0': + resolution: {integrity: sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==} + engines: {node: '>= 10.0.0'} + cpu: [arm] + os: [linux] + libc: [musl] + + '@parcel/watcher-linux-arm64-glibc@2.6.0': + resolution: {integrity: sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@parcel/watcher-linux-arm64-musl@2.6.0': + resolution: {integrity: sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@parcel/watcher-linux-x64-glibc@2.6.0': + resolution: {integrity: sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@parcel/watcher-linux-x64-musl@2.6.0': + resolution: {integrity: sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@parcel/watcher-win32-arm64@2.6.0': + resolution: {integrity: sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [win32] + + '@parcel/watcher-win32-x64@2.6.0': + resolution: {integrity: sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [win32] + + '@parcel/watcher@2.6.0': + resolution: {integrity: sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==} + engines: {node: '>= 10.0.0'} + '@playwright/browser-chromium@1.63.0': resolution: {integrity: sha512-m2daAx2QmBFeO8iqVjeCrYlihlhw1FchLQayCCZsZ2IdvA7Uk7sFsjNm7RleAt2rDARH/ZEtXQi7e65WB1VGPQ==} engines: {node: '>=20'} @@ -1839,6 +2097,108 @@ packages: '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + '@rspack/binding-darwin-arm64@2.3.4': + resolution: {integrity: sha512-eBD71fbmoJKnxcHD03bukbAIOP5r7nD0Ehs+mUrUQlZ6N53EhuJsTeJ1oYdg5L4GoSeQ+KecCqME81Nm0COLrA==} + cpu: [arm64] + os: [darwin] + + '@rspack/binding-darwin-x64@2.3.4': + resolution: {integrity: sha512-CqdfzTLPVFQCniOy/GDVWbg+rqg31qfdzbFf8NYCzdDkCQg+p15hU2HsckD/1sLsaNB8Y55EjGz4ZyGDny0cHg==} + cpu: [x64] + os: [darwin] + + '@rspack/binding-linux-arm64-gnu@2.3.4': + resolution: {integrity: sha512-T/Y1FYiSegcNc+oHuDOLRGIcc+eSdBnfbS70d51EWQj4+0TG/tlfuqFKeAIL3mnKUV5lDLaTz3vsoD0Sws5Fxw==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rspack/binding-linux-arm64-musl@2.3.4': + resolution: {integrity: sha512-WZHCzZ532UfXFXNU8XyM8jb+I6wddegbs/7IXsyw7xiPwwZX1D/M6iKFVpBYdvKcupUM8bS8Uw2REirR/cERVw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rspack/binding-linux-ppc64-gnu@2.3.4': + resolution: {integrity: sha512-WeizqeI6HIh7Ax9w2tlmpTtipJWxXcdgt3QqI3N9LOixymlMD5yMBMZNPqwZ6cHXT9gOQ69SvPcVgMwxsdmceQ==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rspack/binding-linux-riscv64-gnu@2.3.4': + resolution: {integrity: sha512-h+001Vbq8LyGwPMNkeRWidPOVKwlAbwNPskY3CjNlSw3euHkVchfhM3uo6+1h0GyTtb3rzsWqsfm1kar7m/tiQ==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rspack/binding-linux-riscv64-musl@2.3.4': + resolution: {integrity: sha512-S1rlaCnNVG5s4WZ9odLsqN3ySh5TEdNTLXWapEK8x3iQl56aLtdvqXTfbJWHWnYLJuS7M1WqnQGdJNdjy2NDsA==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rspack/binding-linux-s390x-gnu@2.3.4': + resolution: {integrity: sha512-0SkgGrgulVMam3xel5dMNKQ+U7BEpCczhF1avGT1DzDVIbMfIOsbb32gApQNSz0E7RfAQ/Pa5eWiA9oyRq7ZMQ==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rspack/binding-linux-x64-gnu@2.3.4': + resolution: {integrity: sha512-q7E6x3rJJ/9fJyLuRe5+KyEPi23BF/xkAU4xCM5VwLkTf+rVyOkDZfu0qOkxmILjrxllQPV+b/ojBL/ZaIeQPw==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rspack/binding-linux-x64-musl@2.3.4': + resolution: {integrity: sha512-rey4Tyasui/WeMn6KfhH5xyZGOMt+Ny+GDK7nGh9TSz/cb3/bisxqGzpbu6GJK8leDmTUDD5ZdpODexytA5rzQ==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rspack/binding-wasm32-wasi@2.3.4': + resolution: {integrity: sha512-sDt2MSXZrIaMBa6UaEqmXEqebwpTOPAXLdo9CYJ2Fa9FJWP4TCYbn30mbvV38ZC2n5YX411DRbjck+s97CceIg==} + cpu: [wasm32] + + '@rspack/binding-win32-arm64-msvc@2.3.4': + resolution: {integrity: sha512-24YC1YSodLAJ8VsMQJmJSHCNvHTqK9JP5hj50T50WE8lCHNsNl/rIYXO9V0VlCYT/HshE6EHHzAeKdahiEOtcw==} + cpu: [arm64] + os: [win32] + + '@rspack/binding-win32-ia32-msvc@2.3.4': + resolution: {integrity: sha512-xmUNu6kgV9lLEkRP1Zb+t6i1Z1ZMEWXmLlMalPx8tHqndz2RflNMBBx6kjB2nAPQBIZgWufwm7dVGS0HKomCmw==} + cpu: [ia32] + os: [win32] + + '@rspack/binding-win32-x64-msvc@2.3.4': + resolution: {integrity: sha512-WY+AkJqpbLtLEZiG1fE7CVJZ54y0qHeCiVmLxGBsh4OOGIDCs6v2Ub5COcPrYVzGJFGyeHUS29dV7JAs93qIHw==} + cpu: [x64] + os: [win32] + + '@rspack/binding@2.3.4': + resolution: {integrity: sha512-wSOT16LVITL/IKeIiLXgN5Q5jZIDqnQ7Gmk+wzKOSZ6OHYNfEBXAKhSJuYtCBq8ovJuGl8cJjdqatAlHE5XKIA==} + + '@rspack/cli@2.3.4': + resolution: {integrity: sha512-K6TTCSCR/u96jLll0pp3efSrrDz0gDuD5Or4AEMFEG3mm7jFghoNGRQ26cX9gbsKNBD/hoeqrJdbPq1p4fpkVA==} + hasBin: true + peerDependencies: + '@rspack/core': ^2.3.0-0 + '@rspack/dev-server': ^2.0.0-0 + peerDependenciesMeta: + '@rspack/dev-server': + optional: true + + '@rspack/core@2.3.4': + resolution: {integrity: sha512-T8HGkIjPVDlGlIN8st/ICe8Gfixq8te75g/8crSdNSf8F+6884sBcKNky0CRdfPxao1C5SXV+Vjv1XJTjyu83w==} + engines: {node: ^20.19.0 || >=22.12.0} + peerDependencies: + '@module-federation/runtime-tools': ^0.24.1 || ^2.0.0 + '@swc/helpers': ^0.5.23 + peerDependenciesMeta: + '@module-federation/runtime-tools': + optional: true + '@swc/helpers': + optional: true + '@shikijs/core@4.6.0': resolution: {integrity: sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw==} engines: {node: '>=20'} @@ -1880,6 +2240,98 @@ packages: '@swc/helpers@0.5.15': resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==} + '@tailwindcss/cli@4.3.5': + resolution: {integrity: sha512-+evrrLZEgNPDXgdIxD6Zfc23WhSYZQeGwniO5u9M4zC92kbEtIjKd8l2QWeO7du8kl4gF8z7YArnUGHG4y2Jzg==} + hasBin: true + + '@tailwindcss/node@4.3.5': + resolution: {integrity: sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==} + + '@tailwindcss/oxide-android-arm64@4.3.5': + resolution: {integrity: sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [android] + + '@tailwindcss/oxide-darwin-arm64@4.3.5': + resolution: {integrity: sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [darwin] + + '@tailwindcss/oxide-darwin-x64@4.3.5': + resolution: {integrity: sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==} + engines: {node: '>= 20'} + cpu: [x64] + os: [darwin] + + '@tailwindcss/oxide-freebsd-x64@4.3.5': + resolution: {integrity: sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==} + engines: {node: '>= 20'} + cpu: [x64] + os: [freebsd] + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.5': + resolution: {integrity: sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==} + engines: {node: '>= 20'} + cpu: [arm] + os: [linux] + + '@tailwindcss/oxide-linux-arm64-gnu@4.3.5': + resolution: {integrity: sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@tailwindcss/oxide-linux-arm64-musl@4.3.5': + resolution: {integrity: sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@tailwindcss/oxide-linux-x64-gnu@4.3.5': + resolution: {integrity: sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@tailwindcss/oxide-linux-x64-musl@4.3.5': + resolution: {integrity: sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@tailwindcss/oxide-wasm32-wasi@4.3.5': + resolution: {integrity: sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + bundledDependencies: + - '@napi-rs/wasm-runtime' + - '@emnapi/core' + - '@emnapi/runtime' + - '@tybys/wasm-util' + - '@emnapi/wasi-threads' + - tslib + + '@tailwindcss/oxide-win32-arm64-msvc@4.3.5': + resolution: {integrity: sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [win32] + + '@tailwindcss/oxide-win32-x64-msvc@4.3.5': + resolution: {integrity: sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==} + engines: {node: '>= 20'} + cpu: [x64] + os: [win32] + + '@tailwindcss/oxide@4.3.5': + resolution: {integrity: sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==} + engines: {node: '>= 20'} + '@testing-library/dom@10.4.1': resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} engines: {node: '>=18'} @@ -2467,6 +2919,9 @@ packages: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} + colorjs.io@0.7.1: + resolution: {integrity: sha512-LY7OHnJZxHwT5UlzNa9bbhHHDbzB6yE5+3MIPwJEQKRvSCt/T4G7epsj+9j2BExUIIfXFIJGsIXUKdfrK9Q5tA==} + comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} @@ -2607,6 +3062,10 @@ packages: resolution: {integrity: sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==} engines: {node: '>=14'} + enhanced-resolve@5.27.0: + resolution: {integrity: sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==} + engines: {node: '>=10.13.0'} + entities@4.5.0: resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} engines: {node: '>=0.12'} @@ -2696,6 +3155,9 @@ packages: github-slugger@2.0.0: resolution: {integrity: sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==} + graceful-fs@4.2.12: + resolution: {integrity: sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==} + h3@1.15.11: resolution: {integrity: sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==} @@ -2712,6 +3174,10 @@ packages: ocache: optional: true + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + hast-util-to-html@9.0.6: resolution: {integrity: sha512-1SZUxCN3TtJAE7e2BQN2MBHsoZ1gnmi9GoCP5Di59CSWptIezSAW09yDZyVbanb78V9eCwrKqdQsjtfVTxYHWA==} @@ -2733,6 +3199,9 @@ packages: httpxy@0.5.6: resolution: {integrity: sha512-iqc3nOxvNb5FxbhJozt8wNmHgjlmk4zzba512jMEXVwHCEBCbGAj49eGfy5PI8ts3/LFSFq8siiSNqwfY1AlfQ==} + immutable@5.2.1: + resolution: {integrity: sha512-CgXNM1BhKqpMjFHTyqQSk09OWqzHNJ/U4BdeBgXoBdR2DdgBdOSv131cO1/YMgzopqnka3B/i949UaMLEKUxOA==} + import-without-cache@0.4.1: resolution: {integrity: sha512-vXoV9PjKHEednCUu01e98TkImxy67e3BJXbTIOmIq4Hyzw3IAwYRcuPkfeTzJzwyyts4kjuA73x+pWJLc4f86A==} engines: {node: ^22.18.0 || >=24.0.0} @@ -2745,6 +3214,14 @@ packages: engines: {node: '>=20'} hasBin: true + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + is-plain-obj@4.1.0: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} @@ -2752,6 +3229,10 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + jose@6.2.17: resolution: {integrity: sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==} @@ -2881,6 +3362,10 @@ packages: resolution: {integrity: sha512-CRieJmvHx+7rNqnA5SKdsYsER6rfkUIE/jruIUw+fLhsQ4sORfuMtr3+FQzsQ9/y8lhk061V4Fl1DFdHiyBB6g==} engines: {node: '>=22.0.0'} + mri@1.2.0: + resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==} + engines: {node: '>=4'} + mrmime@2.0.1: resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==} engines: {node: '>=10'} @@ -2926,6 +3411,9 @@ packages: nlcst-to-string@4.0.0: resolution: {integrity: sha512-YKLBCcUYKAg0FNlOBT6aI91qFmSiFKiluk655WzPF+DDMA02qIyy8uiRqI8QXtcFpEvll12LpL5MXqEmAZ+dcA==} + node-addon-api@7.1.1: + resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==} + node-fetch-native@1.6.7: resolution: {integrity: sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==} @@ -3044,6 +3532,10 @@ packages: package-manager-detector@1.9.0: resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} + pagefind@1.6.0: + resolution: {integrity: sha512-yeOd9EA0TUE1PUfbQIluBxzPadBG5/0BV48FAxwMVLkhZcOvwCz6TX4/a/Ofz97pF9/FwwT7CVbTC97BfmI+LQ==} + hasBin: true + path-key@3.1.1: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} @@ -3174,17 +3666,142 @@ packages: vue-tsc: optional: true - rolldown@1.2.15: - resolution: {integrity: sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==} - engines: {node: ^20.19.0 || >=22.12.0} + rolldown@1.2.15: + resolution: {integrity: sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + rou3@0.9.2: + resolution: {integrity: sha512-3SOzvaAg8rkHrXtRjpCvCvbyO5to9oOO27Z/XqHEYXfMRVSw/qMIVdmaOk9W2lcRLtR6dlqTjo9hDeJk70QBYQ==} + + rou3@1.0.0: + resolution: {integrity: sha512-ySeaQkSrua+ut9g+65I7FHqOFBaY8tV0FmccXItoq0q21se32Q3u4YiW7/RqXSosWgYJaaKwRHXy3BST9PeCNQ==} + engines: {node: '>=20.19.0'} + + rxjs@7.8.2: + resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==} + + sass-embedded-all-unknown@1.108.2: + resolution: {integrity: sha512-VlIJTjCc82VhLKV7EAPJ4fdJn/EM0q0djOzYBjmsuK1i95b1oVKS6NPa4qQMjeKq3LPTsNyH6eYHZTHKCMhIzw==} + cpu: ['!arm', '!arm64', '!riscv64', '!x64'] + + sass-embedded-android-arm64@1.108.2: + resolution: {integrity: sha512-9OWtObry0k/4u+ervuEcgcMM1YVZCqZbcPxGkXuuDjykbWyyvcaVZ1F+8Fup7wod6BVGqbiQfgdfsXd4zsbcPg==} + engines: {node: '>=14.0.0'} + cpu: [arm64] + os: [android] + + sass-embedded-android-arm@1.108.2: + resolution: {integrity: sha512-18L7VPiIqT/nUOy9bo+dhURVGrRE1c3qClueOEQu4AlkuCs8atnSErkA4icMo4pklzY2XQ3NCRhKfaCe66Lbuw==} + engines: {node: '>=14.0.0'} + cpu: [arm] + os: [android] + + sass-embedded-android-riscv64@1.108.2: + resolution: {integrity: sha512-K5Hgenk+cfq+eZ5rqfpf6DyqkpZjawmAEpPBBcZFNFpsEdfu2F1L2ld0cFYGmifz7V54Kh9Q9MIhG/5ma3EAAg==} + engines: {node: '>=14.0.0'} + cpu: [riscv64] + os: [android] + + sass-embedded-android-x64@1.108.2: + resolution: {integrity: sha512-HalOpck3jfo6+PNjDGeohrfswMStSPdvcsHFdWkF8wib5aTwrpirFTY3ZdtGBXLlg5fccN6c3kQGUwMlOZRobw==} + engines: {node: '>=14.0.0'} + cpu: [x64] + os: [android] + + sass-embedded-darwin-arm64@1.108.2: + resolution: {integrity: sha512-wca4RdevELodsjjk+4K1lqhzVfnBf0nCvvtw7YEpbXxGgkMJhHDbh/mf8Gyy3zCKISls9MKm7dPU23G8GGnmeQ==} + engines: {node: '>=14.0.0'} + cpu: [arm64] + os: [darwin] + + sass-embedded-darwin-x64@1.108.2: + resolution: {integrity: sha512-MJnsh5mVPA2Hy7XKaryfAwUCoDy4MuCkcDbe0Jj4j7F7iaVAhX2dPAyvBvMGBIhhMEeFfYlkxYX/Lhbl+7x8SQ==} + engines: {node: '>=14.0.0'} + cpu: [x64] + os: [darwin] + + sass-embedded-linux-arm64@1.108.2: + resolution: {integrity: sha512-DQGGHEe+P1cv3ydBC0Gyh8I42X7xRIOBF+/1o5DyEuexMLHEEF7ZI9rmu8xJfBJv6lW0r8Gsrjke09c63dAOaQ==} + engines: {node: '>=14.0.0'} + cpu: [arm64] + os: [linux] + libc: glibc + + sass-embedded-linux-arm@1.108.2: + resolution: {integrity: sha512-OdsYCHqp5oh3vLqJCov4xXKeEUWS0+8ff+HIofWgTQYEC9Z3+3SYMRiNiGO37Qxt+QNsKXSvo+hsIqVMrfHHfw==} + engines: {node: '>=14.0.0'} + cpu: [arm] + os: [linux] + libc: glibc + + sass-embedded-linux-musl-arm64@1.108.2: + resolution: {integrity: sha512-pYa1W4FYqMPsTMNi4/T76AEcqXpgUntzHpaJUsK+TaxQ+Y9+oaOxPL5mVz+Rg+RBj1UOHJRJ4GO86hVrF8dUqg==} + engines: {node: '>=14.0.0'} + cpu: [arm64] + os: [linux] + libc: musl + + sass-embedded-linux-musl-arm@1.108.2: + resolution: {integrity: sha512-TEjaziqiHj08QHZztOD26HQAkdC5mQLvFj+GMv8sUCxgEPAusDR/bx6KieWfNqAhajXte9aczwdjYVsURMp7KA==} + engines: {node: '>=14.0.0'} + cpu: [arm] + os: [linux] + libc: musl + + sass-embedded-linux-musl-riscv64@1.108.2: + resolution: {integrity: sha512-g+6V6IIYK3dRF7fYQBppNRCtnZl22JncUhmYLL8eTqTIiBpjhIFXavguVX6Z0JW0ZMvlqL3K2TmDMh3sVXpeDA==} + engines: {node: '>=14.0.0'} + cpu: [riscv64] + os: [linux] + libc: musl + + sass-embedded-linux-musl-x64@1.108.2: + resolution: {integrity: sha512-X2XN+HepJ3+GGDrvBc13Qn0DqQh8rs7C6N6qA/IrUvNcWvhCTdB2G3pBYsSds61LiQM26S+pAwFirX4SbwIMRw==} + engines: {node: '>=14.0.0'} + cpu: [x64] + os: [linux] + libc: musl + + sass-embedded-linux-riscv64@1.108.2: + resolution: {integrity: sha512-GL5t80FVizbU1QgJI3eh8125ZtR8i//csqDqncrIwzDBioJwxIYNNhLdKHpp5DjCdD9qst04p4KG1aVM+XPw/Q==} + engines: {node: '>=14.0.0'} + cpu: [riscv64] + os: [linux] + libc: glibc + + sass-embedded-linux-x64@1.108.2: + resolution: {integrity: sha512-9SNMGIYzfdMAflPlNLQro9gIWbrbrSibwffatFaEmjMPBHqy2gNwg7VuzDRHBygbSqsrsqfhokYGchCyzCZI9Q==} + engines: {node: '>=14.0.0'} + cpu: [x64] + os: [linux] + libc: glibc + + sass-embedded-unknown-all@1.108.2: + resolution: {integrity: sha512-FYjLjAyr5BxEI2oAB+nT4OkrQZmEcQz8sVRQbxFUtw30MbEZN8WjEEbjqxQjSw4IaYhA8PuUAjvZoTyvcoRYdA==} + os: ['!android', '!darwin', '!linux', '!win32'] + + sass-embedded-win32-arm64@1.108.2: + resolution: {integrity: sha512-7TGjLKlKjAwWIZhM+VrXzc1jj/Z/88bLqf3/jJSkzM2vbsj6kDp7F0DmIs9wJ0KBLAMnu5ZOCFDG61oJfJuT8Q==} + engines: {node: '>=14.0.0'} + cpu: [arm64] + os: [win32] + + sass-embedded-win32-x64@1.108.2: + resolution: {integrity: sha512-zgy9m/e47V0Ib2fDmpAqDO6seFqeVa+cgYitdsMEp704x8e+diybz2fg7rsdGXqa/XlGR2dzT7vtcFSbZkF44w==} + engines: {node: '>=14.0.0'} + cpu: [x64] + os: [win32] + + sass-embedded@1.108.2: + resolution: {integrity: sha512-+T+jag2BFS2RKipKF80uCAuNztA8VC7T9PU716xMe9Ob1Su4uDZf9vj0JBeSxcQo1vy6EMdiwZFXTRmvuAhl0g==} + engines: {node: '>=20.19.0'} hasBin: true - rou3@0.9.2: - resolution: {integrity: sha512-3SOzvaAg8rkHrXtRjpCvCvbyO5to9oOO27Z/XqHEYXfMRVSw/qMIVdmaOk9W2lcRLtR6dlqTjo9hDeJk70QBYQ==} - - rou3@1.0.0: - resolution: {integrity: sha512-ySeaQkSrua+ut9g+65I7FHqOFBaY8tV0FmccXItoq0q21se32Q3u4YiW7/RqXSosWgYJaaKwRHXy3BST9PeCNQ==} + sass@1.108.2: + resolution: {integrity: sha512-kugK8djotnG9HQRPTOf36asKYlxg8rWWsNLYHOgWDIVOiZQqlRfKBgF4XXM6kfw146kIDMvm57B4GIkvDSyTzA==} engines: {node: '>=20.19.0'} + hasBin: true satteri@0.10.5: resolution: {integrity: sha512-Ao1LKpAEa9Wdg0otgbVKViZHEq9ebdXe4DMrp3s9vQAU0HNIuHnFEuMuOcm0ZIXyV0Yzxj91NvhLpvXZJO/5ZQ==} @@ -3277,11 +3894,30 @@ packages: resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} engines: {node: '>=18'} + supports-color@8.1.1: + resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==} + engines: {node: '>=10'} + svgo@4.1.0: resolution: {integrity: sha512-bkxnTg1kSU0guhIBmibA6UUhrQmPVA1XsQLN+ylCd+UWzbnLkySOcXpyk1mrl05f+pcaCx2eHb+sp6BgMZWX+Q==} engines: {node: '>=16'} hasBin: true + sync-child-process@1.1.1: + resolution: {integrity: sha512-54zMOnH5qgjdKW8SGpCx3daSP+v+TtTfOxgPdhUE3P0hytMMpknZfP67S4JeRcx5IQRWJERz6890yO4dkTywww==} + engines: {node: '>=16.0.0'} + + sync-message-port@1.2.0: + resolution: {integrity: sha512-gAQ9qrUN/UCypHtGFbbe7Rc/f9bzO88IwrG8TDo/aMKAApKyD6E3W4Cm0EfhfBb6Z6SKt59tTCTfD+n1xmAvMg==} + engines: {node: '>=16.0.0'} + + tailwindcss@4.3.5: + resolution: {integrity: sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==} + + tapable@2.3.4: + resolution: {integrity: sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==} + engines: {node: '>=6'} + tiny-inflate@1.0.3: resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} @@ -3360,6 +3996,11 @@ packages: tslib@2.9.1: resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + tsx@4.23.15: + resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==} + engines: {node: '>=18.0.0'} + hasBin: true + typescript@6.0.3: resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} engines: {node: '>=14.17'} @@ -3482,6 +4123,9 @@ packages: unstorage@2.0.0-beta.0: resolution: {integrity: sha512-VeTY+zQ3ozrNtIFBRQRuSwanHdpuRH+4t/ZzchZIVQO8/oKq2xl7fJ9c+z76tWJDW/BEXSEuzpHOxqoAl6B64A==} + varint@6.0.0: + resolution: {integrity: sha512-cXEIW6cfr15lFv563k4GuVuW/fiwjknytD37jIOLSdSWuOI6WnO/oKwmP2FQTU2l01LP8/M5TSAJpzUaGe3uWg==} + verkit@0.5.0: resolution: {integrity: sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g==} engines: {node: '>=18.12.0'} @@ -3822,6 +4466,49 @@ snapshots: '@babel/helper-string-parser': 7.29.11 '@babel/helper-validator-identifier': 7.29.7 + '@biomejs/biome@2.6.9': + optionalDependencies: + '@biomejs/cli-android-arm64': 2.6.9 + '@biomejs/cli-android-x64': 2.6.9 + '@biomejs/cli-darwin-arm64': 2.6.9 + '@biomejs/cli-darwin-x64': 2.6.9 + '@biomejs/cli-linux-arm64': 2.6.9 + '@biomejs/cli-linux-arm64-musl': 2.6.9 + '@biomejs/cli-linux-x64': 2.6.9 + '@biomejs/cli-linux-x64-musl': 2.6.9 + '@biomejs/cli-win32-arm64': 2.6.9 + '@biomejs/cli-win32-x64': 2.6.9 + + '@biomejs/cli-android-arm64@2.6.9': + optional: true + + '@biomejs/cli-android-x64@2.6.9': + optional: true + + '@biomejs/cli-darwin-arm64@2.6.9': + optional: true + + '@biomejs/cli-darwin-x64@2.6.9': + optional: true + + '@biomejs/cli-linux-arm64-musl@2.6.9': + optional: true + + '@biomejs/cli-linux-arm64@2.6.9': + optional: true + + '@biomejs/cli-linux-x64-musl@2.6.9': + optional: true + + '@biomejs/cli-linux-x64@2.6.9': + optional: true + + '@biomejs/cli-win32-arm64@2.6.9': + optional: true + + '@biomejs/cli-win32-x64@2.6.9': + optional: true + '@blazediff/core@1.10.0': {} '@bruits/satteri-darwin-arm64@0.10.5': @@ -3855,6 +4542,8 @@ snapshots: '@bruits/satteri-win32-x64-msvc@0.10.5': optional: true + '@bufbuild/protobuf@2.17.0': {} + '@capsizecss/unpack@4.0.1': dependencies: fontkitten: 1.0.3 @@ -3930,6 +4619,12 @@ snapshots: tslib: 2.9.1 optional: true + '@emnapi/core@2.0.0-beta.3': + dependencies: + '@emnapi/wasi-threads': 2.2.0 + tslib: 2.9.1 + optional: true + '@emnapi/runtime@1.11.1': dependencies: tslib: 2.9.1 @@ -3940,6 +4635,11 @@ snapshots: tslib: 2.9.1 optional: true + '@emnapi/runtime@2.0.0-beta.3': + dependencies: + tslib: 2.9.1 + optional: true + '@emnapi/wasi-threads@1.2.2': dependencies: tslib: 2.9.1 @@ -3950,6 +4650,11 @@ snapshots: tslib: 2.9.1 optional: true + '@emnapi/wasi-threads@2.2.0': + dependencies: + tslib: 2.9.1 + optional: true + '@epic-web/invariant@1.0.0': {} '@esbuild/aix-ppc64@0.28.1': @@ -4240,6 +4945,16 @@ snapshots: '@img/sharp-win32-x64@0.35.5': optional: true + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + '@jridgewell/resolve-uri@3.1.2': {} '@jridgewell/sourcemap-codec@1.6.0': {} @@ -4268,6 +4983,13 @@ snapshots: '@tybys/wasm-util': 0.10.4 optional: true + '@napi-rs/wasm-runtime@1.2.7(@emnapi/core@2.0.0-beta.3)(@emnapi/runtime@2.0.0-beta.3)': + dependencies: + '@emnapi/core': 2.0.0-beta.3 + '@emnapi/runtime': 2.0.0-beta.3 + '@tybys/wasm-util': 0.10.4 + optional: true + '@next/env@15.5.29': {} '@next/swc-darwin-arm64@15.5.29': @@ -4631,6 +5353,83 @@ snapshots: '@oxlint/plugins@1.79.0': {} + '@pagefind/darwin-arm64@1.6.0': + optional: true + + '@pagefind/darwin-x64@1.6.0': + optional: true + + '@pagefind/freebsd-x64@1.6.0': + optional: true + + '@pagefind/linux-arm64@1.6.0': + optional: true + + '@pagefind/linux-x64@1.6.0': + optional: true + + '@pagefind/windows-arm64@1.6.0': + optional: true + + '@pagefind/windows-x64@1.6.0': + optional: true + + '@parcel/watcher-android-arm64@2.6.0': + optional: true + + '@parcel/watcher-darwin-arm64@2.6.0': + optional: true + + '@parcel/watcher-darwin-x64@2.6.0': + optional: true + + '@parcel/watcher-freebsd-x64@2.6.0': + optional: true + + '@parcel/watcher-linux-arm-glibc@2.6.0': + optional: true + + '@parcel/watcher-linux-arm-musl@2.6.0': + optional: true + + '@parcel/watcher-linux-arm64-glibc@2.6.0': + optional: true + + '@parcel/watcher-linux-arm64-musl@2.6.0': + optional: true + + '@parcel/watcher-linux-x64-glibc@2.6.0': + optional: true + + '@parcel/watcher-linux-x64-musl@2.6.0': + optional: true + + '@parcel/watcher-win32-arm64@2.6.0': + optional: true + + '@parcel/watcher-win32-x64@2.6.0': + optional: true + + '@parcel/watcher@2.6.0': + dependencies: + detect-libc: 2.1.2 + is-glob: 4.0.3 + node-addon-api: 7.1.1 + picomatch: 4.0.7 + optionalDependencies: + '@parcel/watcher-android-arm64': 2.6.0 + '@parcel/watcher-darwin-arm64': 2.6.0 + '@parcel/watcher-darwin-x64': 2.6.0 + '@parcel/watcher-freebsd-x64': 2.6.0 + '@parcel/watcher-linux-arm-glibc': 2.6.0 + '@parcel/watcher-linux-arm-musl': 2.6.0 + '@parcel/watcher-linux-arm64-glibc': 2.6.0 + '@parcel/watcher-linux-arm64-musl': 2.6.0 + '@parcel/watcher-linux-x64-glibc': 2.6.0 + '@parcel/watcher-linux-x64-musl': 2.6.0 + '@parcel/watcher-win32-arm64': 2.6.0 + '@parcel/watcher-win32-x64': 2.6.0 + '@playwright/browser-chromium@1.63.0': dependencies: playwright-core: 1.63.0 @@ -4702,6 +5501,77 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} + '@rspack/binding-darwin-arm64@2.3.4': + optional: true + + '@rspack/binding-darwin-x64@2.3.4': + optional: true + + '@rspack/binding-linux-arm64-gnu@2.3.4': + optional: true + + '@rspack/binding-linux-arm64-musl@2.3.4': + optional: true + + '@rspack/binding-linux-ppc64-gnu@2.3.4': + optional: true + + '@rspack/binding-linux-riscv64-gnu@2.3.4': + optional: true + + '@rspack/binding-linux-riscv64-musl@2.3.4': + optional: true + + '@rspack/binding-linux-s390x-gnu@2.3.4': + optional: true + + '@rspack/binding-linux-x64-gnu@2.3.4': + optional: true + + '@rspack/binding-linux-x64-musl@2.3.4': + optional: true + + '@rspack/binding-wasm32-wasi@2.3.4': + dependencies: + '@emnapi/core': 2.0.0-beta.3 + '@emnapi/runtime': 2.0.0-beta.3 + '@napi-rs/wasm-runtime': 1.2.7(@emnapi/core@2.0.0-beta.3)(@emnapi/runtime@2.0.0-beta.3) + optional: true + + '@rspack/binding-win32-arm64-msvc@2.3.4': + optional: true + + '@rspack/binding-win32-ia32-msvc@2.3.4': + optional: true + + '@rspack/binding-win32-x64-msvc@2.3.4': + optional: true + + '@rspack/binding@2.3.4': + optionalDependencies: + '@rspack/binding-darwin-arm64': 2.3.4 + '@rspack/binding-darwin-x64': 2.3.4 + '@rspack/binding-linux-arm64-gnu': 2.3.4 + '@rspack/binding-linux-arm64-musl': 2.3.4 + '@rspack/binding-linux-ppc64-gnu': 2.3.4 + '@rspack/binding-linux-riscv64-gnu': 2.3.4 + '@rspack/binding-linux-riscv64-musl': 2.3.4 + '@rspack/binding-linux-s390x-gnu': 2.3.4 + '@rspack/binding-linux-x64-gnu': 2.3.4 + '@rspack/binding-linux-x64-musl': 2.3.4 + '@rspack/binding-wasm32-wasi': 2.3.4 + '@rspack/binding-win32-arm64-msvc': 2.3.4 + '@rspack/binding-win32-ia32-msvc': 2.3.4 + '@rspack/binding-win32-x64-msvc': 2.3.4 + + '@rspack/cli@2.3.4(@rspack/core@2.3.4)': + dependencies: + '@rspack/core': 2.3.4 + + '@rspack/core@2.3.4': + dependencies: + '@rspack/binding': 2.3.4 + '@shikijs/core@4.6.0': dependencies: '@shikijs/primitive': 4.6.0 @@ -4750,6 +5620,77 @@ snapshots: dependencies: tslib: 2.9.1 + '@tailwindcss/cli@4.3.5': + dependencies: + '@parcel/watcher': 2.6.0 + '@tailwindcss/node': 4.3.5 + '@tailwindcss/oxide': 4.3.5 + enhanced-resolve: 5.27.0 + mri: 1.2.0 + picocolors: 1.1.1 + tailwindcss: 4.3.5 + + '@tailwindcss/node@4.3.5': + dependencies: + '@jridgewell/remapping': 2.3.5 + enhanced-resolve: 5.27.0 + jiti: 2.7.0 + lightningcss: 1.33.0 + magic-string: 1.4.2 + source-map-js: 1.2.1 + tailwindcss: 4.3.5 + + '@tailwindcss/oxide-android-arm64@4.3.5': + optional: true + + '@tailwindcss/oxide-darwin-arm64@4.3.5': + optional: true + + '@tailwindcss/oxide-darwin-x64@4.3.5': + optional: true + + '@tailwindcss/oxide-freebsd-x64@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-arm64-gnu@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-arm64-musl@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-x64-gnu@4.3.5': + optional: true + + '@tailwindcss/oxide-linux-x64-musl@4.3.5': + optional: true + + '@tailwindcss/oxide-wasm32-wasi@4.3.5': + optional: true + + '@tailwindcss/oxide-win32-arm64-msvc@4.3.5': + optional: true + + '@tailwindcss/oxide-win32-x64-msvc@4.3.5': + optional: true + + '@tailwindcss/oxide@4.3.5': + optionalDependencies: + '@tailwindcss/oxide-android-arm64': 4.3.5 + '@tailwindcss/oxide-darwin-arm64': 4.3.5 + '@tailwindcss/oxide-darwin-x64': 4.3.5 + '@tailwindcss/oxide-freebsd-x64': 4.3.5 + '@tailwindcss/oxide-linux-arm-gnueabihf': 4.3.5 + '@tailwindcss/oxide-linux-arm64-gnu': 4.3.5 + '@tailwindcss/oxide-linux-arm64-musl': 4.3.5 + '@tailwindcss/oxide-linux-x64-gnu': 4.3.5 + '@tailwindcss/oxide-linux-x64-musl': 4.3.5 + '@tailwindcss/oxide-wasm32-wasi': 4.3.5 + '@tailwindcss/oxide-win32-arm64-msvc': 4.3.5 + '@tailwindcss/oxide-win32-x64-msvc': 4.3.5 + '@testing-library/dom@10.4.1': dependencies: '@babel/code-frame': 7.29.7 @@ -4832,13 +5773,13 @@ snapshots: '@ungap/structured-clone@1.4.0': {} - '@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3)': + '@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3)': dependencies: - '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) - '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)) + '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) playwright: 1.63.0 tinyrainbow: 3.2.0 - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)) + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) transitivePeerDependencies: - bufferutil - msw @@ -4846,37 +5787,37 @@ snapshots: - vite optional: true - '@vitest/browser-playwright@5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3)': + '@vitest/browser-playwright@5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3)': dependencies: - '@vitest/browser': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3) - '@vitest/mocker': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + '@vitest/browser': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/mocker': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) playwright: 1.63.0 tinyrainbow: 3.2.0 - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) transitivePeerDependencies: - bufferutil - msw - utf-8-validate - vite - '@vitest/browser-preview@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3)': + '@vitest/browser-preview@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3)': dependencies: '@testing-library/dom': 10.4.1 '@testing-library/user-event': 14.6.7(@testing-library/dom@10.4.1) - '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)) + '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) transitivePeerDependencies: - bufferutil - msw - utf-8-validate - vite - '@vitest/browser-preview@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3)': + '@vitest/browser-preview@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3)': dependencies: '@testing-library/dom': 10.4.1 '@testing-library/user-event': 14.6.7(@testing-library/dom@10.4.1) - '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3) - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3) + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) transitivePeerDependencies: - bufferutil - msw @@ -4884,12 +5825,12 @@ snapshots: - vite optional: true - '@vitest/browser-preview@5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3)': + '@vitest/browser-preview@5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3)': dependencies: '@testing-library/dom': 10.4.1 '@testing-library/user-event': 14.6.7(@testing-library/dom@10.4.1) - '@vitest/browser': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3) - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + '@vitest/browser': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3) + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) transitivePeerDependencies: - bufferutil - msw @@ -4897,17 +5838,17 @@ snapshots: - vite optional: true - '@vitest/browser@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3)': + '@vitest/browser@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3)': dependencies: '@blazediff/core': 1.10.0 - '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)) + '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) '@vitest/ui': 5.0.3(vitest@5.0.3) '@vitest/utils': 5.0.3 magic-string: 1.4.2 pngjs: 7.0.0 sirv: 3.0.2 tinyrainbow: 3.2.0 - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)) + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) ws: 8.22.0 transitivePeerDependencies: - bufferutil @@ -4915,17 +5856,17 @@ snapshots: - utf-8-validate - vite - '@vitest/browser@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3)': + '@vitest/browser@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3)': dependencies: '@blazediff/core': 1.10.0 - '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) + '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) '@vitest/ui': 5.0.3(vitest@5.0.3) '@vitest/utils': 5.0.3 magic-string: 1.4.2 pngjs: 7.0.0 sirv: 3.0.2 tinyrainbow: 3.2.0 - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) ws: 8.22.0 transitivePeerDependencies: - bufferutil @@ -4934,17 +5875,17 @@ snapshots: - vite optional: true - '@vitest/browser@5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3)': + '@vitest/browser@5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3)': dependencies: '@blazediff/core': 1.10.0 - '@vitest/mocker': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + '@vitest/mocker': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) '@vitest/ui': 5.0.3(vitest@5.0.3) '@vitest/utils': 5.0.3 magic-string: 1.4.2 pngjs: 7.0.0 sirv: 3.0.2 tinyrainbow: 3.2.0 - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) ws: 8.22.0 transitivePeerDependencies: - bufferutil @@ -4952,33 +5893,33 @@ snapshots: - utf-8-validate - vite - '@vitest/mocker@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))': + '@vitest/mocker@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))': dependencies: '@jridgewell/trace-mapping': 0.3.31 '@vitest/spy': 5.0.3 estree-walker: 3.0.3 magic-string: 1.4.2 optionalDependencies: - vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)' + vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)' - '@vitest/mocker@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))': + '@vitest/mocker@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))': dependencies: '@jridgewell/trace-mapping': 0.3.31 '@vitest/spy': 5.0.3 estree-walker: 3.0.3 magic-string: 1.4.2 optionalDependencies: - vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)' + vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)' optional: true - '@vitest/mocker@5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))': + '@vitest/mocker@5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@jridgewell/trace-mapping': 0.3.31 '@vitest/spy': 5.0.3 estree-walker: 3.0.3 magic-string: 1.4.2 optionalDependencies: - vite: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1) + vite: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1) '@vitest/pretty-format@5.0.3': dependencies: @@ -5001,7 +5942,7 @@ snapshots: pathe: 2.0.3 sirv: 3.0.2 tinyrainbow: 3.2.0 - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)) + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) '@vitest/utils@5.0.3': dependencies: @@ -5009,7 +5950,7 @@ snapshots: convert-source-map: 2.0.0 tinyrainbow: 3.2.0 - '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)': + '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)': dependencies: '@oxc-project/runtime': 0.153.0 '@oxc-project/types': 0.153.0 @@ -5029,10 +5970,14 @@ snapshots: '@voidzero-dev/vite-plus-win32-x64-msvc': 1.1.0 esbuild: 0.28.1 fsevents: 2.3.3 + jiti: 2.7.0 + sass: 1.108.2 + sass-embedded: 1.108.2 + tsx: 4.23.15 typescript: 6.0.3 yaml: 2.9.1 - '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)': + '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)': dependencies: '@oxc-project/runtime': 0.153.0 '@oxc-project/types': 0.153.0 @@ -5052,6 +5997,10 @@ snapshots: '@voidzero-dev/vite-plus-win32-x64-msvc': 1.1.0 esbuild: 0.28.1 fsevents: 2.3.3 + jiti: 2.7.0 + sass: 1.108.2 + sass-embedded: 1.108.2 + tsx: 4.23.15 typescript: 7.1.0-dev.20261001.1 yaml: 2.9.1 optional: true @@ -5217,7 +6166,7 @@ snapshots: assertion-error@2.0.1: {} - astro@7.3.8(@types/node@25.0.3)(db0@0.4.2)(esbuild@0.28.1)(yaml@2.9.1): + astro@7.3.8(@types/node@25.0.3)(db0@0.4.2)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1): dependencies: '@astrojs/compiler-rs': 0.5.2 '@astrojs/internal-helpers': 0.12.0 @@ -5266,8 +6215,8 @@ snapshots: unifont: 0.7.5 unstorage: 1.17.6(db0@0.4.2) verkit: 0.5.0 - vite: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1) - vitefu: 1.1.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + vite: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1) + vitefu: 1.1.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) xxhash-wasm: 1.1.0 yargs-parser: 22.0.0 zod: 4.6.7 @@ -5353,6 +6302,8 @@ snapshots: clsx@2.1.1: {} + colorjs.io@0.7.1: {} + comma-separated-tokens@2.0.3: {} commander@11.1.0: {} @@ -5469,6 +6420,11 @@ snapshots: empathic@2.1.0: {} + enhanced-resolve@5.27.0: + dependencies: + graceful-fs: 4.2.12 + tapable: 2.3.4 + entities@4.5.0: {} env-runner@0.2.3: @@ -5564,6 +6520,8 @@ snapshots: github-slugger@2.0.0: {} + graceful-fs@4.2.12: {} + h3@1.15.11: dependencies: cookie-es: 1.2.3 @@ -5584,6 +6542,8 @@ snapshots: crossws: 0.4.17(srvx@1.0.8) ocache: 0.3.1 + has-flag@4.0.0: {} + hast-util-to-html@9.0.6: dependencies: '@types/hast': 3.0.5 @@ -5612,16 +6572,26 @@ snapshots: httpxy@0.5.6: {} + immutable@5.2.1: {} + import-without-cache@0.4.1: {} iron-webcrypto@1.2.1: {} is-docker@4.0.0: {} + is-extglob@2.1.1: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + is-plain-obj@4.1.0: {} isexe@2.0.0: {} + jiti@2.7.0: {} + jose@6.2.17: {} js-tokens@4.0.0: {} @@ -5739,13 +6709,15 @@ snapshots: - bufferutil - utf-8-validate + mri@1.2.0: {} + mrmime@2.0.1: {} nanoid@3.3.18: {} neotraverse@1.0.1: {} - next@15.5.29(@types/node@25.0.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1): + next@15.5.29(@types/node@25.0.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(sass@1.108.2): dependencies: '@next/env': 15.5.29 '@swc/helpers': 0.5.15 @@ -5763,6 +6735,7 @@ snapshots: '@next/swc-linux-x64-musl': 15.5.29 '@next/swc-win32-arm64-msvc': 15.5.29 '@next/swc-win32-x64-msvc': 15.5.29 + sass: 1.108.2 sharp: 0.35.5(@types/node@25.0.3) transitivePeerDependencies: - '@babel/core' @@ -5791,6 +6764,8 @@ snapshots: dependencies: '@types/nlcst': 2.0.3 + node-addon-api@7.1.1: {} + node-fetch-native@1.6.7: {} node-forge@1.4.0: {} @@ -5825,7 +6800,7 @@ snapshots: regex: 6.1.0 regex-recursion: 6.0.2 - oxfmt@0.72.0(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(playwright@1.63.0)(typescript@6.0.3)(yaml@2.9.1)): + oxfmt@0.72.0(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)): dependencies: tinypool: 2.2.0 optionalDependencies: @@ -5848,9 +6823,9 @@ snapshots: '@oxfmt/binding-win32-arm64-msvc': 0.72.0 '@oxfmt/binding-win32-ia32-msvc': 0.72.0 '@oxfmt/binding-win32-x64-msvc': 0.72.0 - vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(playwright@1.63.0)(typescript@6.0.3)(yaml@2.9.1) + vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1) - oxfmt@0.72.0(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): + oxfmt@0.72.0(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): dependencies: tinypool: 2.2.0 optionalDependencies: @@ -5873,10 +6848,10 @@ snapshots: '@oxfmt/binding-win32-arm64-msvc': 0.72.0 '@oxfmt/binding-win32-ia32-msvc': 0.72.0 '@oxfmt/binding-win32-x64-msvc': 0.72.0 - vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1) + vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1) optional: true - oxfmt@0.73.0(@astrojs/compiler-rs@0.5.2)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): + oxfmt@0.73.0(@astrojs/compiler-rs@0.5.2)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): dependencies: tinypool: 2.2.0 optionalDependencies: @@ -5900,7 +6875,7 @@ snapshots: '@oxfmt/binding-win32-arm64-msvc': 0.73.0 '@oxfmt/binding-win32-ia32-msvc': 0.73.0 '@oxfmt/binding-win32-x64-msvc': 0.73.0 - vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1) + vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1) oxlint-tsgolint@7.0.2003: optionalDependencies: @@ -5920,7 +6895,7 @@ snapshots: '@oxlint-tsgolint/win32-arm64': 7.0.2008 '@oxlint-tsgolint/win32-x64': 7.0.2008 - oxlint@1.87.0(oxlint-tsgolint@7.0.2003)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(playwright@1.63.0)(typescript@6.0.3)(yaml@2.9.1)): + oxlint@1.87.0(oxlint-tsgolint@7.0.2003)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)): optionalDependencies: '@oxlint/binding-android-arm-eabi': 1.87.0 '@oxlint/binding-android-arm64': 1.87.0 @@ -5942,9 +6917,9 @@ snapshots: '@oxlint/binding-win32-ia32-msvc': 1.87.0 '@oxlint/binding-win32-x64-msvc': 1.87.0 oxlint-tsgolint: 7.0.2003 - vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(playwright@1.63.0)(typescript@6.0.3)(yaml@2.9.1) + vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1) - oxlint@1.87.0(oxlint-tsgolint@7.0.2003)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): + oxlint@1.87.0(oxlint-tsgolint@7.0.2003)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): optionalDependencies: '@oxlint/binding-android-arm-eabi': 1.87.0 '@oxlint/binding-android-arm64': 1.87.0 @@ -5966,10 +6941,10 @@ snapshots: '@oxlint/binding-win32-ia32-msvc': 1.87.0 '@oxlint/binding-win32-x64-msvc': 1.87.0 oxlint-tsgolint: 7.0.2003 - vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1) + vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1) optional: true - oxlint@1.95.0(oxlint-tsgolint@7.0.2008)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): + oxlint@1.95.0(oxlint-tsgolint@7.0.2008)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): optionalDependencies: '@oxlint/binding-android-arm-eabi': 1.95.0 '@oxlint/binding-android-arm64': 1.95.0 @@ -5991,7 +6966,7 @@ snapshots: '@oxlint/binding-win32-ia32-msvc': 1.95.0 '@oxlint/binding-win32-x64-msvc': 1.95.0 oxlint-tsgolint: 7.0.2008 - vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1) + vite-plus: 1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1) p-limit@7.3.3: dependencies: @@ -6006,6 +6981,16 @@ snapshots: package-manager-detector@1.9.0: {} + pagefind@1.6.0: + optionalDependencies: + '@pagefind/darwin-arm64': 1.6.0 + '@pagefind/darwin-x64': 1.6.0 + '@pagefind/freebsd-x64': 1.6.0 + '@pagefind/linux-arm64': 1.6.0 + '@pagefind/linux-x64': 1.6.0 + '@pagefind/windows-arm64': 1.6.0 + '@pagefind/windows-x64': 1.6.0 + path-key@3.1.1: {} path-to-regexp@6.3.0: {} @@ -6130,6 +7115,106 @@ snapshots: rou3@1.0.0: {} + rxjs@7.8.2: + dependencies: + tslib: 2.9.1 + + sass-embedded-all-unknown@1.108.2: + dependencies: + sass: 1.108.2 + optional: true + + sass-embedded-android-arm64@1.108.2: + optional: true + + sass-embedded-android-arm@1.108.2: + optional: true + + sass-embedded-android-riscv64@1.108.2: + optional: true + + sass-embedded-android-x64@1.108.2: + optional: true + + sass-embedded-darwin-arm64@1.108.2: + optional: true + + sass-embedded-darwin-x64@1.108.2: + optional: true + + sass-embedded-linux-arm64@1.108.2: + optional: true + + sass-embedded-linux-arm@1.108.2: + optional: true + + sass-embedded-linux-musl-arm64@1.108.2: + optional: true + + sass-embedded-linux-musl-arm@1.108.2: + optional: true + + sass-embedded-linux-musl-riscv64@1.108.2: + optional: true + + sass-embedded-linux-musl-x64@1.108.2: + optional: true + + sass-embedded-linux-riscv64@1.108.2: + optional: true + + sass-embedded-linux-x64@1.108.2: + optional: true + + sass-embedded-unknown-all@1.108.2: + dependencies: + sass: 1.108.2 + optional: true + + sass-embedded-win32-arm64@1.108.2: + optional: true + + sass-embedded-win32-x64@1.108.2: + optional: true + + sass-embedded@1.108.2: + dependencies: + '@bufbuild/protobuf': 2.17.0 + colorjs.io: 0.7.1 + immutable: 5.2.1 + rxjs: 7.8.2 + supports-color: 8.1.1 + sync-child-process: 1.1.1 + varint: 6.0.0 + optionalDependencies: + sass-embedded-all-unknown: 1.108.2 + sass-embedded-android-arm: 1.108.2 + sass-embedded-android-arm64: 1.108.2 + sass-embedded-android-riscv64: 1.108.2 + sass-embedded-android-x64: 1.108.2 + sass-embedded-darwin-arm64: 1.108.2 + sass-embedded-darwin-x64: 1.108.2 + sass-embedded-linux-arm: 1.108.2 + sass-embedded-linux-arm64: 1.108.2 + sass-embedded-linux-musl-arm: 1.108.2 + sass-embedded-linux-musl-arm64: 1.108.2 + sass-embedded-linux-musl-riscv64: 1.108.2 + sass-embedded-linux-musl-x64: 1.108.2 + sass-embedded-linux-riscv64: 1.108.2 + sass-embedded-linux-x64: 1.108.2 + sass-embedded-unknown-all: 1.108.2 + sass-embedded-win32-arm64: 1.108.2 + sass-embedded-win32-x64: 1.108.2 + + sass@1.108.2: + dependencies: + chokidar: 5.0.0 + immutable: 5.2.1 + source-map-js: 1.2.1 + optionalDependencies: + '@parcel/watcher': 2.6.0 + optional: true + satteri@0.10.5: dependencies: '@types/estree-jsx': 1.0.5 @@ -6218,7 +7303,6 @@ snapshots: '@img/sharp-win32-ia32': 0.35.5 '@img/sharp-win32-x64': 0.35.5 '@types/node': 25.0.3 - optional: true shebang-command@2.0.0: dependencies: @@ -6267,6 +7351,10 @@ snapshots: supports-color@10.2.2: {} + supports-color@8.1.1: + dependencies: + has-flag: 4.0.0 + svgo@4.1.0: dependencies: commander: 11.1.0 @@ -6277,6 +7365,16 @@ snapshots: picocolors: 1.1.1 sax: 1.6.1 + sync-child-process@1.1.1: + dependencies: + sync-message-port: 1.2.0 + + sync-message-port@1.2.0: {} + + tailwindcss@4.3.5: {} + + tapable@2.3.4: {} + tiny-inflate@1.0.3: {} tinybench@6.2.0: {} @@ -6302,7 +7400,7 @@ snapshots: trough@2.2.0: {} - tsdown@0.23.3(typescript@7.1.0-dev.20261001.1): + tsdown@0.23.3(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1): dependencies: cac: 7.1.0 defu: 6.1.7 @@ -6319,6 +7417,7 @@ snapshots: unconfig-core: 7.5.0 verkit: 0.5.0 optionalDependencies: + tsx: 4.23.15 typescript: 7.1.0-dev.20261001.1 transitivePeerDependencies: - '@typescript/native-preview' @@ -6329,6 +7428,12 @@ snapshots: tslib@2.9.1: {} + tsx@4.23.15: + dependencies: + esbuild: 0.28.1 + optionalDependencies: + fsevents: 2.3.3 + typescript@6.0.3: {} typescript@7.1.0-dev.20261001.1: @@ -6416,6 +7521,8 @@ snapshots: unstorage@2.0.0-beta.0: {} + varint@6.0.0: {} + verkit@0.5.0: {} vfile-message@4.0.3: @@ -6428,24 +7535,24 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(playwright@1.63.0)(typescript@6.0.3)(yaml@2.9.1): + vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1): dependencies: '@oxc-project/types': 0.153.0 '@oxlint/plugins': 1.79.0 - '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) - '@vitest/browser-preview': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) - '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)) + '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/browser-preview': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) '@vitest/pretty-format': 5.0.3 '@vitest/snapshot': 5.0.3 '@vitest/spy': 5.0.3 '@vitest/utils': 5.0.3 - oxfmt: 0.72.0(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(playwright@1.63.0)(typescript@6.0.3)(yaml@2.9.1)) - oxlint: 1.87.0(oxlint-tsgolint@7.0.2003)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(playwright@1.63.0)(typescript@6.0.3)(yaml@2.9.1)) + oxfmt: 0.72.0(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) + oxlint: 1.87.0(oxlint-tsgolint@7.0.2003)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/ui@5.0.3(vitest@5.0.3))(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) oxlint-tsgolint: 7.0.2003 - vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)' - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)) + vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)' + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) optionalDependencies: - '@vitest/browser-playwright': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3) + '@vitest/browser-playwright': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3) '@voidzero-dev/vite-plus-darwin-arm64': 1.1.0 '@voidzero-dev/vite-plus-darwin-x64': 1.1.0 '@voidzero-dev/vite-plus-linux-arm64-gnu': 1.1.0 @@ -6489,24 +7596,24 @@ snapshots: - vue-tsc - yaml - vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1): + vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1): dependencies: '@oxc-project/types': 0.153.0 '@oxlint/plugins': 1.79.0 - '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3) - '@vitest/browser-preview': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3) - '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) + '@vitest/browser': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/browser-preview': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) '@vitest/pretty-format': 5.0.3 '@vitest/snapshot': 5.0.3 '@vitest/spy': 5.0.3 '@vitest/utils': 5.0.3 - oxfmt: 0.72.0(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) - oxlint: 1.87.0(oxlint-tsgolint@7.0.2003)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(playwright@1.63.0)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) + oxfmt: 0.72.0(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) + oxlint: 1.87.0(oxlint-tsgolint@7.0.2003)(vite-plus@1.1.0(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/ui@5.0.3)(esbuild@0.28.1)(jiti@2.7.0)(playwright@1.63.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) oxlint-tsgolint: 7.0.2003 - vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)' - vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) + vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)' + vitest: 5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) optionalDependencies: - '@vitest/browser-playwright': 5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/browser-playwright': 5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3) '@voidzero-dev/vite-plus-darwin-arm64': 1.1.0 '@voidzero-dev/vite-plus-darwin-x64': 1.1.0 '@voidzero-dev/vite-plus-linux-arm64-gnu': 1.1.0 @@ -6551,7 +7658,7 @@ snapshots: - yaml optional: true - vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1): + vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -6562,16 +7669,20 @@ snapshots: '@types/node': 25.0.3 esbuild: 0.28.1 fsevents: 2.3.3 + jiti: 2.7.0 + sass: 1.108.2 + sass-embedded: 1.108.2 + tsx: 4.23.15 yaml: 2.9.1 - vitefu@1.1.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)): + vitefu@1.1.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)): optionalDependencies: - vite: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1) + vite: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1) - vitest@5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)): + vitest@5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3))(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 - '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)) + '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)) chai: 6.2.2 es-module-lexer: 2.3.2 expect-type: 1.4.0 @@ -6582,20 +7693,20 @@ snapshots: tinybench: 6.2.0 tinyexec: 1.3.1 tinyglobby: 0.2.17 - vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1)' + vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1)' why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 25.0.3 - '@vitest/browser-playwright': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3) - '@vitest/browser-preview': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/browser-playwright': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(playwright@1.63.0)(vitest@5.0.3) + '@vitest/browser-preview': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1))(vitest@5.0.3) '@vitest/ui': 5.0.3(vitest@5.0.3) transitivePeerDependencies: - msw - vitest@5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): + vitest@5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3(vitest@5.0.3))(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 - '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) + '@vitest/mocker': 5.0.3(@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)) chai: 6.2.2 es-module-lexer: 2.3.2 expect-type: 1.4.0 @@ -6606,21 +7717,21 @@ snapshots: tinybench: 6.2.0 tinyexec: 1.3.1 tinyglobby: 0.2.17 - vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)' + vite: '@voidzero-dev/vite-plus-core@1.1.0(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1)(yaml@2.9.1)' why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 25.0.3 - '@vitest/browser-playwright': 5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3) - '@vitest/browser-preview': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/browser-playwright': 5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/browser-preview': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3) '@vitest/ui': 5.0.3(vitest@5.0.3) transitivePeerDependencies: - msw optional: true - vitest@5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)): + vitest@5.0.3(@types/node@25.0.3)(@vitest/browser-playwright@5.0.3)(@vitest/browser-preview@5.0.3)(@vitest/ui@5.0.3)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 - '@vitest/mocker': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1)) + '@vitest/mocker': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1)) chai: 6.2.2 es-module-lexer: 2.3.2 expect-type: 1.4.0 @@ -6631,12 +7742,12 @@ snapshots: tinybench: 6.2.0 tinyexec: 1.3.1 tinyglobby: 0.2.17 - vite: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1) + vite: 8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1) why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 25.0.3 - '@vitest/browser-playwright': 5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3) - '@vitest/browser-preview': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/browser-playwright': 5.0.3(playwright@1.63.0)(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3) + '@vitest/browser-preview': 5.0.3(vite@8.3.2(@types/node@25.0.3)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.3) '@vitest/ui': 5.0.3(vitest@5.0.3) transitivePeerDependencies: - msw diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 442497445..cbb721f9f 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -4,6 +4,8 @@ packages: - packages/vite-task-client allowBuilds: + # Prebuilt native binaries come as optional dependencies, so build scripts aren't needed. + '@parcel/watcher': false '@playwright/browser-chromium': true bun: true deno: true @@ -19,11 +21,15 @@ minimumReleaseAgeExclude: catalog: '@anthropic-ai/sandbox-runtime': 0.0.78 + '@biomejs/biome': 2.6.9 '@openai/codex': 0.160.0 + '@playwright/browser-chromium': 1.63.0 + '@rspack/cli': 2.3.4 + '@rspack/core': 2.3.4 + '@tailwindcss/cli': 4.3.5 '@tsconfig/strictest': ^2.0.8 '@types/cross-spawn': 6.0.6 '@types/node': 25.0.3 - '@playwright/browser-chromium': 1.63.0 '@vitest/browser-playwright': 5.0.3 astro: 7.3.8 bun: 1.4.2 @@ -38,6 +44,7 @@ catalog: oxfmt: 0.73.0 oxlint: ^1.55.0 oxlint-tsgolint: ^7.0.0 + pagefind: 1.6.0 # Playwright 1.52 pins the browser package to Chromium 136. playwright: 1.63.0 # The e2e tests run this pnpm; keep it in sync with `packageManager`. @@ -45,7 +52,11 @@ catalog: postject: 1.0.0-alpha.6 react: 19.3.1 react-dom: 19.3.1 + sass-embedded: 1.108.2 + sharp: 0.35.5 + tailwindcss: 4.3.5 tsdown: 0.23.3 + tsx: 4.23.15 typescript: ^6.0.3 vite: npm:@voidzero-dev/vite-plus-core@1.1.0 vite-plus: 1.1.0