From 17c939684be9051caca95e1f1b44351f8aa415fc Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 08:27:10 +0800 Subject: [PATCH 01/48] feat(fspy): replace Linux LD_PRELOAD and seccomp_unotify with freestanding ELF/SIGSYS tracker Switch Linux file-access tracking from `LD_PRELOAD` + `seccomp_unotify` to the freestanding `target_os = "none"` ELF launcher + `SIGSYS` backend (`fspy_preload_linux`), unify Unix exec/shebang resolution in `no_std` `fspy_shared_unix`, simplify macOS into `fspy_preload_macos`, and add Linux hardening and JS ecosystem E2E cache tests: - `fspy_shared_unix`: rewrite exec/shebang/path resolution to `#![no_std]` shared across `fspy_preload_linux` and `fspy_preload_macos`, with unit tests for Linux, macOS, and `nostd_exec`. - `fspy_preload_linux`: freestanding bare-metal ELF/`SIGSYS` launcher binary built for `x86_64-unknown-none` and `aarch64-unknown-none-softfloat` (checked in CI). - `fspy_preload_macos`: macOS-only `cdylib` replacing `fspy_preload_unix` and `fspy_client_unix`; remove `fspy_seccomp_unotify`. - `fspy`: split `src/unix/` into `src/linux/` and `src/macos/`, add `tests/linux_hardening.rs` and update `tests/untracked_fallback.rs` and existing suites. - `vt_bin`: update `preexisting_ld_preload` snapshot and add 10 JS ecosystem E2E cache fixtures (`biome`, `deno`, `esbuild`, `miniflare`, `oxfmt`, `rspack`, `sass-embedded`, `sharp`, `tailwindcss-v4`, `tsx`). - `CHANGELOG.md`: add user-facing entry referencing all 4 PRs in the stack. Co-authored-by: Gemini 4 Neon --- .github/workflows/ci.yml | 4 +- CHANGELOG.md | 1 + Cargo.lock | 109 +- Cargo.toml | 14 +- crates/fspy/Cargo.toml | 56 +- crates/fspy/README.md | 30 +- crates/fspy/src/command.rs | 45 +- crates/fspy/src/error.rs | 3 - crates/fspy/src/lib.rs | 10 +- crates/fspy/src/linux/mod.rs | 421 ++++++ .../src/{unix => macos}/macos_artifacts.rs | 2 +- crates/fspy/src/macos/mod.rs | 130 ++ crates/fspy/src/unix/mod.rs | 210 --- .../fspy/src/unix/syscall_handler/execve.rs | 24 - .../fspy/src/unix/syscall_handler/getdents.rs | 16 - crates/fspy/src/unix/syscall_handler/mod.rs | 120 -- .../src/unix/syscall_handler/namespace.rs | 91 -- crates/fspy/src/unix/syscall_handler/open.rs | 35 - crates/fspy/src/unix/syscall_handler/stat.rs | 68 - crates/fspy/tests/exec_empty_path.rs | 6 +- crates/fspy/tests/invalid_dirfd.rs | 5 +- crates/fspy/tests/linux_hardening.rs | 396 ++++++ crates/fspy/tests/node_fs.rs | 73 +- crates/fspy/tests/rust_std.rs | 19 +- crates/fspy/tests/shebang.rs | 3 - crates/fspy/tests/static_executable.rs | 7 +- crates/fspy/tests/test_utils/mod.rs | 27 +- crates/fspy/tests/untracked_fallback.rs | 207 ++- crates/fspy_benchmark/README.md | 2 +- crates/fspy_client_unix/Cargo.toml | 26 - crates/fspy_client_unix/README.md | 8 - crates/fspy_client_unix/src/convert.rs | 239 ---- crates/fspy_client_unix/src/lib.rs | 153 -- crates/fspy_client_unix/src/raw_exec.rs | 122 -- crates/fspy_preload_linux/Cargo.toml | 28 + crates/fspy_preload_linux/README.md | 25 + crates/fspy_preload_linux/build.rs | 7 + crates/fspy_preload_linux/src/main.rs | 1089 +++++++++++++++ .../.clippy.toml | 0 .../Cargo.toml | 16 +- crates/fspy_preload_macos/README.md | 4 + crates/fspy_preload_macos/src/client.rs | 177 +++ .../src/interceptions/access.rs | 18 +- .../src/interceptions/dirent.rs | 85 ++ .../src/interceptions/dyld.rs | 0 .../src/interceptions/mod.rs | 4 - .../src/interceptions/namespace.rs | 116 ++ .../src/interceptions/open.rs | 76 +- .../src/interceptions/spawn/exec/mod.rs | 140 ++ .../src/interceptions/spawn/mod.rs | 0 .../src/interceptions/spawn/posix_spawn.rs | 104 ++ .../src/interceptions/stat.rs | 36 + crates/fspy_preload_macos/src/lib.rs | 7 + .../src/libc.rs | 10 +- .../src/macros/macos.rs | 0 crates/fspy_preload_macos/src/macros/mod.rs | 7 + crates/fspy_preload_macos/src/which.rs | 85 ++ crates/fspy_preload_unix/.clippy.toml | 1 - crates/fspy_preload_unix/README.md | 5 - crates/fspy_preload_unix/src/client.rs | 44 - .../src/interceptions/dirent.rs | 88 -- .../src/interceptions/linux_syscall.rs | 95 -- .../src/interceptions/namespace.rs | 150 -- .../src/interceptions/spawn/exec/mod.rs | 334 ----- .../src/interceptions/spawn/posix_spawn.rs | 143 -- .../src/interceptions/stat.rs | 82 -- crates/fspy_preload_unix/src/lib.rs | 11 - crates/fspy_preload_unix/src/macros/linux.rs | 133 -- crates/fspy_preload_unix/src/macros/mod.rs | 13 - crates/fspy_seccomp_unotify/.clippy.toml | 1 - crates/fspy_seccomp_unotify/Cargo.toml | 40 - crates/fspy_seccomp_unotify/README.md | 6 - .../src/bindings/alloc.rs | 106 -- .../fspy_seccomp_unotify/src/bindings/mod.rs | 87 -- crates/fspy_seccomp_unotify/src/lib.rs | 10 - .../src/payload/filter.rs | 28 - .../fspy_seccomp_unotify/src/payload/mod.rs | 23 - .../src/supervisor/handler/arg.rs | 229 --- .../src/supervisor/handler/mod.rs | 49 - .../src/supervisor/listener.rs | 99 -- .../src/supervisor/mod.rs | 135 -- crates/fspy_seccomp_unotify/src/target.rs | 33 - .../fspy_seccomp_unotify/tests/arg_types.rs | 144 -- crates/fspy_shared_unix/Cargo.toml | 22 +- crates/fspy_shared_unix/README.md | 3 +- crates/fspy_shared_unix/src/codec.rs | 52 + crates/fspy_shared_unix/src/elf.rs | 63 - crates/fspy_shared_unix/src/exec/mod.rs | 326 ----- crates/fspy_shared_unix/src/exec/shebang.rs | 402 ------ crates/fspy_shared_unix/src/exec/which.rs | 135 -- crates/fspy_shared_unix/src/lib.rs | 19 +- crates/fspy_shared_unix/src/linux.rs | 539 +++++++ crates/fspy_shared_unix/src/macos.rs | 308 ++++ crates/fspy_shared_unix/src/nostd_exec/mod.rs | 290 ++++ .../fspy_shared_unix/src/nostd_exec/open.rs | 92 ++ .../src/nostd_exec/shebang.rs | 276 ++++ crates/fspy_shared_unix/src/open_exec.rs | 13 - crates/fspy_shared_unix/src/payload.rs | 141 -- .../fspy_shared_unix/src/spawn/linux/mod.rs | 66 - crates/fspy_shared_unix/src/spawn/macos.rs | 99 -- crates/fspy_shared_unix/src/spawn/mod.rs | 122 -- .../fixtures/biome_cache/biome.json | 13 + .../fixtures/biome_cache/package.json | 4 + .../fixtures/biome_cache/snapshots.toml | 33 + .../biome_cache/snapshots/biome_cache.md | 38 + .../fixtures/biome_cache/src/index.js | 1 + .../fixtures/biome_cache/vite-task.json | 8 + .../fixtures/bun_build_cache/package.json | 4 + .../scripts/compile-and-run.js | 29 + .../fixtures/bun_build_cache/snapshots.toml | 89 ++ .../snapshots/bun_build_bundle.md | 57 + .../snapshots/bun_build_compile.md | 47 + .../fixtures/bun_build_cache/src/cli.js | 7 + .../fixtures/bun_build_cache/src/data.txt | 1 + .../fixtures/bun_build_cache/src/dep.js | 1 + .../fixtures/bun_build_cache/src/index.js | 3 + .../fixtures/bun_build_cache/vite-task.json | 12 + .../fixtures/deno_run_cache/package.json | 5 + .../fixtures/deno_run_cache/snapshots.toml | 63 + .../snapshots/deno_run_cache.md | 66 + .../deno_run_cache/src/child-data.txt | 1 + .../fixtures/deno_run_cache/src/child.ts | 3 + .../fixtures/deno_run_cache/src/main.ts | 35 + .../deno_run_cache/src/worker-data.txt | 1 + .../fixtures/deno_run_cache/src/worker.ts | 5 + .../fixtures/deno_run_cache/vite-task.json | 8 + .../fixtures/esbuild_cache/build.mjs | 7 + .../fixtures/esbuild_cache/package.json | 5 + .../fixtures/esbuild_cache/snapshots.toml | 45 + .../esbuild_cache/snapshots/esbuild_cache.md | 47 + .../fixtures/esbuild_cache/src/dep.js | 1 + .../fixtures/esbuild_cache/src/index.js | 3 + .../fixtures/esbuild_cache/vite-task.json | 8 + .../miniflare_worker_cache/package.json | 5 + .../fixtures/miniflare_worker_cache/run.mjs | 24 + .../miniflare_worker_cache/snapshots.toml | 45 + .../snapshots/miniflare_worker_cache.md | 47 + .../miniflare_worker_cache/src/data.mjs | 1 + .../miniflare_worker_cache/src/worker.mjs | 7 + .../miniflare_worker_cache/vite-task.json | 8 + .../fixtures/oxfmt_cache/.oxfmtrc.json | 3 + .../fixtures/oxfmt_cache/package.json | 4 + .../fixtures/oxfmt_cache/snapshots.toml | 33 + .../oxfmt_cache/snapshots/oxfmt_cache.md | 47 + .../fixtures/oxfmt_cache/src/index.js | 1 + .../fixtures/oxfmt_cache/vite-task.json | 8 + .../preexisting_ld_preload/snapshots.toml | 8 +- .../snapshots/preexisting_ld_preload.md | 2 +- .../fixtures/rspack_build_cache/package.json | 4 + .../rspack_build_cache/rspack.config.cjs | 11 + .../rspack_build_cache/snapshots.toml | 45 + .../snapshots/rspack_build_cache.md | 47 + .../fixtures/rspack_build_cache/src/dep.js | 1 + .../fixtures/rspack_build_cache/src/index.js | 3 + .../rspack_build_cache/vite-task.json | 8 + .../fixtures/sass_embedded_cache/build.mjs | 6 + .../fixtures/sass_embedded_cache/package.json | 5 + .../sass_embedded_cache/snapshots.toml | 47 + .../snapshots/sass_embedded_cache.md | 51 + .../sass_embedded_cache/src/_vars.scss | 1 + .../sass_embedded_cache/src/main.scss | 5 + .../sass_embedded_cache/vite-task.json | 8 + .../fixtures/sharp_image_cache/build.mjs | 11 + .../fixtures/sharp_image_cache/package.json | 5 + .../fixtures/sharp_image_cache/snapshots.toml | 43 + .../snapshots/sharp_image_cache.md | 47 + .../fixtures/sharp_image_cache/src/icon.svg | 1 + .../fixtures/sharp_image_cache/vite-task.json | 8 + .../tailwindcss_v4_cache/package.json | 4 + .../tailwindcss_v4_cache/snapshots.toml | 45 + .../snapshots/tailwindcss_v4_cache.md | 56 + .../tailwindcss_v4_cache/src/index.html | 1 + .../tailwindcss_v4_cache/src/input.css | 1 + .../tailwindcss_v4_cache/vite-task.json | 8 + .../fixtures/tsx_fork_cache/package.json | 5 + .../fixtures/tsx_fork_cache/snapshots.toml | 43 + .../snapshots/tsx_fork_cache.md | 47 + .../fixtures/tsx_fork_cache/src/child.ts | 7 + .../fixtures/tsx_fork_cache/src/data.txt | 1 + .../fixtures/tsx_fork_cache/src/parent.ts | 18 + .../fixtures/tsx_fork_cache/vite-task.json | 8 + .../src/lib.rs | 2 +- crates/vt_pty_terminal_test_client/Cargo.toml | 2 +- crates/vt_remote_cache/Cargo.toml | 2 +- crates/vt_subprocess_test/Cargo.toml | 2 +- packages/tools/package.json | 7 + pnpm-lock.yaml | 1243 +++++++++++++++-- pnpm-workspace.yaml | 11 +- 188 files changed, 7422 insertions(+), 5114 deletions(-) create mode 100644 crates/fspy/src/linux/mod.rs rename crates/fspy/src/{unix => macos}/macos_artifacts.rs (95%) create mode 100644 crates/fspy/src/macos/mod.rs delete mode 100644 crates/fspy/src/unix/mod.rs delete mode 100644 crates/fspy/src/unix/syscall_handler/execve.rs delete mode 100644 crates/fspy/src/unix/syscall_handler/getdents.rs delete mode 100644 crates/fspy/src/unix/syscall_handler/mod.rs delete mode 100644 crates/fspy/src/unix/syscall_handler/namespace.rs delete mode 100644 crates/fspy/src/unix/syscall_handler/open.rs delete mode 100644 crates/fspy/src/unix/syscall_handler/stat.rs create mode 100644 crates/fspy/tests/linux_hardening.rs delete mode 100644 crates/fspy_client_unix/Cargo.toml delete mode 100644 crates/fspy_client_unix/README.md delete mode 100644 crates/fspy_client_unix/src/convert.rs delete mode 100644 crates/fspy_client_unix/src/lib.rs delete mode 100644 crates/fspy_client_unix/src/raw_exec.rs create mode 100644 crates/fspy_preload_linux/Cargo.toml create mode 100644 crates/fspy_preload_linux/README.md create mode 100644 crates/fspy_preload_linux/build.rs create mode 100644 crates/fspy_preload_linux/src/main.rs rename crates/{fspy_client_unix => fspy_preload_macos}/.clippy.toml (100%) rename crates/{fspy_preload_unix => fspy_preload_macos}/Cargo.toml (54%) create mode 100644 crates/fspy_preload_macos/README.md create mode 100644 crates/fspy_preload_macos/src/client.rs rename crates/{fspy_preload_unix => fspy_preload_macos}/src/interceptions/access.rs (52%) create mode 100644 crates/fspy_preload_macos/src/interceptions/dirent.rs rename crates/{fspy_preload_unix => fspy_preload_macos}/src/interceptions/dyld.rs (100%) rename crates/{fspy_preload_unix => fspy_preload_macos}/src/interceptions/mod.rs (51%) create mode 100644 crates/fspy_preload_macos/src/interceptions/namespace.rs rename crates/{fspy_preload_unix => fspy_preload_macos}/src/interceptions/open.rs (50%) create mode 100644 crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs rename crates/{fspy_preload_unix => fspy_preload_macos}/src/interceptions/spawn/mod.rs (100%) create mode 100644 crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs create mode 100644 crates/fspy_preload_macos/src/interceptions/stat.rs create mode 100644 crates/fspy_preload_macos/src/lib.rs rename crates/{fspy_preload_unix => fspy_preload_macos}/src/libc.rs (84%) rename crates/{fspy_preload_unix => fspy_preload_macos}/src/macros/macos.rs (100%) create mode 100644 crates/fspy_preload_macos/src/macros/mod.rs create mode 100644 crates/fspy_preload_macos/src/which.rs delete mode 120000 crates/fspy_preload_unix/.clippy.toml delete mode 100644 crates/fspy_preload_unix/README.md delete mode 100644 crates/fspy_preload_unix/src/client.rs delete mode 100644 crates/fspy_preload_unix/src/interceptions/dirent.rs delete mode 100644 crates/fspy_preload_unix/src/interceptions/linux_syscall.rs delete mode 100644 crates/fspy_preload_unix/src/interceptions/namespace.rs delete mode 100644 crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs delete mode 100644 crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs delete mode 100644 crates/fspy_preload_unix/src/interceptions/stat.rs delete mode 100644 crates/fspy_preload_unix/src/lib.rs delete mode 100644 crates/fspy_preload_unix/src/macros/linux.rs delete mode 100644 crates/fspy_preload_unix/src/macros/mod.rs delete mode 120000 crates/fspy_seccomp_unotify/.clippy.toml delete mode 100644 crates/fspy_seccomp_unotify/Cargo.toml delete mode 100644 crates/fspy_seccomp_unotify/README.md delete mode 100644 crates/fspy_seccomp_unotify/src/bindings/alloc.rs delete mode 100644 crates/fspy_seccomp_unotify/src/bindings/mod.rs delete mode 100644 crates/fspy_seccomp_unotify/src/lib.rs delete mode 100644 crates/fspy_seccomp_unotify/src/payload/filter.rs delete mode 100644 crates/fspy_seccomp_unotify/src/payload/mod.rs delete mode 100644 crates/fspy_seccomp_unotify/src/supervisor/handler/arg.rs delete mode 100644 crates/fspy_seccomp_unotify/src/supervisor/handler/mod.rs delete mode 100644 crates/fspy_seccomp_unotify/src/supervisor/listener.rs delete mode 100644 crates/fspy_seccomp_unotify/src/supervisor/mod.rs delete mode 100644 crates/fspy_seccomp_unotify/src/target.rs delete mode 100644 crates/fspy_seccomp_unotify/tests/arg_types.rs create mode 100644 crates/fspy_shared_unix/src/codec.rs delete mode 100644 crates/fspy_shared_unix/src/elf.rs delete mode 100644 crates/fspy_shared_unix/src/exec/mod.rs delete mode 100644 crates/fspy_shared_unix/src/exec/shebang.rs delete mode 100644 crates/fspy_shared_unix/src/exec/which.rs create mode 100644 crates/fspy_shared_unix/src/linux.rs create mode 100644 crates/fspy_shared_unix/src/macos.rs create mode 100644 crates/fspy_shared_unix/src/nostd_exec/mod.rs create mode 100644 crates/fspy_shared_unix/src/nostd_exec/open.rs create mode 100644 crates/fspy_shared_unix/src/nostd_exec/shebang.rs delete mode 100644 crates/fspy_shared_unix/src/open_exec.rs delete mode 100644 crates/fspy_shared_unix/src/payload.rs delete mode 100644 crates/fspy_shared_unix/src/spawn/linux/mod.rs delete mode 100644 crates/fspy_shared_unix/src/spawn/macos.rs delete mode 100644 crates/fspy_shared_unix/src/spawn/mod.rs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/biome.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/snapshots/biome_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/src/index.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/scripts/compile-and-run.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots/bun_build_bundle.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/snapshots/bun_build_compile.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/cli.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/data.txt create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/dep.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/src/index.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/bun_build_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/snapshots/deno_run_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/child-data.txt create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/child.ts create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/main.ts create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/worker-data.txt create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/src/worker.ts create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/deno_run_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/build.mjs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/snapshots/esbuild_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/src/dep.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/src/index.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/esbuild_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/run.mjs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/snapshots/miniflare_worker_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/src/data.mjs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/src/worker.mjs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/miniflare_worker_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/.oxfmtrc.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/snapshots/oxfmt_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/src/index.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/rspack.config.cjs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/snapshots/rspack_build_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/src/dep.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/src/index.js create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/rspack_build_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/build.mjs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/snapshots/sass_embedded_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/src/_vars.scss create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/src/main.scss create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sass_embedded_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/build.mjs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/snapshots/sharp_image_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/src/icon.svg create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/sharp_image_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/snapshots/tailwindcss_v4_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/src/index.html create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/src/input.css create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tailwindcss_v4_cache/vite-task.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/snapshots/tsx_fork_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/child.ts create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/data.txt create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/src/parent.ts create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/tsx_fork_cache/vite-task.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7d508cca..6204042ba 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index ad334a2d7..4a11fe3c7 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 with non-executable stacks ([#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..33836183e --- /dev/null +++ b/crates/fspy/src/linux/mod.rs @@ -0,0 +1,421 @@ +use std::{ + env, + ffi::CString, + fs, io, + os::{ + fd::{AsRawFd as _, FromRawFd as _, OwnedFd}, + unix::{ + ffi::OsStrExt as _, + fs::{DirBuilderExt as _, MetadataExt as _, PermissionsExt 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 no + /// writable directory permits executing files (e.g. `noexec` mounts), in + /// which case `spawn` falls back to untracked execution. + preload_path: Option>, + seccomp_available: bool, +} + +impl SpyImpl { + /// Materializes `fspy_preload_linux` into a writable, executable directory + /// (falling back past `noexec` temp mounts) 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!( + "no writable executable directory found for Linux task tracking; \ + falling back to untracked execution (caching disabled)" + ); + } + 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 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 pipe_reader = tokio::net::unix::pipe::Receiver::from_owned_fd(read_end) + .map_err(SpawnError::OsSpawn)?; + 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 first candidate user directory +/// whose filesystem allows executing binaries, skipping `noexec` mounts (such +/// as CIS-hardened `/tmp`). Returns `None` if no writable executable directory +/// is available so `SpyImpl::spawn` can fall back cleanly to untracked execution. +fn materialize_executable_preload() -> Option { + if let Ok(path) = PRELOAD_LINUX.materialize().executable().at_user_temp_dir("vp_run") + && is_path_executable(&path) + { + return Some(path); + } + + let mut fallback_bases = Vec::new(); + if let Some(dir) = env::var_os("XDG_RUNTIME_DIR") + && !dir.is_empty() + { + fallback_bases.push(PathBuf::from(dir)); + } + if let Some(dir) = env::var_os("XDG_CACHE_HOME") + && !dir.is_empty() + { + fallback_bases.push(PathBuf::from(dir)); + } else if let Some(home) = env::var_os("HOME") + && !home.is_empty() + { + fallback_bases.push(PathBuf::from(home).join(".cache")); + } + fallback_bases.push(PathBuf::from("/var/tmp")); + + materialize_in_candidates(&fallback_bases, is_path_executable) +} + +fn materialize_in_candidates( + bases: &[PathBuf], + is_executable: impl Fn(&Path) -> bool, +) -> Option { + for base in bases { + let Ok(user_dir) = ensure_private_user_dir(base, "vp_run") else { + continue; + }; + let Ok(path) = PRELOAD_LINUX.materialize().executable().at(&user_dir) else { + continue; + }; + if is_executable(&path) { + return Some(path); + } + } + None +} + +/// Creates (if needed) and validates a `0o700` directory `{base}/{prefix}-{uid}` +/// owned solely by the current user, matching `vt_materialized_artifact`. +fn ensure_private_user_dir(base: &Path, prefix: &str) -> io::Result { + if !base.exists() { + fs::create_dir_all(base)?; + } + // SAFETY: `geteuid` has no preconditions and always succeeds. + let uid = unsafe { libc::geteuid() }; + let dir = base.join(format!("{prefix}-{uid}")); + match fs::DirBuilder::new().mode(0o700).create(&dir) { + Err(err) if err.kind() != io::ErrorKind::AlreadyExists => return Err(err), + _ => {} + } + let metadata = fs::symlink_metadata(&dir)?; + if !metadata.is_dir() || metadata.uid() != uid || metadata.permissions().mode() & 0o022 != 0 { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("{} is not a private user-owned directory", dir.display()), + )); + } + Ok(dir) +} + +/// 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()); + } + + #[test] + fn materialize_in_candidates_skips_non_executable_mount_and_falls_back() { + let dir1 = tempfile::tempdir().unwrap(); + let dir2 = tempfile::tempdir().unwrap(); + let bases = [dir1.path().to_path_buf(), dir2.path().to_path_buf()]; + + // Simulate `dir1` mounted `noexec`: candidate search must fall back to `dir2`. + let chosen = super::materialize_in_candidates(&bases, |p| p.starts_with(dir2.path())) + .expect("expected fallback to second candidate dir"); + assert!(chosen.starts_with(dir2.path())); + assert!(super::is_path_executable(&chosen)); + + // When no candidate permits execution, return `None` so spawn falls back to untracked. + assert!(super::materialize_in_candidates(&bases, |_| false).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..d8a85ff9c --- /dev/null +++ b/crates/fspy/tests/linux_hardening.rs @@ -0,0 +1,396 @@ +//! Linux hardening tests covering `vfork`/`posix_spawn` memory reclamation, +//! `memfd_create` + `execveat(AT_EMPTY_PATH)`, deep `execve` chain FD/env/filter +//! hygiene, and invalid user pointers returning `EFAULT`. +#![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 posix_spawn_kcmp_denied_and_overflow_rss_stays_bounded() -> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + use std::ffi::CString; + + use linux_raw_sys::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, sock_filter, sock_fprog, + }; + + 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"); + } + + // Deny `kcmp` with `EPERM` (matching Docker's default seccomp profile). + #[expect(clippy::cast_possible_truncation, reason = "cBPF opcodes and syscall nr fit")] + let filter = [ + sock_filter { code: (BPF_LD | BPF_W | BPF_ABS) as u16, jt: 0, jf: 0, k: 0 }, + sock_filter { + code: (BPF_JMP | BPF_JEQ | BPF_K) as u16, + jt: 0, + jf: 1, + k: libc::SYS_kcmp as u32, + }, + sock_filter { + code: (BPF_RET | BPF_K) as u16, + jt: 0, + jf: 0, + k: SECCOMP_RET_ERRNO | ((libc::EPERM as u32) & 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: u16::try_from(filter.len()).unwrap(), + filter: filter.as_ptr().cast_mut(), + }; + // SAFETY: installs a minimal BPF filter returning `EPERM` for `SYS_kcmp`. + let seccomp_rc = unsafe { + libc::syscall(libc::SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &raw const prog) + }; + assert_eq!( + seccomp_rc, + 0, + "failed to install kcmp-denying seccomp filter: {}", + std::io::Error::last_os_error() + ); + + let prog_path = std::sync::Arc::new(CString::new("/bin/sleep").unwrap()); + let arg0 = std::sync::Arc::new(CString::new("sleep").unwrap()); + let arg1 = std::sync::Arc::new(CString::new("0.05").unwrap()); + + let env_cstrs: std::sync::Arc> = std::sync::Arc::new( + std::env::vars().map(|(k, v)| CString::new(format!("{k}={v}")).unwrap()).collect(), + ); + + // 4 waves x 72 concurrent threads synchronized at a barrier (> 64 fixed + // `EXEC_SLOTS`) under denied `kcmp`, genuinely exercising both the + // `clear_child_tid` slot fast path and the `OverflowScratch` parked list. + let concurrent_spawners = 72usize; + let mut baseline_rss = 0usize; + for wave in 0..4 { + let barrier = std::sync::Arc::new(std::sync::Barrier::new(concurrent_spawners)); + let mut handles = Vec::with_capacity(concurrent_spawners); + for i in 0..concurrent_spawners { + let barrier = std::sync::Arc::clone(&barrier); + let prog_path = std::sync::Arc::clone(&prog_path); + let arg0 = std::sync::Arc::clone(&arg0); + let arg1 = std::sync::Arc::clone(&arg1); + let env_cstrs = std::sync::Arc::clone(&env_cstrs); + handles.push(std::thread::spawn(move || { + let argv = + [arg0.as_ptr().cast_mut(), arg1.as_ptr().cast_mut(), std::ptr::null_mut()]; + 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()); + barrier.wait(); + let mut pid: libc::pid_t = 0; + // SAFETY: `prog_path`, `argv`, and `envp` are valid NUL-terminated arrays. + let rc = unsafe { + libc::posix_spawn( + &raw mut pid, + prog_path.as_ptr(), + std::ptr::null(), + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + assert_eq!(rc, 0, "posix_spawn wave {wave} thread {i} failed with errno {rc}"); + pid + })); + } + let pids: Vec = handles.into_iter().map(|h| h.join().unwrap()).collect(); + for pid in pids { + 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 wave == 0 { + baseline_rss = vm_rss_kib(); + } + } + + let final_rss = vm_rss_kib(); + let growth = final_rss.saturating_sub(baseline_rss); + assert!( + growth < 6144, + "parent VmRSS grew by {growth} KiB across 216 concurrent overflow posix_spawns with kcmp denied \ + (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 deep_exec_chain_preserves_fd_env_and_seccomp_filter_hygiene() -> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + 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 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 unexpected high FDs leaked from launcher handoff (allow + // stdin/stdout/stderr and the `/proc/self/fd` directory handle itself). + 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 extra_fds: Vec = open_fds.into_iter().filter(|&fd| fd > 2).collect(); + assert!( + extra_fds.len() <= 2, + "unexpected leaked open FDs across exec chain: {extra_fds:?}" + ); + + let depth: usize = + std::env::var("FSPY_TEST_EXEC_DEPTH").ok().and_then(|s| s.parse().ok()).unwrap_or(0); + 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(()) +} + +#[test(tokio::test)] +async fn invalid_user_pointers_return_efault_under_fspy() -> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + use std::ffi::CString; + + let bad_ptr = 1usize; + // SAFETY: intentionally passing invalid pointers to verify `-EFAULT` + // instead of crashing inside the `SIGSYS` handler. + unsafe { + assert_eq!( + libc::syscall(libc::SYS_openat, libc::AT_FDCWD, bad_ptr, libc::O_RDONLY, 0), + -1 + ); + assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::EFAULT)); + + assert_eq!(libc::syscall(libc::SYS_execve, bad_ptr, 0usize, 0usize), -1); + assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::EFAULT)); + + let prog = CString::new("/bin/true").unwrap(); + assert_eq!(libc::syscall(libc::SYS_execve, prog.as_ptr(), bad_ptr, 0usize), -1); + assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::EFAULT)); + + let bad_argv = [std::ptr::dangling::(), std::ptr::null()]; + assert_eq!( + libc::syscall(libc::SYS_execve, prog.as_ptr(), bad_argv.as_ptr(), 0usize), + -1 + ); + assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::EFAULT)); + } + }); + + 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..aacf28cf7 100644 --- a/crates/fspy/tests/shebang.rs +++ b/crates/fspy/tests/shebang.rs @@ -42,9 +42,6 @@ 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()?; 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..7505fcc1c --- /dev/null +++ b/crates/fspy_preload_linux/src/main.rs @@ -0,0 +1,1089 @@ +#![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::{MaybeUninit, size_of}, + ptr::{self, NonNull}, + slice, + sync::atomic::{AtomicI32, AtomicPtr, AtomicU64, 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::{Mode, OFlags, PATH_MAX, fcntl_dupfd, openat}, + }; + use fspy_nostd_alloc::{PageAllocator, PageBump, fs::fd_path, page_bump, pooled_bump}; + use fspy_shared::ipc::{ + AccessMode, IpcPath, IpcStr, + channel::{ChannelConf, Sender}, + }; + use fspy_shared_unix::{ + Env, Exec, RawExec, + linux::{ + BOOTSTRAP_ENV_NAME, Bootstrap, ExecAtFlags, Target, encode_bootstrap, + ensure_bootstrap_env, resolve_exec, + }, + }; + use linux_raw_sys::{ + errno::{E2BIG, ENOSYS, EPERM, ESRCH}, + 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; + + /// Linux `kcmp(2)` resource type comparing virtual memory (`mm_struct`). + const KCMP_VM: usize = 1; + + /// Upper bound on a single `argv`/`envp` string copied from user memory + /// (matches Linux `MAX_ARG_STRLEN` up to 64 KiB pages). + const MAX_EXEC_STRING_LEN: usize = 2 * 1024 * 1024; + + /// Number of reusable exec scratch slots for reclaiming `CLONE_VM` + /// (`vfork` / `posix_spawn`) exec buffers once the child detaches. + const MAX_EXEC_SLOTS: usize = 64; + const SLOT_FREE: u64 = 0; + const SLOT_BUSY: u64 = 1; + + 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, + } + + struct ExecSlot { + /// `0` = free, `1` = exclusively owned in-flight/reclaiming, + /// `(gen << 32) | child_pid` (`gen >= 1`) = parked by a `CLONE_VM` + /// child calling `execve`. + state: AtomicU64, + /// Registered with `set_tid_address` right before `SYS_execve` in a + /// `CLONE_VM` child: the Linux kernel's `mm_release()` atomically writes + /// `0` here the instant `execve` detaches the child's `mm_struct` (or + /// if the child dies), allowing zero-syscall reclamation even when + /// `kcmp` is denied by Docker/seccomp and without PID-reuse hazards. + active_tid: AtomicI32, + arena: UnsafeCell>, + duped_fd: UnsafeCell, + } + + // SAFETY: Access to `arena` and `duped_fd` is serialized via `state` CAS + // transitions (`SLOT_FREE -> SLOT_BUSY` and `parked(gen, pid) -> SLOT_BUSY`). + unsafe impl Sync for ExecSlot {} + + impl ExecSlot { + const fn new() -> Self { + Self { + state: AtomicU64::new(SLOT_FREE), + active_tid: AtomicI32::new(0), + arena: UnsafeCell::new(None), + duped_fd: UnsafeCell::new(-1), + } + } + } + + /// Overflow scratch node used when all [`MAX_EXEC_SLOTS`] fixed slots are + /// simultaneously busy. For `CLONE_VM` children, pushed onto + /// [`OVERFLOW_PARKED_HEAD`] and reclaimed once `active_tid` becomes `0` + /// (written by the kernel's `mm_release()` on exec/exit, or by failure + /// cleanup) or `kcmp` reports VM detachment. + struct OverflowScratch { + next: AtomicPtr, + active_tid: AtomicI32, + child_pid: i32, + parked: bool, + arena: UnsafeCell>, + duped_fd: UnsafeCell, + } + + // SAFETY: `arena` and `duped_fd` are mutated exclusively by the owning + // thread before `active_tid` transitions to `0` (`Release`), and only + // dropped by a reclaimer that observes `active_tid == 0` (`Acquire`) or + // kernel VM detachment after detaching the node from `OVERFLOW_PARKED_HEAD`. + unsafe impl Sync for OverflowScratch {} + + static STARTUP_BUMP: SyncCell = SyncCell(UnsafeCell::new(page_bump())); + static RUNTIME: SyncCell> = SyncCell(UnsafeCell::new(None)); + static EXEC_SLOTS: [ExecSlot; MAX_EXEC_SLOTS] = [const { ExecSlot::new() }; MAX_EXEC_SLOTS]; + static PARK_GEN: AtomicU64 = AtomicU64::new(1); + static OVERFLOW_PARKED_HEAD: 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, + // Disable `io_uring` so runtimes such as libuv / Node.js fall back to + // standard filesystem syscalls instead of bypassing tracking via rings. + Sysno::io_uring_setup, + ]; + + #[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, + // Disable `io_uring` so runtimes such as libuv / Node.js fall back to + // standard filesystem syscalls instead of bypassing tracking via rings. + Sysno::io_uring_setup, + ]; + + 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::ResolvedPath { path, execfn, sigmask } => { + let path_cstr = + path.to_os_c_string_in(bump).expect("resolved target path contains NUL"); + let execfn_cstr = + execfn.to_os_c_string_in(bump).expect("resolved execfn contains NUL"); + let file = openat( + CWD, + path_cstr.as_c_str().as_thin(), + OFlags::RDONLY | OFlags::CLOEXEC, + Mode::empty(), + ) + .expect("cannot open resolved target"); + + 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), + ) + } + } + 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(); + } + } + + #[expect(clippy::cast_possible_truncation, reason = "Linux pid_t is i32")] + fn getpid() -> i32 { + // SAFETY: `getpid` takes no arguments and cannot fail. + unsafe { syscalls::raw::syscall0(Sysno::getpid as usize).cast_signed() as i32 } + } + + 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 without risking a + /// `SIGSEGV` if `path_ptr` is unreadable. + fn report_path_at( + call: &Syscall<'_>, + 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; + } + let mut buf = [MaybeUninit::::uninit(); PATH_MAX]; + let raw: &[u8] = if let Some(cached) = call.cached_cstr(path_ptr) { + cached + } else { + let Ok(Some(bytes)) = fspy_elf_loader::copy_user_cstr(path_ptr, &mut buf) else { + return; + }; + bytes + }; + 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 Some(dirfd) = dirfd else { + return; + }; + let arena = pooled_bump(); + let Ok(Some(base)) = fd_path(&arena, dirfd) else { + return; + }; + let base_bytes = base.as_units(); + let mut joined = Vec::new_in(&arena); + if joined.try_reserve_exact(base_bytes.len() + 1 + raw.len()).is_err() { + return; + } + joined.extend_from_slice(base_bytes); + if !base_bytes.ends_with(b"/") { + joined.push(b'/'); + } + joined.extend_from_slice(raw); + send_path(mode, BStr::new(&joined)); + } + + 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::io_uring_setup => Err(Error::NOSYS), + 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; let the kernel answer directly. + if (raw_flags & AT_EXECVE_CHECK) != 0 { + 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(call, Some(CWD), a[0], open_mode(arg_u32(a[1])), false), + Sysno::openat => report_path_at(call, dirfd(0), a[1], open_mode(arg_u32(a[2])), false), + Sysno::openat2 => report_openat2(call, 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(call, 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(call, 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(call, dirfd(0), a[1], AccessMode::Read, empty_ok); + } + Sysno::statx => { + let empty_ok = (arg_u32(a[2]) & AT_EMPTY_PATH) != 0; + report_path_at(call, dirfd(0), a[1], AccessMode::Read, empty_ok); + } + Sysno::faccessat => { + report_path_at(call, dirfd(0), a[1], AccessMode::Read, false); + } + Sysno::faccessat2 => { + let empty_ok = (arg_u32(a[3]) & AT_EMPTY_PATH) != 0; + report_path_at(call, dirfd(0), a[1], AccessMode::Read, empty_ok); + } + #[cfg(target_arch = "x86_64")] + Sysno::mkdir => report_path_at(call, Some(CWD), a[0], AccessMode::Mkdir, false), + Sysno::mkdirat => report_path_at(call, dirfd(0), a[1], AccessMode::Mkdir, false), + #[cfg(target_arch = "x86_64")] + Sysno::rename => report_path_at(call, Some(CWD), a[1], AccessMode::RenameTarget, false), + Sysno::renameat | Sysno::renameat2 => { + report_path_at(call, dirfd(2), a[3], AccessMode::RenameTarget, false); + } + #[cfg(target_arch = "x86_64")] + Sysno::link | Sysno::symlink => { + report_path_at(call, Some(CWD), a[1], AccessMode::Write, false); + } + Sysno::linkat => report_path_at(call, dirfd(2), a[3], AccessMode::Write, false), + Sysno::symlinkat => report_path_at(call, dirfd(1), a[2], AccessMode::Write, false), + _ => {} + } + } + + fn report_openat2( + call: &Syscall<'_>, + 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. + 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(call, dirfd, path_ptr, mode, false); + } + + /// Fault-safe copy of an arbitrarily long NUL-terminated user string into + /// `allocator`. + fn copy_user_cstr_vec(addr: usize, allocator: A) -> Result> { + if addr == 0 { + return Err(Error::FAULT); + } + let mut out = Vec::new_in(allocator); + let mut chunk = [MaybeUninit::::uninit(); 4096]; + let mut offset = 0usize; + loop { + let cur = addr.checked_add(offset).ok_or(Error::FAULT)?; + if let Some(bytes) = fspy_elf_loader::copy_user_cstr(cur, &mut chunk)? { + out.try_reserve_exact(bytes.len()).map_err(|_| Error::NOMEM)?; + out.extend_from_slice(bytes); + return Ok(out); + } + // SAFETY: `copy_user_cstr` initialized all `chunk.len()` bytes on `Ok(None)`. + let filled = unsafe { slice::from_raw_parts(chunk.as_ptr().cast::(), chunk.len()) }; + out.try_reserve(filled.len()).map_err(|_| Error::NOMEM)?; + out.extend_from_slice(filled); + offset = offset.checked_add(chunk.len()).ok_or(Error::FAULT)?; + if offset > MAX_EXEC_STRING_LEN { + return Err(Error::from_raw_os_error(E2BIG.cast_signed())); + } + } + } + + fn copy_user_cstr_array( + arr_ptr: usize, + allocator: A, + mut map_fn: impl FnMut(Vec) -> T, + ) -> Result> { + if arr_ptr == 0 { + return Ok(Vec::new_in(allocator)); + } + let mut out = Vec::new_in(allocator.clone()); + let mut idx = 0usize; + loop { + let byte_off = idx.checked_mul(size_of::()).ok_or(Error::FAULT)?; + let elem_addr = arr_ptr.checked_add(byte_off).ok_or(Error::FAULT)?; + // SAFETY: `usize` is valid for any bit pattern. + let str_ptr = unsafe { fspy_elf_loader::copy_user_value::(elem_addr) }?; + if str_ptr == 0 { + return Ok(out); + } + let bytes = copy_user_cstr_vec(str_ptr, allocator.clone())?; + out.try_reserve(1).map_err(|_| Error::NOMEM)?; + out.push(map_fn(bytes)); + idx += 1; + } + } + + fn copy_user_exec( + prog_ptr: usize, + argv_ptr: usize, + envp_ptr: usize, + allocator: A, + ) -> Result> { + let program = copy_user_cstr_vec(prog_ptr, allocator.clone())?; + let args = copy_user_cstr_array(argv_ptr, allocator.clone(), |arg| arg)?; + let envs: Vec, A> = copy_user_cstr_array(envp_ptr, allocator.clone(), |mut env| { + if let Some(eq_pos) = env.iter().position(|&b| b == b'=') { + let value = copy_bytes(&env[eq_pos + 1..], allocator.clone()); + env.truncate(eq_pos); + (env, Some(value)) + } else { + (env, None) + } + })?; + Ok(Exec { program, args, envs }) + } + + #[inline] + fn park_state(pid: i32) -> u64 { + loop { + let generation = PARK_GEN.fetch_add(1, Ordering::Relaxed) & 0xffff_ffff; + if generation != 0 { + return (generation << 32) | u64::from(pid.cast_unsigned()); + } + } + } + + #[inline] + #[expect(clippy::cast_possible_truncation, reason = "Linux pid_t fits in lower 32 bits")] + const fn parked_pid(state: u64) -> i32 { + (state as u32).cast_signed() + } + + #[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()) }; + } + + /// Returns `true` if `child_pid` no longer shares our virtual memory + /// (`mm_struct`) or has exited, so its parked `CLONE_VM` exec scratch + /// mapping is guaranteed unreachable and safe to `munmap`. + fn is_vm_detached(my_pid: i32, child_pid: i32) -> bool { + if child_pid <= 0 || child_pid == my_pid { + return false; + } + // SAFETY: `kcmp(my_pid, child_pid, KCMP_VM, 0, 0)` compares the two + // processes' `mm_struct` pointers (`0` = same VM, `> 0` = different VM). + let rc = unsafe { + syscalls::raw::syscall5( + Sysno::kcmp as usize, + my_pid.cast_unsigned() as usize, + child_pid.cast_unsigned() as usize, + KCMP_VM, + 0, + 0, + ) + .cast_signed() + }; + if rc == 0 { + return false; + } + if rc > 0 { + return true; + } + #[expect( + clippy::cast_possible_truncation, + reason = "Linux negative syscall errno fits in u32" + )] + let errno = (-rc).cast_unsigned() as u32; + if errno == ESRCH { + return true; + } + if errno == EPERM || errno == ENOSYS { + // Fallback if `kcmp` is denied and `clear_child_tid` was not yet + // cleared (e.g. child killed before `set_tid_address`): probe liveness. + // SAFETY: `kill(child_pid, 0)` probes liveness without sending a signal. + let krc = unsafe { + syscalls::raw::syscall2(Sysno::kill as usize, child_pid.cast_unsigned() as usize, 0) + .cast_signed() + }; + return krc == -(ESRCH.cast_signed() as isize); + } + false + } + + unsafe fn push_overflow_parked(node: *mut OverflowScratch) { + let mut head = OVERFLOW_PARKED_HEAD.load(Ordering::Acquire); + loop { + // SAFETY: Caller owns `node` exclusively until CAS publishes it. + unsafe { (*node).next.store(head, Ordering::Relaxed) }; + match OVERFLOW_PARKED_HEAD.compare_exchange_weak( + head, + node, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return, + Err(actual) => head = actual, + } + } + } + + fn reclaim_overflow_scratch(my_pid: &mut i32) { + if OVERFLOW_PARKED_HEAD.load(Ordering::Acquire).is_null() { + return; + } + let mut cur = OVERFLOW_PARKED_HEAD.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 `OverflowScratch` node. + let active_tid = unsafe { (*cur).active_tid.load(Ordering::Acquire) }; + // SAFETY: `child_pid` is immutable after initialization. + let child_pid = unsafe { (*cur).child_pid }; + let detached = if active_tid == 0 { + true + } else { + if *my_pid == 0 { + *my_pid = getpid(); + } + is_vm_detached(*my_pid, child_pid) + }; + if detached { + // SAFETY: Child detached (`mm_release` cleared `active_tid` or + // `kcmp` confirmed detachment) or failure cleanup already + // detached `set_tid_address` and cleared `active_tid`. + unsafe { + *(*cur).duped_fd.get() = -1; + *(*cur).arena.get() = None; + ptr::drop_in_place(cur); + PageAllocator.deallocate( + NonNull::new_unchecked(cur).cast(), + Layout::new::(), + ); + } + } else { + // SAFETY: `cur` is still attached; return it to the parked list. + unsafe { push_overflow_parked(cur) }; + } + cur = next; + } + } + + /// Reclaims any parked `CLONE_VM` exec scratch slots and overflow nodes + /// whose child has already detached (`execve` succeeded) or exited, keeping + /// parent RSS bounded across arbitrarily many `vfork`/`posix_spawn` spawns + /// even when `kcmp` is denied or more than 64 children are live at once. + fn reclaim_detached_exec_slots() { + let mut my_pid = 0_i32; + for slot in &EXEC_SLOTS { + let state = slot.state.load(Ordering::Acquire); + if state <= SLOT_BUSY { + continue; + } + let detached = if slot.active_tid.load(Ordering::Acquire) == 0 + && slot.state.load(Ordering::Acquire) == state + { + true + } else { + if my_pid == 0 { + my_pid = getpid(); + } + is_vm_detached(my_pid, parked_pid(state)) + }; + if !detached { + continue; + } + if slot + .state + .compare_exchange(state, SLOT_BUSY, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + { + // SAFETY: Exclusive ownership via `SLOT_BUSY` and `child_pid` + // has detached from our VM. Do NOT close `duped_fd` — it + // belonged to the child's fd table. + unsafe { + *slot.duped_fd.get() = -1; + *slot.arena.get() = None; + } + slot.active_tid.store(0, Ordering::Release); + slot.state.store(SLOT_FREE, Ordering::Release); + } + } + reclaim_overflow_scratch(&mut my_pid); + } + + fn acquire_exec_slot() -> Option<&'static ExecSlot> { + EXEC_SLOTS.iter().find(|slot| { + slot.state + .compare_exchange(SLOT_FREE, SLOT_BUSY, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + }) + } + + /// Failure cleanup invoked by `fspy_elf_loader` when `SYS_execve` returns + /// an error on a pooled [`ExecSlot`]. + unsafe fn cleanup_exec_slot(raw: *mut c_void) { + // SAFETY: `raw` is a `&'static ExecSlot` owned by this failed `execve`. + let slot = unsafe { &*(raw.cast::()) }; + // Detach `clear_child_tid` FIRST while `active_tid != 0` and our thread + // is still attached to the VM (so no reclaimer can claim this slot). + if slot.state.load(Ordering::Acquire) > SLOT_BUSY { + set_tid_address(ptr::null()); + } + slot.state.store(SLOT_BUSY, Ordering::Release); + // SAFETY: Exclusive ownership of `slot` in the same process that opened + // `duped_fd` and allocated `arena`. + unsafe { + let fd = *slot.duped_fd.get(); + *slot.duped_fd.get() = -1; + if fd >= 0 { + drop(OwnedFd::from_raw_fd(fd)); + } + *slot.arena.get() = None; + } + slot.active_tid.store(0, Ordering::Release); + slot.state.store(SLOT_FREE, Ordering::Release); + } + + /// Failure cleanup invoked by `fspy_elf_loader` when `SYS_execve` returns + /// an error on an [`OverflowScratch`] allocation. + unsafe fn cleanup_overflow_scratch(raw: *mut c_void) { + let Some(ptr) = NonNull::new(raw.cast::()) else { + return; + }; + // SAFETY: `ptr` is valid and still live because either it was never + // parked, or our thread is still attached to the VM with `active_tid != 0`. + let parked = unsafe { (*ptr.as_ptr()).parked }; + if parked { + set_tid_address(ptr::null()); + // SAFETY: No reclaimer accesses `duped_fd`/`arena` while `active_tid != 0`. + unsafe { + let fd = *(*ptr.as_ptr()).duped_fd.get(); + *(*ptr.as_ptr()).duped_fd.get() = -1; + if fd >= 0 { + drop(OwnedFd::from_raw_fd(fd)); + } + *(*ptr.as_ptr()).arena.get() = None; + (*ptr.as_ptr()).active_tid.store(0, Ordering::Release); + } + let mut my_pid = 0; + reclaim_overflow_scratch(&mut my_pid); + } else { + // SAFETY: Not pushed onto `OVERFLOW_PARKED_HEAD`; exclusively owned. + unsafe { + let fd = *(*ptr.as_ptr()).duped_fd.get(); + if fd >= 0 { + drop(OwnedFd::from_raw_fd(fd)); + } + ptr::drop_in_place(ptr.as_ptr()); + PageAllocator.deallocate(ptr.cast(), Layout::new::()); + } + } + } + + /// 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_detached_exec_slots(); + + if let Some(slot) = acquire_exec_slot() { + // SAFETY: We hold exclusive `SLOT_BUSY` ownership of `slot`. + unsafe { + *slot.duped_fd.get() = -1; + *slot.arena.get() = Some(page_bump()); + } + // SAFETY: `slot.arena` was just initialized to `Some` and stays + // live until `cleanup_exec_slot` or post-detach reclamation drops it. + let arena: &'static PageBump = unsafe { (*slot.arena.get()).as_ref().unwrap() }; + + match prepare_exec_in(dirfd, prog_ptr, argv_ptr, envp_ptr, flags, sigmask, arena) { + Ok((raw_out, duped_fd)) => { + // SAFETY: Exclusive `SLOT_BUSY` ownership before publishing. + unsafe { *slot.duped_fd.get() = duped_fd }; + if is_shared_vm_child { + let child_pid = getpid(); + slot.active_tid.store(child_pid, Ordering::Release); + // Publish parked state BEFORE arming `set_tid_address` so + // `SIGKILL` at any point leaves the slot reclaimable. + slot.state.store(park_state(child_pid), Ordering::Release); + set_tid_address(&raw const slot.active_tid); + } + return Ok(SyscallAction::Execve { + prog: raw_out.prog.cast(), + argv: raw_out.argv.cast(), + envp: raw_out.envp.cast(), + cleanup: Some((cleanup_exec_slot, ptr::from_ref(slot).cast_mut().cast())), + }); + } + Err(err) => { + // SAFETY: `slot` is exclusively owned; release it on error. + unsafe { cleanup_exec_slot(ptr::from_ref(slot).cast_mut().cast()) }; + return Err(err); + } + } + } + + // Overflow fallback when more than `MAX_EXEC_SLOTS` concurrent `vfork` + // children are mid-exec simultaneously. + let layout = Layout::new::(); + let mem = PageAllocator.allocate(layout).map_err(|_| Error::NOMEM)?; + let ptr: NonNull = mem.cast(); + let child_pid = if is_shared_vm_child { getpid() } else { 0 }; + // SAFETY: `ptr` is freshly page-allocated with `Layout::new::()`. + unsafe { + ptr.as_ptr().write(OverflowScratch { + next: AtomicPtr::new(ptr::null_mut()), + active_tid: AtomicI32::new(child_pid), + child_pid, + parked: false, + arena: UnsafeCell::new(Some(page_bump())), + duped_fd: UnsafeCell::new(-1), + }); + } + // SAFETY: `ptr` remains live until `cleanup_overflow_scratch` or post-detach sweep. + let arena: &'static PageBump = unsafe { (*(*ptr.as_ptr()).arena.get()).as_ref().unwrap() }; + match prepare_exec_in(dirfd, prog_ptr, argv_ptr, envp_ptr, flags, sigmask, arena) { + Ok((raw_out, duped_fd)) => { + // SAFETY: Exclusive ownership of `ptr` before publishing. + unsafe { + *(*ptr.as_ptr()).duped_fd.get() = duped_fd; + if is_shared_vm_child { + (*ptr.as_ptr()).parked = true; + // Publish onto `OVERFLOW_PARKED_HEAD` BEFORE arming + // `set_tid_address` so `SIGKILL` at any point leaves + // the overflow scratch node reclaimable. + push_overflow_parked(ptr.as_ptr()); + set_tid_address(&raw const (*ptr.as_ptr()).active_tid); + } + } + Ok(SyscallAction::Execve { + prog: raw_out.prog.cast(), + argv: raw_out.argv.cast(), + envp: raw_out.envp.cast(), + cleanup: Some((cleanup_overflow_scratch, ptr.as_ptr().cast())), + }) + } + Err(err) => { + // SAFETY: Not parked; release overflow scratch on resolution/validation failure. + unsafe { cleanup_overflow_scratch(ptr.as_ptr().cast()) }; + Err(err) + } + } + } + + 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 mut exec = copy_user_exec(prog_ptr, argv_ptr, envp_ptr, arena)?; + let resolved = resolve_exec(&mut exec, dirfd, flags, |p| send_path(AccessMode::Read, p))?; + fspy_elf_loader::validate_exec(resolved.file.as_fd())?; + + // 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 = + if resolved.fd_backed { Some(fcntl_dupfd(resolved.file.as_fd(), 3)?) } else { None }; + + let rt = runtime(); + let target = if let Some(ref fd) = duped_fd { + Target::ResolvedFd { + fd: fd.as_raw_fd(), + execfn: IpcStr::from_bytes(&resolved.execfn), + sigmask, + } + } else { + Target::ResolvedPath { + path: IpcStr::from_bytes(&exec.program), + 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.map_or(-1, |fd| { + let raw = fd.as_raw_fd(); + core::mem::forget(fd); + raw + }); + 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..3ba32b0f9 --- /dev/null +++ b/crates/fspy_shared_unix/src/linux.rs @@ -0,0 +1,539 @@ +//! 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, the original +/// execution name for `AT_EXECFN`, and whether the binary must be handed off by +/// file descriptor rather than pathname. +pub struct ResolvedExec { + pub file: OwnedFd, + pub execfn: Vec, + pub fd_backed: bool, +} + +/// 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` already resolved to an absolute pathname. + /// `sigmask` is the calling thread's virtualized signal mask prior to exec. + ResolvedPath { path: &'a IpcStr, execfn: &'a IpcStr, sigmask: u64 }, + /// Child `fexecve` or unlinked-directory `execveat` handed off by open fd. + /// `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 (with +/// `exec.program` normalized to an absolute path whenever `fd_backed` is +/// `false`), 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; + } + + let fd_backed = if is_abs { + false + } else if let Some(resolved) = abs_path { + let resolved_bytes = resolved.as_units(); + if is_deleted_dir_path(cur_dirfd, &allocator) { + true + } else { + exec.program = to_vec_in(resolved_bytes, allocator.clone()); + false + } + } else { + true + }; + + return Ok(ResolvedExec { file, execfn, fd_backed }); + } +} + +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, fd_backed: true })); + }; + + 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 is_deleted_dir_path(dirfd: Option>, allocator: &A) -> bool { + let Some(dirfd) = dirfd else { + return false; + }; + if dirfd.as_raw_fd() == CWD.as_raw_fd() { + return false; + } + matches!(fd_path(allocator, dirfd), Ok(Some(base)) if base.as_units().ends_with(b" (deleted)")) +} + +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::ResolvedPath { path: target_path, execfn, sigmask: 0x1234 }, + 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::ResolvedPath { path: p1, execfn: e1, sigmask: m1 }, + Target::ResolvedPath { path: p2, execfn: e2, sigmask: m2 }, + ) => { + assert_eq!(p1.as_bytes(), p2.as_bytes()); + assert_eq!(e1.as_bytes(), e2.as_bytes()); + assert_eq!(m1, m2); + } + ( + 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!(!resolved.fd_backed); + 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 -> fd_backed = true. + 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"]); + let resolved = resolve_exec(&mut exec, Some(fd), ExecAtFlags::EMPTY_PATH, |_| {}).unwrap(); + assert!(resolved.fd_backed); + + // 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..95081d7b0 --- /dev/null +++ b/crates/fspy_shared_unix/src/macos.rs @@ -0,0 +1,308 @@ +//! 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 split_parent_file_name(&exec.program) { + Some((b"/bin" | b"/usr/bin", 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) +} + +/// Splits an absolute path into `(parent, file_name)`, normalizing repeated +/// trailing or interior slashes before the final component. +fn split_parent_file_name(path: &[u8]) -> Option<(&[u8], &[u8])> { + let trimmed = path.strip_suffix(b"/").unwrap_or(path); + let slash = trimmed.iter().rposition(|&b| b == b'/')?; + let file_name = &trimmed[slash + 1..]; + if file_name.is_empty() { + return None; + } + let mut parent = &trimmed[..slash]; + while parent.len() > 1 && parent.ends_with(b"/") { + parent = &parent[..parent.len() - 1]; + } + if parent.is_empty() { + parent = b"/"; + } + Some((parent, file_name)) +} + +#[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::split_parent_file_name; + + #[test] + fn splits_parent_and_file_name() { + assert_eq!( + split_parent_file_name(b"/bin/sh"), + Some((b"/bin".as_slice(), b"sh".as_slice())) + ); + assert_eq!( + split_parent_file_name(b"/usr/bin/cat"), + Some((b"/usr/bin".as_slice(), b"cat".as_slice())) + ); + assert_eq!( + split_parent_file_name(b"/bin//sh"), + Some((b"/bin".as_slice(), b"sh".as_slice())) + ); + assert_eq!(split_parent_file_name(b"/foo"), Some((b"/".as_slice(), b"foo".as_slice()))); + assert_eq!(split_parent_file_name(b"/"), None); + } + + #[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/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/.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/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 @@ +

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_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..89e157f20 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:*", @@ -34,7 +38,10 @@ "postject": "catalog:", "react": "catalog:", "react-dom": "catalog:", + "sass-embedded": "catalog:", + "sharp": "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..abb05df54 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 @@ -72,9 +84,18 @@ 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 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 +127,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 +149,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 +169,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,16 +193,16 @@ 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 @@ -188,18 +221,27 @@ 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) 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 +372,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 +493,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 +596,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 +1096,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 +1847,88 @@ packages: resolution: {integrity: sha512-S0uyoxakDINJ4DPgqxGlEEvrdSMeQb7Z2lKVjxoY2gwsbZbfg2Xr8Klfeo5ZeraHmmdBCELFUHkSe6KEmBpMvg==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + '@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 +2050,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 +2193,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 +2872,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 +3015,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 +3108,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 +3127,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 +3152,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 +3167,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 +3182,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 +3315,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 +3364,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==} @@ -3174,17 +3615,142 @@ packages: vue-tsc: optional: true - rolldown@1.2.15: - resolution: {integrity: sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true + 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 - rou3@0.9.2: - resolution: {integrity: sha512-3SOzvaAg8rkHrXtRjpCvCvbyO5to9oOO27Z/XqHEYXfMRVSw/qMIVdmaOk9W2lcRLtR6dlqTjo9hDeJk70QBYQ==} + sass-embedded-unknown-all@1.108.2: + resolution: {integrity: sha512-FYjLjAyr5BxEI2oAB+nT4OkrQZmEcQz8sVRQbxFUtw30MbEZN8WjEEbjqxQjSw4IaYhA8PuUAjvZoTyvcoRYdA==} + os: ['!android', '!darwin', '!linux', '!win32'] - rou3@1.0.0: - resolution: {integrity: sha512-ySeaQkSrua+ut9g+65I7FHqOFBaY8tV0FmccXItoq0q21se32Q3u4YiW7/RqXSosWgYJaaKwRHXy3BST9PeCNQ==} + 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 + + 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 +3843,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 +3945,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 +4072,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 +4415,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 +4491,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 +4568,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 +4584,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 +4599,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 +4894,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 +4932,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 +5302,62 @@ snapshots: '@oxlint/plugins@1.79.0': {} + '@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 +5429,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 +5548,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 +5701,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 +5715,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 +5753,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 +5766,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 +5784,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 +5803,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 +5821,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 +5870,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 +5878,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 +5898,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 +5925,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 +6094,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 +6143,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 +6230,8 @@ snapshots: clsx@2.1.1: {} + colorjs.io@0.7.1: {} + comma-separated-tokens@2.0.3: {} commander@11.1.0: {} @@ -5469,6 +6348,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 +6448,8 @@ snapshots: github-slugger@2.0.0: {} + graceful-fs@4.2.12: {} + h3@1.15.11: dependencies: cookie-es: 1.2.3 @@ -5584,6 +6470,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 +6500,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 +6637,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 +6663,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 +6692,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 +6728,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 +6751,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 +6776,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 +6803,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 +6823,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 +6845,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 +6869,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 +6894,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: @@ -6130,6 +7033,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 +7221,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 +7269,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 +7283,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 +7318,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 +7335,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 +7346,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 +7439,8 @@ snapshots: unstorage@2.0.0-beta.0: {} + varint@6.0.0: {} + verkit@0.5.0: {} vfile-message@4.0.3: @@ -6428,24 +7453,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 +7514,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 +7576,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 +7587,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 +7611,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 +7635,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 +7660,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..76bfc8514 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 @@ -45,7 +51,10 @@ 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 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 From 0adff271c468af467eb20f29c6d367c770b2d8a1 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 08:44:44 +0800 Subject: [PATCH 02/48] fix(fspy): address CI failures and vfork slot reclamation review Co-authored-by: Gemini 4 Neon --- crates/fspy/tests/linux_hardening.rs | 45 +++++++++++--- crates/fspy_preload_linux/src/main.rs | 60 +++++++++---------- .../fixtures/biome_cache/.gitattributes | 1 + .../fixtures/oxfmt_cache/.gitattributes | 1 + packages/tools/package.json | 1 + pnpm-lock.yaml | 6 ++ pnpm-workspace.yaml | 1 + 7 files changed, 76 insertions(+), 39 deletions(-) create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/biome_cache/.gitattributes create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/oxfmt_cache/.gitattributes diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs index d8a85ff9c..bb044efbe 100644 --- a/crates/fspy/tests/linux_hardening.rs +++ b/crates/fspy/tests/linux_hardening.rs @@ -272,7 +272,25 @@ async fn memfd_execveat_empty_path_tracks_child_accesses() -> anyhow::Result<()> #[test(tokio::test)] async fn deep_exec_chain_preserves_fd_env_and_seccomp_filter_hygiene() -> anyhow::Result<()> { - let cmd = vt_subprocess_test::command_for_fn!((), |()| { + // 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 { @@ -291,6 +309,9 @@ async fn deep_exec_chain_preserves_fd_env_and_seccomp_filter_hygiene() -> anyhow "__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"); @@ -302,20 +323,28 @@ async fn deep_exec_chain_preserves_fd_env_and_seccomp_filter_hygiene() -> anyhow ); } - // Verify no unexpected high FDs leaked from launcher handoff (allow - // stdin/stdout/stderr and the `/proc/self/fd` directory handle itself). + // 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 extra_fds: Vec = open_fds.into_iter().filter(|&fd| fd > 2).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!( - extra_fds.len() <= 2, - "unexpected leaked open FDs across exec chain: {extra_fds:?}" + leaked_fds.is_empty(), + "unexpected leaked open FDs at depth {depth} (inherited={inherited_fds:?}): {leaked_fds:?}" ); - let depth: usize = - std::env::var("FSPY_TEST_EXEC_DEPTH").ok().and_then(|s| s.parse().ok()).unwrap_or(0); if depth >= 5 { return; } diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index 7505fcc1c..8550caf37 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -156,9 +156,6 @@ mod runtime { Sysno::symlinkat, Sysno::execve, Sysno::execveat, - // Disable `io_uring` so runtimes such as libuv / Node.js fall back to - // standard filesystem syscalls instead of bypassing tracking via rings. - Sysno::io_uring_setup, ]; #[cfg(target_arch = "aarch64")] @@ -177,9 +174,6 @@ mod runtime { Sysno::symlinkat, Sysno::execve, Sysno::execveat, - // Disable `io_uring` so runtimes such as libuv / Node.js fall back to - // standard filesystem syscalls instead of bypassing tracking via rings. - Sysno::io_uring_setup, ]; static INTERCEPTOR: SyscallInterceptor = @@ -496,7 +490,6 @@ mod runtime { let borrow_dirfd = |raw: usize| unsafe { BorrowedFd::try_borrow_raw(arg_i32(raw)) }; match call.sysno { - Sysno::io_uring_setup => Err(Error::NOSYS), Sysno::execve => handle_exec( Some(CWD), call.args[0], @@ -960,18 +953,23 @@ mod runtime { // live until `cleanup_exec_slot` or post-detach reclamation drops it. let arena: &'static PageBump = unsafe { (*slot.arena.get()).as_ref().unwrap() }; + if is_shared_vm_child { + let child_pid = getpid(); + slot.active_tid.store(child_pid, Ordering::Release); + // Publish parked state and arm `set_tid_address` BEFORE + // `prepare_exec_in` so `SIGKILL` at any point (including during + // path resolution or ELF validation) leaves the slot reclaimable + // once the kernel's `mm_release()` clears `active_tid`. + slot.state.store(park_state(child_pid), Ordering::Release); + set_tid_address(&raw const slot.active_tid); + } + match prepare_exec_in(dirfd, prog_ptr, argv_ptr, envp_ptr, flags, sigmask, arena) { Ok((raw_out, duped_fd)) => { - // SAFETY: Exclusive `SLOT_BUSY` ownership before publishing. + // SAFETY: While this thread is alive and attached to the VM + // (`active_tid != 0` for `CLONE_VM` children, or `SLOT_BUSY` + // otherwise), no reclaimer can claim `slot`. unsafe { *slot.duped_fd.get() = duped_fd }; - if is_shared_vm_child { - let child_pid = getpid(); - slot.active_tid.store(child_pid, Ordering::Release); - // Publish parked state BEFORE arming `set_tid_address` so - // `SIGKILL` at any point leaves the slot reclaimable. - slot.state.store(park_state(child_pid), Ordering::Release); - set_tid_address(&raw const slot.active_tid); - } return Ok(SyscallAction::Execve { prog: raw_out.prog.cast(), argv: raw_out.argv.cast(), @@ -980,7 +978,7 @@ mod runtime { }); } Err(err) => { - // SAFETY: `slot` is exclusively owned; release it on error. + // SAFETY: `slot` is still owned by this live thread; release it on error. unsafe { cleanup_exec_slot(ptr::from_ref(slot).cast_mut().cast()) }; return Err(err); } @@ -999,27 +997,27 @@ mod runtime { next: AtomicPtr::new(ptr::null_mut()), active_tid: AtomicI32::new(child_pid), child_pid, - parked: false, + parked: is_shared_vm_child, arena: UnsafeCell::new(Some(page_bump())), duped_fd: UnsafeCell::new(-1), }); + if is_shared_vm_child { + // Publish onto `OVERFLOW_PARKED_HEAD` and arm `set_tid_address` + // BEFORE `prepare_exec_in` so `SIGKILL` at any point leaves the + // overflow scratch node reclaimable once `mm_release()` clears + // `active_tid`. + push_overflow_parked(ptr.as_ptr()); + set_tid_address(&raw const (*ptr.as_ptr()).active_tid); + } } // SAFETY: `ptr` remains live until `cleanup_overflow_scratch` or post-detach sweep. let arena: &'static PageBump = unsafe { (*(*ptr.as_ptr()).arena.get()).as_ref().unwrap() }; match prepare_exec_in(dirfd, prog_ptr, argv_ptr, envp_ptr, flags, sigmask, arena) { Ok((raw_out, duped_fd)) => { - // SAFETY: Exclusive ownership of `ptr` before publishing. - unsafe { - *(*ptr.as_ptr()).duped_fd.get() = duped_fd; - if is_shared_vm_child { - (*ptr.as_ptr()).parked = true; - // Publish onto `OVERFLOW_PARKED_HEAD` BEFORE arming - // `set_tid_address` so `SIGKILL` at any point leaves - // the overflow scratch node reclaimable. - push_overflow_parked(ptr.as_ptr()); - set_tid_address(&raw const (*ptr.as_ptr()).active_tid); - } - } + // SAFETY: While this thread is alive and attached (`active_tid != 0` + // for `CLONE_VM` children, or unparked otherwise), no reclaimer + // touches `duped_fd`. + unsafe { *(*ptr.as_ptr()).duped_fd.get() = duped_fd }; Ok(SyscallAction::Execve { prog: raw_out.prog.cast(), argv: raw_out.argv.cast(), @@ -1028,7 +1026,7 @@ mod runtime { }) } Err(err) => { - // SAFETY: Not parked; release overflow scratch on resolution/validation failure. + // SAFETY: `ptr` is still owned by this live thread; release it on error. unsafe { cleanup_overflow_scratch(ptr.as_ptr().cast()) }; Err(err) } 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/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/packages/tools/package.json b/packages/tools/package.json index 89e157f20..4528de7bc 100644 --- a/packages/tools/package.json +++ b/packages/tools/package.json @@ -40,6 +40,7 @@ "react-dom": "catalog:", "sass-embedded": "catalog:", "sharp": "catalog:", + "tailwindcss": "catalog:", "tsdown": "catalog:", "tsx": "catalog:", "typescript": "7.1.0-dev.20261001.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index abb05df54..beb785936 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -90,6 +90,9 @@ catalogs: 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 @@ -227,6 +230,9 @@ importers: 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(tsx@4.23.15)(typescript@7.1.0-dev.20261001.1) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 76bfc8514..e51a53874 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -53,6 +53,7 @@ catalog: 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 From ccd3078fe32b2d35967b10e3aa3bb0a3d22beb4f Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 10:48:45 +0800 Subject: [PATCH 03/48] test(e2e): run the vitest browser case with Chromium's sandbox on Playwright passes `--no-sandbox` by default. Keep the sandbox on so the Linux tracker runs alongside the sandboxed renderer's own seccomp filter, which used to trap the tracker's `process_vm_readv` and crash the renderer. Also mark the launcher's `copy_user_cstr` calls `unsafe`, matching the `fspy_elf_loader` API, which now assumes trapped syscall pointers are valid. Co-Authored-By: Claude Opus 5.5 --- crates/fspy_preload_linux/src/main.rs | 21 ++++++++++++------- .../vitest_browser_cache/vitest.config.js | 5 ++++- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index 8550caf37..c799ae356 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -417,8 +417,8 @@ mod runtime { } } - /// Reports a path-based syscall to the IPC channel without risking a - /// `SIGSEGV` if `path_ptr` is unreadable. + /// 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( call: &Syscall<'_>, dirfd: Option>, @@ -436,7 +436,9 @@ mod runtime { let raw: &[u8] = if let Some(cached) = call.cached_cstr(path_ptr) { cached } else { - let Ok(Some(bytes)) = fspy_elf_loader::copy_user_cstr(path_ptr, &mut buf) else { + // SAFETY: `path_ptr` is the trapped syscall's path argument. + let Ok(Some(bytes)) = (unsafe { fspy_elf_loader::copy_user_cstr(path_ptr, &mut buf) }) + else { return; }; bytes @@ -603,7 +605,7 @@ mod runtime { return; } // SAFETY: `open_how` is a `#[repr(C)]` struct of `u64` fields valid for - // any bit pattern. + // 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; }; @@ -615,8 +617,8 @@ mod runtime { report_path_at(call, dirfd, path_ptr, mode, false); } - /// Fault-safe copy of an arbitrarily long NUL-terminated user string into - /// `allocator`. + /// Copies an arbitrarily long NUL-terminated string from a trapped + /// syscall's argument into `allocator`. fn copy_user_cstr_vec(addr: usize, allocator: A) -> Result> { if addr == 0 { return Err(Error::FAULT); @@ -626,7 +628,9 @@ mod runtime { let mut offset = 0usize; loop { let cur = addr.checked_add(offset).ok_or(Error::FAULT)?; - if let Some(bytes) = fspy_elf_loader::copy_user_cstr(cur, &mut chunk)? { + // SAFETY: `addr` is a string pointer from the trapped syscall, and + // `cur` stays before its NUL. + if let Some(bytes) = unsafe { fspy_elf_loader::copy_user_cstr(cur, &mut chunk) }? { out.try_reserve_exact(bytes.len()).map_err(|_| Error::NOMEM)?; out.extend_from_slice(bytes); return Ok(out); @@ -655,7 +659,8 @@ mod runtime { loop { let byte_off = idx.checked_mul(size_of::()).ok_or(Error::FAULT)?; let elem_addr = arr_ptr.checked_add(byte_off).ok_or(Error::FAULT)?; - // SAFETY: `usize` is valid for any bit pattern. + // SAFETY: `usize` is valid for any bit pattern, and `elem_addr` is + // inside the trapped syscall's NULL-terminated pointer array. let str_ptr = unsafe { fspy_elf_loader::copy_user_value::(elem_addr) }?; if str_ptr == 0 { return Ok(out); 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' }], }, }, From f0cbde26d17090af665d3c05dcfd05ec0007e6aa Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 11:04:14 +0800 Subject: [PATCH 04/48] refactor(fspy_preload_linux): borrow user path strings directly and reuse resolve_path_at Now that `fspy_elf_loader` exposes zero-copy `user_cstr` instead of `copy_user_cstr` / `cached_cstr`: - Simplify `report_path_at` to borrow the trapped syscall's path string directly (zero copies and no arena acquire for absolute paths) and delegate relative paths to `fspy_nostd_alloc::fs::resolve_path_at`, matching `fspy_preload_macos`. - Simplify `copy_user_cstr_vec` to use `user_cstr` directly without a 4 KiB chunk buffer loop while keeping the `MAX_EXEC_STRING_LEN` `E2BIG` guard. Co-authored-by: Gemini 4 Neon --- crates/fspy_preload_linux/src/main.rs | 120 +++++++++----------------- 1 file changed, 41 insertions(+), 79 deletions(-) diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index c799ae356..c15581831 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -10,9 +10,8 @@ mod runtime { alloc::Layout, cell::UnsafeCell, ffi::c_void, - mem::{MaybeUninit, size_of}, + mem::size_of, ptr::{self, NonNull}, - slice, sync::atomic::{AtomicI32, AtomicPtr, AtomicU64, Ordering}, }; @@ -22,9 +21,13 @@ mod runtime { use fspy_nostd::{ BorrowedFd, CStr, CWD, Error, OwnedFd, RawFd, Result, Thin, env::InitialStack, - fs::{Mode, OFlags, PATH_MAX, fcntl_dupfd, openat}, + fs::{Mode, OFlags, fcntl_dupfd, openat}, + }; + use fspy_nostd_alloc::{ + PageAllocator, PageBump, + fs::{fd_path, resolve_path_at}, + page_bump, pooled_bump, }; - use fspy_nostd_alloc::{PageAllocator, PageBump, fs::fd_path, page_bump, pooled_bump}; use fspy_shared::ipc::{ AccessMode, IpcPath, IpcStr, channel::{ChannelConf, Sender}, @@ -420,7 +423,6 @@ mod runtime { /// 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( - call: &Syscall<'_>, dirfd: Option>, path_ptr: usize, mode: AccessMode, @@ -432,17 +434,11 @@ mod runtime { } return; } - let mut buf = [MaybeUninit::::uninit(); PATH_MAX]; - let raw: &[u8] = if let Some(cached) = call.cached_cstr(path_ptr) { - cached - } else { - // SAFETY: `path_ptr` is the trapped syscall's path argument. - let Ok(Some(bytes)) = (unsafe { fspy_elf_loader::copy_user_cstr(path_ptr, &mut buf) }) - else { - return; - }; - bytes + // 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); @@ -453,24 +449,10 @@ mod runtime { send_path(mode, BStr::new(raw)); return; } - let Some(dirfd) = dirfd else { - return; - }; let arena = pooled_bump(); - let Ok(Some(base)) = fd_path(&arena, dirfd) else { - return; - }; - let base_bytes = base.as_units(); - let mut joined = Vec::new_in(&arena); - if joined.try_reserve_exact(base_bytes.len() + 1 + raw.len()).is_err() { - return; - } - joined.extend_from_slice(base_bytes); - if !base_bytes.ends_with(b"/") { - joined.push(b'/'); + if let Ok(Some(resolved)) = resolve_path_at(&arena, dirfd, c_path) { + send_path(mode, BStr::new(resolved.as_units())); } - joined.extend_from_slice(raw); - send_path(mode, BStr::new(&joined)); } fn report_fd(fd: BorrowedFd<'_>, mode: AccessMode) { @@ -486,7 +468,7 @@ mod runtime { /// /// `call` holds the live (and `/proc/*/exe`-rewritten) arguments of a /// trapped syscall listed in [`TRACKED_SYSCALLS`]. - unsafe fn handle_syscall(call: &Syscall<'_>) -> Result { + 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)) }; @@ -529,7 +511,7 @@ mod runtime { } /// Reports a tracked filesystem syscall to the IPC channel. - fn handle_fs_syscall(call: &Syscall<'_>) { + 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])) }; @@ -537,9 +519,9 @@ mod runtime { match call.sysno { #[cfg(target_arch = "x86_64")] - Sysno::open => report_path_at(call, Some(CWD), a[0], open_mode(arg_u32(a[1])), false), - Sysno::openat => report_path_at(call, dirfd(0), a[1], open_mode(arg_u32(a[2])), false), - Sysno::openat2 => report_openat2(call, dirfd(0), a[1], a[2], a[3]), + 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) { @@ -553,54 +535,48 @@ mod runtime { } #[cfg(target_arch = "x86_64")] Sysno::stat | Sysno::lstat | Sysno::access => { - report_path_at(call, Some(CWD), a[0], AccessMode::Read, false); + 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(call, dirfd(0), a[1], AccessMode::Read, empty_ok); + 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(call, dirfd(0), a[1], AccessMode::Read, empty_ok); + 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(call, dirfd(0), a[1], AccessMode::Read, empty_ok); + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); } Sysno::faccessat => { - report_path_at(call, dirfd(0), a[1], AccessMode::Read, false); + 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(call, dirfd(0), a[1], AccessMode::Read, empty_ok); + report_path_at(dirfd(0), a[1], AccessMode::Read, empty_ok); } #[cfg(target_arch = "x86_64")] - Sysno::mkdir => report_path_at(call, Some(CWD), a[0], AccessMode::Mkdir, false), - Sysno::mkdirat => report_path_at(call, dirfd(0), a[1], AccessMode::Mkdir, false), + 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(call, Some(CWD), a[1], AccessMode::RenameTarget, false), + Sysno::rename => report_path_at(Some(CWD), a[1], AccessMode::RenameTarget, false), Sysno::renameat | Sysno::renameat2 => { - report_path_at(call, dirfd(2), a[3], AccessMode::RenameTarget, false); + report_path_at(dirfd(2), a[3], AccessMode::RenameTarget, false); } #[cfg(target_arch = "x86_64")] Sysno::link | Sysno::symlink => { - report_path_at(call, Some(CWD), a[1], AccessMode::Write, false); + report_path_at(Some(CWD), a[1], AccessMode::Write, false); } - Sysno::linkat => report_path_at(call, dirfd(2), a[3], AccessMode::Write, false), - Sysno::symlinkat => report_path_at(call, dirfd(1), a[2], 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( - call: &Syscall<'_>, - dirfd: Option>, - path_ptr: usize, - how_ptr: usize, - size: usize, - ) { + fn report_openat2(dirfd: Option>, path_ptr: usize, how_ptr: usize, size: usize) { if how_ptr == 0 || size < size_of::() { return; } @@ -614,36 +590,22 @@ mod runtime { reason = "O_ACCMODE bits live in low 32 bits of open_how.flags" )] let mode = open_mode(how.flags as u32); - report_path_at(call, dirfd, path_ptr, mode, false); + report_path_at(dirfd, path_ptr, mode, false); } /// Copies an arbitrarily long NUL-terminated string from a trapped /// syscall's argument into `allocator`. fn copy_user_cstr_vec(addr: usize, allocator: A) -> Result> { - if addr == 0 { - return Err(Error::FAULT); + // SAFETY: `addr` is a NUL-terminated string pointer from the trapped syscall. + let cstr = unsafe { fspy_elf_loader::user_cstr(addr) }?; + let bytes = cstr.count().as_units(); + if bytes.len() > MAX_EXEC_STRING_LEN { + return Err(Error::from_raw_os_error(E2BIG.cast_signed())); } let mut out = Vec::new_in(allocator); - let mut chunk = [MaybeUninit::::uninit(); 4096]; - let mut offset = 0usize; - loop { - let cur = addr.checked_add(offset).ok_or(Error::FAULT)?; - // SAFETY: `addr` is a string pointer from the trapped syscall, and - // `cur` stays before its NUL. - if let Some(bytes) = unsafe { fspy_elf_loader::copy_user_cstr(cur, &mut chunk) }? { - out.try_reserve_exact(bytes.len()).map_err(|_| Error::NOMEM)?; - out.extend_from_slice(bytes); - return Ok(out); - } - // SAFETY: `copy_user_cstr` initialized all `chunk.len()` bytes on `Ok(None)`. - let filled = unsafe { slice::from_raw_parts(chunk.as_ptr().cast::(), chunk.len()) }; - out.try_reserve(filled.len()).map_err(|_| Error::NOMEM)?; - out.extend_from_slice(filled); - offset = offset.checked_add(chunk.len()).ok_or(Error::FAULT)?; - if offset > MAX_EXEC_STRING_LEN { - return Err(Error::from_raw_os_error(E2BIG.cast_signed())); - } - } + out.try_reserve_exact(bytes.len()).map_err(|_| Error::NOMEM)?; + out.extend_from_slice(bytes); + Ok(out) } fn copy_user_cstr_array( From 74820e97eaa5389f8121e35dfb1947a78666fa6b Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 11:24:48 +0800 Subject: [PATCH 05/48] refactor(fspy): simplify exec scratch, argv copy, and launcher materialization Remove defences against cases real programs don't hit: - Exec scratch: drop the 64-slot pool, generation counter, and the `kcmp` / `kill(pid, 0)` detachment probe. Each re-routed exec gets one scratch node; only `CLONE_VM` children park theirs after a successful prepare, and the kernel's `set_tid_address` clear lets a later exec trap free it. - argv/envp: copy with `RawExec::to_exec` instead of hand-rolled loops with a 2 MiB `E2BIG` cap; the kernel enforces its own limits on the re-exec. - Launcher materialization: drop the `XDG_RUNTIME_DIR` / `XDG_CACHE_HOME` / `~/.cache` / `/var/tmp` fallback chain. A `noexec` temp directory now warns with a `TMPDIR` hint and runs tasks untracked, as before. - Tests: remove the `kcmp`-denied overflow test and the garbage-pointer `EFAULT` test; the posix_spawn RSS test still guards against leaks. The changelog no longer lists a non-executable stack as a requirement. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/fspy/src/linux/mod.rs | 115 +----- crates/fspy/tests/linux_hardening.rs | 163 +------- crates/fspy_preload_linux/src/main.rs | 516 ++++++-------------------- 4 files changed, 124 insertions(+), 672 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a11fe3c7..6891e10d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +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 with non-executable stacks ([#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)). +- **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/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index 33836183e..beb5ae4c2 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -1,13 +1,9 @@ use std::{ - env, ffi::CString, - fs, io, + io, os::{ fd::{AsRawFd as _, FromRawFd as _, OwnedFd}, - unix::{ - ffi::OsStrExt as _, - fs::{DirBuilderExt as _, MetadataExt as _, PermissionsExt as _}, - }, + unix::ffi::OsStrExt as _, }, path::{Path, PathBuf}, }; @@ -33,25 +29,25 @@ const PRELOAD_LINUX: Artifact = artifact!("fspy_preload", "CARGO_BIN_FILE_FSPY_P #[derive(Debug)] pub struct SpyImpl { - /// Materialized executable path to `fspy_preload_linux`, or `None` when no - /// writable directory permits executing files (e.g. `noexec` mounts), in - /// which case `spawn` falls back to untracked execution. + /// 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 a writable, executable directory - /// (falling back past `noexec` temp mounts) and probes whether this - /// environment permits installing a seccomp filter. + /// 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!( - "no writable executable directory found for Linux task tracking; \ - falling back to untracked execution (caching disabled)" + "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 @@ -196,76 +192,13 @@ fn spawn_untracked( }) } -/// Materializes `fspy_preload_linux` into the first candidate user directory -/// whose filesystem allows executing binaries, skipping `noexec` mounts (such -/// as CIS-hardened `/tmp`). Returns `None` if no writable executable directory -/// is available so `SpyImpl::spawn` can fall back cleanly to untracked execution. +/// 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 { - if let Ok(path) = PRELOAD_LINUX.materialize().executable().at_user_temp_dir("vp_run") - && is_path_executable(&path) - { - return Some(path); - } - - let mut fallback_bases = Vec::new(); - if let Some(dir) = env::var_os("XDG_RUNTIME_DIR") - && !dir.is_empty() - { - fallback_bases.push(PathBuf::from(dir)); - } - if let Some(dir) = env::var_os("XDG_CACHE_HOME") - && !dir.is_empty() - { - fallback_bases.push(PathBuf::from(dir)); - } else if let Some(home) = env::var_os("HOME") - && !home.is_empty() - { - fallback_bases.push(PathBuf::from(home).join(".cache")); - } - fallback_bases.push(PathBuf::from("/var/tmp")); - - materialize_in_candidates(&fallback_bases, is_path_executable) -} - -fn materialize_in_candidates( - bases: &[PathBuf], - is_executable: impl Fn(&Path) -> bool, -) -> Option { - for base in bases { - let Ok(user_dir) = ensure_private_user_dir(base, "vp_run") else { - continue; - }; - let Ok(path) = PRELOAD_LINUX.materialize().executable().at(&user_dir) else { - continue; - }; - if is_executable(&path) { - return Some(path); - } - } - None -} - -/// Creates (if needed) and validates a `0o700` directory `{base}/{prefix}-{uid}` -/// owned solely by the current user, matching `vt_materialized_artifact`. -fn ensure_private_user_dir(base: &Path, prefix: &str) -> io::Result { - if !base.exists() { - fs::create_dir_all(base)?; - } - // SAFETY: `geteuid` has no preconditions and always succeeds. - let uid = unsafe { libc::geteuid() }; - let dir = base.join(format!("{prefix}-{uid}")); - match fs::DirBuilder::new().mode(0o700).create(&dir) { - Err(err) if err.kind() != io::ErrorKind::AlreadyExists => return Err(err), - _ => {} - } - let metadata = fs::symlink_metadata(&dir)?; - if !metadata.is_dir() || metadata.uid() != uid || metadata.permissions().mode() & 0o022 != 0 { - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - format!("{} is not a private user-owned directory", dir.display()), - )); - } - Ok(dir) + 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 @@ -402,20 +335,4 @@ mod tests { })); assert!(image.dynamic().unwrap().is_none()); } - - #[test] - fn materialize_in_candidates_skips_non_executable_mount_and_falls_back() { - let dir1 = tempfile::tempdir().unwrap(); - let dir2 = tempfile::tempdir().unwrap(); - let bases = [dir1.path().to_path_buf(), dir2.path().to_path_buf()]; - - // Simulate `dir1` mounted `noexec`: candidate search must fall back to `dir2`. - let chosen = super::materialize_in_candidates(&bases, |p| p.starts_with(dir2.path())) - .expect("expected fallback to second candidate dir"); - assert!(chosen.starts_with(dir2.path())); - assert!(super::is_path_executable(&chosen)); - - // When no candidate permits execution, return `None` so spawn falls back to untracked. - assert!(super::materialize_in_candidates(&bases, |_| false).is_none()); - } } diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs index bb044efbe..23151bb37 100644 --- a/crates/fspy/tests/linux_hardening.rs +++ b/crates/fspy/tests/linux_hardening.rs @@ -1,6 +1,6 @@ //! Linux hardening tests covering `vfork`/`posix_spawn` memory reclamation, -//! `memfd_create` + `execveat(AT_EMPTY_PATH)`, deep `execve` chain FD/env/filter -//! hygiene, and invalid user pointers returning `EFAULT`. +//! `memfd_create` + `execveat(AT_EMPTY_PATH)`, and deep `execve` chain +//! FD/env/filter hygiene. #![cfg(target_os = "linux")] mod test_utils; @@ -76,130 +76,6 @@ async fn posix_spawn_parent_rss_stays_bounded() -> anyhow::Result<()> { Ok(()) } -#[test(tokio::test)] -async fn posix_spawn_kcmp_denied_and_overflow_rss_stays_bounded() -> anyhow::Result<()> { - let cmd = vt_subprocess_test::command_for_fn!((), |()| { - use std::ffi::CString; - - use linux_raw_sys::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, sock_filter, sock_fprog, - }; - - 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"); - } - - // Deny `kcmp` with `EPERM` (matching Docker's default seccomp profile). - #[expect(clippy::cast_possible_truncation, reason = "cBPF opcodes and syscall nr fit")] - let filter = [ - sock_filter { code: (BPF_LD | BPF_W | BPF_ABS) as u16, jt: 0, jf: 0, k: 0 }, - sock_filter { - code: (BPF_JMP | BPF_JEQ | BPF_K) as u16, - jt: 0, - jf: 1, - k: libc::SYS_kcmp as u32, - }, - sock_filter { - code: (BPF_RET | BPF_K) as u16, - jt: 0, - jf: 0, - k: SECCOMP_RET_ERRNO | ((libc::EPERM as u32) & 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: u16::try_from(filter.len()).unwrap(), - filter: filter.as_ptr().cast_mut(), - }; - // SAFETY: installs a minimal BPF filter returning `EPERM` for `SYS_kcmp`. - let seccomp_rc = unsafe { - libc::syscall(libc::SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &raw const prog) - }; - assert_eq!( - seccomp_rc, - 0, - "failed to install kcmp-denying seccomp filter: {}", - std::io::Error::last_os_error() - ); - - let prog_path = std::sync::Arc::new(CString::new("/bin/sleep").unwrap()); - let arg0 = std::sync::Arc::new(CString::new("sleep").unwrap()); - let arg1 = std::sync::Arc::new(CString::new("0.05").unwrap()); - - let env_cstrs: std::sync::Arc> = std::sync::Arc::new( - std::env::vars().map(|(k, v)| CString::new(format!("{k}={v}")).unwrap()).collect(), - ); - - // 4 waves x 72 concurrent threads synchronized at a barrier (> 64 fixed - // `EXEC_SLOTS`) under denied `kcmp`, genuinely exercising both the - // `clear_child_tid` slot fast path and the `OverflowScratch` parked list. - let concurrent_spawners = 72usize; - let mut baseline_rss = 0usize; - for wave in 0..4 { - let barrier = std::sync::Arc::new(std::sync::Barrier::new(concurrent_spawners)); - let mut handles = Vec::with_capacity(concurrent_spawners); - for i in 0..concurrent_spawners { - let barrier = std::sync::Arc::clone(&barrier); - let prog_path = std::sync::Arc::clone(&prog_path); - let arg0 = std::sync::Arc::clone(&arg0); - let arg1 = std::sync::Arc::clone(&arg1); - let env_cstrs = std::sync::Arc::clone(&env_cstrs); - handles.push(std::thread::spawn(move || { - let argv = - [arg0.as_ptr().cast_mut(), arg1.as_ptr().cast_mut(), std::ptr::null_mut()]; - 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()); - barrier.wait(); - let mut pid: libc::pid_t = 0; - // SAFETY: `prog_path`, `argv`, and `envp` are valid NUL-terminated arrays. - let rc = unsafe { - libc::posix_spawn( - &raw mut pid, - prog_path.as_ptr(), - std::ptr::null(), - std::ptr::null(), - argv.as_ptr(), - envp.as_ptr(), - ) - }; - assert_eq!(rc, 0, "posix_spawn wave {wave} thread {i} failed with errno {rc}"); - pid - })); - } - let pids: Vec = handles.into_iter().map(|h| h.join().unwrap()).collect(); - for pid in pids { - 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 wave == 0 { - baseline_rss = vm_rss_kib(); - } - } - - let final_rss = vm_rss_kib(); - let growth = final_rss.saturating_sub(baseline_rss); - assert!( - growth < 6144, - "parent VmRSS grew by {growth} KiB across 216 concurrent overflow posix_spawns with kcmp denied \ - (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"); @@ -388,38 +264,3 @@ async fn deep_exec_chain_preserves_fd_env_and_seccomp_filter_hygiene() -> anyhow let _accesses = test_utils::spawn_command(cmd).await?; Ok(()) } - -#[test(tokio::test)] -async fn invalid_user_pointers_return_efault_under_fspy() -> anyhow::Result<()> { - let cmd = vt_subprocess_test::command_for_fn!((), |()| { - use std::ffi::CString; - - let bad_ptr = 1usize; - // SAFETY: intentionally passing invalid pointers to verify `-EFAULT` - // instead of crashing inside the `SIGSYS` handler. - unsafe { - assert_eq!( - libc::syscall(libc::SYS_openat, libc::AT_FDCWD, bad_ptr, libc::O_RDONLY, 0), - -1 - ); - assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::EFAULT)); - - assert_eq!(libc::syscall(libc::SYS_execve, bad_ptr, 0usize, 0usize), -1); - assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::EFAULT)); - - let prog = CString::new("/bin/true").unwrap(); - assert_eq!(libc::syscall(libc::SYS_execve, prog.as_ptr(), bad_ptr, 0usize), -1); - assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::EFAULT)); - - let bad_argv = [std::ptr::dangling::(), std::ptr::null()]; - assert_eq!( - libc::syscall(libc::SYS_execve, prog.as_ptr(), bad_argv.as_ptr(), 0usize), - -1 - ); - assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::EFAULT)); - } - }); - - let _accesses = test_utils::spawn_command(cmd).await?; - Ok(()) -} diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index c15581831..aa2be4e96 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -12,7 +12,7 @@ mod runtime { ffi::c_void, mem::size_of, ptr::{self, NonNull}, - sync::atomic::{AtomicI32, AtomicPtr, AtomicU64, Ordering}, + sync::atomic::{AtomicI32, AtomicPtr, Ordering}, }; use allocator_api2::{alloc::Allocator, vec::Vec}; @@ -33,15 +33,14 @@ mod runtime { channel::{ChannelConf, Sender}, }; use fspy_shared_unix::{ - Env, Exec, RawExec, + Exec, RawExec, linux::{ BOOTSTRAP_ENV_NAME, Bootstrap, ExecAtFlags, Target, encode_bootstrap, ensure_bootstrap_env, resolve_exec, }, }; - use linux_raw_sys::{ - errno::{E2BIG, ENOSYS, EPERM, ESRCH}, - general::{AT_EMPTY_PATH, O_ACCMODE, O_RDWR, O_WRONLY, SIG_SETMASK, open_how}, + use linux_raw_sys::general::{ + AT_EMPTY_PATH, O_ACCMODE, O_RDWR, O_WRONLY, SIG_SETMASK, open_how, }; use syscalls::Sysno; @@ -52,19 +51,6 @@ mod runtime { /// the process image. const AT_EXECVE_CHECK: u32 = 0x10000; - /// Linux `kcmp(2)` resource type comparing virtual memory (`mm_struct`). - const KCMP_VM: usize = 1; - - /// Upper bound on a single `argv`/`envp` string copied from user memory - /// (matches Linux `MAX_ARG_STRLEN` up to 64 KiB pages). - const MAX_EXEC_STRING_LEN: usize = 2 * 1024 * 1024; - - /// Number of reusable exec scratch slots for reclaiming `CLONE_VM` - /// (`vfork` / `posix_spawn`) exec buffers once the child detaches. - const MAX_EXEC_SLOTS: usize = 64; - const SLOT_FREE: u64 = 0; - const SLOT_BUSY: u64 = 1; - struct SyncCell(UnsafeCell); // SAFETY: `STARTUP_BUMP` and `RUNTIME` are initialized once in the fresh, @@ -78,61 +64,32 @@ mod runtime { sender: Option, } - struct ExecSlot { - /// `0` = free, `1` = exclusively owned in-flight/reclaiming, - /// `(gen << 32) | child_pid` (`gen >= 1`) = parked by a `CLONE_VM` - /// child calling `execve`. - state: AtomicU64, - /// Registered with `set_tid_address` right before `SYS_execve` in a - /// `CLONE_VM` child: the Linux kernel's `mm_release()` atomically writes - /// `0` here the instant `execve` detaches the child's `mm_struct` (or - /// if the child dies), allowing zero-syscall reclamation even when - /// `kcmp` is denied by Docker/seccomp and without PID-reuse hazards. - active_tid: AtomicI32, - arena: UnsafeCell>, - duped_fd: UnsafeCell, - } - - // SAFETY: Access to `arena` and `duped_fd` is serialized via `state` CAS - // transitions (`SLOT_FREE -> SLOT_BUSY` and `parked(gen, pid) -> SLOT_BUSY`). - unsafe impl Sync for ExecSlot {} - - impl ExecSlot { - const fn new() -> Self { - Self { - state: AtomicU64::new(SLOT_FREE), - active_tid: AtomicI32::new(0), - arena: UnsafeCell::new(None), - duped_fd: UnsafeCell::new(-1), - } - } - } - - /// Overflow scratch node used when all [`MAX_EXEC_SLOTS`] fixed slots are - /// simultaneously busy. For `CLONE_VM` children, pushed onto - /// [`OVERFLOW_PARKED_HEAD`] and reclaimed once `active_tid` becomes `0` - /// (written by the kernel's `mm_release()` on exec/exit, or by failure - /// cleanup) or `kcmp` reports VM detachment. - struct OverflowScratch { + /// 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, - child_pid: i32, parked: bool, arena: UnsafeCell>, duped_fd: UnsafeCell, } - // SAFETY: `arena` and `duped_fd` are mutated exclusively by the owning - // thread before `active_tid` transitions to `0` (`Release`), and only - // dropped by a reclaimer that observes `active_tid == 0` (`Acquire`) or - // kernel VM detachment after detaching the node from `OVERFLOW_PARKED_HEAD`. - unsafe impl Sync for OverflowScratch {} + // 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 EXEC_SLOTS: [ExecSlot; MAX_EXEC_SLOTS] = [const { ExecSlot::new() }; MAX_EXEC_SLOTS]; - static PARK_GEN: AtomicU64 = AtomicU64::new(1); - static OVERFLOW_PARKED_HEAD: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + static PARKED_EXEC_SCRATCH: AtomicPtr = AtomicPtr::new(ptr::null_mut()); #[cfg(target_arch = "x86_64")] const TRACKED_SYSCALLS: &[Sysno] = &[ @@ -379,12 +336,6 @@ mod runtime { } } - #[expect(clippy::cast_possible_truncation, reason = "Linux pid_t is i32")] - fn getpid() -> i32 { - // SAFETY: `getpid` takes no arguments and cannot fail. - unsafe { syscalls::raw::syscall0(Sysno::getpid as usize).cast_signed() as i32 } - } - fn send_path(mode: AccessMode, path: &BStr) { let bytes: &[u8] = path.as_ref(); if bytes.starts_with(b"/dev/") @@ -593,83 +544,6 @@ mod runtime { report_path_at(dirfd, path_ptr, mode, false); } - /// Copies an arbitrarily long NUL-terminated string from a trapped - /// syscall's argument into `allocator`. - fn copy_user_cstr_vec(addr: usize, allocator: A) -> Result> { - // SAFETY: `addr` is a NUL-terminated string pointer from the trapped syscall. - let cstr = unsafe { fspy_elf_loader::user_cstr(addr) }?; - let bytes = cstr.count().as_units(); - if bytes.len() > MAX_EXEC_STRING_LEN { - return Err(Error::from_raw_os_error(E2BIG.cast_signed())); - } - let mut out = Vec::new_in(allocator); - out.try_reserve_exact(bytes.len()).map_err(|_| Error::NOMEM)?; - out.extend_from_slice(bytes); - Ok(out) - } - - fn copy_user_cstr_array( - arr_ptr: usize, - allocator: A, - mut map_fn: impl FnMut(Vec) -> T, - ) -> Result> { - if arr_ptr == 0 { - return Ok(Vec::new_in(allocator)); - } - let mut out = Vec::new_in(allocator.clone()); - let mut idx = 0usize; - loop { - let byte_off = idx.checked_mul(size_of::()).ok_or(Error::FAULT)?; - let elem_addr = arr_ptr.checked_add(byte_off).ok_or(Error::FAULT)?; - // SAFETY: `usize` is valid for any bit pattern, and `elem_addr` is - // inside the trapped syscall's NULL-terminated pointer array. - let str_ptr = unsafe { fspy_elf_loader::copy_user_value::(elem_addr) }?; - if str_ptr == 0 { - return Ok(out); - } - let bytes = copy_user_cstr_vec(str_ptr, allocator.clone())?; - out.try_reserve(1).map_err(|_| Error::NOMEM)?; - out.push(map_fn(bytes)); - idx += 1; - } - } - - fn copy_user_exec( - prog_ptr: usize, - argv_ptr: usize, - envp_ptr: usize, - allocator: A, - ) -> Result> { - let program = copy_user_cstr_vec(prog_ptr, allocator.clone())?; - let args = copy_user_cstr_array(argv_ptr, allocator.clone(), |arg| arg)?; - let envs: Vec, A> = copy_user_cstr_array(envp_ptr, allocator.clone(), |mut env| { - if let Some(eq_pos) = env.iter().position(|&b| b == b'=') { - let value = copy_bytes(&env[eq_pos + 1..], allocator.clone()); - env.truncate(eq_pos); - (env, Some(value)) - } else { - (env, None) - } - })?; - Ok(Exec { program, args, envs }) - } - - #[inline] - fn park_state(pid: i32) -> u64 { - loop { - let generation = PARK_GEN.fetch_add(1, Ordering::Relaxed) & 0xffff_ffff; - if generation != 0 { - return (generation << 32) | u64::from(pid.cast_unsigned()); - } - } - } - - #[inline] - #[expect(clippy::cast_possible_truncation, reason = "Linux pid_t fits in lower 32 bits")] - const fn parked_pid(state: u64) -> i32 { - (state as u32).cast_signed() - } - #[inline] fn set_tid_address(addr: *const AtomicI32) { // SAFETY: `addr` is either null or points to a live `AtomicI32` that @@ -678,59 +552,12 @@ mod runtime { let _ = unsafe { syscalls::raw::syscall1(Sysno::set_tid_address as usize, addr.addr()) }; } - /// Returns `true` if `child_pid` no longer shares our virtual memory - /// (`mm_struct`) or has exited, so its parked `CLONE_VM` exec scratch - /// mapping is guaranteed unreachable and safe to `munmap`. - fn is_vm_detached(my_pid: i32, child_pid: i32) -> bool { - if child_pid <= 0 || child_pid == my_pid { - return false; - } - // SAFETY: `kcmp(my_pid, child_pid, KCMP_VM, 0, 0)` compares the two - // processes' `mm_struct` pointers (`0` = same VM, `> 0` = different VM). - let rc = unsafe { - syscalls::raw::syscall5( - Sysno::kcmp as usize, - my_pid.cast_unsigned() as usize, - child_pid.cast_unsigned() as usize, - KCMP_VM, - 0, - 0, - ) - .cast_signed() - }; - if rc == 0 { - return false; - } - if rc > 0 { - return true; - } - #[expect( - clippy::cast_possible_truncation, - reason = "Linux negative syscall errno fits in u32" - )] - let errno = (-rc).cast_unsigned() as u32; - if errno == ESRCH { - return true; - } - if errno == EPERM || errno == ENOSYS { - // Fallback if `kcmp` is denied and `clear_child_tid` was not yet - // cleared (e.g. child killed before `set_tid_address`): probe liveness. - // SAFETY: `kill(child_pid, 0)` probes liveness without sending a signal. - let krc = unsafe { - syscalls::raw::syscall2(Sysno::kill as usize, child_pid.cast_unsigned() as usize, 0) - .cast_signed() - }; - return krc == -(ESRCH.cast_signed() as isize); - } - false - } - - unsafe fn push_overflow_parked(node: *mut OverflowScratch) { - let mut head = OVERFLOW_PARKED_HEAD.load(Ordering::Acquire); + 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 OVERFLOW_PARKED_HEAD.compare_exchange_weak( + match PARKED_EXEC_SCRATCH.compare_exchange_weak( head, node, Ordering::AcqRel, @@ -742,155 +569,65 @@ mod runtime { } } - fn reclaim_overflow_scratch(my_pid: &mut i32) { - if OVERFLOW_PARKED_HEAD.load(Ordering::Acquire).is_null() { + /// 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 = OVERFLOW_PARKED_HEAD.swap(ptr::null_mut(), Ordering::AcqRel); + 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 `OverflowScratch` node. - let active_tid = unsafe { (*cur).active_tid.load(Ordering::Acquire) }; - // SAFETY: `child_pid` is immutable after initialization. - let child_pid = unsafe { (*cur).child_pid }; - let detached = if active_tid == 0 { - true - } else { - if *my_pid == 0 { - *my_pid = getpid(); - } - is_vm_detached(*my_pid, child_pid) - }; - if detached { - // SAFETY: Child detached (`mm_release` cleared `active_tid` or - // `kcmp` confirmed detachment) or failure cleanup already - // detached `set_tid_address` and cleared `active_tid`. - unsafe { - *(*cur).duped_fd.get() = -1; - *(*cur).arena.get() = None; - ptr::drop_in_place(cur); - PageAllocator.deallocate( - NonNull::new_unchecked(cur).cast(), - Layout::new::(), - ); - } + // 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 attached; return it to the parked list. - unsafe { push_overflow_parked(cur) }; + // SAFETY: `cur` is still in use by its child; park it again. + unsafe { push_parked_exec_scratch(cur) }; } cur = next; } } - /// Reclaims any parked `CLONE_VM` exec scratch slots and overflow nodes - /// whose child has already detached (`execve` succeeded) or exited, keeping - /// parent RSS bounded across arbitrarily many `vfork`/`posix_spawn` spawns - /// even when `kcmp` is denied or more than 64 children are live at once. - fn reclaim_detached_exec_slots() { - let mut my_pid = 0_i32; - for slot in &EXEC_SLOTS { - let state = slot.state.load(Ordering::Acquire); - if state <= SLOT_BUSY { - continue; - } - let detached = if slot.active_tid.load(Ordering::Acquire) == 0 - && slot.state.load(Ordering::Acquire) == state - { - true - } else { - if my_pid == 0 { - my_pid = getpid(); - } - is_vm_detached(my_pid, parked_pid(state)) - }; - if !detached { - continue; - } - if slot - .state - .compare_exchange(state, SLOT_BUSY, Ordering::AcqRel, Ordering::Relaxed) - .is_ok() - { - // SAFETY: Exclusive ownership via `SLOT_BUSY` and `child_pid` - // has detached from our VM. Do NOT close `duped_fd` — it - // belonged to the child's fd table. - unsafe { - *slot.duped_fd.get() = -1; - *slot.arena.get() = None; - } - slot.active_tid.store(0, Ordering::Release); - slot.state.store(SLOT_FREE, Ordering::Release); - } - } - reclaim_overflow_scratch(&mut my_pid); - } - - fn acquire_exec_slot() -> Option<&'static ExecSlot> { - EXEC_SLOTS.iter().find(|slot| { - slot.state - .compare_exchange(SLOT_FREE, SLOT_BUSY, Ordering::AcqRel, Ordering::Relaxed) - .is_ok() - }) - } - /// Failure cleanup invoked by `fspy_elf_loader` when `SYS_execve` returns - /// an error on a pooled [`ExecSlot`]. - unsafe fn cleanup_exec_slot(raw: *mut c_void) { - // SAFETY: `raw` is a `&'static ExecSlot` owned by this failed `execve`. - let slot = unsafe { &*(raw.cast::()) }; - // Detach `clear_child_tid` FIRST while `active_tid != 0` and our thread - // is still attached to the VM (so no reclaimer can claim this slot). - if slot.state.load(Ordering::Acquire) > SLOT_BUSY { - set_tid_address(ptr::null()); - } - slot.state.store(SLOT_BUSY, Ordering::Release); - // SAFETY: Exclusive ownership of `slot` in the same process that opened - // `duped_fd` and allocated `arena`. + /// 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 = *slot.duped_fd.get(); - *slot.duped_fd.get() = -1; + let fd = *(*node).duped_fd.get(); + *(*node).duped_fd.get() = -1; if fd >= 0 { drop(OwnedFd::from_raw_fd(fd)); } - *slot.arena.get() = None; - } - slot.active_tid.store(0, Ordering::Release); - slot.state.store(SLOT_FREE, Ordering::Release); - } - - /// Failure cleanup invoked by `fspy_elf_loader` when `SYS_execve` returns - /// an error on an [`OverflowScratch`] allocation. - unsafe fn cleanup_overflow_scratch(raw: *mut c_void) { - let Some(ptr) = NonNull::new(raw.cast::()) else { - return; - }; - // SAFETY: `ptr` is valid and still live because either it was never - // parked, or our thread is still attached to the VM with `active_tid != 0`. - let parked = unsafe { (*ptr.as_ptr()).parked }; - if parked { - set_tid_address(ptr::null()); - // SAFETY: No reclaimer accesses `duped_fd`/`arena` while `active_tid != 0`. - unsafe { - let fd = *(*ptr.as_ptr()).duped_fd.get(); - *(*ptr.as_ptr()).duped_fd.get() = -1; - if fd >= 0 { - drop(OwnedFd::from_raw_fd(fd)); - } - *(*ptr.as_ptr()).arena.get() = None; - (*ptr.as_ptr()).active_tid.store(0, Ordering::Release); - } - let mut my_pid = 0; - reclaim_overflow_scratch(&mut my_pid); - } else { - // SAFETY: Not pushed onto `OVERFLOW_PARKED_HEAD`; exclusively owned. - unsafe { - let fd = *(*ptr.as_ptr()).duped_fd.get(); - if fd >= 0 { - drop(OwnedFd::from_raw_fd(fd)); - } - ptr::drop_in_place(ptr.as_ptr()); - PageAllocator.deallocate(ptr.cast(), Layout::new::()); + 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); } } } @@ -908,96 +645,47 @@ mod runtime { sigmask: u64, is_shared_vm_child: bool, ) -> Result { - reclaim_detached_exec_slots(); - - if let Some(slot) = acquire_exec_slot() { - // SAFETY: We hold exclusive `SLOT_BUSY` ownership of `slot`. - unsafe { - *slot.duped_fd.get() = -1; - *slot.arena.get() = Some(page_bump()); - } - // SAFETY: `slot.arena` was just initialized to `Some` and stays - // live until `cleanup_exec_slot` or post-detach reclamation drops it. - let arena: &'static PageBump = unsafe { (*slot.arena.get()).as_ref().unwrap() }; - - if is_shared_vm_child { - let child_pid = getpid(); - slot.active_tid.store(child_pid, Ordering::Release); - // Publish parked state and arm `set_tid_address` BEFORE - // `prepare_exec_in` so `SIGKILL` at any point (including during - // path resolution or ELF validation) leaves the slot reclaimable - // once the kernel's `mm_release()` clears `active_tid`. - slot.state.store(park_state(child_pid), Ordering::Release); - set_tid_address(&raw const slot.active_tid); - } - - match prepare_exec_in(dirfd, prog_ptr, argv_ptr, envp_ptr, flags, sigmask, arena) { - Ok((raw_out, duped_fd)) => { - // SAFETY: While this thread is alive and attached to the VM - // (`active_tid != 0` for `CLONE_VM` children, or `SLOT_BUSY` - // otherwise), no reclaimer can claim `slot`. - unsafe { *slot.duped_fd.get() = duped_fd }; - return Ok(SyscallAction::Execve { - prog: raw_out.prog.cast(), - argv: raw_out.argv.cast(), - envp: raw_out.envp.cast(), - cleanup: Some((cleanup_exec_slot, ptr::from_ref(slot).cast_mut().cast())), - }); - } - Err(err) => { - // SAFETY: `slot` is still owned by this live thread; release it on error. - unsafe { cleanup_exec_slot(ptr::from_ref(slot).cast_mut().cast()) }; - return Err(err); - } - } - } + reclaim_exec_scratch(); - // Overflow fallback when more than `MAX_EXEC_SLOTS` concurrent `vfork` - // children are mid-exec simultaneously. - let layout = Layout::new::(); - let mem = PageAllocator.allocate(layout).map_err(|_| Error::NOMEM)?; - let ptr: NonNull = mem.cast(); - let child_pid = if is_shared_vm_child { getpid() } else { 0 }; - // SAFETY: `ptr` is freshly page-allocated with `Layout::new::()`. + 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 { - ptr.as_ptr().write(OverflowScratch { + node.write(ExecScratch { next: AtomicPtr::new(ptr::null_mut()), - active_tid: AtomicI32::new(child_pid), - child_pid, - parked: is_shared_vm_child, + active_tid: AtomicI32::new(0), + parked: false, arena: UnsafeCell::new(Some(page_bump())), duped_fd: UnsafeCell::new(-1), }); - if is_shared_vm_child { - // Publish onto `OVERFLOW_PARKED_HEAD` and arm `set_tid_address` - // BEFORE `prepare_exec_in` so `SIGKILL` at any point leaves the - // overflow scratch node reclaimable once `mm_release()` clears - // `active_tid`. - push_overflow_parked(ptr.as_ptr()); - set_tid_address(&raw const (*ptr.as_ptr()).active_tid); - } } - // SAFETY: `ptr` remains live until `cleanup_overflow_scratch` or post-detach sweep. - let arena: &'static PageBump = unsafe { (*(*ptr.as_ptr()).arena.get()).as_ref().unwrap() }; - match prepare_exec_in(dirfd, prog_ptr, argv_ptr, envp_ptr, flags, sigmask, arena) { - Ok((raw_out, duped_fd)) => { - // SAFETY: While this thread is alive and attached (`active_tid != 0` - // for `CLONE_VM` children, or unparked otherwise), no reclaimer - // touches `duped_fd`. - unsafe { *(*ptr.as_ptr()).duped_fd.get() = duped_fd }; - Ok(SyscallAction::Execve { - prog: raw_out.prog.cast(), - argv: raw_out.argv.cast(), - envp: raw_out.envp.cast(), - cleanup: Some((cleanup_overflow_scratch, ptr.as_ptr().cast())), - }) - } - Err(err) => { - // SAFETY: `ptr` is still owned by this live thread; release it on error. - unsafe { cleanup_overflow_scratch(ptr.as_ptr().cast()) }; - Err(err) + // 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( @@ -1009,7 +697,13 @@ mod runtime { sigmask: u64, arena: &'static PageBump, ) -> Result<(RawExec, RawFd)> { - let mut exec = copy_user_exec(prog_ptr, argv_ptr, envp_ptr, arena)?; + 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())?; From f624e33f9a044c716ea119e43bb85b5c9279a64d Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 12:42:37 +0800 Subject: [PATCH 06/48] fix(fspy): hand off the validated exec fd, report unresolvable paths, match main's SIP paths - Child execs always pass the already-validated descriptor to the new launcher image instead of a pathname to reopen. The file can be replaced or unlinked in between, and `execve("/proc/self/fd/N")` on an `O_CLOEXEC` descriptor closed it on exec, which made the launcher panic. - A relative path whose directory is too long to name (`ENAMETOOLONG`) or can't be allocated now marks the trace incomplete instead of being dropped silently. Lookups a sandbox blocks, such as `/proc/self/fd` in Chromium's PID namespace, still stay silent. - macOS: ignore `.` components when matching `/bin` and `/usr/bin` for SIP substitution, as `Path::parent` did on main (`/bin/./sh`). Co-Authored-By: Claude Opus 5.5 --- crates/fspy/tests/linux_hardening.rs | 83 ++++++++++++++++++++++++- crates/fspy_preload_linux/src/main.rs | 87 +++++++++++---------------- crates/fspy_shared_unix/src/linux.rs | 62 ++++--------------- crates/fspy_shared_unix/src/macos.rs | 64 ++++++++++---------- 4 files changed, 157 insertions(+), 139 deletions(-) diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs index 23151bb37..6bf56c256 100644 --- a/crates/fspy/tests/linux_hardening.rs +++ b/crates/fspy/tests/linux_hardening.rs @@ -1,6 +1,7 @@ //! Linux hardening tests covering `vfork`/`posix_spawn` memory reclamation, -//! `memfd_create` + `execveat(AT_EMPTY_PATH)`, and deep `execve` chain -//! FD/env/filter hygiene. +//! `memfd_create` + `execveat(AT_EMPTY_PATH)`, `execve("/proc/self/fd/N")`, +//! traces marked incomplete when a path cannot be resolved, and deep `execve` +//! chain FD/env/filter hygiene. #![cfg(target_os = "linux")] mod test_utils; @@ -146,6 +147,84 @@ async fn memfd_execveat_empty_path_tracks_child_accesses() -> anyhow::Result<()> 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 unresolvable_relative_path_marks_trace_incomplete() -> anyhow::Result<()> { + // A cwd deeper than `PATH_MAX` makes `getcwd` fail with `ENAMETOOLONG`, so + // a relative `open` there cannot be recorded. The trace must then be + // reported incomplete instead of silently missing the access. + let dir = tempfile::tempdir()?; + let cmd = vt_subprocess_test::command_for_fn!( + dir.path().to_str().unwrap().to_owned(), + |root: String| { + std::env::set_current_dir(&root).unwrap(); + let component = "d".repeat(200); + for _ in 0..25 { + std::fs::create_dir(&component).unwrap(); + std::env::set_current_dir(&component).unwrap(); + } + std::fs::write("input.txt", b"x").unwrap(); + let _ = std::fs::read("input.txt").unwrap(); + } + ); + + let termination = fspy::Command::from(cmd) + .spawn(tokio_util::sync::CancellationToken::new()) + .await? + .wait_handle + .await?; + assert!(termination.status.success()); + assert!(matches!(termination.path_accesses, Err(fspy::TrackingIncomplete))); + 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 diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index aa2be4e96..91d947648 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -19,9 +19,8 @@ mod runtime { use bstr::BStr; use fspy_elf_loader::{Syscall, SyscallAction, SyscallInterceptor}; use fspy_nostd::{ - BorrowedFd, CStr, CWD, Error, OwnedFd, RawFd, Result, Thin, - env::InitialStack, - fs::{Mode, OFlags, fcntl_dupfd, openat}, + BorrowedFd, CStr, CWD, Error, OwnedFd, RawFd, Result, Thin, env::InitialStack, + fs::fcntl_dupfd, }; use fspy_nostd_alloc::{ PageAllocator, PageBump, @@ -220,34 +219,6 @@ mod runtime { ) } } - Target::ResolvedPath { path, execfn, sigmask } => { - let path_cstr = - path.to_os_c_string_in(bump).expect("resolved target path contains NUL"); - let execfn_cstr = - execfn.to_os_c_string_in(bump).expect("resolved execfn contains NUL"); - let file = openat( - CWD, - path_cstr.as_c_str().as_thin(), - OFlags::RDONLY | OFlags::CLOEXEC, - Mode::empty(), - ) - .expect("cannot open resolved target"); - - 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), - ) - } - } Target::ResolvedFd { fd, execfn, sigmask } => { let execfn_cstr = execfn.to_os_c_string_in(bump).expect("resolved execfn contains NUL"); @@ -349,6 +320,14 @@ mod runtime { } } + /// Marks the trace incomplete: a tracked syscall touched a path that could + /// not be resolved, so caching from this run could miss an input. + fn report_loss() { + if let Some(sender) = runtime().sender.as_ref() { + sender.report_loss(); + } + } + #[expect( clippy::cast_possible_truncation, clippy::cast_possible_wrap, @@ -401,11 +380,22 @@ mod runtime { 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())); + match resolve_path_at(&arena, dirfd, c_path) { + Ok(Some(resolved)) => send_path(mode, BStr::new(resolved.as_units())), + // The path exists but is too long to name, or naming it ran out of + // memory: a later run could depend on it, so the trace is partial. + Err(Error::NAMETOOLONG | Error::NOMEM) => report_loss(), + // No usable `dirfd` or a deleted cwd (the call fails or touches + // nothing), or a sandbox where `/proc/self/fd` cannot be read, such + // as Chromium's PID namespace, whose file access a broker performs. + Ok(None) | Err(_) => {} } } + /// Reports an access through an open descriptor. Failing to name it is not + /// a loss: opening the descriptor already recorded its path (or reported + /// the loss), and sandboxes such as Chromium's run in a PID namespace + /// where `/proc/self/fd` does not resolve. fn report_fd(fd: BorrowedFd<'_>, mode: AccessMode) { let arena = pooled_bump(); if let Ok(Some(resolved)) = fd_path(&arena, fd) { @@ -707,26 +697,20 @@ mod runtime { let resolved = resolve_exec(&mut exec, dirfd, flags, |p| send_path(AccessMode::Read, p))?; fspy_elf_loader::validate_exec(resolved.file.as_fd())?; - // Keep `duped_fd` open across `SYS_execve` (`fcntl_dupfd` clears + // 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 = - if resolved.fd_backed { Some(fcntl_dupfd(resolved.file.as_fd(), 3)?) } else { None }; + let duped_fd = fcntl_dupfd(resolved.file.as_fd(), 3)?; let rt = runtime(); - let target = if let Some(ref fd) = duped_fd { - Target::ResolvedFd { - fd: fd.as_raw_fd(), - execfn: IpcStr::from_bytes(&resolved.execfn), - sigmask, - } - } else { - Target::ResolvedPath { - path: IpcStr::from_bytes(&exec.program), - execfn: IpcStr::from_bytes(&resolved.execfn), - sigmask, - } + 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, @@ -738,11 +722,8 @@ mod runtime { exec.program = copy_bytes(rt.preload_path.as_bytes(), arena); let raw_out = RawExec::from_exec(exec); - let duped_raw = duped_fd.map_or(-1, |fd| { - let raw = fd.as_raw_fd(); - core::mem::forget(fd); - raw - }); + let duped_raw = duped_fd.as_raw_fd(); + core::mem::forget(duped_fd); Ok((raw_out, duped_raw)) } } diff --git a/crates/fspy_shared_unix/src/linux.rs b/crates/fspy_shared_unix/src/linux.rs index 3ba32b0f9..865a782a3 100644 --- a/crates/fspy_shared_unix/src/linux.rs +++ b/crates/fspy_shared_unix/src/linux.rs @@ -47,13 +47,11 @@ bitflags! { } } -/// Output of [`resolve_exec`]: the open final binary descriptor, the original -/// execution name for `AT_EXECFN`, and whether the binary must be handed off by -/// file descriptor rather than pathname. +/// 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, - pub fd_backed: bool, } /// What the freshly exec'd `fspy_preload_linux` binary should load and run. @@ -63,10 +61,8 @@ pub enum Target<'a> { /// 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` already resolved to an absolute pathname. - /// `sigmask` is the calling thread's virtualized signal mask prior to exec. - ResolvedPath { path: &'a IpcStr, execfn: &'a IpcStr, sigmask: u64 }, - /// Child `fexecve` or unlinked-directory `execveat` handed off by open fd. + /// 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 }, } @@ -141,10 +137,9 @@ pub fn ensure_bootstrap_env( /// handling and recursive `#!` shebang expansion, reporting every read path via /// `on_path_read`. /// -/// On success, `exec.program` and `exec.args` reflect the final binary (with -/// `exec.program` normalized to an absolute path whenever `fd_backed` is -/// `false`), and [`ResolvedExec::file`] holds an open `O_CLOEXEC` descriptor to -/// that binary ready for ELF validation or loading. +/// 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 /// @@ -225,21 +220,7 @@ pub fn resolve_exec( continue; } - let fd_backed = if is_abs { - false - } else if let Some(resolved) = abs_path { - let resolved_bytes = resolved.as_units(); - if is_deleted_dir_path(cur_dirfd, &allocator) { - true - } else { - exec.program = to_vec_in(resolved_bytes, allocator.clone()); - false - } - } else { - true - }; - - return Ok(ResolvedExec { file, execfn, fd_backed }); + return Ok(ResolvedExec { file, execfn }); } } @@ -295,7 +276,7 @@ fn resolve_empty_path( let Some(shebang) = parse_shebang_bytes(&peek_buf[..n], ParseShebangOptions::linux(), allocator.clone())? else { - return Ok(EmptyPathStep::Resolved(ResolvedExec { file, execfn, fd_backed: true })); + return Ok(EmptyPathStep::Resolved(ResolvedExec { file, execfn })); }; drop(file); @@ -312,16 +293,6 @@ fn resolve_empty_path( /// 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 is_deleted_dir_path(dirfd: Option>, allocator: &A) -> bool { - let Some(dirfd) = dirfd else { - return false; - }; - if dirfd.as_raw_fd() == CWD.as_raw_fd() { - return false; - } - matches!(fd_path(allocator, dirfd), Ok(Some(base)) if base.as_units().ends_with(b" (deleted)")) -} - fn bytes_to_cstring( bytes: &[u8], allocator: A, @@ -404,7 +375,6 @@ mod tests { let cases = [ Target::Unresolved { path: target_path, error_pipe_fd: 7 }, - Target::ResolvedPath { path: target_path, execfn, sigmask: 0x1234 }, Target::ResolvedFd { fd: 9, execfn, sigmask: 0x5678 }, ]; @@ -435,14 +405,6 @@ mod tests { assert_eq!(p1.as_bytes(), p2.as_bytes()); assert_eq!(f1, f2); } - ( - Target::ResolvedPath { path: p1, execfn: e1, sigmask: m1 }, - Target::ResolvedPath { path: p2, execfn: e2, sigmask: m2 }, - ) => { - assert_eq!(p1.as_bytes(), p2.as_bytes()); - assert_eq!(e1.as_bytes(), e2.as_bytes()); - assert_eq!(m1, m2); - } ( Target::ResolvedFd { fd: f1, execfn: e1, sigmask: m1 }, Target::ResolvedFd { fd: f2, execfn: e2, sigmask: m2 }, @@ -481,7 +443,6 @@ mod tests { let resolved = resolve_exec(&mut exec, Some(CWD), ExecAtFlags::empty(), |p| seen.push(p.to_vec())) .unwrap(); - assert!(!resolved.fd_backed); 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); @@ -516,13 +477,12 @@ mod tests { Some(Error::LOOP) ); - // AT_EMPTY_PATH on open executable fd -> fd_backed = true. + // 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"]); - let resolved = resolve_exec(&mut exec, Some(fd), ExecAtFlags::EMPTY_PATH, |_| {}).unwrap(); - assert!(resolved.fd_backed); + 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"); diff --git a/crates/fspy_shared_unix/src/macos.rs b/crates/fspy_shared_unix/src/macos.rs index 95081d7b0..73cf5fb71 100644 --- a/crates/fspy_shared_unix/src/macos.rs +++ b/crates/fspy_shared_unix/src/macos.rs @@ -159,8 +159,8 @@ impl<'a> EncodedPayload<'a> { exec.program = absolute_relative(&exec.program, allocator.clone())?; } - let injectable = match split_parent_file_name(&exec.program) { - Some((b"/bin" | b"/usr/bin", file_name)) => { + 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 @@ -207,23 +207,21 @@ fn bytes_to_cstring( CString::from_vec_with_nul(owned).ok_or(Error::NOENT) } -/// Splits an absolute path into `(parent, file_name)`, normalizing repeated -/// trailing or interior slashes before the final component. -fn split_parent_file_name(path: &[u8]) -> Option<(&[u8], &[u8])> { - let trimmed = path.strip_suffix(b"/").unwrap_or(path); - let slash = trimmed.iter().rposition(|&b| b == b'/')?; - let file_name = &trimmed[slash + 1..]; - if file_name.is_empty() { - return None; +/// 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; } - let mut parent = &trimmed[..slash]; - while parent.len() > 1 && parent.ends_with(b"/") { - parent = &parent[..parent.len() - 1]; + match parts[..count] { + [b"bin", file_name] | [b"usr", b"bin", file_name] => Some(file_name), + _ => None, } - if parent.is_empty() { - parent = b"/"; - } - Some((parent, file_name)) } #[doc(hidden)] @@ -246,24 +244,24 @@ pub static COREUTILS_FUNCTIONS_FOR_TEST: Set<&'static [u8]> = phf_set! { #[cfg(test)] mod tests { - use super::split_parent_file_name; + use super::sip_bin_file_name; #[test] - fn splits_parent_and_file_name() { - assert_eq!( - split_parent_file_name(b"/bin/sh"), - Some((b"/bin".as_slice(), b"sh".as_slice())) - ); - assert_eq!( - split_parent_file_name(b"/usr/bin/cat"), - Some((b"/usr/bin".as_slice(), b"cat".as_slice())) - ); - assert_eq!( - split_parent_file_name(b"/bin//sh"), - Some((b"/bin".as_slice(), b"sh".as_slice())) - ); - assert_eq!(split_parent_file_name(b"/foo"), Some((b"/".as_slice(), b"foo".as_slice()))); - assert_eq!(split_parent_file_name(b"/"), None); + 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")] From 978bce316c9d4bdfdbcf0b68e63c1a773ad5c0a1 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 12:54:58 +0800 Subject: [PATCH 07/48] revert(fspy_preload_linux): drop the loss report for unnameable relative paths f624e33f marked a trace incomplete when a relative path's directory was too long to name (`ENAMETOOLONG`) or naming it ran out of memory. Real tasks don't hit either: a workspace directory more than 4 KiB deep doesn't occur, paths outside the workspace are discarded anyway, and a failed page allocation leaves the process in trouble regardless. Restore the silent skip, as main's seccomp path did, and drop the test that built an artificial deep cwd. Co-Authored-By: Claude Opus 5.5 --- crates/fspy/tests/linux_hardening.rs | 33 +-------------------------- crates/fspy_preload_linux/src/main.rs | 23 ++----------------- 2 files changed, 3 insertions(+), 53 deletions(-) diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs index 6bf56c256..413f1efe9 100644 --- a/crates/fspy/tests/linux_hardening.rs +++ b/crates/fspy/tests/linux_hardening.rs @@ -1,7 +1,6 @@ //! Linux hardening tests covering `vfork`/`posix_spawn` memory reclamation, //! `memfd_create` + `execveat(AT_EMPTY_PATH)`, `execve("/proc/self/fd/N")`, -//! traces marked incomplete when a path cannot be resolved, and deep `execve` -//! chain FD/env/filter hygiene. +//! and deep `execve` chain FD/env/filter hygiene. #![cfg(target_os = "linux")] mod test_utils; @@ -195,36 +194,6 @@ async fn execve_proc_self_fd_of_cloexec_descriptor_runs_and_tracks() -> anyhow:: Ok(()) } -#[test(tokio::test)] -async fn unresolvable_relative_path_marks_trace_incomplete() -> anyhow::Result<()> { - // A cwd deeper than `PATH_MAX` makes `getcwd` fail with `ENAMETOOLONG`, so - // a relative `open` there cannot be recorded. The trace must then be - // reported incomplete instead of silently missing the access. - let dir = tempfile::tempdir()?; - let cmd = vt_subprocess_test::command_for_fn!( - dir.path().to_str().unwrap().to_owned(), - |root: String| { - std::env::set_current_dir(&root).unwrap(); - let component = "d".repeat(200); - for _ in 0..25 { - std::fs::create_dir(&component).unwrap(); - std::env::set_current_dir(&component).unwrap(); - } - std::fs::write("input.txt", b"x").unwrap(); - let _ = std::fs::read("input.txt").unwrap(); - } - ); - - let termination = fspy::Command::from(cmd) - .spawn(tokio_util::sync::CancellationToken::new()) - .await? - .wait_handle - .await?; - assert!(termination.status.success()); - assert!(matches!(termination.path_accesses, Err(fspy::TrackingIncomplete))); - 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 diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index 91d947648..04b5719e6 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -320,14 +320,6 @@ mod runtime { } } - /// Marks the trace incomplete: a tracked syscall touched a path that could - /// not be resolved, so caching from this run could miss an input. - fn report_loss() { - if let Some(sender) = runtime().sender.as_ref() { - sender.report_loss(); - } - } - #[expect( clippy::cast_possible_truncation, clippy::cast_possible_wrap, @@ -380,22 +372,11 @@ mod runtime { return; } let arena = pooled_bump(); - match resolve_path_at(&arena, dirfd, c_path) { - Ok(Some(resolved)) => send_path(mode, BStr::new(resolved.as_units())), - // The path exists but is too long to name, or naming it ran out of - // memory: a later run could depend on it, so the trace is partial. - Err(Error::NAMETOOLONG | Error::NOMEM) => report_loss(), - // No usable `dirfd` or a deleted cwd (the call fails or touches - // nothing), or a sandbox where `/proc/self/fd` cannot be read, such - // as Chromium's PID namespace, whose file access a broker performs. - Ok(None) | Err(_) => {} + if let Ok(Some(resolved)) = resolve_path_at(&arena, dirfd, c_path) { + send_path(mode, BStr::new(resolved.as_units())); } } - /// Reports an access through an open descriptor. Failing to name it is not - /// a loss: opening the descriptor already recorded its path (or reported - /// the loss), and sandboxes such as Chromium's run in a PID namespace - /// where `/proc/self/fd` does not resolve. fn report_fd(fd: BorrowedFd<'_>, mode: AccessMode) { let arena = pooled_bump(); if let Ok(Some(resolved)) = fd_path(&arena, fd) { From 1533537b3b7593cafdbae6f16d166523636b2f1d Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 13:13:40 +0800 Subject: [PATCH 08/48] test(e2e): add pagefind_cache fixture covering static-PIE ELF64 binaries Add `pagefind@1.6.0` to `packages/tools` and a `pagefind_cache` E2E snapshot fixture (`site/index.html` -> `dist/pagefind/`). On Linux x86-64, `@pagefind/linux-x64` ships a static-PIE (`ET_DYN`, no `PT_INTERP`) executable with no `musl` libc restriction, closing the remaining executable-kind cell alongside dynamic PIE (`biome`/`deno`/ `workerd`/`sass-embedded`), dynamic non-PIE (`bun`/`node`), and static non-PIE (`esbuild`/`typescript` 7). Co-authored-by: Gemini 4 Neon --- .../fixtures/pagefind_cache/package.json | 4 + .../fixtures/pagefind_cache/site/index.html | 9 +++ .../fixtures/pagefind_cache/snapshots.toml | 57 ++++++++++++++ .../snapshots/pagefind_cache.md | 58 ++++++++++++++ .../fixtures/pagefind_cache/vite-task.json | 8 ++ packages/tools/package.json | 1 + pnpm-lock.yaml | 76 +++++++++++++++++++ pnpm-workspace.yaml | 1 + 8 files changed, 214 insertions(+) create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/site/index.html create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/snapshots/pagefind_cache.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/pagefind_cache/vite-task.json 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/packages/tools/package.json b/packages/tools/package.json index 4528de7bc..c648aebf2 100644 --- a/packages/tools/package.json +++ b/packages/tools/package.json @@ -33,6 +33,7 @@ "oxfmt": "catalog:", "oxlint": "catalog:", "oxlint-tsgolint": "catalog:", + "pagefind": "catalog:", "playwright": "catalog:", "pnpm": "catalog:", "postject": "catalog:", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index beb785936..64436fb10 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -72,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 @@ -209,6 +212,9 @@ importers: oxlint-tsgolint: specifier: 'catalog:' version: 7.0.2008 + pagefind: + specifier: 'catalog:' + version: 1.6.0 playwright: specifier: 1.63.0 version: 1.63.0 @@ -1853,6 +1859,41 @@ 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'} @@ -3491,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'} @@ -5308,6 +5353,27 @@ 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 @@ -6915,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: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index e51a53874..cbb721f9f 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -44,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`. From ed8d0e26940a9c1563562e444dc2d5c009f92b34 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 13:18:07 +0800 Subject: [PATCH 09/48] fix(fspy): record AT_EXECVE_CHECK path lookups and set up error pipe before spawn - In `fspy_preload_linux`, record the target path via `report_path_at` (honoring `AT_EMPTY_PATH`) before replaying `execveat(AT_EXECVE_CHECK)` so Linux 6.14+ executability probes are tracked like `faccessat2`. - In `fspy::linux`, construct the tokio `pipe::Receiver` before spawning the launcher child so a setup failure cannot leave an orphaned child. Co-authored-by: Gemini 4 Neon --- crates/fspy/src/linux/mod.rs | 4 ++-- crates/fspy_preload_linux/src/main.rs | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index beb5ae4c2..6924b2b4b 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -72,6 +72,8 @@ impl SpyImpl { .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(); @@ -104,8 +106,6 @@ impl SpyImpl { // `fspy_preload_linux` terminates before writing a status code. drop(write_end); - let mut pipe_reader = tokio::net::unix::pipe::Receiver::from_owned_fd(read_end) - .map_err(SpawnError::OsSpawn)?; let mut buf = [0u8; 4]; let mut filled = 0usize; let mut cancelled = false; diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index 04b5719e6..51ddd7815 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -408,8 +408,16 @@ mod runtime { Sysno::execveat => { let raw_flags = arg_u32(call.args[4]); // Linux 6.14+ `AT_EXECVE_CHECK` validates executability without - // replacing the process image; let the kernel answer directly. + // 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 { From 14bd0ec4bb7c02c0d51f30bf34e525952aad66de Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 13:21:08 +0800 Subject: [PATCH 10/48] test(fspy): keep `sh` basename in long-shebang test for BusyBox /bin/sh On Alpine Linux (musl), `/bin/sh` is a multi-call BusyBox binary that dispatches based on `argv[0]`'s basename, so symlinking `/bin/sh` to `.../xxxx...` failed with `applet not found`. Put the length padding in the parent directory and keep the symlink named `sh`. Co-authored-by: Gemini 4 Neon --- crates/fspy/tests/shebang.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/fspy/tests/shebang.rs b/crates/fspy/tests/shebang.rs index aacf28cf7..f1c60874a 100644 --- a/crates/fspy/tests/shebang.rs +++ b/crates/fspy/tests/shebang.rs @@ -47,13 +47,16 @@ 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?; From 93c4868d8427e405bf0c07ce93b75abf0775974b Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 13:26:11 +0800 Subject: [PATCH 11/48] ci: install Bun runtime binary in Test (musl) Now that Bun tests run on Linux (including Alpine musl via `@oven/bun-linux-x64-musl`), run `pnpm --filter vite-task-tools rebuild bun` in `test-musl` before running ignored tests. Narrowed to `bun` so `deno` and `workerd` (which do not ship musl binaries) do not fail postinstall. Co-authored-by: Gemini 4 Neon --- .github/workflows/ci.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6204042ba..c6f0b0ee8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 From 627415740fb357a56412f66ade70fbcff17dd953 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 17:13:10 +0800 Subject: [PATCH 12/48] fix(fspy): harden macOS preload interposers and expand Unix tests - Fix fopen/freopen mode parsing ('+' -> ReadWrite, NULL guard) - Ignore empty path "" in handle_open_at instead of recording CWD/dirfd - Skip non-regular files (e.g. directories) in which::resolve_in_path - Classify O_RDONLY with O_CREAT/O_TRUNC as ReadWrite and record both paths on renamex_np/renameatx_np with RENAME_SWAP - Unify macOS top-level exec failures on SpawnError::OsSpawn - Resolve symlinks and '..' for SIP checks, strip only our own DYLD_INSERT_LIBRARIES entry, track posix_spawn addchdir_np/addfchdir_np, cache dyld main image index in O(1), rename COREUTILS_FUNCTIONS, and clean up intercept! original dead-code boilerplate - Add macOS preload integration tests, spawn error tests, and expand shebang and invalid_dirfd cross-platform Unix tests Co-authored-by: Gemini 4 Neon --- crates/fspy/src/macos/macos_artifacts.rs | 4 +- crates/fspy/src/macos/mod.rs | 4 +- crates/fspy/tests/invalid_dirfd.rs | 62 +++ crates/fspy/tests/macos_preload.rs | 492 ++++++++++++++++++ crates/fspy/tests/shebang.rs | 161 ++++++ crates/fspy/tests/spawn_errors.rs | 106 ++++ crates/fspy_preload_macos/src/client.rs | 55 +- .../src/interceptions/dyld.rs | 38 +- .../src/interceptions/namespace.rs | 8 + .../src/interceptions/spawn/exec/mod.rs | 25 - .../src/interceptions/spawn/posix_spawn.rs | 158 +++++- crates/fspy_preload_macos/src/libc.rs | 10 + crates/fspy_preload_macos/src/macros/macos.rs | 2 + crates/fspy_preload_macos/src/which.rs | 33 +- crates/fspy_shared_unix/src/macos.rs | 194 +++++-- crates/fspy_shared_unix/src/nostd_exec/mod.rs | 59 +++ .../fspy_shared_unix/src/nostd_exec/open.rs | 32 +- 17 files changed, 1359 insertions(+), 84 deletions(-) create mode 100644 crates/fspy/tests/macos_preload.rs create mode 100644 crates/fspy/tests/spawn_errors.rs diff --git a/crates/fspy/src/macos/macos_artifacts.rs b/crates/fspy/src/macos/macos_artifacts.rs index c4dd70739..5976ff355 100644 --- a/crates/fspy/src/macos/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::macos::COREUTILS_FUNCTIONS_FOR_TEST; + use fspy_shared_unix::macos::COREUTILS_FUNCTIONS; use super::*; @@ -25,7 +25,7 @@ mod tests { }) .collect(); let mut actual_functions: Vec<&str> = - COREUTILS_FUNCTIONS_FOR_TEST.iter().copied().map(|f| from_utf8(f).unwrap()).collect(); + COREUTILS_FUNCTIONS.iter().copied().map(|f| from_utf8(f).unwrap()).collect(); expected_functions.sort_unstable(); actual_functions.sort_unstable(); diff --git a/crates/fspy/src/macos/mod.rs b/crates/fspy/src/macos/mod.rs index dd60deb02..4fa6d1434 100644 --- a/crates/fspy/src/macos/mod.rs +++ b/crates/fspy/src/macos/mod.rs @@ -80,9 +80,7 @@ impl SpyImpl { .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())) - })?; + .map_err(|err| SpawnError::OsSpawn(io::Error::from_raw_os_error(err.raw_os_error())))?; command.set_exec(exec); command.env("FSPY", "1"); diff --git a/crates/fspy/tests/invalid_dirfd.rs b/crates/fspy/tests/invalid_dirfd.rs index bb2f6396e..f3b275302 100644 --- a/crates/fspy/tests/invalid_dirfd.rs +++ b/crates/fspy/tests/invalid_dirfd.rs @@ -190,3 +190,65 @@ async fn absolute_path_at_invalid_dirfd() -> anyhow::Result<()> { Ok(()) } + +/// An unopened positive descriptor passes `BorrowedFd::try_borrow_raw` and +/// exercises `fd_path` returning `Ok(None)` (`EBADF` / `ENOENT`) on both Linux +/// and macOS. +#[test(tokio::test)] +async fn relative_path_at_unopened_positive_dirfd() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let tmp_path = std::fs::canonicalize(tmp_dir.path())?.join("abs_via_unopened"); + std::fs::write(&tmp_path, "")?; + + let accesses = track_fn!(tmp_path.to_str().unwrap().to_owned(), |tmp_path: String| { + let unopened_fd: libc::c_int = 9999; + // Confirm `9999` is not open in this process. + // SAFETY: `F_GETFD` on a closed descriptor simply fails with `EBADF`. + assert_eq!(unsafe { libc::fcntl(unopened_fd, libc::F_GETFD) }, -1); + assert_eq!(errno(), libc::EBADF); + + let path = c"hello_unopened"; + // SAFETY: valid C strings and output buffers; kernel rejects the unopened fd. + unsafe { + assert_eq!(libc::openat(unopened_fd, path.as_ptr(), libc::O_RDONLY), -1); + assert_eq!(errno(), libc::EBADF); + + let mut stat = std::mem::MaybeUninit::::uninit(); + assert_eq!(libc::fstatat(unopened_fd, path.as_ptr(), stat.as_mut_ptr(), 0), -1); + assert_eq!(errno(), libc::EBADF); + + assert_eq!(libc::faccessat(unopened_fd, path.as_ptr(), libc::F_OK, 0), -1); + assert_eq!(errno(), libc::EBADF); + + assert!(libc::fdopendir(unopened_fd).is_null()); + assert_eq!(errno(), libc::EBADF); + } + #[cfg(target_os = "linux")] + { + assert_eq!(syscall_statx(unopened_fd, path.as_ptr(), 0), -1); + assert_eq!(errno(), libc::EBADF); + } + #[cfg(all(target_os = "linux", target_env = "gnu"))] + { + assert_eq!(glibc_statx(unopened_fd, path.as_ptr(), 0), -1); + assert_eq!(errno(), libc::EBADF); + + assert_eq!(glibc_execveat(unopened_fd, path), -1); + assert_eq!(errno(), libc::EBADF); + } + + // An absolute path ignores the unopened positive dirfd and succeeds. + let abs = std::ffi::CString::new(tmp_path).unwrap(); + // SAFETY: `abs` is a valid C string; absolute paths ignore `dirfd`. + let fd = unsafe { libc::openat(unopened_fd, abs.as_ptr(), libc::O_RDONLY) }; + assert!(fd >= 0, "openat with absolute path failed with errno {}", errno()); + // SAFETY: `fd` was opened above. + unsafe { libc::close(fd) }; + }) + .await?; + + assert_not_contains(&accesses, &std::env::current_dir()?.join("hello_unopened")); + assert_contains(&accesses, &tmp_path, PathAccess::Read); + + Ok(()) +} diff --git a/crates/fspy/tests/macos_preload.rs b/crates/fspy/tests/macos_preload.rs new file mode 100644 index 000000000..28765e2c4 --- /dev/null +++ b/crates/fspy/tests/macos_preload.rs @@ -0,0 +1,492 @@ +#![cfg(target_os = "macos")] +mod test_utils; + +use std::{ + ffi::CString, + fs::{self, Permissions}, + os::unix::fs::PermissionsExt as _, + path::Path, + ptr::null, +}; + +use fspy::PathAccess; +use test_log::test; +use test_utils::{assert_contains, assert_not_contains}; + +fn write_executable(path: &Path, content: &str) -> anyhow::Result<()> { + fs::write(path, content)?; + fs::set_permissions(path, Permissions::from_mode(0o755))?; + Ok(()) +} + +/// Runs `f` in a forked child process and asserts it exits cleanly with code 0. +fn run_in_fork(f: impl FnOnce()) { + // SAFETY: `fork()` is followed immediately by `exec*` or `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed: {}", std::io::Error::last_os_error()); + if pid == 0 { + f(); + // SAFETY: terminate child immediately without running parent destructors. + unsafe { libc::_exit(127) }; + } + 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, + "child failed with raw status {status:#x}" + ); +} + +#[test(tokio::test)] +async fn exec_family_variants_succeed_and_preserve_tracking() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let bin_dir = root.join("bin"); + fs::create_dir(&bin_dir)?; + + let execve_marker = root.join("marker_execve"); + let execv_marker = root.join("marker_execv"); + let execvp_marker = root.join("marker_execvp"); + let execlp_marker = root.join("marker_execlp"); + let execle_marker = root.join("marker_execle"); + for marker in [&execve_marker, &execv_marker, &execvp_marker, &execlp_marker, &execle_marker] { + fs::write(marker, "ok")?; + } + + let script_execve = root.join("s_execve.sh"); + write_executable( + &script_execve, + &format!( + "#!/bin/sh\n[ \"$CUSTOM_ENV\" = \"from_execve\" ] || exit 2\ncat \"{}\" >/dev/null\n", + execve_marker.display() + ), + )?; + let script_execv = root.join("s_execv.sh"); + write_executable( + &script_execv, + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", execv_marker.display()), + )?; + let script_execvp = bin_dir.join("fspy_test_execvp_cmd"); + write_executable( + &script_execvp, + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", execvp_marker.display()), + )?; + let script_execlp = bin_dir.join("fspy_test_execlp_cmd"); + write_executable( + &script_execlp, + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", execlp_marker.display()), + )?; + let script_execle = root.join("s_execle.sh"); + write_executable( + &script_execle, + &format!( + "#!/bin/sh\n[ \"$CUSTOM_ENV\" = \"from_execle\" ] || exit 2\ncat \"{}\" >/dev/null\n", + execle_marker.display() + ), + )?; + + let args = ( + script_execve.to_str().unwrap().to_owned(), + script_execv.to_str().unwrap().to_owned(), + script_execle.to_str().unwrap().to_owned(), + bin_dir.to_str().unwrap().to_owned(), + ); + + let accesses = track_fn!(args, |(script_execve, script_execv, script_execle, bin_dir): ( + String, + String, + String, + String + )| { + // 1. execve with custom envp (fspy must inject tracking env into it) + run_in_fork(|| { + let prog = CString::new(script_execve.as_str()).unwrap(); + let argv = [prog.as_ptr(), null()]; + let env0 = CString::new("CUSTOM_ENV=from_execve").unwrap(); + let env1 = CString::new("PATH=/bin:/usr/bin").unwrap(); + let envp = [env0.as_ptr(), env1.as_ptr(), null()]; + // SAFETY: all pointers are valid NUL-terminated strings / arrays. + unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), envp.as_ptr()) }; + }); + + // 2. execv + run_in_fork(|| { + let prog = CString::new(script_execv.as_str()).unwrap(); + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execv(prog.as_ptr(), argv.as_ptr()) }; + }); + + // 3. execvp (searches PATH) + run_in_fork(|| { + let new_path = format!("{bin_dir}:/bin:/usr/bin"); + // SAFETY: running in single-threaded forked child. + unsafe { std::env::set_var("PATH", new_path) }; + let prog = c"fspy_test_execvp_cmd"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + + // 4. execlp (searches PATH, variadic argv) + run_in_fork(|| { + let new_path = format!("{bin_dir}:/bin:/usr/bin"); + // SAFETY: running in single-threaded forked child. + unsafe { std::env::set_var("PATH", new_path) }; + let prog = c"fspy_test_execlp_cmd"; + // SAFETY: variadic args terminated by NULL. + unsafe { libc::execlp(prog.as_ptr(), prog.as_ptr(), null::()) }; + }); + + // 5. execle (variadic argv + trailing envp) + run_in_fork(|| { + let prog = CString::new(script_execle.as_str()).unwrap(); + let env0 = CString::new("CUSTOM_ENV=from_execle").unwrap(); + let env1 = CString::new("PATH=/bin:/usr/bin").unwrap(); + let envp = [env0.as_ptr(), env1.as_ptr(), null()]; + // SAFETY: variadic args terminated by NULL followed by valid `envp`. + unsafe { + libc::execle(prog.as_ptr(), prog.as_ptr(), null::(), envp.as_ptr()) + }; + }); + }) + .await?; + + for marker in [&execve_marker, &execv_marker, &execvp_marker, &execlp_marker, &execle_marker] { + assert_contains(&accesses, marker, PathAccess::Read); + } + + Ok(()) +} + +#[test(tokio::test)] +async fn which_path_search_handles_unset_empty_and_directory_entries() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let dir_with_subdir = root.join("dir_with_subdir"); + let dir_with_real = root.join("dir_with_real"); + let empty_entry_cwd = root.join("empty_entry_cwd"); + fs::create_dir(&dir_with_subdir)?; + fs::create_dir(&dir_with_real)?; + fs::create_dir(&empty_entry_cwd)?; + + // Place a directory named `same_name` in the first PATH entry, and an executable + // script with the same name in the second PATH entry. + fs::create_dir(dir_with_subdir.join("same_name"))?; + let skipped_marker = root.join("marker_dir_skip"); + fs::write(&skipped_marker, "ok")?; + write_executable( + &dir_with_real.join("same_name"), + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", skipped_marker.display()), + )?; + + // Place an executable in `empty_entry_cwd` to be found via an empty PATH component. + let empty_marker = root.join("marker_empty_path"); + fs::write(&empty_marker, "ok")?; + write_executable( + &empty_entry_cwd.join("local_cmd"), + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", empty_marker.display()), + )?; + + let args = ( + dir_with_subdir.to_str().unwrap().to_owned(), + dir_with_real.to_str().unwrap().to_owned(), + empty_entry_cwd.to_str().unwrap().to_owned(), + ); + + let accesses = track_fn!(args, |(dir_with_subdir, dir_with_real, empty_entry_cwd): ( + String, + String, + String + )| { + // 1. Directory on PATH is skipped in favor of a later regular executable. + run_in_fork(|| { + let path = format!("{dir_with_subdir}:{dir_with_real}:/bin:/usr/bin"); + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", path) }; + let prog = c"same_name"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + + // 2. Directory on PATH with no later match fails with EACCES. + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", &dir_with_subdir) }; + let prog = c"same_name"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + let ret = unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + assert_eq!(ret, -1); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::EACCES), + "directory-only PATH match must fail with EACCES" + ); + // SAFETY: exit child cleanly after checking errno. + unsafe { libc::_exit(0) }; + }); + + // 3. Unset PATH falls back to default PATH (`/usr/local/bin:/bin:/usr/bin`). + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::remove_var("PATH") }; + let prog = c"true"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + + // 4. Empty PATH component searches the current working directory. + run_in_fork(|| { + std::env::set_current_dir(&empty_entry_cwd).unwrap(); + // Leading colon creates an empty first PATH entry (= CWD). + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", ":/bin:/usr/bin") }; + let prog = c"local_cmd"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + }) + .await?; + + assert_contains(&accesses, &skipped_marker, PathAccess::Read); + assert_contains(&accesses, &empty_marker, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn sip_stripping_and_dyld_insert_libraries_merging() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sed_input = root.join("input.txt"); + fs::write(&sed_input, "hello world\n")?; + let awk_link = root.join("awk_link"); + std::os::unix::fs::symlink("/usr/bin/awk", &awk_link)?; + + let args = (sed_input.to_str().unwrap().to_owned(), awk_link.to_str().unwrap().to_owned()); + + let accesses = track_fn!(args, |(sed_input, awk_link): (String, String)| { + // 1. Non-injectable SIP binary (`/usr/bin/sed`) executes cleanly. + let out = std::process::Command::new("/usr/bin/sed") + .args(["s/world/fspy/", &sed_input]) + .output() + .unwrap(); + assert!(out.status.success(), "sed failed: {}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(out.stdout, b"hello fspy\n"); + + // 2. Non-injectable SIP binary invoked via symlink strips FSPY_PAYLOAD. + let out = std::process::Command::new(&awk_link) + .arg("BEGIN { printf \"%s\", ENVIRON[\"FSPY_PAYLOAD\"] }") + .output() + .unwrap(); + assert!(out.status.success(), "awk failed: {}", String::from_utf8_lossy(&out.stderr)); + assert!( + out.stdout.is_empty(), + "FSPY_PAYLOAD must be stripped for symlinked SIP binary, got {:?}", + String::from_utf8_lossy(&out.stdout) + ); + + // 3. Pre-existing DYLD_INSERT_LIBRARIES on an injectable binary is preserved + // with fspy's preload appended rather than clobbered. + let user_lib = "/usr/lib/libSystem.B.dylib"; + let out = std::process::Command::new("/bin/sh") + .env("DYLD_INSERT_LIBRARIES", user_lib) + .args(["-c", "printf '%s' \"$DYLD_INSERT_LIBRARIES\""]) + .output() + .unwrap(); + assert!(out.status.success(), "sh failed: {}", String::from_utf8_lossy(&out.stderr)); + let dyld = String::from_utf8(out.stdout).unwrap(); + let parts: Vec<&str> = dyld.split(':').collect(); + assert!( + parts.len() >= 2 + && parts[0] == user_lib + && Path::new(parts.last().unwrap()) + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("dylib")), + "expected user preload preserved before fspy preload, got {dyld:?}" + ); + }) + .await?; + + assert_contains(&accesses, Path::new("/usr/bin/sed"), PathAccess::Read); + assert_contains(&accesses, &awk_link, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn fopen_and_freopen_plus_modes_record_read_write() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let p_r = root.join("mode_r"); + let p_w = root.join("mode_w"); + let p_a = root.join("mode_a"); + let p_rplus = root.join("mode_rplus"); + let p_wplus = root.join("mode_wplus"); + let p_aplus = root.join("mode_aplus"); + let p_freopen = root.join("mode_freopen_rplus"); + fs::write(&p_r, "r")?; + fs::write(&p_rplus, "r+")?; + fs::write(&p_freopen, "freopen")?; + + let root_str = root.to_str().unwrap().to_owned(); + let accesses = track_fn!(root_str, |root_str: String| { + let open_and_close = |name: &str, mode: &core::ffi::CStr| { + let p = CString::new(format!("{root_str}/{name}")).unwrap(); + // SAFETY: `p` and `mode` are valid NUL-terminated C strings. + let fp = unsafe { libc::fopen(p.as_ptr(), mode.as_ptr()) }; + assert!(!fp.is_null(), "fopen({name}, {mode:?}) failed"); + // SAFETY: `fp` was returned by `fopen` above. + unsafe { libc::fclose(fp) }; + }; + + open_and_close("mode_r", c"r"); + open_and_close("mode_w", c"w"); + open_and_close("mode_a", c"a"); + open_and_close("mode_rplus", c"r+"); + open_and_close("mode_wplus", c"w+"); + open_and_close("mode_aplus", c"a+"); + + let p_tmp = CString::new(format!("{root_str}/mode_r")).unwrap(); + let p_re = CString::new(format!("{root_str}/mode_freopen_rplus")).unwrap(); + // SAFETY: valid C strings and FILE stream from `fopen`. + unsafe { + let fp = libc::fopen(p_tmp.as_ptr(), c"r".as_ptr()); + assert!(!fp.is_null()); + let fp2 = libc::freopen(p_re.as_ptr(), c"r+".as_ptr(), fp); + assert!(!fp2.is_null()); + libc::fclose(fp2); + } + }) + .await?; + + assert_contains(&accesses, &p_r, PathAccess::Read); + assert_contains(&accesses, &p_w, PathAccess::Write); + assert_contains(&accesses, &p_a, PathAccess::Write); + assert_contains(&accesses, &p_rplus, PathAccess::ReadWrite); + assert_contains(&accesses, &p_wplus, PathAccess::ReadWrite); + assert_contains(&accesses, &p_aplus, PathAccess::ReadWrite); + assert_contains(&accesses, &p_freopen, PathAccess::ReadWrite); + + Ok(()) +} + +#[test(tokio::test)] +async fn empty_path_calls_do_not_record_cwd_or_dirfd() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sub_dir = root.join("sub"); + fs::create_dir(&sub_dir)?; + + let args = (root.to_str().unwrap().to_owned(), sub_dir.to_str().unwrap().to_owned()); + let accesses = track_fn!(args, |(root_str, sub_str): (String, String)| { + std::env::set_current_dir(&root_str).unwrap(); + let sub_c = CString::new(sub_str).unwrap(); + // SAFETY: `sub_c` and `c""` are valid NUL-terminated C strings. + unsafe { + assert_eq!(libc::open(c"".as_ptr(), libc::O_RDONLY), -1); + let mut st = std::mem::MaybeUninit::::zeroed(); + assert_eq!(libc::stat(c"".as_ptr(), st.as_mut_ptr()), -1); + assert_eq!(libc::lstat(c"".as_ptr(), st.as_mut_ptr()), -1); + assert_eq!(libc::access(c"".as_ptr(), libc::F_OK), -1); + + let dirfd = libc::open(sub_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY); + assert!(dirfd >= 0); + assert_eq!(libc::openat(dirfd, c"".as_ptr(), libc::O_RDONLY), -1); + assert_eq!(libc::fstatat(dirfd, c"".as_ptr(), st.as_mut_ptr(), 0), -1); + libc::close(dirfd); + } + }) + .await?; + + assert_not_contains(&accesses, &root); + // `sub_dir` itself was opened with `O_RDONLY`, not written or re-recorded via `openat("", ...)`. + assert_contains(&accesses, &sub_dir, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn open_rdonly_with_creat_or_trunc_and_rename_swap() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let p_creat = root.join("rdonly_creat"); + let p_trunc = root.join("rdonly_trunc"); + fs::write(&p_trunc, "content")?; + let swap_a = root.join("swap_a"); + let swap_b = root.join("swap_b"); + fs::write(&swap_a, "aaa")?; + fs::write(&swap_b, "bbb")?; + + let root_str = root.to_str().unwrap().to_owned(); + let accesses = track_fn!(root_str, |root_str: String| { + let c_creat = CString::new(format!("{root_str}/rdonly_creat")).unwrap(); + let c_trunc = CString::new(format!("{root_str}/rdonly_trunc")).unwrap(); + let c_a = CString::new(format!("{root_str}/swap_a")).unwrap(); + let c_b = CString::new(format!("{root_str}/swap_b")).unwrap(); + // SAFETY: all paths are valid NUL-terminated C strings. + unsafe { + let fd = libc::open(c_creat.as_ptr(), libc::O_RDONLY | libc::O_CREAT, 0o644); + assert!(fd >= 0, "open(O_RDONLY|O_CREAT) failed: {}", std::io::Error::last_os_error()); + libc::close(fd); + + let fd = libc::open(c_trunc.as_ptr(), libc::O_RDONLY | libc::O_TRUNC); + if fd >= 0 { + libc::close(fd); + } + + assert_eq!( + libc::renamex_np(c_a.as_ptr(), c_b.as_ptr(), libc::RENAME_SWAP), + 0, + "renamex_np(RENAME_SWAP) failed: {}", + std::io::Error::last_os_error() + ); + } + }) + .await?; + + assert_contains(&accesses, &p_creat, PathAccess::ReadWrite); + assert_contains(&accesses, &p_trunc, PathAccess::ReadWrite); + assert_contains(&accesses, &swap_a, PathAccess::RenameTarget); + assert_contains(&accesses, &swap_b, PathAccess::RenameTarget); + + Ok(()) +} + +#[test(tokio::test)] +async fn posix_spawn_addchdir_np_resolves_relative_program() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sub = root.join("child_cwd"); + fs::create_dir(&sub)?; + let marker = sub.join("marker_chdir"); + fs::write(&marker, "ok")?; + let script = sub.join("run.sh"); + write_executable(&script, "#!/bin/sh\ncat marker_chdir >/dev/null\n")?; + + let sub_str = sub.to_str().unwrap().to_owned(); + let accesses = track_fn!(sub_str, |sub_str: String| { + // `std::process::Command::current_dir` uses `posix_spawn_file_actions_addchdir_np` + // on macOS. + let status = std::process::Command::new("./run.sh") + .current_dir(&sub_str) + .status() + .expect("posix_spawn with addchdir_np failed"); + assert!(status.success()); + }) + .await?; + + assert_contains(&accesses, &script, PathAccess::Read); + assert_contains(&accesses, &marker, PathAccess::Read); + + Ok(()) +} diff --git a/crates/fspy/tests/shebang.rs b/crates/fspy/tests/shebang.rs index f1c60874a..fdaccb0d2 100644 --- a/crates/fspy/tests/shebang.rs +++ b/crates/fspy/tests/shebang.rs @@ -87,3 +87,164 @@ async fn spawn_shebang_with_long_interpreter_path() -> anyhow::Result<()> { Ok(()) } + +/// macOS splits shebang arguments on whitespace; Linux passes everything after +/// the interpreter as a single argument. +#[test(tokio::test)] +async fn shebang_argument_splitting_matches_platform() -> anyhow::Result<()> { + let tmp_dir = tempfile::TempDir::new()?; + let script_path = tmp_dir.path().canonicalize()?.join("split_args.sh"); + fs::write(&script_path, "#!/bin/echo foo bar\n").await?; + fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).await?; + let script_str = script_path.to_str().unwrap().to_owned(); + + let expected = if cfg!(target_os = "macos") { + format!("foo bar {script_str}\n") + } else { + format!("foo bar {script_str}\n") + }; + let untraced = Command::new(&script_str).stdin(Stdio::null()).output()?; + assert!(untraced.status.success()); + assert_eq!(String::from_utf8_lossy(&untraced.stdout), expected); + + let args = (script_str, expected); + let accesses = track_fn!(args, |(script_str, expected): (String, String)| { + let output = Command::new(&script_str) + .stdin(Stdio::null()) + .output() + .expect("Failed to execute shebang script"); + assert!(output.status.success()); + assert_eq!(String::from_utf8_lossy(&output.stdout), expected); + }) + .await?; + + assert_contains(&accesses, &script_path, PathAccess::Read); + + Ok(()) +} + +/// Chained shebang depth limits: Linux allows 5 hops and rejects the 6th with +/// `ELOOP`; macOS allows 1 hop and rejects the 2nd with `ENOEXEC`. +#[test(tokio::test)] +async fn chained_shebang_depth_matches_platform() -> anyhow::Result<()> { + let tmp_dir = tempfile::TempDir::new()?; + let root = tmp_dir.path().canonicalize()?; + + let mut scripts = Vec::new(); + let base = root.join("hop1.sh"); + fs::write(&base, "#!/bin/sh\necho chained-ok\n").await?; + fs::set_permissions(&base, std::fs::Permissions::from_mode(0o755)).await?; + scripts.push(base); + + let max_hops = if cfg!(target_os = "macos") { 2 } else { 6 }; + for i in 2..=max_hops { + let prev = scripts.last().unwrap(); + let next = root.join(format!("hop{i}.sh")); + fs::write(&next, format!("#!{}\n", prev.display())).await?; + fs::set_permissions(&next, std::fs::Permissions::from_mode(0o755)).await?; + scripts.push(next); + } + + let max_ok = scripts[scripts.len() - 2].to_str().unwrap().to_owned(); + let too_deep = scripts[scripts.len() - 1].to_str().unwrap().to_owned(); + let expected_errno = if cfg!(target_os = "macos") { libc::ENOEXEC } else { libc::ELOOP }; + + let args = (max_ok, too_deep, expected_errno); + let accesses = + track_fn!(args, |(max_ok, too_deep, expected_errno): (String, String, libc::c_int)| { + let output = Command::new(&max_ok) + .stdin(Stdio::null()) + .output() + .expect("max allowed shebang depth should succeed"); + assert!(output.status.success()); + assert_eq!(output.stdout, b"chained-ok\n"); + + let err = Command::new(&too_deep) + .stdin(Stdio::null()) + .status() + .expect_err("exceeding shebang recursion depth should fail"); + assert_eq!(err.raw_os_error(), Some(expected_errno)); + }) + .await?; + + for script in &scripts { + assert_contains(&accesses, script, PathAccess::Read); + } + + Ok(()) +} + +/// A shebang line exceeding the kernel's buffer limit must fail with `ENOEXEC`. +#[test(tokio::test)] +async fn overlong_shebang_is_rejected_with_enoexec() -> anyhow::Result<()> { + fn posix_spawn_errno(path: &std::ffi::CStr) -> libc::c_int { + let argv = [path.as_ptr().cast_mut(), std::ptr::null_mut()]; + let envp = [std::ptr::null_mut::()]; + let mut pid: libc::pid_t = 0; + // SAFETY: `path`, `argv`, and `envp` are valid NUL/NULL-terminated. + let rc = unsafe { + libc::posix_spawn( + &raw mut pid, + path.as_ptr(), + std::ptr::null(), + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + if rc == 0 { + let mut status = 0; + // SAFETY: reap unexpected child. + unsafe { libc::waitpid(pid, &raw mut status, 0) }; + } + rc + } + + let tmp_dir = tempfile::TempDir::new()?; + let script_path = tmp_dir.path().canonicalize()?.join("overlong.sh"); + // Longer than both Linux's 256-byte and macOS's 512-byte kernel buffers. + let content = format!("#!/{}\n", "a".repeat(520)); + fs::write(&script_path, content).await?; + fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).await?; + let script_str = script_path.to_str().unwrap().to_owned(); + + // Use `posix_spawn` directly: `posix_spawnp` (used by `std::process::Command`) + // falls back to `/bin/sh` on `ENOEXEC` on macOS. + let c_script = std::ffi::CString::new(script_str.as_str())?; + assert_eq!(posix_spawn_errno(&c_script), libc::ENOEXEC); + + let accesses = track_fn!(script_str, |script_str: String| { + let c_script = std::ffi::CString::new(script_str.as_str()).unwrap(); + assert_eq!(posix_spawn_errno(&c_script), libc::ENOEXEC); + }) + .await?; + + assert_contains(&accesses, &script_path, PathAccess::Read); + + Ok(()) +} + +/// Executing a FIFO must not block (opened with `O_NONBLOCK`) and must fail +/// with `EACCES`, matching the kernel's `execve`. +#[test(tokio::test)] +async fn exec_fifo_does_not_block_and_returns_eacces() -> anyhow::Result<()> { + let tmp_dir = tempfile::TempDir::new()?; + let fifo_path = tmp_dir.path().canonicalize()?.join("exec_fifo"); + let fifo_cstr = std::ffi::CString::new(fifo_path.to_str().unwrap())?; + // SAFETY: `fifo_cstr` is a valid NUL-terminated path. + assert_eq!(unsafe { libc::mkfifo(fifo_cstr.as_ptr(), 0o755) }, 0); + let fifo_str = fifo_path.to_str().unwrap().to_owned(); + + let untraced_err = Command::new(&fifo_str).stdin(Stdio::null()).status().unwrap_err(); + assert_eq!(untraced_err.raw_os_error(), Some(libc::EACCES)); + + let accesses = track_fn!(fifo_str, |fifo_str: String| { + let err = Command::new(&fifo_str).stdin(Stdio::null()).status().unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EACCES)); + }) + .await?; + + assert_contains(&accesses, &fifo_path, PathAccess::Read); + + Ok(()) +} diff --git a/crates/fspy/tests/spawn_errors.rs b/crates/fspy/tests/spawn_errors.rs new file mode 100644 index 000000000..79aaf2c2d --- /dev/null +++ b/crates/fspy/tests/spawn_errors.rs @@ -0,0 +1,106 @@ +//! Top-level spawn error handling across Unix platforms (Linux `Target::Unresolved` +//! and macOS `EncodedPayload::prepare_exec`). +#![cfg(unix)] + +use std::{fs, os::unix::fs::PermissionsExt as _}; + +use fspy::error::SpawnError; +use test_log::test; +use tokio_util::sync::CancellationToken; + +fn assert_os_spawn_errno(result: Result, expected_errno: i32) { + match result { + Err(SpawnError::OsSpawn(err)) => { + assert_eq!( + err.raw_os_error(), + Some(expected_errno), + "expected errno {expected_errno}, got {err:?}" + ); + } + Err(other) => panic!("expected SpawnError::OsSpawn({expected_errno}), got {other:?}"), + Ok(_) => panic!("expected SpawnError::OsSpawn({expected_errno}), but spawn succeeded"), + } +} + +#[test(tokio::test)] +async fn top_level_spawn_exec_errors_return_os_spawn_with_expected_errno() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + // 1a. Malformed/empty shebang and overlong shebang -> ENOEXEC (rejected during + // exec preparation on both Linux and macOS). + let malformed_shebang = root.join("malformed_shebang.sh"); + fs::write(&malformed_shebang, "#!\n")?; + fs::set_permissions(&malformed_shebang, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&malformed_shebang).spawn(CancellationToken::new()).await, + libc::ENOEXEC, + ); + + let overlong_shebang = root.join("overlong_shebang.sh"); + fs::write(&overlong_shebang, format!("#!/{}\n", "a".repeat(520)))?; + fs::set_permissions(&overlong_shebang, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&overlong_shebang).spawn(CancellationToken::new()).await, + libc::ENOEXEC, + ); + + // 1b. Shebang-less executable -> ENOEXEC on Linux (`fspy_preload_linux` uses + // raw `execve`, which does not fall back to `/bin/sh`, unlike macOS + // `posix_spawnp` / `execvp` used by `tokio::process::Command`). + #[cfg(target_os = "linux")] + { + let shebangless = root.join("shebangless"); + fs::write(&shebangless, "not a binary or shebang script\n")?; + fs::set_permissions(&shebangless, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&shebangless).spawn(CancellationToken::new()).await, + libc::ENOEXEC, + ); + } + + // 2. Script with missing interpreter -> ENOENT + let missing_interp = root.join("missing_interp.sh"); + fs::write(&missing_interp, "#!/nonexistent/fspy_missing_interpreter\n")?; + fs::set_permissions(&missing_interp, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&missing_interp).spawn(CancellationToken::new()).await, + libc::ENOENT, + ); + + // 3. Non-executable (0o644) file as shebang interpreter -> EACCES + let non_exec = root.join("non_exec_file"); + fs::write(&non_exec, "plain file\n")?; + fs::set_permissions(&non_exec, fs::Permissions::from_mode(0o644))?; + let script_non_exec = root.join("via_non_exec.sh"); + fs::write(&script_non_exec, format!("#!{}\n", non_exec.display()))?; + fs::set_permissions(&script_non_exec, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&script_non_exec).spawn(CancellationToken::new()).await, + libc::EACCES, + ); + + // 4. Directory as shebang interpreter -> EACCES + let dir_target = root.join("a_directory"); + fs::create_dir(&dir_target)?; + let script_dir = root.join("via_dir.sh"); + fs::write(&script_dir, format!("#!{}\n", dir_target.display()))?; + fs::set_permissions(&script_dir, fs::Permissions::from_mode(0o755))?; + assert_os_spawn_errno( + fspy::Command::new(&script_dir).spawn(CancellationToken::new()).await, + libc::EACCES, + ); + + // Direct top-level spawns of a non-executable 0o644 file or a directory are + // rejected during `resolve_program()` with `SpawnError::Which`. + assert!(matches!( + fspy::Command::new(&non_exec).spawn(CancellationToken::new()).await, + Err(SpawnError::Which { .. }) + )); + assert!(matches!( + fspy::Command::new(&dir_target).spawn(CancellationToken::new()).await, + Err(SpawnError::Which { .. }) + )); + + Ok(()) +} diff --git a/crates/fspy_preload_macos/src/client.rs b/crates/fspy_preload_macos/src/client.rs index b17a6c77d..51ad776c0 100644 --- a/crates/fspy_preload_macos/src/client.rs +++ b/crates/fspy_preload_macos/src/client.rs @@ -60,15 +60,39 @@ impl Client<'_> { search_path: bool, raw_exec: RawExec, allocator: &A, + ) -> Result { + // SAFETY: caller upholds `RawExec::to_exec`'s pointer contract. + unsafe { self.handle_exec_in_dir(search_path, None, raw_exec, allocator) } + } + + /// Resolves and prepares an exec call, resolving relative paths against + /// `cwd` (when `Some`, e.g. from `posix_spawn_file_actions_addchdir_np`) + /// instead of the current working directory. + /// + /// # 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_in_dir( + &self, + search_path: bool, + cwd: Option<&[u8]>, + 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| { + exec.program = which::resolve_in_path(&exec.program, cwd, allocator, |candidate| { self.send_path(AccessMode::Read, candidate); })?; } - self.encoded_payload.prepare_exec(&mut exec, |path| { + self.encoded_payload.prepare_exec_in_dir(&mut exec, cwd, |path| { self.send_path(AccessMode::Read, path); })?; Ok(RawExec::from_exec(exec)) @@ -90,6 +114,7 @@ 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, + _ if flags & (::libc::O_CREAT | ::libc::O_TRUNC) != 0 => AccessMode::ReadWrite, _ => AccessMode::Read, } } @@ -98,16 +123,19 @@ pub const fn open_flags_mode(flags: c_int) -> AccessMode { /// /// # Safety /// -/// `mode` must be a valid NUL-terminated C string. +/// `mode` must be null or point to 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. + if mode.is_null() { + return AccessMode::Read; + } + // SAFETY: caller guarantees non-null `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, + if mode_bytes.contains(&b'+') { + AccessMode::ReadWrite + } else if mode_bytes.contains(&b'w') || mode_bytes.contains(&b'a') { + AccessMode::Write + } else { + AccessMode::Read } } @@ -134,11 +162,14 @@ pub unsafe fn handle_open_at(dirfd: c_int, path: *const c_char, mode: AccessMode if path.is_null() { return; } + // SAFETY: non-null `path` is NUL-terminated for the duration of this call. + let c_path = unsafe { CStr::::from_ptr(path.cast()) }; + if c_path.count().as_units().is_empty() { + 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())); } diff --git a/crates/fspy_preload_macos/src/interceptions/dyld.rs b/crates/fspy_preload_macos/src/interceptions/dyld.rs index 9ea93d026..bdf825039 100644 --- a/crates/fspy_preload_macos/src/interceptions/dyld.rs +++ b/crates/fspy_preload_macos/src/interceptions/dyld.rs @@ -16,6 +16,8 @@ //! [`RuntimeState::loadInsertedLibraries`]: https://github.com/apple-oss-distributions/dyld/blob/fd8d0c4d52320ebf64db34f3cb280310d905c5ae/dyld/DyldRuntimeState.cpp#L676-L680 //! [`normalizeImageIndex`]: https://github.com/apple-oss-distributions/dyld/blob/fd8d0c4d52320ebf64db34f3cb280310d905c5ae/dyld/DyldAPIs.cpp#L238-L253 +use std::sync::atomic::{AtomicU32, Ordering}; + use crate::{ libc::{c_char, intptr_t, mach_header}, macros::intercept, @@ -24,24 +26,46 @@ use crate::{ /// `MH_EXECUTE` from ``. const MH_EXECUTE: u32 = 0x2; -/// Maps an index in the presented order to dyld's actual index. -/// -/// The main executable is looked up on every call rather than cached: its -/// index stays fixed only because of undocumented dyld behavior. -fn actual_image_index(image_index: u32) -> u32 { +/// Sentinel indicating the main executable's dyld image index is not yet cached. +const UNSET_INDEX: u32 = u32::MAX; + +/// Cached dyld index of the `MH_EXECUTE` image. Verified in O(1) on every call +/// so we never rely on dyld keeping the index fixed across image mutations, +/// while avoiding an O(N) linear scan per query. +static MAIN_IMAGE_INDEX: AtomicU32 = AtomicU32::new(UNSET_INDEX); + +fn find_main_image_index() -> Option { + let cached = MAIN_IMAGE_INDEX.load(Ordering::Relaxed); + if cached != UNSET_INDEX { + // SAFETY: dyld returns null for out-of-range indices. + let header = unsafe { _dyld_get_image_header::original()(cached) }; + // SAFETY: a non-null header points to the loaded image's mach header. + if !header.is_null() && unsafe { (*header).filetype } == MH_EXECUTE { + return Some(cached); + } + } + let mut main_index = 0; loop { // SAFETY: dyld returns null for out-of-range indices. let header = unsafe { _dyld_get_image_header::original()(main_index) }; if header.is_null() { - return image_index; + return None; } // SAFETY: a non-null header points to the loaded image's mach header. if unsafe { (*header).filetype } == MH_EXECUTE { - break; + MAIN_IMAGE_INDEX.store(main_index, Ordering::Relaxed); + return Some(main_index); } main_index += 1; } +} + +/// Maps an index in the presented order to dyld's actual index. +fn actual_image_index(image_index: u32) -> u32 { + let Some(main_index) = find_main_image_index() else { + return image_index; + }; match image_index { 0 => main_index, index if index <= main_index => index - 1, diff --git a/crates/fspy_preload_macos/src/interceptions/namespace.rs b/crates/fspy_preload_macos/src/interceptions/namespace.rs index de445bbc5..fa83e07fa 100644 --- a/crates/fspy_preload_macos/src/interceptions/namespace.rs +++ b/crates/fspy_preload_macos/src/interceptions/namespace.rs @@ -53,6 +53,10 @@ unsafe extern "C" fn renamex_np( new: *const c_char, flags: libc::c_uint, ) -> c_int { + if flags & libc::RENAME_SWAP != 0 { + // SAFETY: old is a valid C string pointer provided by the caller. + unsafe { handle_open_path(old, AccessMode::RenameTarget) }; + } // 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. @@ -67,6 +71,10 @@ unsafe extern "C" fn renameatx_np( new: *const c_char, flags: libc::c_uint, ) -> c_int { + if flags & libc::RENAME_SWAP != 0 { + // SAFETY: olddirfd is -1 or valid, and old is a valid C string. + unsafe { handle_open_at(olddirfd, old, AccessMode::RenameTarget) }; + } // 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. diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs b/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs index aef0ba972..cb5c09df5 100644 --- a/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs +++ b/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs @@ -74,11 +74,6 @@ unsafe extern "C" fn execve( 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()) }; @@ -87,11 +82,6 @@ unsafe extern "C" fn execl(path: *const c_char, arg: *const c_char, mut valist: 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()) }; @@ -100,11 +90,6 @@ unsafe extern "C" fn execlp(path: *const c_char, arg: *const c_char, mut valist: 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 { @@ -116,11 +101,6 @@ unsafe extern "C" fn execle(path: *const c_char, arg: *const c_char, mut valist: 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() }) } @@ -130,11 +110,6 @@ intercept!(execvp(64): unsafe extern "C" fn( 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_macos/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs index 96fb71b2a..32ef164c7 100644 --- a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs +++ b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs @@ -1,3 +1,11 @@ +use std::sync::{ + Mutex, + atomic::{AtomicUsize, Ordering}, +}; + +use allocator_api2::vec::Vec as AllocVec; +use fspy_nostd::{BorrowedFd, CStr, CWD, Thin}; +use fspy_nostd_alloc::fs::{fd_path, resolve_path_at}; use fspy_shared_unix::RawExec; use libc::{c_char, c_int}; @@ -12,6 +20,152 @@ type PosixSpawnFn = unsafe extern "C" fn( envp: *const *mut c_char, ) -> c_int; +/// Number of `posix_spawn_file_actions_t` handles currently tracked in +/// [`SPAWN_CHDIRS`]. Allows `posix_spawn(p)` and `destroy` to skip the mutex +/// completely in the common case when no chdir action is active. +static ACTIVE_CHDIRS: AtomicUsize = AtomicUsize::new(0); + +/// Maps live `posix_spawn_file_actions_t` handle values (`*file_actions as usize`) +/// to their effective absolute working directory from `addchdir_np` / `addfchdir_np`. +static SPAWN_CHDIRS: Mutex)>> = Mutex::new(Vec::new()); + +fn set_spawn_chdir(key: usize, path: Vec) { + let mut map = SPAWN_CHDIRS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some((_, existing)) = map.iter_mut().find(|(k, _)| *k == key) { + *existing = path; + } else { + map.push((key, path)); + ACTIVE_CHDIRS.store(map.len(), Ordering::Release); + } +} + +fn remove_spawn_chdir(key: usize) { + if ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 { + return; + } + let mut map = SPAWN_CHDIRS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(pos) = map.iter().position(|(k, _)| *k == key) { + map.swap_remove(pos); + ACTIVE_CHDIRS.store(map.len(), Ordering::Release); + } +} + +fn get_spawn_chdir_in( + file_actions: *const libc::posix_spawn_file_actions_t, + allocator: A, +) -> Option> { + if file_actions.is_null() || ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 { + return None; + } + // SAFETY: caller passed a non-null `file_actions` pointer to `posix_spawn(p)`. + let key = (unsafe { *file_actions }) as usize; + if key == 0 { + return None; + } + let map = SPAWN_CHDIRS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let out = map.iter().find(|(k, _)| *k == key).map(|(_, bytes)| { + let mut out = AllocVec::with_capacity_in(bytes.len(), allocator); + out.extend_from_slice(bytes); + out + }); + drop(map); + out +} + +intercept!(posix_spawn_file_actions_addchdir_np: unsafe extern "C" fn( + file_actions: *mut libc::posix_spawn_file_actions_t, + path: *const c_char, +) -> c_int); +unsafe extern "C" fn posix_spawn_file_actions_addchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + path: *const c_char, +) -> c_int { + // SAFETY: forwarding caller arguments to the original libc function. + let ret = unsafe { posix_spawn_file_actions_addchdir_np::original()(file_actions, path) }; + if ret == 0 && !file_actions.is_null() && !path.is_null() { + // SAFETY: `original` succeeded on non-null `file_actions`. + let key = (unsafe { *file_actions }) as usize; + if key != 0 { + // SAFETY: non-null `path` is a valid NUL-terminated C string. + let c_path = unsafe { CStr::::from_ptr(path.cast()) }; + let raw = c_path.count().as_units(); + if raw.starts_with(b"/") { + set_spawn_chdir(key, raw.to_vec()); + } else if !raw.is_empty() { + let prev = + get_spawn_chdir_in(file_actions.cast_const(), allocator_api2::alloc::Global); + let resolved = prev.map_or_else( + || { + let arena = fspy_nostd_alloc::pooled_bump(); + resolve_path_at(&arena, Some(CWD), c_path) + .ok() + .flatten() + .map(|p| p.as_units().to_vec()) + }, + |base| { + let mut joined = base.to_vec(); + if joined.last() != Some(&b'/') { + joined.push(b'/'); + } + joined.extend_from_slice(raw); + Some(joined) + }, + ); + if let Some(dir) = resolved { + set_spawn_chdir(key, dir); + } + } + } + } + ret +} + +intercept!(posix_spawn_file_actions_addfchdir_np: unsafe extern "C" fn( + file_actions: *mut libc::posix_spawn_file_actions_t, + fd: c_int, +) -> c_int); +unsafe extern "C" fn posix_spawn_file_actions_addfchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + fd: c_int, +) -> c_int { + // SAFETY: forwarding caller arguments to the original libc function. + let ret = unsafe { posix_spawn_file_actions_addfchdir_np::original()(file_actions, fd) }; + if ret == 0 && !file_actions.is_null() { + // SAFETY: `original` succeeded on non-null `file_actions`. + let key = (unsafe { *file_actions }) as usize; + if key != 0 { + // SAFETY: `fd` was accepted by `addfchdir_np`. + let borrowed = unsafe { BorrowedFd::try_borrow_raw(fd) }; + if let Some(borrowed) = borrowed { + let arena = fspy_nostd_alloc::pooled_bump(); + if let Ok(Some(dir)) = fd_path(&arena, borrowed) { + set_spawn_chdir(key, dir.as_units().to_vec()); + } + } + } + } + ret +} + +intercept!(posix_spawn_file_actions_destroy: unsafe extern "C" fn( + file_actions: *mut libc::posix_spawn_file_actions_t, +) -> c_int); +unsafe extern "C" fn posix_spawn_file_actions_destroy( + file_actions: *mut libc::posix_spawn_file_actions_t, +) -> c_int { + if !file_actions.is_null() { + // Remove before freeing `*file_actions` to prevent an ABA race if + // another thread immediately allocates the same address in `init`. + // SAFETY: caller passed a non-null `file_actions` pointer. + let key = (unsafe { *file_actions }) as usize; + if key != 0 { + remove_spawn_chdir(key); + } + } + // SAFETY: forwarding caller argument to the original libc function. + unsafe { posix_spawn_file_actions_destroy::original()(file_actions) } +} + #[expect( clippy::too_many_arguments, reason = "mirrors the posix_spawn(3) signature which requires all these parameters" @@ -30,10 +184,12 @@ unsafe fn handle_posix_spawn( .expect("posix_spawn(p) unexpectedly called before client initialized in ctor"); let arena = fspy_nostd_alloc::pooled_bump(); + let spawn_cwd = get_spawn_chdir_in(file_actions, &arena); // SAFETY: file, argv, and envp are valid pointers forwarded from posix_spawn(p). let raw_command = match unsafe { - client.handle_exec( + client.handle_exec_in_dir( search_path, + spawn_cwd.as_deref(), RawExec { prog: file, argv: argv.cast(), envp: envp.cast() }, &arena, ) diff --git a/crates/fspy_preload_macos/src/libc.rs b/crates/fspy_preload_macos/src/libc.rs index cdf1b91d0..90465781e 100644 --- a/crates/fspy_preload_macos/src/libc.rs +++ b/crates/fspy_preload_macos/src/libc.rs @@ -57,4 +57,14 @@ unsafe extern "C" { pub unsafe fn _dyld_get_image_vmaddr_slide(image_index: u32) -> intptr_t; pub unsafe fn _dyld_get_image_name(image_index: u32) -> *const c_char; + + pub unsafe fn posix_spawn_file_actions_addchdir_np( + file_actions: *mut posix_spawn_file_actions_t, + path: *const c_char, + ) -> c_int; + + pub unsafe fn posix_spawn_file_actions_addfchdir_np( + file_actions: *mut posix_spawn_file_actions_t, + fd: c_int, + ) -> c_int; } diff --git a/crates/fspy_preload_macos/src/macros/macos.rs b/crates/fspy_preload_macos/src/macros/macos.rs index fd3191192..ed0b0f97e 100644 --- a/crates/fspy_preload_macos/src/macros/macos.rs +++ b/crates/fspy_preload_macos/src/macros/macos.rs @@ -18,6 +18,8 @@ macro_rules! intercept { #[expect(clippy::allow_attributes, reason = "macro-generated: imports may or may not be used depending on expansion context")] #[allow(unused_imports, reason = "macro-generated: imports may or may not be used depending on expansion context")] use super::*; + #[expect(clippy::allow_attributes, reason = "macro-generated: some interposers delegate to another original symbol")] + #[allow(dead_code, reason = "macro-generated: some interposers delegate to another original symbol")] pub fn original() -> $fn_sig { $crate::libc::$name } diff --git a/crates/fspy_preload_macos/src/which.rs b/crates/fspy_preload_macos/src/which.rs index 38c2d8c5f..fda532a1f 100644 --- a/crates/fspy_preload_macos/src/which.rs +++ b/crates/fspy_preload_macos/src/which.rs @@ -32,6 +32,7 @@ fn getenv_path() -> &'static [u8] { /// `execvp` / musl `execvp`. pub fn resolve_in_path( file: &[u8], + cwd: Option<&[u8]>, allocator: A, mut on_path_read: impl FnMut(&BStr), ) -> Result> { @@ -54,8 +55,14 @@ pub fn resolve_in_path( for dir in path_env.split(|&ch| ch == b':') { candidate.clear(); + if let Some(base) = cwd.filter(|_| !dir.starts_with(b"/")) { + candidate.extend_from_slice(base); + if candidate.last() != Some(&b'/') { + candidate.push(b'/'); + } + } candidate.extend_from_slice(dir); - if !dir.is_empty() { + if !dir.is_empty() && candidate.last() != Some(&b'/') { candidate.push(b'/'); } candidate.extend_from_slice(file); @@ -68,8 +75,28 @@ pub fn resolve_in_path( match faccessat(CWD, c_candidate.as_thin(), AccessFlags::X_OK) { Ok(()) => { - candidate.pop(); // strip trailing NUL - return Ok(candidate); + let mut st = core::mem::MaybeUninit::<::libc::stat>::zeroed(); + // SAFETY: `c_candidate` is NUL-terminated and `st` is writable storage. + if unsafe { ::libc::stat(c_candidate.as_ptr().cast(), st.as_mut_ptr()) } == 0 { + // SAFETY: `stat` succeeded and initialized `st`. + let st = unsafe { st.assume_init() }; + if (st.st_mode & ::libc::S_IFMT) == ::libc::S_IFREG { + candidate.pop(); // strip trailing NUL + return Ok(candidate); + } + seen_eacces = true; + last_err = Error::ACCES; + } else { + match Error::last_os_error() { + err @ (Error::ACCES | Error::NOENT | Error::NOTDIR) => { + if err == Error::ACCES { + seen_eacces = true; + } + last_err = err; + } + other => return Err(other), + } + } } Err(err @ (Error::ACCES | Error::NOENT | Error::NOTDIR)) => { if err == Error::ACCES { diff --git a/crates/fspy_shared_unix/src/macos.rs b/crates/fspy_shared_unix/src/macos.rs index 73cf5fb71..8fe859d6b 100644 --- a/crates/fspy_shared_unix/src/macos.rs +++ b/crates/fspy_shared_unix/src/macos.rs @@ -13,7 +13,8 @@ use crate::{ codec::{decode_b64, encode_b64}, nostd_exec::{ Exec, append_path_env, ensure_env, - open::{absolute_relative, open_executable, pread_header}, + open::{absolute_relative, join_relative_to_base, open_executable, pread_header}, + remove_path_env, shebang::{ MACOS_MAX_LINE_LEN, MACOS_MAX_RECURSION, ParseShebangOptions, apply_shebang, parse_shebang_bytes, @@ -113,37 +114,52 @@ impl<'a> EncodedPayload<'a> { pub fn prepare_exec( &self, exec: &mut Exec
, - mut on_path_read: impl FnMut(&BStr), + on_path_read: impl FnMut(&BStr), ) -> Result<()> { - if exec.program.is_empty() { - return Err(Error::NOENT); - } + self.prepare_exec_in_dir(exec, None, on_path_read) + } + /// Like [`Self::prepare_exec`], resolving relative program paths against + /// `cwd` (when `Some`, e.g. from `posix_spawn_file_actions_addchdir_np`) + /// instead of the current working directory. + /// + /// # Errors + /// + /// Returns the same OS-compatible `errno` values as [`Self::prepare_exec`]. + pub fn prepare_exec_in_dir( + &self, + exec: &mut Exec, + cwd: Option<&[u8]>, + mut on_path_read: impl FnMut(&BStr), + ) -> Result<()> { let allocator = exec.allocator().clone(); let mut peek_buf = [0u8; MACOS_MAX_LINE_LEN]; let mut depth = 0usize; - loop { + let final_file = loop { if exec.program.is_empty() { return Err(Error::NOENT); } - if exec.program.starts_with(b"/") { + let open_path = if exec.program.starts_with(b"/") { on_path_read(BStr::new(&exec.program)); + None } else { - let abs = absolute_relative(&exec.program, allocator.clone())?; + let abs = resolve_relative(&exec.program, cwd, allocator.clone())?; on_path_read(BStr::new(&abs)); - } + cwd.is_some().then_some(abs) + }; - let c_path = bytes_to_cstring(&exec.program, allocator.clone())?; + let c_path = + bytes_to_cstring(open_path.as_deref().unwrap_or(&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(), )? { + drop(file); depth += 1; if depth > MACOS_MAX_RECURSION { return Err(Error::NOEXEC); @@ -152,19 +168,39 @@ impl<'a> EncodedPayload<'a> { apply_shebang(exec, shebang, script_arg); continue; } - break; - } + break file; + }; if !exec.program.starts_with(b"/") { - exec.program = absolute_relative(&exec.program, allocator.clone())?; + exec.program = resolve_relative(&exec.program, cwd, allocator.clone())?; } - let injectable = match sip_bin_file_name(&exec.program) { + let canonical_path = + fspy_nostd_alloc::fs::fcntl_getpath(allocator.clone(), final_file.as_fd()) + .ok() + .map(CString::count); + drop(final_file); + let sip_check_path = + canonical_path.as_ref().map_or(exec.program.as_slice(), CString::as_units); + + let injectable = match sip_bin_file_name(sip_check_path) { 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) { + } else if COREUTILS_FUNCTIONS.contains(file_name) { + let argv0_matches = exec.args.first().is_some_and(|arg0| { + let base = arg0.rsplit(|&b| b == b'/').next().unwrap_or(arg0); + base == file_name + }); + if !argv0_matches { + let name_vec = to_vec_in(file_name, allocator.clone()); + if let Some(arg0) = exec.args.first_mut() { + *arg0 = name_vec; + } else { + exec.args.push(name_vec); + } + } exec.program = to_vec_in(self.payload.coreutils_path.as_bytes(), allocator); true } else { @@ -186,16 +222,29 @@ impl<'a> EncodedPayload<'a> { self.encoded_string.as_bytes(), )?; } else { - exec.envs.retain(|(name, _)| { - name.as_slice() != DYLD_INSERT_LIBRARIES - && name.as_slice() != PAYLOAD_ENV_NAME.as_bytes() - }); + remove_path_env( + &mut exec.envs, + DYLD_INSERT_LIBRARIES, + self.payload.preload_path.as_bytes(), + ); + exec.envs.retain(|(name, _)| name.as_slice() != PAYLOAD_ENV_NAME.as_bytes()); } Ok(()) } } +fn resolve_relative( + path: &[u8], + cwd: Option<&[u8]>, + allocator: A, +) -> Result> { + match cwd { + Some(base) => join_relative_to_base(base, path, allocator), + None => absolute_relative(path, allocator), + } +} + fn bytes_to_cstring( bytes: &[u8], allocator: A, @@ -208,24 +257,34 @@ fn bytes_to_cstring( } /// 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. +/// `/usr/bin`, normalizing empty, `.`, and `..` components lexically. 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; + let mut depth = 0usize; + for part in rest.split(|&b| b == b'/') { + match part { + b"" | b"." => {} + b".." => depth = depth.saturating_sub(1), + _ => { + if depth < parts.len() { + parts[depth] = part; + } + depth += 1; + } + } } - match parts[..count] { + if depth > parts.len() { + return None; + } + match parts[..depth] { [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! { +/// Coreutils applets provided by the bundled uutils `coreutils` binary. +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", @@ -254,7 +313,9 @@ mod tests { (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"/bin/../bin/sh", Some(b"sh")), + (b"/usr/bin/sub/a/b/../../../cat", Some(b"cat")), + (b"/../../bin/sh", Some(b"sh")), (b"/usr/local/bin/sh", None), (b"/foo", None), (b"/", None), @@ -303,4 +364,77 @@ mod tests { }; assert_eq!(payload.prepare_exec(&mut exec, |_| {}).unwrap_err(), fspy_nostd::Error::NOEXEC); } + + #[cfg(target_os = "macos")] + #[test] + fn non_injectable_sip_binary_strips_only_our_preload_and_resolves_symlinks() { + use std::os::unix::ffi::OsStrExt as _; + + use allocator_api2::alloc::Global; + use fspy_shared::ipc::{IpcStr, channel::channel}; + + use super::{DYLD_INSERT_LIBRARIES, EncodedPayload, PAYLOAD_ENV_NAME, Payload}; + use crate::nostd_exec::{Exec, to_vec_in}; + + let receiver = channel(1 << 30, Global).unwrap(); + let preload = b"/tmp/fspy_preload.dylib"; + let payload = EncodedPayload::encode( + Payload { + ipc_channel_conf: receiver.conf(), + preload_path: IpcStr::from_bytes(preload), + bash_path: IpcStr::from_bytes(b"/tmp/fspy_bash"), + coreutils_path: IpcStr::from_bytes(b"/tmp/fspy_coreutils"), + }, + Global, + ); + + // 1. Non-injectable SIP binary with both a user preload and ours: keeps user preload. + let mut envs = allocator_api2::vec::Vec::new_in(Global); + envs.push(( + to_vec_in(DYLD_INSERT_LIBRARIES, Global), + Some(to_vec_in(b"/tmp/user.dylib:/tmp/fspy_preload.dylib", Global)), + )); + envs.push(( + to_vec_in(PAYLOAD_ENV_NAME.as_bytes(), Global), + Some(to_vec_in(payload.encoded_string.as_bytes(), Global)), + )); + let mut exec = Exec { + program: to_vec_in(b"/usr/bin/sed", Global), + args: allocator_api2::vec::Vec::new_in(Global), + envs, + }; + payload.prepare_exec(&mut exec, |_| {}).unwrap(); + let dyld = exec + .envs + .iter() + .find(|(k, _)| k.as_slice() == DYLD_INSERT_LIBRARIES) + .and_then(|(_, v)| v.as_deref()); + assert_eq!(dyld, Some(b"/tmp/user.dylib".as_slice())); + assert!(!exec.envs.iter().any(|(k, _)| k.as_slice() == PAYLOAD_ENV_NAME.as_bytes())); + + // 2. Non-injectable SIP binary via symlink with only our preload: removes env var entirely. + let dir = tempfile::tempdir().unwrap(); + let sed_link = dir.path().join("my_sed"); + std::os::unix::fs::symlink("/usr/bin/sed", &sed_link).unwrap(); + let mut envs = allocator_api2::vec::Vec::new_in(Global); + envs.push((to_vec_in(DYLD_INSERT_LIBRARIES, Global), Some(to_vec_in(preload, Global)))); + let mut exec = Exec { + program: to_vec_in(sed_link.as_os_str().as_bytes(), Global), + args: allocator_api2::vec::Vec::new_in(Global), + envs, + }; + payload.prepare_exec(&mut exec, |_| {}).unwrap(); + assert!(!exec.envs.iter().any(|(k, _)| k.as_slice() == DYLD_INSERT_LIBRARIES)); + + // 3. Symlink to `/bin/sh` resolves via F_GETPATH and swaps to bash_path. + let sh_link = dir.path().join("my_sh"); + std::os::unix::fs::symlink("/bin/sh", &sh_link).unwrap(); + let mut exec = Exec { + program: to_vec_in(sh_link.as_os_str().as_bytes(), Global), + args: allocator_api2::vec::Vec::new_in(Global), + envs: allocator_api2::vec::Vec::new_in(Global), + }; + payload.prepare_exec(&mut exec, |_| {}).unwrap(); + assert_eq!(exec.program.as_slice(), b"/tmp/fspy_bash"); + } } diff --git a/crates/fspy_shared_unix/src/nostd_exec/mod.rs b/crates/fspy_shared_unix/src/nostd_exec/mod.rs index c7b546837..48b11b16a 100644 --- a/crates/fspy_shared_unix/src/nostd_exec/mod.rs +++ b/crates/fspy_shared_unix/src/nostd_exec/mod.rs @@ -223,6 +223,45 @@ pub fn append_path_env(envs: &mut Vec, A>, name: &[ } } +/// Removes all colon-separated occurrences of `value` from env var `name`, +/// removing the variable itself when no entries remain. +#[cfg_attr( + not(any(target_os = "macos", test)), + expect(dead_code, reason = "used by macOS DYLD_INSERT_LIBRARIES cleanup") +)] +pub fn remove_path_env(envs: &mut Vec, A>, name: &[u8], value: &[u8]) { + let allocator = envs.allocator().clone(); + let mut i = 0; + while i < envs.len() { + if envs[i].0.as_bstr() != name { + i += 1; + continue; + } + let Some(existing) = envs[i].1.as_deref() else { + i += 1; + continue; + }; + if !existing.split(|&b| b == b':').any(|part| part == value) { + i += 1; + continue; + } + let mut new_value = Vec::with_capacity_in(existing.len(), allocator.clone()); + for part in existing.split(|&b| b == b':').filter(|&part| part != value && !part.is_empty()) + { + if !new_value.is_empty() { + new_value.push(b':'); + } + new_value.extend_from_slice(part); + } + if new_value.is_empty() { + envs.remove(i); + } else { + envs[i].1 = Some(new_value); + i += 1; + } + } +} + #[cfg(test)] mod tests { use core::ptr; @@ -287,4 +326,24 @@ mod tests { 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())); } + + #[test] + fn remove_path_env_strips_only_target_entry() { + let mut envs: Vec, Global> = Vec::new_in(Global); + append_path_env(&mut envs, b"DYLD_INSERT_LIBRARIES", b"/ours.dylib"); + remove_path_env(&mut envs, b"DYLD_INSERT_LIBRARIES", b"/ours.dylib"); + assert!(envs.is_empty()); + + envs.push(( + to_vec_in(b"DYLD_INSERT_LIBRARIES", Global), + Some(to_vec_in(b"/user1.dylib:/ours.dylib:/user2.dylib", Global)), + )); + remove_path_env(&mut envs, b"DYLD_INSERT_LIBRARIES", b"/ours.dylib"); + assert_eq!(envs.len(), 1); + assert_eq!(envs[0].1.as_deref(), Some(b"/user1.dylib:/user2.dylib".as_slice())); + + // Untouched when the target entry is absent. + remove_path_env(&mut envs, b"DYLD_INSERT_LIBRARIES", b"/ours.dylib"); + assert_eq!(envs[0].1.as_deref(), Some(b"/user1.dylib:/user2.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 index da9b4666a..7d231e88a 100644 --- a/crates/fspy_shared_unix/src/nostd_exec/open.rs +++ b/crates/fspy_shared_unix/src/nostd_exec/open.rs @@ -43,6 +43,28 @@ pub fn pread_header(fd: BorrowedFd<'_>, buf: &mut [u8]) -> Result { Ok(total) } +/// Makes a relative `path` absolute against `base_dir` (which must be +/// absolute), 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 join_relative_to_base( + base_dir: &[u8], + path: &[u8], + allocator: A, +) -> Result> { + debug_assert!(!path.starts_with(b"/")); + if path.is_empty() { + return Err(Error::INVAL); + } + let mut abs = Vec::with_capacity_in(base_dir.len() + 1 + path.len(), allocator); + abs.extend_from_slice(base_dir); + append_relative_segments(&mut abs, path); + Ok(abs) +} + /// Makes a relative `path` absolute against the current working directory, /// matching `std::path::absolute` without touching `std` or libc malloc. #[cfg_attr( @@ -55,6 +77,15 @@ pub fn absolute_relative(path: &[u8], allocator: A) -> Result(abs: &mut Vec, path: &[u8]) { for segment in path.split(|&b| b == b'/') { if segment.is_empty() || segment == b"." { continue; @@ -67,7 +98,6 @@ pub fn absolute_relative(path: &[u8], allocator: A) -> Result Date: Fri, 27 Nov 2026 17:43:58 +0800 Subject: [PATCH 13/48] fix(fspy): harden Linux seccomp tracker, expand syscall tests, and add arm64 CI Harden the Linux ELF/SIGSYS tracker across fspy, fspy_preload_linux, and fspy_shared_unix: - Probe seccomp availability on a short-lived OS thread using SECCOMP_RET_TRAP instead of fork() - Remove local noexec checks in favor of vt_materialized_artifact and lazily re-materialize on ENOENT - Avoid error-pipe FD < 3 collisions and kill/wait child on cancellation mid-handshake - Use fspy_elf_loader::try_exec_elf on_ready to eliminate error-pipe TOCTOU and scrub __FSPY_BOOTSTRAP from /proc/self/environ - Reclaim CLONE_VM ExecScratch via on_vfork_return and kcmp(KCMP_VM) with set_tid_address fallback - Fix O_PATH shebang execveat(AT_EMPTY_PATH), O_RDONLY|(O_CREAT|O_TRUNC) open_mode, renameat2(RENAME_EXCHANGE), and ensure_env/RawExec::to_exec hardening - Add Linux hardening and syscall integration tests plus release-mode and linux-arm64 CI jobs Co-authored-by: Gemini 4 Neon --- .github/workflows/ci.yml | 38 ++ Cargo.lock | 1 + Cargo.toml | 1 + crates/fspy/Cargo.toml | 1 + crates/fspy/src/linux/mod.rs | 302 +++++---- crates/fspy/tests/linux_hardening.rs | 299 +++++++++ crates/fspy/tests/linux_syscalls.rs | 590 ++++++++++++++++++ .../fspy_elf_loader_test_launcher/Cargo.toml | 2 +- crates/fspy_elf_loader_tests/Cargo.toml | 2 +- crates/fspy_preload_linux/Cargo.toml | 2 +- crates/fspy_preload_linux/build.rs | 1 + crates/fspy_preload_linux/src/main.rs | 254 ++++++-- crates/fspy_shared_unix/src/linux.rs | 121 ++-- crates/fspy_shared_unix/src/macos.rs | 3 +- crates/fspy_shared_unix/src/nostd_exec/mod.rs | 166 +++-- .../fspy_shared_unix/src/nostd_exec/open.rs | 4 +- 16 files changed, 1515 insertions(+), 272 deletions(-) create mode 100644 crates/fspy/tests/linux_syscalls.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c6f0b0ee8..d5d101cbd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -156,6 +156,10 @@ jobs: if: ${{ env.TEST_TARGET == 'x86_64-unknown-linux-gnu' }} run: $TEST_CARGO_CMD test --release -p fspy_elf_loader_tests --target $TEST_BUILD_TARGET + - name: Run fspy hardening tests (release) + if: ${{ env.TEST_TARGET == 'x86_64-unknown-linux-gnu' }} + run: $TEST_CARGO_CMD test --release -p fspy --test linux_hardening --test linux_syscalls --test untracked_fallback --target $TEST_BUILD_TARGET + # x86_64-apple-darwin runs on arm64 runner under Rosetta; install x64 Node # so fspy's x86_64 preload dylib can be injected into spawned node procs. - uses: oxc-project/setup-node@f46a72f95efdc55273fcd042d61c84e723b2892c # v1.4.1 @@ -388,6 +392,9 @@ jobs: - name: Run ELF loader tests (release) run: cargo test --release -p fspy_elf_loader_tests + - name: Run fspy hardening tests (release) + run: cargo test --release -p fspy --test linux_hardening --test linux_syscalls --test untracked_fallback + - uses: oxc-project/setup-node@f46a72f95efdc55273fcd042d61c84e723b2892c # v1.4.1 # Run only Bun's postinstall on musl (`deno` and `workerd` do not ship @@ -398,6 +405,36 @@ jobs: - name: Run ignored tests run: cargo test -- --ignored + test-linux-arm64: + needs: detect-changes + if: needs.detect-changes.outputs.code-changed == 'true' + name: Test (linux-arm64) + runs-on: ubuntu-24.04-arm + steps: + - uses: taiki-e/checkout-action@7d1e50e93dc4fb3bba58f85018fadf77898aee8b # v1.4.2 + + - name: Update submodules + run: git submodule update --init --recursive + + - uses: oxc-project/setup-rust@3d6fb132fbe7cdcb66bf8ec193911c2945369d12 # v1.0.17 + with: + save-cache: ${{ github.ref_name == 'main' }} + cache-key: test-linux-arm64 + + - run: rustup target add aarch64-unknown-linux-musl aarch64-unknown-none-softfloat + + - name: Run ELF loader tests (debug) + run: cargo test -p fspy_elf_loader -p fspy_elf_loader_tests + + - name: Run ELF loader tests (release) + run: cargo test --release -p fspy_elf_loader -p fspy_elf_loader_tests + + - name: Run fspy tests (debug) + run: cargo test -p fspy + + - name: Run fspy hardening tests (release) + run: cargo test --release -p fspy --test linux_hardening --test linux_syscalls --test untracked_fallback + fmt: name: Format and Check Deps runs-on: namespace-profile-linux-x64-default @@ -445,6 +482,7 @@ jobs: - clippy - build-freebsd - test + - test-linux-arm64 - test-macos-x64 - test-musl - build-windows-tests diff --git a/Cargo.lock b/Cargo.lock index 7107a42d6..22acfaf5e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1366,6 +1366,7 @@ dependencies = [ "elf", "flate2", "fspy_detours_sys", + "fspy_elf_loader", "fspy_preload_linux", "fspy_preload_macos", "fspy_preload_windows", diff --git a/Cargo.toml b/Cargo.toml index f40b0b4b3..5238a6526 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -80,6 +80,7 @@ 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_detours_sys = { path = "crates/fspy_detours_sys" } +fspy_elf_loader = { path = "crates/fspy_elf_loader" } fspy_preload_macos = { path = "crates/fspy_preload_macos", artifact = "cdylib" } fspy_preload_windows = { path = "crates/fspy_preload_windows", artifact = "cdylib" } fspy_shm = { path = "crates/fspy_shm" } diff --git a/crates/fspy/Cargo.toml b/crates/fspy/Cargo.toml index 3a6214648..14d7e603c 100644 --- a/crates/fspy/Cargo.toml +++ b/crates/fspy/Cargo.toml @@ -68,6 +68,7 @@ nix = { workspace = true, features = ["fs"] } [target.'cfg(target_os = "linux")'.dev-dependencies] elf = { workspace = true } +fspy_elf_loader = { 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" } diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index 6924b2b4b..a4f8710df 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -1,11 +1,9 @@ use std::{ - ffi::CString, io, - os::{ - fd::{AsRawFd as _, FromRawFd as _, OwnedFd}, - unix::ffi::OsStrExt as _, - }, - path::{Path, PathBuf}, + mem::offset_of, + os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd}, + path::Path, + sync::RwLock, }; use fspy_shared::ipc::{IpcStr, PathAccess, channel::channel}; @@ -13,7 +11,10 @@ use fspy_shared_unix::linux::{BOOTSTRAP_ENV_NAME, Bootstrap, Target, encode_boot 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}, + ptrace::{ + BPF_ABS, BPF_JEQ, BPF_JMP, BPF_K, BPF_LD, BPF_RET, BPF_W, SECCOMP_RET_ALLOW, + SECCOMP_RET_TRAP, SECCOMP_SET_MODE_FILTER, seccomp_data, sock_filter, sock_fprog, + }, }; use syscalls::Sysno; use tokio::io::AsyncReadExt as _; @@ -29,32 +30,62 @@ const PRELOAD_LINUX: Artifact = artifact!("fspy_preload", "CARGO_BIN_FILE_FSPY_P #[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>, + /// Materialized executable path to `fspy_preload_linux`, or `None` when + /// seccomp is unavailable or materialization failed (in which case `spawn` + /// falls back to untracked execution). Wrapped in `RwLock` so a file reaped + /// from the temp directory (e.g. by `systemd-tmpfiles`) can be lazily + /// re-materialized on `ENOENT`. + preload_path: RwLock>>, seccomp_available: bool, } impl SpyImpl { /// Materializes `fspy_preload_linux` into the user's temp directory and /// probes whether this environment permits installing a seccomp filter. + #[expect( + clippy::unnecessary_wraps, + reason = "matches cross-platform SpyImpl::init() -> io::Result signature" + )] pub fn init() -> io::Result { - let seccomp_available = probe_seccomp_available()?; + let seccomp_available = probe_seccomp_available(); let preload_path = if seccomp_available { - let materialized = materialize_executable_preload().map(|p| p.as_path().into()); + let materialized = materialize_preload(); 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" + "failed to materialize the Linux task tracker binary, so Linux task \ + tracking is off and caching is disabled" ); } materialized } else { None }; - Ok(Self { preload_path, seccomp_available }) + Ok(Self { preload_path: RwLock::new(preload_path), seccomp_available }) + } + + fn preload_path(&self) -> Option> { + if !self.seccomp_available { + return None; + } + self.preload_path + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_deref() + .map(clone_ipc_str) + } + + fn rematerialize_preload(&self, failed_path: &IpcStr) -> Option> { + let mut guard = + self.preload_path.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(current) = guard.as_deref() + && (current.as_bytes() != failed_path.as_bytes() + || Path::new(current.as_os_str()).exists()) + { + return Some(clone_ipc_str(current)); + } + let new_path = materialize_preload(); + *guard = new_path.as_deref().map(clone_ipc_str); + new_path } pub(crate) async fn spawn( @@ -62,9 +93,7 @@ impl SpyImpl { mut command: Command, cancellation_token: CancellationToken, ) -> Result { - let Some(preload_path) = - (self.seccomp_available).then_some(self.preload_path.as_deref()).flatten() - else { + let Some(preload_path) = self.preload_path() else { return spawn_untracked(command, cancellation_token); }; @@ -72,14 +101,14 @@ impl SpyImpl { .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) + let 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, + preload_path: &preload_path, target: Target::Unresolved { path: target_path, error_pipe_fd: write_raw_fd }, }; let bump = bumpalo::Bump::new(); @@ -101,48 +130,26 @@ impl SpyImpl { }); } - 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)); + let mut child = match tokio_command.spawn() { + Ok(child) => child, + Err(err) + if err.kind() == io::ErrorKind::NotFound + && !Path::new(preload_path.as_os_str()).exists() => + { + match self.rematerialize_preload(&preload_path) { + Some(new_path) if new_path.as_bytes() == preload_path.as_bytes() => { + tokio_command.spawn().map_err(SpawnError::OsSpawn)? } - }, - () = cancellation_token.cancelled() => { - cancelled = true; - break; + _ => return Err(SpawnError::OsSpawn(err)), } } - } - drop(pipe_reader); + Err(err) => return Err(SpawnError::OsSpawn(err)), + }; + // 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); - 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))); - } - } + await_startup_handshake(pipe_reader, &mut child, &cancellation_token).await?; Ok(TrackedChild { stdin: child.stdin.take(), @@ -167,6 +174,54 @@ impl SpyImpl { } } +async fn await_startup_handshake( + mut pipe_reader: tokio::net::unix::pipe::Receiver, + child: &mut tokio::process::Child, + cancellation_token: &CancellationToken, +) -> Result<(), SpawnError> { + let mut buf = [0u8; 4]; + let mut filled = 0usize; + 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) => { + drop(pipe_reader); + let _ = child.start_kill(); + let _ = child.wait().await; + return Err(SpawnError::OsSpawn(err)); + } + }, + () = cancellation_token.cancelled() => { + drop(pipe_reader); + let _ = child.start_kill(); + let _ = child.wait().await; + return Err(SpawnError::OsSpawn(io::Error::new( + io::ErrorKind::Interrupted, + "spawn cancelled", + ))); + } + } + } + drop(pipe_reader); + + 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(()) +} + fn spawn_untracked( command: Command, cancellation_token: CancellationToken, @@ -192,76 +247,68 @@ fn spawn_untracked( }) } -/// 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) +fn clone_ipc_str(s: &IpcStr) -> Box { + Path::new(s.as_os_str()).into() } -/// 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 +fn materialize_preload() -> Option> { + PRELOAD_LINUX + .materialize() + .executable() + .at_user_temp_dir("vp_run") + .ok() + .map(|p| p.as_path().into()) } -/// 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 { +/// Probes once on a dedicated short-lived OS thread whether +/// `PR_SET_NO_NEW_PRIVS` and `seccomp(SECCOMP_SET_MODE_FILTER)` with +/// `SECCOMP_RET_TRAP` are permitted in the current environment. +/// +/// Both `PR_SET_NO_NEW_PRIVS` and `SECCOMP_SET_MODE_FILTER` (without +/// `SECCOMP_FILTER_FLAG_TSYNC`) are per-thread in Linux, so running the probe +/// on a dedicated thread avoids `fork()` in multi-threaded processes while +/// leaving every other thread completely unaffected. +fn probe_seccomp_available() -> bool { + const SENTINEL_SYSNO: u32 = 0x7fff_ffff; + + let Ok(handle) = std::thread::Builder::new().name("fspy-seccomp-probe".into()).spawn(|| { + #[expect( + clippy::cast_possible_truncation, + reason = "cBPF opcodes and seccomp_data 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: SENTINEL_SYSNO, + }, + sock_filter { code: (BPF_RET | BPF_K) as u16, jt: 0, jf: 0, k: SECCOMP_RET_TRAP }, + 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 per-thread seccomp filter on this short-lived + // probe thread using a valid stack-local cBPF program. + 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); - } + }) else { + return false; + }; + handle.join().unwrap_or(false) } /// 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`. +/// pipe receiver) and whose write end stays blocking and at FD `>= 3` (so child +/// stdio `dup2` onto FD 0/1/2 never collides with `error_pipe_fd`). fn create_error_pipe() -> io::Result<(OwnedFd, OwnedFd)> { let mut fds = [-1; 2]; // SAFETY: `fds` is a valid 2-element array for `pipe2`. @@ -273,6 +320,19 @@ fn create_error_pipe() -> io::Result<(OwnedFd, OwnedFd)> { // SAFETY: `pipe2` returned two newly opened descriptors. let write_end = unsafe { OwnedFd::from_raw_fd(fds[1]) }; + let write_end = if write_end.as_raw_fd() < 3 { + // SAFETY: `write_end` is a valid open descriptor; duplicating to `>= 3` + // prevents child stdio `dup2` from clobbering `error_pipe_fd`. + let dup = unsafe { libc::fcntl(write_end.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 3) }; + if dup == -1 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `F_DUPFD_CLOEXEC` returned a newly opened descriptor. + unsafe { OwnedFd::from_raw_fd(dup) } + } else { + write_end + }; + // SAFETY: `read_end` is a valid open descriptor. let flags = unsafe { libc::fcntl(read_end.as_raw_fd(), libc::F_GETFL) }; if flags == -1 { @@ -311,8 +371,8 @@ mod tests { 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), + abi::EM_X86_64 => fspy_elf_loader::LAUNCHER_REGION_X86_64, + abi::EM_AARCH64 => fspy_elf_loader::LAUNCHER_REGION_AARCH64, machine => panic!("unsupported preload machine: {machine}"), }; let segments: Vec<_> = image.segments().unwrap().iter().collect(); diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs index 413f1efe9..19ee75632 100644 --- a/crates/fspy/tests/linux_hardening.rs +++ b/crates/fspy/tests/linux_hardening.rs @@ -312,3 +312,302 @@ async fn deep_exec_chain_preserves_fd_env_and_seccomp_filter_hygiene() -> anyhow let _accesses = test_utils::spawn_command(cmd).await?; Ok(()) } + +#[test(tokio::test)] +async fn e2big_on_execve_and_posix_spawn_cleans_up_scratch_without_leaking() -> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + use std::ffi::CString; + + fn count_open_fds() -> usize { + std::fs::read_dir("/proc/self/fd") + .unwrap() + .filter_map(|e| e.ok()?.file_name().to_str()?.parse::().ok()) + .filter(|&fd| { + // SAFETY: `F_GETFD` only queries flags and returns `-1` for + // the already-closed `read_dir` descriptor. + unsafe { libc::fcntl(fd, libc::F_GETFD) >= 0 } + }) + .count() + } + + let prog = CString::new("/bin/true").unwrap(); + let arg0 = CString::new("true").unwrap(); + let argv = [arg0.as_ptr(), std::ptr::null()]; + + // Exceeds Linux `MAX_ARG_STRLEN` (32 * PAGE_SIZE) on both 4 KiB and + // 64 KiB page kernels so `SYS_execve` fails cleanly with `E2BIG`. + let mut big = Vec::with_capacity(4 + 3 * 1024 * 1024 + 1); + big.extend_from_slice(b"BIG="); + big.resize(4 + 3 * 1024 * 1024, b'x'); + let big_cstr = CString::new(big).unwrap(); + let huge_envp = [big_cstr.as_ptr(), std::ptr::null()]; + + let fds_before = count_open_fds(); + + // 1. Direct `execve` returns `-1` / `E2BIG` and runs `cleanup_exec_scratch`. + // SAFETY: `prog`, `argv`, and `huge_envp` are valid NUL/NULL-terminated arrays. + let rc = unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), huge_envp.as_ptr()) }; + assert_eq!(rc, -1, "oversized execve unexpectedly succeeded"); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::E2BIG), + "expected E2BIG from oversized execve" + ); + assert_eq!(count_open_fds(), fds_before, "execve E2BIG leaked an open FD"); + + // 2. `posix_spawn` (`CLONE_VM | CLONE_VFORK`) returns `E2BIG` cleanly + // and releases its parked `ExecScratch` and duped FD without crashing. + let mut pid: libc::pid_t = 0; + let argv_mut = [arg0.as_ptr().cast_mut(), std::ptr::null_mut()]; + let huge_envp_mut = [big_cstr.as_ptr().cast_mut(), std::ptr::null_mut()]; + // SAFETY: `prog`, `argv_mut`, and `huge_envp_mut` are valid arrays. + let spawn_rc = unsafe { + libc::posix_spawn( + &raw mut pid, + prog.as_ptr(), + std::ptr::null(), + std::ptr::null(), + argv_mut.as_ptr(), + huge_envp_mut.as_ptr(), + ) + }; + assert_eq!(spawn_rc, libc::E2BIG, "expected E2BIG from oversized posix_spawn"); + assert_eq!(count_open_fds(), fds_before, "posix_spawn E2BIG leaked an open FD"); + + // 3. Process remains healthy: a normal `posix_spawn` still succeeds. + let empty_envp = [std::ptr::null_mut::()]; + let mut ok_pid: libc::pid_t = 0; + // SAFETY: `prog`, `argv_mut`, and `empty_envp` are valid arrays. + let ok_rc = unsafe { + libc::posix_spawn( + &raw mut ok_pid, + prog.as_ptr(), + std::ptr::null(), + std::ptr::null(), + argv_mut.as_ptr(), + empty_envp.as_ptr(), + ) + }; + assert_eq!(ok_rc, 0, "follow-up posix_spawn failed with errno {ok_rc}"); + let mut status: libc::c_int = 0; + // SAFETY: `ok_pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(ok_pid, &raw mut status, 0) }, ok_pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} + +#[test(tokio::test)] +async fn inherited_sigsys_ign_and_blocked_mask_survive_execve() -> anyhow::Result<()> { + let probe_path = Path::new("/fspy-inherited-sigsys-probe"); + let cmd = vt_subprocess_test::command_for_fn!( + probe_path.to_str().unwrap().to_owned(), + |probe_path: String| { + use std::{ffi::CString, os::unix::ffi::OsStrExt as _}; + + if std::env::var_os("FSPY_TEST_SIGSYS_STAGE").is_some() { + // Verify `SIGSYS` is still virtually `SIG_IGN`. + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut old: libc::sigaction = unsafe { std::mem::zeroed() }; + // SAFETY: querying current disposition for `SIGSYS`. + let rc = unsafe { libc::sigaction(libc::SIGSYS, std::ptr::null(), &raw mut old) }; + assert_eq!(rc, 0); + assert_eq!( + old.sa_sigaction, + libc::SIG_IGN, + "inherited SIGSYS SIG_IGN was not preserved across execve" + ); + + // Verify both `SIGSYS` and `SIGUSR1` remain blocked in the signal mask. + // SAFETY: `sigset_t` is a plain C struct valid when zeroed. + let mut cur_mask: libc::sigset_t = unsafe { std::mem::zeroed() }; + // SAFETY: querying current thread signal mask. + let mask_rc = unsafe { + libc::sigprocmask(libc::SIG_SETMASK, std::ptr::null(), &raw mut cur_mask) + }; + assert_eq!(mask_rc, 0); + // SAFETY: `cur_mask` was initialized by `sigprocmask`. + let sigsys_blocked = + unsafe { libc::sigismember(&raw const cur_mask, libc::SIGSYS) }; + assert_eq!(sigsys_blocked, 1, "inherited blocked SIGSYS was lost across execve"); + // SAFETY: `cur_mask` was initialized by `sigprocmask`. + let sigusr1_blocked = + unsafe { libc::sigismember(&raw const cur_mask, libc::SIGUSR1) }; + assert_eq!(sigusr1_blocked, 1, "inherited blocked SIGUSR1 was lost across execve"); + + // Verify syscall tracking still works with virtualized SIGSYS ignored+blocked. + let _ = std::fs::File::open(&probe_path); + return; + } + + // Stage 0: set `SIGSYS` to `SIG_IGN` and block `SIGSYS` + `SIGUSR1`. + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut ign: libc::sigaction = unsafe { std::mem::zeroed() }; + ign.sa_sigaction = libc::SIG_IGN; + // SAFETY: installing `SIG_IGN` for `SIGSYS`. + let ign_rc = + unsafe { libc::sigaction(libc::SIGSYS, &raw const ign, std::ptr::null_mut()) }; + assert_eq!(ign_rc, 0); + + // SAFETY: `sigset_t` is initialized via `sigemptyset`/`sigaddset`. + let mut block_set: libc::sigset_t = unsafe { std::mem::zeroed() }; + // SAFETY: valid stack-local `sigset_t`. + unsafe { + libc::sigemptyset(&raw mut block_set); + libc::sigaddset(&raw mut block_set, libc::SIGSYS); + libc::sigaddset(&raw mut block_set, libc::SIGUSR1); + assert_eq!( + libc::sigprocmask(libc::SIG_BLOCK, &raw const block_set, std::ptr::null_mut()), + 0 + ); + } + + let exe = std::fs::read_link("/proc/self/exe").unwrap(); + let prog = CString::new(exe.as_os_str().as_bytes()).unwrap(); + 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() + .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("FSPY_TEST_SIGSYS_STAGE=1").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/NULL-terminated arrays. + unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), envp.as_ptr()) }; + panic!("execve failed: {}", std::io::Error::last_os_error()); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn proc_self_environ_does_not_expose_fspy_bootstrap() -> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + fn assert_bootstrap_scrubbed(label: &str) { + assert!( + std::env::var_os("__FSPY_BOOTSTRAP").is_none(), + "{label}: __FSPY_BOOTSTRAP present in process env" + ); + let raw = std::fs::read("/proc/self/environ").unwrap(); + let needle = b"__FSPY_BOOTSTRAP"; + assert!( + !raw.windows(needle.len()).any(|w| w == needle), + "{label}: __FSPY_BOOTSTRAP found in /proc/self/environ" + ); + } + + // Check initial spawn (`Target::Unresolved`). + assert_bootstrap_scrubbed("initial spawn"); + + // Also check a child spawned via `execve` (`Target::ResolvedFd`). + let output = std::process::Command::new("/bin/cat") + .arg("/proc/self/environ") + .output() + .expect("failed to run /bin/cat /proc/self/environ"); + assert!(output.status.success()); + let needle = b"__FSPY_BOOTSTRAP"; + assert!( + !output.stdout.windows(needle.len()).any(|w| w == needle), + "child execve: __FSPY_BOOTSTRAP found in /proc/self/environ" + ); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} + +#[test(tokio::test)] +async fn child_execve_with_stale_bootstrap_env_succeeds() -> anyhow::Result<()> { + let probe_path = Path::new("/fspy-stale-bootstrap-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; + + // 1. Exec static test binary with duplicate stale `__FSPY_BOOTSTRAP` + // entries in `envp` — must overwrite/deduplicate cleanly instead + // of failing with `EINVAL`. + let prog = CString::new(static_bin).unwrap(); + let arg0 = CString::new("test_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 = [ + c"__FSPY_BOOTSTRAP=stale".as_ptr(), + c"__FSPY_BOOTSTRAP=stale2".as_ptr(), + c"KEEP=yes".as_ptr(), + 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: `prog`, `argv`, and `envp` are valid arrays. + unsafe { + libc::execve(prog.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. + assert_eq!(unsafe { libc::waitpid(pid, &raw mut status, 0) }, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "child execve with stale __FSPY_BOOTSTRAP failed with status {status}" + ); + + // 2. Exec `/bin/sh` with stale `__FSPY_BOOTSTRAP=stale` and verify + // the child sees `KEEP=yes` and no `__FSPY_BOOTSTRAP`. + let sh_argv = [ + c"/bin/sh".as_ptr(), + c"-c".as_ptr(), + c"test -z \"${__FSPY_BOOTSTRAP+x}\" && test \"$KEEP\" = \"yes\"".as_ptr(), + std::ptr::null(), + ]; + // SAFETY: `fork()` followed by async-signal-safe `execve` + `_exit`. + let pid2 = unsafe { libc::fork() }; + assert!(pid2 >= 0, "fork failed"); + if pid2 == 0 { + // SAFETY: `sh_argv` and `envp` are valid arrays. + unsafe { + libc::execve(c"/bin/sh".as_ptr(), sh_argv.as_ptr(), envp.as_ptr()); + libc::_exit(127); + } + } + let mut status2: libc::c_int = 0; + // SAFETY: `pid2` is our child and `status2` is writable. + assert_eq!(unsafe { libc::waitpid(pid2, &raw mut status2, 0) }, pid2); + assert!( + libc::WIFEXITED(status2) && libc::WEXITSTATUS(status2) == 0, + "sh execve with stale __FSPY_BOOTSTRAP failed with status {status2}" + ); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} diff --git a/crates/fspy/tests/linux_syscalls.rs b/crates/fspy/tests/linux_syscalls.rs new file mode 100644 index 000000000..2bc5a9a56 --- /dev/null +++ b/crates/fspy/tests/linux_syscalls.rs @@ -0,0 +1,590 @@ +//! Linux-specific syscall coverage tests for `fspy_preload_linux`: +//! - `execveat` variants (`AT_SYMLINK_NOFOLLOW`, non-CWD `dirfd`, `O_PATH` + +//! `AT_EMPTY_PATH` on both ELF binaries and `#!` scripts, `AT_EMPTY_PATH` on +//! non-`CLOEXEC` and `CLOEXEC` `#!` scripts) +//! - `newfstatat`/`fstatat`, `statx`, and `faccessat2` with valid `fd` + `AT_EMPTY_PATH` +//! - `access`/`faccessat`/`faccessat2` and `mkdirat`/`renameat`/`linkat`/`symlinkat`/`openat2` +//! with non-CWD `dirfd` + relative path +//! - `openat2` invalid `how_ptr` / invalid `size` (`EFAULT` / `EINVAL`) +//! - `openat(O_RDONLY | O_CREAT)` / `openat(O_RDONLY | O_TRUNC)` recording `ReadWrite`, +//! and `renameat2(RENAME_EXCHANGE)` recording both paths +//! - Legacy x86-64 `SYS_open`, `SYS_stat`, and `SYS_lstat` +#![cfg(target_os = "linux")] + +mod test_utils; + +use std::{ + fs::{self, File, Permissions}, + os::unix::fs::{PermissionsExt as _, symlink}, + path::Path, +}; + +use fspy::PathAccess; +use test_log::test; +#[cfg(target_arch = "x86_64")] +use test_utils::assert_includes; +use test_utils::{assert_contains, test_bin_path}; + +/// `STATX_BASIC_STATS`. Not defined in `libc` on every musl target. +const STATX_BASIC_STATS: libc::c_uint = 0x7ff; + +/// `RENAME_EXCHANGE`. Not defined in `libc` on every musl target. +const RENAME_EXCHANGE: libc::c_uint = 2; + +/// Kernel `struct statx` (256 bytes, 8-byte aligned). +#[repr(C, align(8))] +struct StatxBuf([u8; 256]); + +/// Kernel `struct open_how` (24 bytes). +#[repr(C)] +struct OpenHow { + flags: u64, + mode: u64, + resolve: u64, +} + +fn errno() -> libc::c_int { + std::io::Error::last_os_error().raw_os_error().unwrap() +} + +fn write_exec(path: &Path, content: &[u8]) { + fs::write(path, content).unwrap(); + fs::set_permissions(path, Permissions::from_mode(0o755)).unwrap(); +} + +#[test(tokio::test)] +async fn execveat_nofollow_dirfd_o_path_and_empty_path_scripts() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + // Copy the static test binary into `root` so we can exec it via non-CWD + // `dirfd` + relative path and via `O_PATH` + `AT_EMPTY_PATH`. + let rel_bin = root.join("rel_bin"); + fs::copy(test_bin_path(), &rel_bin)?; + fs::set_permissions(&rel_bin, Permissions::from_mode(0o755))?; + + let bin_symlink = root.join("bin_link"); + symlink(&rel_bin, &bin_symlink)?; + + let probe_rel_bin = Path::new("/fspy-execveat-rel-bin-probe"); + let probe_rel_script = Path::new("/fspy-execveat-rel-script-probe"); + let probe_opath_bin = Path::new("/fspy-execveat-opath-bin-probe"); + let probe_opath_script = Path::new("/fspy-execveat-opath-script-probe"); + let probe_empty_script = Path::new("/fspy-execveat-empty-script-probe"); + + let rel_script = root.join("rel_script.sh"); + write_exec( + &rel_script, + format!("#!/bin/sh\n{} open_read {}\n", rel_bin.display(), probe_rel_script.display()) + .as_bytes(), + ); + + let opath_script = root.join("opath_script.sh"); + write_exec( + &opath_script, + format!("#!/bin/sh\n{} open_read {}\n", rel_bin.display(), probe_opath_script.display()) + .as_bytes(), + ); + + let empty_script = root.join("empty_script.sh"); + write_exec( + &empty_script, + format!("#!/bin/sh\n{} open_read {}\n", rel_bin.display(), probe_empty_script.display()) + .as_bytes(), + ); + + let args = ( + root.to_str().unwrap().to_owned(), + probe_rel_bin.to_str().unwrap().to_owned(), + probe_opath_bin.to_str().unwrap().to_owned(), + ); + + let accesses = + track_fn!(args, |(root_str, probe_rel_bin, probe_opath_bin): (String, String, String)| { + use std::{ffi::CString, os::fd::AsRawFd as _}; + + fn run_execveat_in_child( + dirfd: libc::c_int, + path: &std::ffi::CStr, + argv: &[*const libc::c_char], + flags: libc::c_int, + ) -> libc::c_int { + 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: arguments are valid NUL/NULL-terminated C strings/arrays. + unsafe { + libc::syscall( + libc::SYS_execveat, + dirfd, + path.as_ptr(), + argv.as_ptr(), + envp.as_ptr(), + flags, + ); + libc::_exit(127); + } + } + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(pid, &raw mut status, 0) }, pid); + assert!( + libc::WIFEXITED(status), + "execveat child terminated abnormally: status={status}" + ); + libc::WEXITSTATUS(status) + } + + // Ensure CWD is `/` so relative names MUST resolve against `dirfd`. + std::env::set_current_dir("/").unwrap(); + let dir = File::open(&root_str).unwrap(); + let dirfd = dir.as_raw_fd(); + + // 1. `AT_SYMLINK_NOFOLLOW` on a symlink -> `ELOOP`. + let argv_link = [c"bin_link".as_ptr(), std::ptr::null()]; + let envp_empty = [std::ptr::null::()]; + // SAFETY: valid arguments to `execveat` expected to fail with `ELOOP`. + let rc = unsafe { + libc::syscall( + libc::SYS_execveat, + dirfd, + c"bin_link".as_ptr(), + argv_link.as_ptr(), + envp_empty.as_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + }; + assert_eq!(rc, -1, "execveat AT_SYMLINK_NOFOLLOW on symlink should fail"); + assert_eq!(errno(), libc::ELOOP); + + // 2. Non-CWD `dirfd` + relative ELF executable. + let probe_rel_c = CString::new(probe_rel_bin).unwrap(); + let argv_rel_bin = [ + c"rel_bin".as_ptr(), + c"open_read".as_ptr(), + probe_rel_c.as_ptr(), + std::ptr::null(), + ]; + assert_eq!(run_execveat_in_child(dirfd, c"rel_bin", &argv_rel_bin, 0), 0); + + // 3. Non-CWD `dirfd` + relative `#!` script. + let argv_rel_script = [c"rel_script.sh".as_ptr(), std::ptr::null()]; + assert_eq!(run_execveat_in_child(dirfd, c"rel_script.sh", &argv_rel_script, 0), 0); + + // 4. `O_PATH` + `AT_EMPTY_PATH` on an ELF executable. + // SAFETY: valid path relative to `dirfd`. + let opath_bin_fd = + unsafe { libc::openat(dirfd, c"rel_bin".as_ptr(), libc::O_PATH | libc::O_CLOEXEC) }; + assert!(opath_bin_fd >= 0, "openat O_PATH bin failed: {}", errno()); + let probe_opath_c = CString::new(probe_opath_bin).unwrap(); + let argv_opath_bin = [ + c"opath_bin".as_ptr(), + c"open_read".as_ptr(), + probe_opath_c.as_ptr(), + std::ptr::null(), + ]; + assert_eq!( + run_execveat_in_child(opath_bin_fd, c"", &argv_opath_bin, libc::AT_EMPTY_PATH), + 0 + ); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(opath_bin_fd) }; + + // 5. `O_PATH` (without `O_CLOEXEC`) + `AT_EMPTY_PATH` on a `#!` script. + // SAFETY: valid path relative to `dirfd`. + let opath_script_fd = + unsafe { libc::openat(dirfd, c"opath_script.sh".as_ptr(), libc::O_PATH) }; + assert!(opath_script_fd >= 0, "openat O_PATH script failed: {}", errno()); + let argv_opath_script = [c"opath_script".as_ptr(), std::ptr::null()]; + assert_eq!( + run_execveat_in_child( + opath_script_fd, + c"", + &argv_opath_script, + libc::AT_EMPTY_PATH + ), + 0 + ); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(opath_script_fd) }; + + // 6. `AT_EMPTY_PATH` on `#!` script: non-`CLOEXEC` succeeds, `CLOEXEC` fails `ENOENT`. + // SAFETY: valid path relative to `dirfd`. + let non_cloexec_fd = + unsafe { libc::openat(dirfd, c"empty_script.sh".as_ptr(), libc::O_RDONLY) }; + assert!(non_cloexec_fd >= 0, "openat non-cloexec script failed: {}", errno()); + let argv_empty_script = [c"empty_script".as_ptr(), std::ptr::null()]; + assert_eq!( + run_execveat_in_child(non_cloexec_fd, c"", &argv_empty_script, libc::AT_EMPTY_PATH), + 0 + ); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(non_cloexec_fd) }; + + // `File::open` sets `O_CLOEXEC` -> `execveat(AT_EMPTY_PATH)` on `#!` returns `ENOENT`. + let cloexec_script = File::open(format!("{root_str}/empty_script.sh")).unwrap(); + // SAFETY: valid arguments to `execveat` expected to fail with `ENOENT`. + let rc_cloexec = unsafe { + libc::syscall( + libc::SYS_execveat, + cloexec_script.as_raw_fd(), + c"".as_ptr(), + argv_empty_script.as_ptr(), + envp_empty.as_ptr(), + libc::AT_EMPTY_PATH, + ) + }; + assert_eq!(rc_cloexec, -1, "AT_EMPTY_PATH on CLOEXEC script should fail"); + assert_eq!(errno(), libc::ENOENT); + }) + .await?; + + assert_contains(&accesses, &rel_bin, PathAccess::Read); + assert_contains(&accesses, &rel_script, PathAccess::Read); + assert_contains(&accesses, &opath_script, PathAccess::Read); + assert_contains(&accesses, &empty_script, PathAccess::Read); + assert_contains(&accesses, probe_rel_bin, PathAccess::Read); + assert_contains(&accesses, probe_rel_script, PathAccess::Read); + assert_contains(&accesses, probe_opath_bin, PathAccess::Read); + assert_contains(&accesses, probe_opath_script, PathAccess::Read); + assert_contains(&accesses, probe_empty_script, PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn empty_path_fstatat_statx_and_faccessat2_record_fd_path() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let f_fstatat = root.join("empty_fstatat"); + let f_statx = root.join("empty_statx"); + let f_faccessat2 = root.join("empty_faccessat2"); + fs::write(&f_fstatat, b"a")?; + fs::write(&f_statx, b"b")?; + fs::write(&f_faccessat2, b"c")?; + + let args = ( + f_fstatat.to_str().unwrap().to_owned(), + f_statx.to_str().unwrap().to_owned(), + f_faccessat2.to_str().unwrap().to_owned(), + ); + + let accesses = track_fn!(args, |(p1, p2, p3): (String, String, String)| { + use std::os::fd::AsRawFd as _; + + // Open each file via `O_PATH` before invoking the `AT_EMPTY_PATH` + // syscalls (the `openat` itself also records Read, and we additionally + // verify the kernel calls succeed / behave as expected under seccomp). + let file1 = File::open(&p1).unwrap(); + let mut st = std::mem::MaybeUninit::::uninit(); + // SAFETY: `file1` is open and `st` is writable. + let rc_fstatat = unsafe { + libc::fstatat(file1.as_raw_fd(), c"".as_ptr(), st.as_mut_ptr(), libc::AT_EMPTY_PATH) + }; + assert_eq!(rc_fstatat, 0); + + let file2 = File::open(&p2).unwrap(); + let mut stx = StatxBuf([0; 256]); + // SAFETY: `file2` is open and `stx` is writable. + let rc_statx = unsafe { + libc::syscall( + libc::SYS_statx, + file2.as_raw_fd(), + c"".as_ptr(), + libc::AT_EMPTY_PATH, + STATX_BASIC_STATS, + core::ptr::from_mut(&mut stx), + ) + }; + assert_eq!(rc_statx, 0); + + let file3 = File::open(&p3).unwrap(); + // SAFETY: `file3` is open and `c""` is a valid C string. + // Kernels before 6.13 reject `AT_EMPTY_PATH` in `faccessat2` with + // `EINVAL` (and pre-5.8 return `ENOSYS`), while `fspy_preload_linux` + // still records the descriptor path before replaying. + let rc = unsafe { + libc::syscall( + libc::SYS_faccessat2, + file3.as_raw_fd(), + c"".as_ptr(), + libc::F_OK, + libc::AT_EMPTY_PATH, + ) + }; + assert!( + rc == 0 || matches!(errno(), libc::EINVAL | libc::ENOSYS), + "unexpected faccessat2(AT_EMPTY_PATH) result: rc={rc}, errno={}", + errno() + ); + }) + .await?; + + assert_contains(&accesses, &f_fstatat, PathAccess::Read); + assert_contains(&accesses, &f_statx, PathAccess::Read); + assert_contains(&accesses, &f_faccessat2, PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn access_and_dirfd_relative_fs_syscalls_are_tracked() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let access_file = root.join("via_access"); + let faccessat_file = root.join("via_faccessat"); + let faccessat2_file = root.join("via_faccessat2"); + let ren_src = root.join("ren_src"); + let ren_dst = root.join("ren_dst"); + let link_src = root.join("link_src"); + let link_dst = root.join("link_dst"); + let sym_dst = root.join("sym_dst"); + let mkdir_dst = root.join("mkdir_dst"); + let openat2_file = root.join("via_openat2"); + + fs::write(&access_file, b"")?; + fs::write(&faccessat_file, b"")?; + fs::write(&faccessat2_file, b"")?; + fs::write(&ren_src, b"")?; + fs::write(&link_src, b"")?; + fs::write(&openat2_file, b"")?; + + let root_str = root.to_str().unwrap().to_owned(); + let accesses = track_fn!(root_str, |root_str: String| { + use std::{ffi::CString, os::fd::AsRawFd as _}; + + // Change CWD to `/` so every relative path below MUST resolve against `dirfd`. + std::env::set_current_dir("/").unwrap(); + let dir = File::open(&root_str).unwrap(); + let dirfd = dir.as_raw_fd(); + + let abs_access = CString::new(format!("{root_str}/via_access")).unwrap(); + // SAFETY: `abs_access` is a valid NUL-terminated path. + assert_eq!(unsafe { libc::access(abs_access.as_ptr(), libc::F_OK) }, 0); + + // SAFETY: `dirfd` is open and names are valid NUL-terminated strings. + unsafe { + assert_eq!(libc::faccessat(dirfd, c"via_faccessat".as_ptr(), libc::F_OK, 0), 0); + + let rc_fa2 = libc::syscall( + libc::SYS_faccessat2, + dirfd, + c"via_faccessat2".as_ptr(), + libc::F_OK, + 0, + ); + assert!( + rc_fa2 == 0 || errno() == libc::ENOSYS, + "faccessat2 failed: rc={rc_fa2}, errno={}", + errno() + ); + + assert_eq!(libc::mkdirat(dirfd, c"mkdir_dst".as_ptr(), 0o755), 0); + assert_eq!(libc::renameat(dirfd, c"ren_src".as_ptr(), dirfd, c"ren_dst".as_ptr()), 0); + assert_eq!( + libc::linkat(dirfd, c"link_src".as_ptr(), dirfd, c"link_dst".as_ptr(), 0), + 0 + ); + assert_eq!(libc::symlinkat(c"target".as_ptr(), dirfd, c"sym_dst".as_ptr()), 0); + + let how = + OpenHow { flags: u64::try_from(libc::O_RDONLY).unwrap(), mode: 0, resolve: 0 }; + let fd = libc::syscall( + libc::SYS_openat2, + dirfd, + c"via_openat2".as_ptr(), + &raw const how, + size_of::(), + ); + assert!(fd >= 0, "openat2 failed: errno={}", errno()); + libc::close(libc::c_int::try_from(fd).unwrap()); + } + }) + .await?; + + assert_contains(&accesses, &access_file, PathAccess::Read); + assert_contains(&accesses, &faccessat_file, PathAccess::Read); + assert_contains(&accesses, &faccessat2_file, PathAccess::Read); + assert_contains(&accesses, &mkdir_dst, PathAccess::Mkdir); + assert_contains(&accesses, &ren_dst, PathAccess::RenameTarget); + assert_contains(&accesses, &link_dst, PathAccess::Write); + assert_contains(&accesses, &sym_dst, PathAccess::Write); + assert_contains(&accesses, &openat2_file, PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn openat2_invalid_how_ptr_and_size_return_efault_and_einval() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let file_path = tmp_dir.path().canonicalize()?.join("probe"); + fs::write(&file_path, b"")?; + + let path_str = file_path.to_str().unwrap().to_owned(); + let _accesses = track_fn!(path_str, |path_str: String| { + use std::ffi::CString; + + let c_path = CString::new(path_str).unwrap(); + + // 1. NULL `how_ptr` -> `EFAULT`. + // SAFETY: kernel validates `how_ptr` and returns `-EFAULT`. + let rc_null = unsafe { + libc::syscall( + libc::SYS_openat2, + libc::AT_FDCWD, + c_path.as_ptr(), + 0_usize, + size_of::(), + ) + }; + assert_eq!(rc_null, -1); + assert_eq!(errno(), libc::EFAULT); + + // 2. First-page bad `how_ptr` -> `EFAULT` without crashing `SIGSYS`. + // SAFETY: `fspy_elf_loader` rejects first-page pointers and kernel returns `-EFAULT`. + let rc_low = unsafe { + libc::syscall( + libc::SYS_openat2, + libc::AT_FDCWD, + c_path.as_ptr(), + 0x10_usize, + size_of::(), + ) + }; + assert_eq!(rc_low, -1); + assert_eq!(errno(), libc::EFAULT); + + // 3. Undersized `size` (< `size_of::()`) -> `EINVAL`. + let how = OpenHow { flags: u64::try_from(libc::O_RDONLY).unwrap(), mode: 0, resolve: 0 }; + // SAFETY: valid `how` pointer with intentionally too-small `size`. + let rc_small = unsafe { + libc::syscall( + libc::SYS_openat2, + libc::AT_FDCWD, + c_path.as_ptr(), + &raw const how, + 8_usize, + ) + }; + assert_eq!(rc_small, -1); + assert_eq!(errno(), libc::EINVAL); + }) + .await?; + + Ok(()) +} + +#[test(tokio::test)] +async fn openat_rdonly_creat_trunc_and_renameat2_exchange() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let created = root.join("rdonly_creat"); + let truncated = root.join("rdonly_trunc"); + fs::write(&truncated, b"old content")?; + let ex_a = root.join("exchange_a"); + let ex_b = root.join("exchange_b"); + fs::write(&ex_a, b"a")?; + fs::write(&ex_b, b"b")?; + + let root_str = root.to_str().unwrap().to_owned(); + let accesses = track_fn!(root_str, |root_str: String| { + use std::os::fd::AsRawFd as _; + + let dir = File::open(&root_str).unwrap(); + let dirfd = dir.as_raw_fd(); + + // 1. `O_RDONLY | O_CREAT` creates the file and must record `ReadWrite`. + // SAFETY: `dirfd` is open and filename is a valid C string. + let fd_creat = unsafe { + libc::openat(dirfd, c"rdonly_creat".as_ptr(), libc::O_RDONLY | libc::O_CREAT, 0o644) + }; + assert!(fd_creat >= 0, "openat O_RDONLY|O_CREAT failed: {}", errno()); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(fd_creat) }; + + // 2. `O_RDONLY | O_TRUNC` truncates the file and must record `ReadWrite`. + // SAFETY: `dirfd` is open and filename is a valid C string. + let fd_trunc = unsafe { + libc::openat(dirfd, c"rdonly_trunc".as_ptr(), libc::O_RDONLY | libc::O_TRUNC) + }; + assert!(fd_trunc >= 0, "openat O_RDONLY|O_TRUNC failed: {}", errno()); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(fd_trunc) }; + + // 3. `renameat2(..., RENAME_EXCHANGE)` swaps both paths and must record both. + // SAFETY: `dirfd` is open and both filenames are valid C strings. + let rc = unsafe { + libc::syscall( + libc::SYS_renameat2, + dirfd, + c"exchange_a".as_ptr(), + dirfd, + c"exchange_b".as_ptr(), + RENAME_EXCHANGE, + ) + }; + assert_eq!(rc, 0, "renameat2(RENAME_EXCHANGE) failed: {}", errno()); + }) + .await?; + + assert_contains(&accesses, &created, PathAccess::ReadWrite); + assert_contains(&accesses, &truncated, PathAccess::ReadWrite); + assert_contains(&accesses, &ex_a, PathAccess::RenameTarget); + assert_contains(&accesses, &ex_b, PathAccess::RenameTarget); + assert_eq!(fs::read(&ex_a)?, b"b"); + assert_eq!(fs::read(&ex_b)?, b"a"); + Ok(()) +} + +#[cfg(target_arch = "x86_64")] +#[test(tokio::test)] +async fn legacy_x86_64_open_stat_lstat_syscalls_are_tracked() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let open_target = root.join("legacy_open"); + let stat_target = root.join("legacy_stat"); + let lstat_target = root.join("legacy_lstat_link"); + fs::write(&open_target, b"open")?; + fs::write(&stat_target, b"stat")?; + symlink(&stat_target, &lstat_target)?; + + let args = ( + open_target.to_str().unwrap().to_owned(), + stat_target.to_str().unwrap().to_owned(), + lstat_target.to_str().unwrap().to_owned(), + ); + + let accesses = track_fn!(args, |(p_open, p_stat, p_lstat): (String, String, String)| { + use std::ffi::CString; + + #[repr(C, align(8))] + struct RawStatBuf([u8; 256]); + + let c_open = CString::new(p_open).unwrap(); + let c_stat = CString::new(p_stat).unwrap(); + let c_lstat = CString::new(p_lstat).unwrap(); + + // SAFETY: valid C string; `SYS_open` takes `(path, flags, mode)`. + let fd = unsafe { libc::syscall(libc::SYS_open, c_open.as_ptr(), libc::O_RDONLY, 0) }; + assert!(fd >= 0, "SYS_open failed: {}", errno()); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(libc::c_int::try_from(fd).unwrap()) }; + + let mut stat_buf = RawStatBuf([0; 256]); + // SAFETY: valid C string and 256-byte aligned buffer (>= x86_64 `struct stat`). + let rc_stat = unsafe { libc::syscall(libc::SYS_stat, c_stat.as_ptr(), &raw mut stat_buf) }; + assert_eq!(rc_stat, 0); + // SAFETY: valid C string and 256-byte aligned buffer (>= x86_64 `struct stat`). + let rc_lstat = + unsafe { libc::syscall(libc::SYS_lstat, c_lstat.as_ptr(), &raw mut stat_buf) }; + assert_eq!(rc_lstat, 0); + }) + .await?; + + assert_includes(&accesses, &open_target, PathAccess::Read); + assert_includes(&accesses, &stat_target, PathAccess::Read); + assert_includes(&accesses, &lstat_target, PathAccess::Read); + Ok(()) +} diff --git a/crates/fspy_elf_loader_test_launcher/Cargo.toml b/crates/fspy_elf_loader_test_launcher/Cargo.toml index 3c74becc8..0d1ae700f 100644 --- a/crates/fspy_elf_loader_test_launcher/Cargo.toml +++ b/crates/fspy_elf_loader_test_launcher/Cargo.toml @@ -8,7 +8,7 @@ publish.workspace = true rust-version.workspace = true [target.'cfg(target_os = "none")'.dependencies] -fspy_elf_loader = { path = "../fspy_elf_loader" } +fspy_elf_loader = { workspace = true } fspy_nostd = { workspace = true } syscalls = { workspace = true } diff --git a/crates/fspy_elf_loader_tests/Cargo.toml b/crates/fspy_elf_loader_tests/Cargo.toml index 669e70444..81f7b8dde 100644 --- a/crates/fspy_elf_loader_tests/Cargo.toml +++ b/crates/fspy_elf_loader_tests/Cargo.toml @@ -9,7 +9,7 @@ rust-version.workspace = true [dev-dependencies] elf = { workspace = true } -fspy_elf_loader = { path = "../fspy_elf_loader" } +fspy_elf_loader = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] libc = { workspace = true } diff --git a/crates/fspy_preload_linux/Cargo.toml b/crates/fspy_preload_linux/Cargo.toml index 4507add47..877360eb0 100644 --- a/crates/fspy_preload_linux/Cargo.toml +++ b/crates/fspy_preload_linux/Cargo.toml @@ -10,7 +10,7 @@ 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_elf_loader = { workspace = true } fspy_nostd = { workspace = true } fspy_nostd_alloc = { workspace = true } fspy_shared = { workspace = true } diff --git a/crates/fspy_preload_linux/build.rs b/crates/fspy_preload_linux/build.rs index 3ef51502e..fb91f8fc8 100644 --- a/crates/fspy_preload_linux/build.rs +++ b/crates/fspy_preload_linux/build.rs @@ -1,4 +1,5 @@ fn main() { + println!("cargo::rerun-if-changed=build.rs"); 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 index 51ddd7815..96bf92bd9 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -12,7 +12,7 @@ mod runtime { ffi::c_void, mem::size_of, ptr::{self, NonNull}, - sync::atomic::{AtomicI32, AtomicPtr, Ordering}, + sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, Ordering}, }; use allocator_api2::{alloc::Allocator, vec::Vec}; @@ -39,7 +39,8 @@ mod runtime { }, }; use linux_raw_sys::general::{ - AT_EMPTY_PATH, O_ACCMODE, O_RDWR, O_WRONLY, SIG_SETMASK, open_how, + AT_EMPTY_PATH, O_ACCMODE, O_CREAT, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, RENAME_EXCHANGE, + SIG_SETMASK, open_how, }; use syscalls::Sysno; @@ -50,11 +51,15 @@ mod runtime { /// the process image. const AT_EXECVE_CHECK: u32 = 0x10000; + /// Linux `kcmp(2)` operation comparing two processes' `mm_struct`s + /// (`enum kcmp_type::KCMP_VM`). + const KCMP_VM: usize = 1; + 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. + // single-threaded launcher process before `try_exec_elf` arms seccomp and + // enters the target; after that `RUNTIME` is strictly read-only. unsafe impl Sync for SyncCell {} struct Runtime { @@ -64,31 +69,41 @@ mod runtime { } /// Scratch memory for one `execve` re-routed through the launcher: the - /// arena holding the rewritten `argv`/`envp`, and any descriptor kept open + /// arena holding the rewritten `argv`/`envp`, and any descriptors 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. + /// [`PARKED_EXEC_SCRATCH`]: + /// - Trapped `posix_spawn` / separate-stack `vfork` children are reclaimed + /// immediately when the parent's `clone` returns via + /// [`reclaim_vfork_child`]. + /// - Untrapped shared-stack `vfork` children are reclaimed on a subsequent + /// exec via `kcmp(my_pid, owner_pid, KCMP_VM, 0, 0) != 0` when + /// [`KCMP_VM_AVAILABLE`] is true, falling back to `set_tid_address` + /// only in restricted containers where `kcmp` is blocked. struct ExecScratch { next: AtomicPtr, active_tid: AtomicI32, + owner_pid: i32, parked: bool, + used_set_tid_address: bool, arena: UnsafeCell>, duped_fd: UnsafeCell, + extra_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`. + // SAFETY: `arena`, `duped_fd`, and `extra_fd` are mutated only by the + // exec'ing thread before it leaves the VM or sets `active_tid` to `0` + // (`Release`), and dropped by a reclaimer only after confirming the child + // is gone (via `on_vfork_return`, `kcmp(KCMP_VM) != 0`, or `active_tid == 0` + // with `Acquire` ordering) 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()); + static KCMP_VM_AVAILABLE: AtomicBool = AtomicBool::new(false); #[cfg(target_arch = "x86_64")] const TRACKED_SYSCALLS: &[Sysno] = &[ @@ -135,8 +150,11 @@ mod runtime { Sysno::execveat, ]; - static INTERCEPTOR: SyscallInterceptor = - SyscallInterceptor { syscalls: TRACKED_SYSCALLS, handle: handle_syscall }; + static INTERCEPTOR: SyscallInterceptor = SyscallInterceptor { + syscalls: TRACKED_SYSCALLS, + handle: handle_syscall, + on_vfork_return: Some(reclaim_vfork_child), + }; #[inline] fn runtime() -> &'static Runtime { @@ -149,6 +167,9 @@ mod runtime { fn run(stack: InitialStack<'_>) -> ! { // SAFETY: `run` executes once in a fresh single-threaded process. let bump: &'static PageBump = unsafe { &*STARTUP_BUMP.0.get() }; + let pid = current_pid(); + KCMP_VM_AVAILABLE.store(shares_vm_with(pid, pid), Ordering::Relaxed); + let bootstrap = Bootstrap::from_env(stack.envs(), bump); let sender = bootstrap.ipc_channel_conf.sender(bump); @@ -161,6 +182,18 @@ mod runtime { }); } + // Capture the raw `(ptr, len)` of any `__FSPY_BOOTSTRAP=...` entries on + // the launcher's initial kernel stack so `on_ready` can zero them in + // place right before entering the target, scrubbing them from + // `/proc/self/environ`. + let mut bootstrap_entries: Vec<(*mut u8, usize), _> = Vec::new_in(bump); + for &entry in stack.envs() { + if is_bootstrap_env(entry) { + let fat = entry.count(); + bootstrap_entries.push((fat.as_ptr().cast_mut(), fat.as_units().len())); + } + } + let filtered_envs = stack.envs().iter().copied().filter(|&entry| !is_bootstrap_env(entry)); match bootstrap.target { @@ -175,15 +208,9 @@ mod runtime { envs: Vec::new_in(bump), }; - let resolved = resolve_exec(&mut exec, Some(CWD), ExecAtFlags::empty(), |p| { + let resolved = match 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()); @@ -191,32 +218,44 @@ mod runtime { } }; - 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( + let on_ready = || { + scrub_bootstrap_env(&bootstrap_entries); + 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) }); + } + }; + + // SAFETY: fresh single-threaded freestanding launcher; + // `try_exec_elf` copies strings onto the new stack before + // invoking `on_ready` and abandoning ours. + match unsafe { + fspy_elf_loader::try_exec_elf( resolved.file, execfn, argv.into_iter(), filtered_envs, stack.auxv(), Some(INTERCEPTOR), + on_ready, ) + } { + Ok(never) => match never {}, + Err(err) => { + write_error_pipe(error_pipe_fd, err.raw_os_error()); + exit_group(127); + } } } Target::ResolvedFd { fd, execfn, sigmask } => { @@ -227,22 +266,41 @@ mod runtime { 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( + // SAFETY: fresh single-threaded freestanding launcher; + // `try_exec_elf` copies strings onto the new stack before + // invoking `on_ready` and abandoning ours. + match unsafe { + fspy_elf_loader::try_exec_elf( file, execfn_cstr.as_c_str().as_thin(), stack.args().iter().copied(), filtered_envs, stack.auxv(), Some(INTERCEPTOR), + || scrub_bootstrap_env(&bootstrap_entries), ) + } { + Ok(never) => match never {}, + Err(err) => panic!("exec_elf failed: {err:?}"), } } } } + fn scrub_bootstrap_env(entries: &[(*mut u8, usize)]) { + for &(ptr, len) in entries { + for i in 0..len { + // SAFETY: `ptr..ptr+len` is a `__FSPY_BOOTSTRAP=...` string on + // our writable initial kernel stack. `try_exec_elf` has already + // finished reading `filtered_envs` and built the target stack, + // so nothing aliases these bytes. Volatile writes prevent + // dead-store elimination before entering the target, keeping + // the bootstrap payload out of `/proc/self/environ`. + unsafe { ptr.add(i).write_volatile(0) }; + } + } + } + fn is_bootstrap_env(entry: CStr<'_, Thin>) -> bool { let bytes = entry.count().as_units(); bytes @@ -338,6 +396,7 @@ mod runtime { match flags & O_ACCMODE { O_RDWR => AccessMode::ReadWrite, O_WRONLY => AccessMode::Write, + O_RDONLY if (flags & (O_CREAT | O_TRUNC)) != 0 => AccessMode::ReadWrite, _ => AccessMode::Read, } } @@ -493,7 +552,13 @@ mod runtime { 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 => { + Sysno::renameat => { + report_path_at(dirfd(2), a[3], AccessMode::RenameTarget, false); + } + Sysno::renameat2 => { + if (arg_u32(a[4]) & RENAME_EXCHANGE) != 0 { + report_path_at(dirfd(0), a[1], AccessMode::RenameTarget, false); + } report_path_at(dirfd(2), a[3], AccessMode::RenameTarget, false); } #[cfg(target_arch = "x86_64")] @@ -523,6 +588,37 @@ mod runtime { report_path_at(dirfd, path_ptr, mode, false); } + #[expect( + clippy::cast_possible_truncation, + clippy::cast_possible_wrap, + reason = "Linux pid_t is a positive 32-bit signed integer" + )] + #[inline] + fn current_pid() -> i32 { + // SAFETY: `getpid` takes no arguments and always succeeds. + unsafe { syscalls::raw::syscall0(Sysno::getpid as usize) as i32 } + } + + #[inline] + fn shares_vm_with(my_pid: i32, other_pid: i32) -> bool { + if my_pid <= 0 || other_pid <= 0 { + return false; + } + // SAFETY: `kcmp(pid1, pid2, KCMP_VM, 0, 0)` takes integer arguments + // only and returns `0` iff both processes share the same `mm_struct`. + let rc = unsafe { + syscalls::raw::syscall5( + Sysno::kcmp as usize, + my_pid.cast_unsigned() as usize, + other_pid.cast_unsigned() as usize, + KCMP_VM, + 0, + 0, + ) + }; + rc == 0 + } + #[inline] fn set_tid_address(addr: *const AtomicI32) { // SAFETY: `addr` is either null or points to a live `AtomicI32` that @@ -562,6 +658,34 @@ mod runtime { } } + /// `fspy_elf_loader` hook invoked in the parent right after a trapped + /// `clone(CLONE_VM | CLONE_VFORK, non_null_stack)` returns with + /// `child_pid > 0` (once the child has already left the parent's + /// `mm_struct`). + unsafe fn reclaim_vfork_child(child_pid: i32) { + 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. + let reclaimable = unsafe { + (*cur).owner_pid == child_pid || (*cur).active_tid.load(Ordering::Acquire) == 0 + }; + if reclaimable { + // SAFETY: `child_pid` has already exited or exec'd (or failure + // cleanup released the node), so nothing references `cur`. + unsafe { free_exec_scratch(cur) }; + } else { + // SAFETY: `cur` is still in use by another child; park it again. + unsafe { push_parked_exec_scratch(cur) }; + } + cur = next; + } + } + /// 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. @@ -569,15 +693,20 @@ mod runtime { if PARKED_EXEC_SCRATCH.load(Ordering::Acquire).is_null() { return; } + let my_pid = current_pid(); 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 { + let reclaimable = unsafe { + (*cur).active_tid.load(Ordering::Acquire) == 0 + || (!(*cur).used_set_tid_address && !shares_vm_with(my_pid, (*cur).owner_pid)) + }; + if reclaimable { // 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. + // `duped_fd` / `extra_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. @@ -592,17 +721,24 @@ mod runtime { 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. + // the calling thread, and `duped_fd`/`extra_fd` are 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)); } + let extra = *(*node).extra_fd.get(); + *(*node).extra_fd.get() = -1; + if extra >= 0 { + drop(OwnedFd::from_raw_fd(extra)); + } if (*node).parked { - // Already published: release its arena and let a later - // reclaim free the node. - set_tid_address(ptr::null()); + // Already published: release its arena and mark reclaimable. + if (*node).used_set_tid_address { + set_tid_address(ptr::null()); + } *(*node).arena.get() = None; (*node).active_tid.store(0, Ordering::Release); } else { @@ -633,14 +769,17 @@ mod runtime { node.write(ExecScratch { next: AtomicPtr::new(ptr::null_mut()), active_tid: AtomicI32::new(0), + owner_pid: 0, parked: false, + used_set_tid_address: false, arena: UnsafeCell::new(Some(page_bump())), duped_fd: UnsafeCell::new(-1), + extra_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) = + let (raw_out, duped_fd, extra_fd) = match prepare_exec_in(dirfd, prog_ptr, argv_ptr, envp_ptr, flags, sigmask, arena) { Ok(prepared) => prepared, Err(err) => { @@ -652,11 +791,19 @@ mod runtime { // SAFETY: the node is owned by this thread until published below. unsafe { *(*node).duped_fd.get() = duped_fd; + *(*node).extra_fd.get() = extra_fd; if is_shared_vm_child { + let use_set_tid = !KCMP_VM_AVAILABLE.load(Ordering::Relaxed); + (*node).owner_pid = current_pid(); (*node).parked = true; + (*node).used_set_tid_address = use_set_tid; (*node).active_tid.store(1, Ordering::Release); + if use_set_tid { + // Register before publishing so `SIGKILL` cannot leave a + // permanently parked node with `active_tid == 1`. + set_tid_address(&raw const (*node).active_tid); + } push_parked_exec_scratch(node); - set_tid_address(&raw const (*node).active_tid); } } Ok(SyscallAction::Execve { @@ -675,7 +822,7 @@ mod runtime { flags: ExecAtFlags, sigmask: u64, arena: &'static PageBump, - ) -> Result<(RawExec, RawFd)> { + ) -> Result<(RawExec, RawFd, RawFd)> { let raw = RawExec { prog: ptr::with_exposed_provenance(prog_ptr), argv: ptr::with_exposed_provenance(argv_ptr), @@ -691,8 +838,9 @@ mod runtime { // 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. + // (and any `resolved.extra_fd`) automatically; once handed back as raw + // fds, `cleanup_exec_scratch` closes them on `SYS_execve` failure while + // a successful exec transfers them to the child. let duped_fd = fcntl_dupfd(resolved.file.as_fd(), 3)?; let rt = runtime(); @@ -712,7 +860,9 @@ mod runtime { 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(); + let extra_raw = resolved.extra_fd.as_ref().map_or(-1, OwnedFd::as_raw_fd); core::mem::forget(duped_fd); - Ok((raw_out, duped_raw)) + core::mem::forget(resolved.extra_fd); + Ok((raw_out, duped_raw, extra_raw)) } } diff --git a/crates/fspy_shared_unix/src/linux.rs b/crates/fspy_shared_unix/src/linux.rs index 865a782a3..e2d762db7 100644 --- a/crates/fspy_shared_unix/src/linux.rs +++ b/crates/fspy_shared_unix/src/linux.rs @@ -7,12 +7,13 @@ 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, + AccessFlags, Mode, OFlags, faccessat, fcntl_dupfd, fcntl_dupfd_cloexec, fcntl_is_cloexec, + fstat, openat, }, }; use fspy_nostd_alloc::{ CString, - fs::{fd_path, resolve_path_at}, + fs::{fd_path, format_proc_self_fd, resolve_path_at}, }; use fspy_shared::ipc::{IpcStr, channel::ChannelConf}; use wincode::{SchemaRead, SchemaWrite}; @@ -47,11 +48,18 @@ bitflags! { } } -/// Output of [`resolve_exec`]: the open final binary descriptor and the -/// original execution name for `AT_EXECFN`. +/// Output of [`resolve_exec`]. +/// +/// Contains the open final binary descriptor, the original execution name for +/// `AT_EXECFN`, and any extra non-`CLOEXEC` readable script descriptor opened +/// when `execveat(..., AT_EMPTY_PATH)` targeted an `O_PATH` `#!` script. pub struct ResolvedExec { pub file: OwnedFd, pub execfn: Vec, + /// Readable non-`CLOEXEC` duplicate of an `O_PATH` shebang script passed to + /// the interpreter as `/dev/fd/`. Kept open across `SYS_execve` and + /// closed on exec failure. + pub extra_fd: Option, } /// What the freshly exec'd `fspy_preload_linux` binary should load and run. @@ -120,12 +128,12 @@ impl<'a> Bootstrap<'a> { } } -/// Ensures [`BOOTSTRAP_ENV_NAME`] is set to `encoded` on `envs`. +/// Ensures [`BOOTSTRAP_ENV_NAME`] is set to `encoded` on `envs`, overwriting +/// and deduplicating any existing entries. /// /// # Errors /// -/// Returns [`Error::INVAL`] if [`BOOTSTRAP_ENV_NAME`] is already present with a -/// different value. +/// Returns [`Error::NOMEM`] if storage cannot be allocated. pub fn ensure_bootstrap_env( envs: &mut Vec, A>, encoded: &str, @@ -161,17 +169,20 @@ pub fn resolve_exec( 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() { + let (execfn, extra_fd, 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), + EmptyPathStep::Shebang { execfn, extra_fd } => { + (execfn, extra_fd, 1usize, Some(CWD), false) + } } } else { let execfn = to_vec_in(&exec.program, allocator.clone()); - (execfn, 0usize, dirfd, flags.contains(ExecAtFlags::SYMLINK_NOFOLLOW)) + (execfn, None, 0usize, dirfd, flags.contains(ExecAtFlags::SYMLINK_NOFOLLOW)) }; loop { @@ -220,13 +231,13 @@ pub fn resolve_exec( continue; } - return Ok(ResolvedExec { file, execfn }); + return Ok(ResolvedExec { file, execfn, extra_fd }); } } enum EmptyPathStep { Resolved(ResolvedExec), - Shebang { execfn: Vec }, + Shebang { execfn: Vec, extra_fd: Option }, } fn resolve_empty_path( @@ -252,8 +263,8 @@ fn resolve_empty_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), + let (file, n, reopened_from_o_path) = match pread_header(fd, peek_buf) { + Ok(n) => (fcntl_dupfd_cloexec(fd, 0)?, n, false), Err(Error::BADF) => { // `fd` may have been opened with `O_PATH`; reopen read-only via `/proc/self/fd`. let reopened = openat( @@ -263,7 +274,7 @@ fn resolve_empty_path( Mode::empty(), )?; let n = pread_header(reopened.as_fd(), peek_buf)?; - (reopened, n) + (reopened, n, true) } Err(err) => return Err(err), }; @@ -276,23 +287,34 @@ fn resolve_empty_path( let Some(shebang) = parse_shebang_bytes(&peek_buf[..n], ParseShebangOptions::linux(), allocator.clone())? else { - return Ok(EmptyPathStep::Resolved(ResolvedExec { file, execfn })); + return Ok(EmptyPathStep::Resolved(ResolvedExec { file, execfn, extra_fd: None })); }; - 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); + + // If `fd` was opened with `O_PATH`, the interpreter cannot read through + // `/dev/fd/` (`EBADF`); hand it a non-`CLOEXEC` duplicate of the + // readable descriptor we reopened above instead. + let (script_fd_num, extra_fd) = if reopened_from_o_path { + let readable = fcntl_dupfd(file.as_fd(), 3)?; + drop(file); + let readable_num = u32::try_from(readable.as_raw_fd()).map_err(|_| Error::BADF)?; + (readable_num, Some(readable)) + } else { + drop(file); + (raw_fd, None) + }; + let script_arg = format_dev_fd(script_fd_num, allocator); apply_shebang(exec, shebang, script_arg); - Ok(EmptyPathStep::Shebang { execfn }) + Ok(EmptyPathStep::Shebang { execfn, extra_fd }) } -/// 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. +/// Copies `bytes` into a NUL-terminated [`CString`], rejecting interior NULs +/// with [`Error::NOENT`]. fn bytes_to_cstring( bytes: &[u8], allocator: A, @@ -304,36 +326,14 @@ fn bytes_to_cstring( 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) + let proc_fd = format_proc_self_fd(&mut buf, fd).count().as_units(); + let digits = proc_fd.strip_prefix(b"/proc/self/fd/").unwrap_or(proc_fd); + let mut out = Vec::with_capacity_in(b"/dev/fd/".len() + digits.len(), allocator); + out.extend_from_slice(b"/dev/fd/"); + out.extend_from_slice(digits); + out } #[cfg(all(test, target_os = "linux"))] @@ -342,7 +342,7 @@ mod tests { fs::{self, File, Permissions}, os::unix::{ ffi::OsStrExt as _, - fs::{PermissionsExt as _, symlink}, + fs::{OpenOptionsExt as _, PermissionsExt as _, symlink}, io::AsRawFd as _, }, path::Path, @@ -495,5 +495,24 @@ mod tests { resolve_exec(&mut exec, Some(script_fd), ExecAtFlags::EMPTY_PATH, |_| {}).err(), Some(Error::NOENT) ); + + // AT_EMPTY_PATH on non-CLOEXEC O_PATH shebang script reopens readable + // and passes `/dev/fd/` (non-CLOEXEC) to the interpreter. + let o_path_cloexec = fs::OpenOptions::new() + .read(true) + .custom_flags(linux_raw_sys::general::O_PATH.cast_signed()) + .open(&script) + .unwrap(); + // SAFETY: `o_path_cloexec` remains open for the `fcntl_dupfd` call. + let o_path_borrowed = unsafe { BorrowedFd::borrow_raw(o_path_cloexec.as_raw_fd()) }; + let o_path_owned = fcntl_dupfd(o_path_borrowed, 3).unwrap(); + let mut exec = make_exec(b"", &[]); + let resolved = + resolve_exec(&mut exec, Some(o_path_owned.as_fd()), ExecAtFlags::EMPTY_PATH, |_| {}) + .unwrap(); + let extra = resolved.extra_fd.as_ref().expect("expected reopened readable script fd"); + assert!(!fcntl_is_cloexec(extra.as_fd()).unwrap()); + let expected_dev_fd = format!("/dev/fd/{}", extra.as_raw_fd()); + assert_eq!(exec.args.last().unwrap().as_slice(), expected_dev_fd.as_bytes()); } } diff --git a/crates/fspy_shared_unix/src/macos.rs b/crates/fspy_shared_unix/src/macos.rs index 8fe859d6b..5e113e84e 100644 --- a/crates/fspy_shared_unix/src/macos.rs +++ b/crates/fspy_shared_unix/src/macos.rs @@ -109,8 +109,7 @@ impl<'a> EncodedPayload<'a> { /// /// 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`). + /// or nested shebangs (`ENOEXEC`), or allocation failure (`ENOMEM`). pub fn prepare_exec( &self, exec: &mut Exec, diff --git a/crates/fspy_shared_unix/src/nostd_exec/mod.rs b/crates/fspy_shared_unix/src/nostd_exec/mod.rs index 48b11b16a..71f6736bb 100644 --- a/crates/fspy_shared_unix/src/nostd_exec/mod.rs +++ b/crates/fspy_shared_unix/src/nostd_exec/mod.rs @@ -11,6 +11,10 @@ use fspy_nostd::{CStr, Error, Result, Thin}; /// `environ` does not contain a `=` byte. pub type Env = (Vec, Option>); +/// Minimum valid user-space address (page 0 is never mapped, matching +/// `fspy_elf_loader`'s `usermem::user_cstr`). +const MIN_USER_ADDR: usize = 4096; + /// 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); @@ -18,6 +22,13 @@ pub fn to_vec_in(bytes: &[u8], allocator: A) -> Vec { vec } +fn try_to_vec_in(bytes: &[u8], allocator: A) -> Result> { + let mut vec = Vec::new_in(allocator); + vec.try_reserve_exact(bytes.len()).map_err(|_| Error::NOMEM)?; + vec.extend_from_slice(bytes); + Ok(vec) +} + /// An exec call's program, arguments, and environment. /// /// The strings live in `A`, so preloads and signal handlers can keep them in a @@ -50,17 +61,27 @@ impl RawExec { unsafe fn collect_c_str_array( strs: *const *const c_char, allocator: A, - mut map_fn: impl FnMut(&[u8]) -> T, + mut map_fn: impl FnMut(&[u8]) -> Result, ) -> Result> { if strs.is_null() { return Ok(Vec::new_in(allocator)); } + if strs.addr() < MIN_USER_ADDR { + return Err(Error::FAULT); + } 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() { + loop { + // SAFETY: `cur_str` points into a valid NULL-terminated array of C + // string pointers (the `argv`/`envp` convention). + let entry_ptr = unsafe { *cur_str }; + if entry_ptr.is_null() { + break; + } + if entry_ptr.addr() < MIN_USER_ADDR { + return Err(Error::FAULT); + } count += 1; // SAFETY: advancing within the bounds of the NULL-terminated array. cur_str = unsafe { cur_str.add(1) }; @@ -71,10 +92,10 @@ impl RawExec { 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. + // SAFETY: `entry_ptr` is non-null and `>= MIN_USER_ADDR` (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)); + str_vec.push(map_fn(bytes)?); } Ok(str_vec) } @@ -96,34 +117,36 @@ impl RawExec { /// 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. + /// Returns [`Error::FAULT`] when `prog` is in page 0 (`< 4096`, including + /// null) or when a non-null `argv`/`envp` array or entry lies in page 0. + /// 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. + /// Returns [`Error::FAULT`] for invalid first-page pointers, 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. + /// When non-null and outside page 0, `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() { + if self.prog.addr() < MIN_USER_ADDR { return Err(Error::FAULT); } - // SAFETY: `self.prog` is non-null and points to a valid NUL-terminated - // C string, as required by the caller. + // SAFETY: `self.prog` is outside page 0 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()); + let program = try_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()) + try_to_vec_in(arg, allocator.clone()) }) }?; @@ -131,15 +154,14 @@ impl RawExec { // 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())), - ) - }, - ) + if let Some(eq_pos) = env.iter().position(|b| *b == b'=') { + Ok(( + try_to_vec_in(&env[..eq_pos], allocator.clone())?, + Some(try_to_vec_in(&env[(eq_pos + 1)..], allocator.clone())?), + )) + } else { + Ok((try_to_vec_in(env, allocator.clone())?, None)) + } }) }?; @@ -170,28 +192,40 @@ impl RawExec { } } -/// 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`]. +/// Ensures an environment variable is set to `value`, overwriting and +/// deduplicating any existing entries with the same `name`. /// /// # Errors /// -/// Returns [`Error::INVAL`] when `name` already exists with a different value. +/// Returns [`Error::NOMEM`] if storage cannot be allocated. 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)))); + let mut updated = false; + let mut i = 0; + while i < envs.len() { + if envs[i].0.as_bstr() == name { + if updated { + envs.remove(i); + continue; + } + if envs[i].1.as_deref() != Some(value) { + envs[i].1 = Some(try_to_vec_in(value, allocator.clone())?); + } + updated = true; + } + i += 1; + } + if !updated { + envs.try_reserve(1).map_err(|_| Error::NOMEM)?; + envs.push(( + try_to_vec_in(name, allocator.clone())?, + Some(try_to_vec_in(value, allocator)?), + )); + } Ok(()) } @@ -346,4 +380,54 @@ mod tests { remove_path_env(&mut envs, b"DYLD_INSERT_LIBRARIES", b"/ours.dylib"); assert_eq!(envs[0].1.as_deref(), Some(b"/user1.dylib:/user2.dylib".as_slice())); } + + #[test] + fn raw_exec_rejects_first_page_pointers() { + let low = ptr::with_exposed_provenance::(0x10); + let low_arr = ptr::with_exposed_provenance::<*const c_char>(0x10); + + let bad_prog = RawExec { prog: low, argv: ptr::null(), envp: ptr::null() }; + // SAFETY: `to_exec` rejects pointers in page 0 without dereferencing them. + assert_eq!(unsafe { bad_prog.to_exec(Global) }.unwrap_err(), Error::FAULT); + + let bad_argv = RawExec { prog: c"/bin/true".as_ptr(), argv: low_arr, envp: ptr::null() }; + // SAFETY: `to_exec` rejects non-null `argv` in page 0 without dereferencing. + assert_eq!(unsafe { bad_argv.to_exec(Global) }.unwrap_err(), Error::FAULT); + + let bad_envp = RawExec { prog: c"/bin/true".as_ptr(), argv: ptr::null(), envp: low_arr }; + // SAFETY: `to_exec` rejects non-null `envp` in page 0 without dereferencing. + assert_eq!(unsafe { bad_envp.to_exec(Global) }.unwrap_err(), Error::FAULT); + + let bad_elem_arr = [low, ptr::null()]; + let bad_elem = + RawExec { prog: c"/bin/true".as_ptr(), argv: bad_elem_arr.as_ptr(), envp: ptr::null() }; + // SAFETY: `bad_elem_arr` is a readable NULL-terminated array; `to_exec` + // rejects the first-page element pointer without dereferencing it. + assert_eq!(unsafe { bad_elem.to_exec(Global) }.unwrap_err(), Error::FAULT); + } + + #[test] + fn ensure_env_inserts_overwrites_and_deduplicates() { + let mut envs: Vec, Global> = Vec::new_in(Global); + ensure_env(&mut envs, b"__FSPY_BOOTSTRAP", b"v1").unwrap(); + assert_eq!(envs.len(), 1); + assert_eq!(envs[0].0.as_slice(), b"__FSPY_BOOTSTRAP"); + assert_eq!(envs[0].1.as_deref(), Some(b"v1".as_slice())); + + // Idempotent when value matches. + ensure_env(&mut envs, b"__FSPY_BOOTSTRAP", b"v1").unwrap(); + assert_eq!(envs.len(), 1); + + // Overwrites a different value and deduplicates multiple occurrences + // (including bare entries without `=`), preserving unrelated variables. + envs.push((to_vec_in(b"KEEP", Global), Some(to_vec_in(b"ok", Global)))); + envs.push((to_vec_in(b"__FSPY_BOOTSTRAP", Global), None)); + envs.push((to_vec_in(b"__FSPY_BOOTSTRAP", Global), Some(to_vec_in(b"stale", Global)))); + ensure_env(&mut envs, b"__FSPY_BOOTSTRAP", b"v2").unwrap(); + assert_eq!(envs.len(), 2); + assert_eq!(envs[0].0.as_slice(), b"__FSPY_BOOTSTRAP"); + assert_eq!(envs[0].1.as_deref(), Some(b"v2".as_slice())); + assert_eq!(envs[1].0.as_slice(), b"KEEP"); + assert_eq!(envs[1].1.as_deref(), Some(b"ok".as_slice())); + } } diff --git a/crates/fspy_shared_unix/src/nostd_exec/open.rs b/crates/fspy_shared_unix/src/nostd_exec/open.rs index 7d231e88a..33484c5e2 100644 --- a/crates/fspy_shared_unix/src/nostd_exec/open.rs +++ b/crates/fspy_shared_unix/src/nostd_exec/open.rs @@ -47,8 +47,8 @@ pub fn pread_header(fd: BorrowedFd<'_>, buf: &mut [u8]) -> Result { /// absolute), 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") + not(target_os = "macos"), + expect(dead_code, reason = "used by macOS posix_spawn chdir path normalization") )] pub fn join_relative_to_base( base_dir: &[u8], From 11c8d7cb187b723b30b72da75a872e25d3ef35aa Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 18:13:19 +0800 Subject: [PATCH 14/48] fix(fspy): tighten kcmp error handling, preload rematerialize, and RawExec second pass Co-authored-by: Gemini 4 Neon --- crates/fspy/src/linux/mod.rs | 12 ++++++++- crates/fspy_preload_linux/src/main.rs | 25 ++++++++++++------- crates/fspy_shared_unix/src/nostd_exec/mod.rs | 12 +++++++-- 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index a4f8710df..d2022ab61 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -93,9 +93,19 @@ impl SpyImpl { mut command: Command, cancellation_token: CancellationToken, ) -> Result { - let Some(preload_path) = self.preload_path() else { + let Some(mut preload_path) = self.preload_path() else { return spawn_untracked(command, cancellation_token); }; + // If the cached launcher binary was removed mid-process (e.g. by + // `systemd-tmpfiles`), re-materialize before building `tokio_command` + // so both `Bootstrap` and `redirect_program` pick up any new fallback + // directory path. + if !Path::new(preload_path.as_os_str()).exists() { + match self.rematerialize_preload(&preload_path) { + Some(new_path) => preload_path = new_path, + None => return spawn_untracked(command, cancellation_token), + } + } let ipc_receiver = channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) .map_err(SpawnError::ChannelCreation)?; diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index 96bf92bd9..0ef5f0653 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -605,18 +605,25 @@ mod runtime { return false; } // SAFETY: `kcmp(pid1, pid2, KCMP_VM, 0, 0)` takes integer arguments - // only and returns `0` iff both processes share the same `mm_struct`. - let rc = unsafe { - syscalls::raw::syscall5( - Sysno::kcmp as usize, - my_pid.cast_unsigned() as usize, - other_pid.cast_unsigned() as usize, + // only and returns `0` iff both processes share the same `mm_struct`, + // `1..=3` for distinct `mm_struct`s, or `-errno` on failure. + match unsafe { + syscalls::syscall!( + Sysno::kcmp, + my_pid.cast_unsigned(), + other_pid.cast_unsigned(), KCMP_VM, 0, - 0, + 0 ) - }; - rc == 0 + } { + Ok(0) => true, + Ok(_) | Err(syscalls::Errno::ESRCH) => false, + // Treat any other error (`EPERM`, `EINVAL`, `ENOSYS`, etc.) + // conservatively as still sharing VM so a live `CLONE_VM` child's + // exec scratch is never freed prematurely. + Err(_) => true, + } } #[inline] diff --git a/crates/fspy_shared_unix/src/nostd_exec/mod.rs b/crates/fspy_shared_unix/src/nostd_exec/mod.rs index 71f6736bb..aacdff3c3 100644 --- a/crates/fspy_shared_unix/src/nostd_exec/mod.rs +++ b/crates/fspy_shared_unix/src/nostd_exec/mod.rs @@ -92,8 +92,16 @@ impl RawExec { 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 and `>= MIN_USER_ADDR` (verified - // by the counting loop) and points to a valid NUL-terminated C string. + // Re-verify against concurrent mutation in multithreaded callers + // between the counting pass and this copy pass. + if entry_ptr.is_null() { + break; + } + if entry_ptr.addr() < MIN_USER_ADDR { + return Err(Error::FAULT); + } + // SAFETY: `entry_ptr` is non-null and `>= MIN_USER_ADDR` 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)?); } From aac1eabb8775918d156a036fbc47a5c5edae6447 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 18:20:29 +0800 Subject: [PATCH 15/48] fix(fspy): propagate virtualized SIGSYS SIG_IGN across tracked execve Co-authored-by: Gemini 4 Neon --- crates/fspy_preload_linux/src/main.rs | 70 +++++++++++++++++++++++---- crates/fspy_shared_unix/src/linux.rs | 12 +++-- 2 files changed, 67 insertions(+), 15 deletions(-) diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index 0ef5f0653..d9167d27f 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -258,12 +258,13 @@ mod runtime { } } } - Target::ResolvedFd { fd, execfn, sigmask } => { + Target::ResolvedFd { fd, execfn, sigmask, sigsys_ignored } => { 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_sigsys_ignored(sigsys_ignored); restore_sigmask(sigmask); // SAFETY: fresh single-threaded freestanding launcher; @@ -341,6 +342,34 @@ mod runtime { } } + fn restore_sigsys_ignored(sigsys_ignored: bool) { + #[repr(C)] + struct KernelSigaction { + handler: usize, + flags: usize, + restorer: usize, + mask: u64, + } + if !sigsys_ignored { + return; + } + let ign = KernelSigaction { handler: 1, flags: 0, restorer: 0, mask: 0 }; + // SAFETY: `ign` is a valid stack-local kernel `sigaction` with `SIG_IGN` + // (`1`). Executing from inside the launcher's `PF_X` allowlist bypasses + // the inherited seccomp filter, and `try_exec_elf`'s `sigsys::install` + // will record `SIG_IGN` in the virtualized table before installing our + // handler. + let _ = unsafe { + syscalls::syscall!( + Sysno::rt_sigaction, + linux_raw_sys::general::SIGSYS, + &raw const ign, + 0usize, + size_of::() + ) + }; + } + 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 @@ -462,6 +491,7 @@ mod runtime { call.args[2], ExecAtFlags::empty(), call.sigmask(), + call.sigsys_ignored(), call.is_shared_vm_child(), ), Sysno::execveat => { @@ -489,6 +519,7 @@ mod runtime { call.args[3], flags, call.sigmask(), + call.sigsys_ignored(), call.is_shared_vm_child(), ) } @@ -758,6 +789,10 @@ mod runtime { /// `fspy_preload_linux`, returning [`SyscallAction::Execve`] so /// `fspy_elf_loader` releases the private `SIGSYS` stack before executing /// the replacement `SYS_execve`. + #[expect( + clippy::too_many_arguments, + reason = "forwards raw trapped execve/execveat arguments plus caller signal state" + )] fn handle_exec( dirfd: Option>, prog_ptr: usize, @@ -765,6 +800,7 @@ mod runtime { envp_ptr: usize, flags: ExecAtFlags, sigmask: u64, + sigsys_ignored: bool, is_shared_vm_child: bool, ) -> Result { reclaim_exec_scratch(); @@ -786,15 +822,23 @@ mod runtime { } // 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, extra_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); - } - }; + let (raw_out, duped_fd, extra_fd) = match prepare_exec_in( + dirfd, + prog_ptr, + argv_ptr, + envp_ptr, + flags, + sigmask, + sigsys_ignored, + 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; @@ -821,6 +865,10 @@ mod runtime { }) } + #[expect( + clippy::too_many_arguments, + reason = "forwards raw trapped execve/execveat arguments plus caller signal state" + )] fn prepare_exec_in( dirfd: Option>, prog_ptr: usize, @@ -828,6 +876,7 @@ mod runtime { envp_ptr: usize, flags: ExecAtFlags, sigmask: u64, + sigsys_ignored: bool, arena: &'static PageBump, ) -> Result<(RawExec, RawFd, RawFd)> { let raw = RawExec { @@ -855,6 +904,7 @@ mod runtime { fd: duped_fd.as_raw_fd(), execfn: IpcStr::from_bytes(&resolved.execfn), sigmask, + sigsys_ignored, }; let bootstrap = Bootstrap { ipc_channel_conf: rt.ipc_channel_conf, diff --git a/crates/fspy_shared_unix/src/linux.rs b/crates/fspy_shared_unix/src/linux.rs index e2d762db7..18b4f3f6f 100644 --- a/crates/fspy_shared_unix/src/linux.rs +++ b/crates/fspy_shared_unix/src/linux.rs @@ -71,8 +71,9 @@ pub enum Target<'a> { 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 }, + /// `sigmask` is the calling thread's virtualized signal mask prior to exec, + /// and `sigsys_ignored` records whether virtualized `SIGSYS` was `SIG_IGN`. + ResolvedFd { fd: RawFd, execfn: &'a IpcStr, sigmask: u64, sigsys_ignored: bool }, } /// Bootstrap configuration passed into `fspy_preload_linux` via @@ -375,7 +376,7 @@ mod tests { let cases = [ Target::Unresolved { path: target_path, error_pipe_fd: 7 }, - Target::ResolvedFd { fd: 9, execfn, sigmask: 0x5678 }, + Target::ResolvedFd { fd: 9, execfn, sigmask: 0x5678, sigsys_ignored: true }, ]; for target in cases { @@ -406,12 +407,13 @@ mod tests { assert_eq!(f1, f2); } ( - Target::ResolvedFd { fd: f1, execfn: e1, sigmask: m1 }, - Target::ResolvedFd { fd: f2, execfn: e2, sigmask: m2 }, + Target::ResolvedFd { fd: f1, execfn: e1, sigmask: m1, sigsys_ignored: i1 }, + Target::ResolvedFd { fd: f2, execfn: e2, sigmask: m2, sigsys_ignored: i2 }, ) => { assert_eq!(f1, f2); assert_eq!(e1.as_bytes(), e2.as_bytes()); assert_eq!(m1, m2); + assert_eq!(i1, i2); } _ => panic!("mismatched target variant"), } From 19f4f323289e81d12dc1e00f2474fc96574f8e12 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 18:26:43 +0800 Subject: [PATCH 16/48] test(fspy_shared_unix): open O_PATH fd directly via openat so musl OpenOptions does not mask it Co-authored-by: Gemini 4 Neon --- crates/fspy_shared_unix/src/linux.rs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/fspy_shared_unix/src/linux.rs b/crates/fspy_shared_unix/src/linux.rs index 18b4f3f6f..c40417e33 100644 --- a/crates/fspy_shared_unix/src/linux.rs +++ b/crates/fspy_shared_unix/src/linux.rs @@ -343,7 +343,7 @@ mod tests { fs::{self, File, Permissions}, os::unix::{ ffi::OsStrExt as _, - fs::{OpenOptionsExt as _, PermissionsExt as _, symlink}, + fs::{PermissionsExt as _, symlink}, io::AsRawFd as _, }, path::Path, @@ -500,14 +500,16 @@ mod tests { // AT_EMPTY_PATH on non-CLOEXEC O_PATH shebang script reopens readable // and passes `/dev/fd/` (non-CLOEXEC) to the interpreter. - let o_path_cloexec = fs::OpenOptions::new() - .read(true) - .custom_flags(linux_raw_sys::general::O_PATH.cast_signed()) - .open(&script) - .unwrap(); - // SAFETY: `o_path_cloexec` remains open for the `fcntl_dupfd` call. - let o_path_borrowed = unsafe { BorrowedFd::borrow_raw(o_path_cloexec.as_raw_fd()) }; - let o_path_owned = fcntl_dupfd(o_path_borrowed, 3).unwrap(); + // Open directly via `openat(O_PATH)` because Rust's `OpenOptions::custom_flags` + // masks off `O_ACCMODE`, which on musl includes `O_PATH` (`O_SEARCH`). + let script_c = bytes_to_cstring(script.as_os_str().as_bytes(), Global).unwrap(); + let o_path_owned = openat( + CWD, + script_c.as_c_str().as_thin(), + OFlags::from_bits_retain(linux_raw_sys::general::O_PATH), + Mode::empty(), + ) + .unwrap(); let mut exec = make_exec(b"", &[]); let resolved = resolve_exec(&mut exec, Some(o_path_owned.as_fd()), ExecAtFlags::EMPTY_PATH, |_| {}) From 74fe011e039832bdab2ac156c8ea1c3e87d0910d Mon Sep 17 00:00:00 2001 From: wan9chi Date: Fri, 27 Nov 2026 18:38:24 +0800 Subject: [PATCH 17/48] fix(fspy_preload_linux): probe kcmp directly so EPERM/ENOSYS arms set_tid_address fallback Co-authored-by: Gemini 4 Neon --- crates/fspy_preload_linux/src/main.rs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index d9167d27f..0b93a7391 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -168,7 +168,7 @@ mod runtime { // SAFETY: `run` executes once in a fresh single-threaded process. let bump: &'static PageBump = unsafe { &*STARTUP_BUMP.0.get() }; let pid = current_pid(); - KCMP_VM_AVAILABLE.store(shares_vm_with(pid, pid), Ordering::Relaxed); + KCMP_VM_AVAILABLE.store(pid > 0 && kcmp_vm(pid, pid) == Ok(0), Ordering::Relaxed); let bootstrap = Bootstrap::from_env(stack.envs(), bump); let sender = bootstrap.ipc_channel_conf.sender(bump); @@ -631,23 +631,28 @@ mod runtime { } #[inline] - fn shares_vm_with(my_pid: i32, other_pid: i32) -> bool { - if my_pid <= 0 || other_pid <= 0 { - return false; - } + fn kcmp_vm(pid1: i32, pid2: i32) -> core::result::Result { // SAFETY: `kcmp(pid1, pid2, KCMP_VM, 0, 0)` takes integer arguments // only and returns `0` iff both processes share the same `mm_struct`, // `1..=3` for distinct `mm_struct`s, or `-errno` on failure. - match unsafe { + unsafe { syscalls::syscall!( Sysno::kcmp, - my_pid.cast_unsigned(), - other_pid.cast_unsigned(), + pid1.cast_unsigned(), + pid2.cast_unsigned(), KCMP_VM, 0, 0 ) - } { + } + } + + #[inline] + fn shares_vm_with(my_pid: i32, other_pid: i32) -> bool { + if my_pid <= 0 || other_pid <= 0 { + return false; + } + match kcmp_vm(my_pid, other_pid) { Ok(0) => true, Ok(_) | Err(syscalls::Errno::ESRCH) => false, // Treat any other error (`EPERM`, `EINVAL`, `ENOSYS`, etc.) From c9a2fb431eded68a399c739f8dcfd3262a4e7173 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 00:44:20 +0800 Subject: [PATCH 18/48] fix(fspy): match kernel AT_EXECFN, document 0111 limit, and make macOS SPAWN_CHDIRS fork-safe Co-authored-by: Gemini 4 Neon --- crates/fspy/README.md | 5 +- crates/fspy/tests/linux_hardening.rs | 159 +++++++++++++++ crates/fspy/tests/linux_syscalls.rs | 116 +++++++++++ crates/fspy/tests/macos_preload.rs | 117 +++++++++++ crates/fspy_elf_loader/README.md | 3 + .../src/interceptions/spawn/posix_spawn.rs | 192 +++++++++++++++--- crates/fspy_shared_unix/src/linux.rs | 106 +++++++++- 7 files changed, 660 insertions(+), 38 deletions(-) diff --git a/crates/fspy/README.md b/crates/fspy/README.md index 0589836c9..08ddb9a02 100644 --- a/crates/fspy/README.md +++ b/crates/fspy/README.md @@ -12,7 +12,10 @@ 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`. +reports `TrackingIncomplete`. Because seccomp sets `PR_SET_NO_NEW_PRIVS` and +userland ELF mapping opens target binaries read-only, setuid/setgid and +file-capability escalations do not apply, and execute-only (`chmod 0111`) +binaries cannot be mapped and fail with `EACCES`. ## macOS implementation diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs index 19ee75632..79cb144ad 100644 --- a/crates/fspy/tests/linux_hardening.rs +++ b/crates/fspy/tests/linux_hardening.rs @@ -611,3 +611,162 @@ async fn child_execve_with_stale_bootstrap_env_succeeds() -> anyhow::Result<()> assert_contains(&accesses, probe_path, fspy::PathAccess::Read); Ok(()) } + +#[test(tokio::test)] +async fn posix_spawn_setsigdef_resets_child_sigsys_without_mutating_parent() -> anyhow::Result<()> { + let probe_path = Path::new("/fspy-posix-spawn-sigdef-probe"); + let cmd = vt_subprocess_test::command_for_fn!( + probe_path.to_str().unwrap().to_owned(), + |probe_path: String| { + use std::{ffi::CString, os::unix::ffi::OsStrExt as _}; + + if std::env::var_os("FSPY_TEST_SPAWN_SIGDEF_CHILD").is_some() { + // Child requested `POSIX_SPAWN_SETSIGDEF` with `SIGSYS` + + // `POSIX_SPAWN_SETSIGMASK` with `SIGSYS | SIGUSR1`, so it must + // observe `SIGSYS == SIG_DFL` (not parent's `SIG_IGN`) and both + // signals blocked. + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut old: libc::sigaction = unsafe { std::mem::zeroed() }; + // SAFETY: querying current disposition for `SIGSYS`. + let rc = unsafe { libc::sigaction(libc::SIGSYS, std::ptr::null(), &raw mut old) }; + assert_eq!(rc, 0); + assert_eq!( + old.sa_sigaction, + libc::SIG_DFL, + "posix_spawn POSIX_SPAWN_SETSIGDEF did not reset child SIGSYS to SIG_DFL" + ); + + // SAFETY: `sigset_t` is a plain C struct valid when zeroed. + let mut cur_mask: libc::sigset_t = unsafe { std::mem::zeroed() }; + // SAFETY: querying current thread signal mask. + let mask_rc = unsafe { + libc::sigprocmask(libc::SIG_SETMASK, std::ptr::null(), &raw mut cur_mask) + }; + assert_eq!(mask_rc, 0); + // SAFETY: `cur_mask` was initialized by `sigprocmask`. + let sigsys_blocked = + unsafe { libc::sigismember(&raw const cur_mask, libc::SIGSYS) }; + assert_eq!( + sigsys_blocked, 1, + "posix_spawn POSIX_SPAWN_SETSIGMASK did not block SIGSYS" + ); + // SAFETY: `cur_mask` was initialized by `sigprocmask`. + let sigusr1_blocked = + unsafe { libc::sigismember(&raw const cur_mask, libc::SIGUSR1) }; + assert_eq!( + sigusr1_blocked, 1, + "posix_spawn POSIX_SPAWN_SETSIGMASK did not block SIGUSR1" + ); + + // Syscall tracking must keep working inside the spawned child. + let _ = std::fs::File::open(&probe_path); + return; + } + + // Parent sets `SIGSYS` to `SIG_IGN`. + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut ign: libc::sigaction = unsafe { std::mem::zeroed() }; + ign.sa_sigaction = libc::SIG_IGN; + // SAFETY: installing `SIG_IGN` for `SIGSYS`. + let ign_rc = + unsafe { libc::sigaction(libc::SIGSYS, &raw const ign, std::ptr::null_mut()) }; + assert_eq!(ign_rc, 0); + + let exe = std::fs::read_link("/proc/self/exe").unwrap(); + let prog = CString::new(exe.as_os_str().as_bytes()).unwrap(); + 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<*mut libc::c_char> = + args.iter().map(|s| s.as_ptr().cast_mut()).collect(); + argv.push(std::ptr::null_mut()); + + let mut env_cstrs: Vec = std::env::vars_os() + .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("FSPY_TEST_SPAWN_SIGDEF_CHILD=1").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()); + + // Configure `posix_spawnattr_t` with `POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK`. + // SAFETY: `posix_spawnattr_t` and `sigset_t` are plain C structs valid when zeroed. + let mut attr: libc::posix_spawnattr_t = unsafe { std::mem::zeroed() }; + // SAFETY: `sigset_t` is valid when zeroed. + let mut sigdef_set: libc::sigset_t = unsafe { std::mem::zeroed() }; + // SAFETY: `sigset_t` is valid when zeroed. + let mut sigmask_set: libc::sigset_t = unsafe { std::mem::zeroed() }; + let mut child_pid: libc::pid_t = 0; + let spawn_flags = + libc::c_short::try_from(libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK) + .unwrap(); + // SAFETY: valid stack-local `posix_spawnattr_t`, `sigset_t`, and C arrays. + let spawn_rc = unsafe { + assert_eq!(libc::posix_spawnattr_init(&raw mut attr), 0); + libc::sigemptyset(&raw mut sigdef_set); + libc::sigaddset(&raw mut sigdef_set, libc::SIGSYS); + libc::sigemptyset(&raw mut sigmask_set); + libc::sigaddset(&raw mut sigmask_set, libc::SIGSYS); + libc::sigaddset(&raw mut sigmask_set, libc::SIGUSR1); + assert_eq!(libc::posix_spawnattr_setflags(&raw mut attr, spawn_flags), 0); + assert_eq!( + libc::posix_spawnattr_setsigdefault(&raw mut attr, &raw const sigdef_set), + 0 + ); + assert_eq!( + libc::posix_spawnattr_setsigmask(&raw mut attr, &raw const sigmask_set), + 0 + ); + let rc = libc::posix_spawn( + &raw mut child_pid, + prog.as_ptr(), + std::ptr::null(), + &raw const attr, + argv.as_ptr(), + envp.as_ptr(), + ); + libc::posix_spawnattr_destroy(&raw mut attr); + rc + }; + assert_eq!(spawn_rc, 0, "posix_spawn failed with errno {spawn_rc}"); + + let mut status: libc::c_int = 0; + // SAFETY: `child_pid` is our child and `status` is writable. + let waited = unsafe { libc::waitpid(child_pid, &raw mut status, 0) }; + assert_eq!(waited, child_pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "posix_spawn child failed with status {status}" + ); + + // Parent must retain `SIGSYS == SIG_IGN`! + // SAFETY: `libc::sigaction` is a plain C struct valid when zeroed. + let mut parent_old: libc::sigaction = unsafe { std::mem::zeroed() }; + // SAFETY: querying parent's `SIGSYS` disposition. + let parent_rc = + unsafe { libc::sigaction(libc::SIGSYS, std::ptr::null(), &raw mut parent_old) }; + assert_eq!(parent_rc, 0); + assert_eq!( + parent_old.sa_sigaction, + libc::SIG_IGN, + "posix_spawn child clobbered parent's SIGSYS SIG_IGN" + ); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} diff --git a/crates/fspy/tests/linux_syscalls.rs b/crates/fspy/tests/linux_syscalls.rs index 2bc5a9a56..d8a4fbb1d 100644 --- a/crates/fspy/tests/linux_syscalls.rs +++ b/crates/fspy/tests/linux_syscalls.rs @@ -588,3 +588,119 @@ async fn legacy_x86_64_open_stat_lstat_syscalls_are_tracked() -> anyhow::Result< assert_includes(&accesses, &lstat_target, PathAccess::Read); Ok(()) } + +#[test(tokio::test)] +async fn execveat_sets_kernel_matching_at_execfn_while_preserving_proc_self_exe() +-> anyhow::Result<()> { + let cmd = vt_subprocess_test::command_for_fn!((), |()| { + use std::{ + ffi::{CStr, CString}, + os::{fd::AsRawFd as _, unix::ffi::OsStrExt as _}, + }; + + if let Some(expected_execfn) = std::env::var_os("FSPY_TEST_EXPECT_EXECFN") { + let expected_exe = std::env::var_os("FSPY_TEST_EXPECT_EXE").unwrap(); + // SAFETY: `getauxval(AT_EXECFN)` returns a pointer to the NUL-terminated + // `AT_EXECFN` string on the initial stack (or 0 if absent). + let raw = unsafe { libc::getauxval(libc::AT_EXECFN) }; + assert_ne!(raw, 0, "AT_EXECFN missing in execveat child"); + // SAFETY: non-zero `AT_EXECFN` points to a valid NUL-terminated C string. + let actual_execfn = unsafe { CStr::from_ptr(raw as *const libc::c_char) }; + assert_eq!( + actual_execfn.to_bytes(), + expected_execfn.as_bytes(), + "AT_EXECFN did not match Linux execveat format" + ); + let actual_exe = std::fs::read_link("/proc/self/exe").unwrap(); + assert_eq!( + actual_exe.as_os_str().as_bytes(), + expected_exe.as_bytes(), + "/proc/self/exe did not preserve real binary path" + ); + return; + } + + let exe = std::fs::read_link("/proc/self/exe").unwrap(); + let exe_dir = exe.parent().unwrap(); + let exe_name = exe.file_name().unwrap(); + + 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 base_envs: Vec = std::env::vars_os() + .filter(|(k, _)| k != "FSPY_TEST_EXPECT_EXECFN" && k != "FSPY_TEST_EXPECT_EXE") + .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(); + + let run_case = |dirfd: libc::c_int, + path: &CStr, + flags: libc::c_int, + expect_execfn: &str, + chdir_root: bool| { + let mut envs = base_envs.clone(); + envs.push(CString::new(format!("FSPY_TEST_EXPECT_EXECFN={expect_execfn}")).unwrap()); + let mut exe_env = b"FSPY_TEST_EXPECT_EXE=".to_vec(); + exe_env.extend_from_slice(exe.as_os_str().as_bytes()); + envs.push(CString::new(exe_env).unwrap()); + let mut envp: Vec<*const libc::c_char> = envs.iter().map(|s| s.as_ptr()).collect(); + envp.push(std::ptr::null()); + + // SAFETY: `fork()` followed by async-signal-safe `chdir`/`execveat`/`_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + // SAFETY: all pointers are valid NUL/NULL-terminated C strings/arrays. + unsafe { + if chdir_root { + let _ = libc::chdir(c"/".as_ptr()); + } + libc::syscall( + libc::SYS_execveat, + dirfd, + path.as_ptr(), + argv.as_ptr(), + envp.as_ptr(), + flags, + ); + libc::_exit(127); + } + } + let mut status: libc::c_int = 0; + // SAFETY: `pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(pid, &raw mut status, 0) }, pid); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "execveat AT_EXECFN check failed for {expect_execfn} with status {status}" + ); + }; + + // 1. `execveat(bin_fd, "", ..., AT_EMPTY_PATH)` -> `/dev/fd/`. + let bin_file = File::open(&exe).unwrap(); + let expect_empty = format!("/dev/fd/{}", bin_file.as_raw_fd()); + run_case(bin_file.as_raw_fd(), c"", libc::AT_EMPTY_PATH, &expect_empty, false); + + // 2. `execveat(dirfd, basename, ..., 0)` -> `/dev/fd//`. + let dir_file = File::open(exe_dir).unwrap(); + let name_c = CString::new(exe_name.as_bytes()).unwrap(); + let expect_rel = format!("/dev/fd/{}/{}", dir_file.as_raw_fd(), exe_name.to_str().unwrap()); + run_case(dir_file.as_raw_fd(), &name_c, 0, &expect_rel, true); + }); + + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} diff --git a/crates/fspy/tests/macos_preload.rs b/crates/fspy/tests/macos_preload.rs index 28765e2c4..9acad7a70 100644 --- a/crates/fspy/tests/macos_preload.rs +++ b/crates/fspy/tests/macos_preload.rs @@ -490,3 +490,120 @@ async fn posix_spawn_addchdir_np_resolves_relative_program() -> anyhow::Result<( Ok(()) } + +#[test(tokio::test)] +async fn posix_spawn_addchdir_np_is_fork_safe_under_concurrent_churn() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sub = root.join("fork_child_cwd"); + fs::create_dir(&sub)?; + let marker = sub.join("marker_fork_chdir"); + fs::write(&marker, "ok")?; + let script = sub.join("run.sh"); + write_executable(&script, "#!/bin/sh\ncat marker_fork_chdir >/dev/null\n")?; + + let sub_str = sub.to_str().unwrap().to_owned(); + let accesses = track_fn!(sub_str, |sub_str: String| { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + + unsafe extern "C" { + fn posix_spawn_file_actions_addchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + path: *const libc::c_char, + ) -> libc::c_int; + } + + let stop = Arc::new(AtomicBool::new(false)); + let sub_c = CString::new(sub_str).unwrap(); + + // Spawn background threads hammering `addchdir_np` + `destroy` while the + // main thread repeatedly calls `fork()` and uses `addchdir_np` + + // `posix_spawn` in the forked child. + let mut workers = Vec::new(); + for _ in 0..2 { + let stop_flag = Arc::clone(&stop); + let dir_c = sub_c.clone(); + workers.push(std::thread::spawn(move || { + while !stop_flag.load(Ordering::Relaxed) { + let mut actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated path. + unsafe { + if libc::posix_spawn_file_actions_init(&raw mut actions) == 0 { + let _ = posix_spawn_file_actions_addchdir_np( + &raw mut actions, + dir_c.as_ptr(), + ); + let _ = libc::posix_spawn_file_actions_destroy(&raw mut actions); + } + } + } + })); + } + + let prog = c"./run.sh"; + let argv = [prog.as_ptr().cast_mut(), std::ptr::null_mut()]; + let path_env = c"PATH=/bin:/usr/bin"; + let envp = [path_env.as_ptr().cast_mut(), std::ptr::null_mut()]; + + for _ in 0..16 { + // SAFETY: child executes only raw libc / `posix_spawn` + `_exit`. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed: {}", std::io::Error::last_os_error()); + if pid == 0 { + let mut actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: all pointers are pre-allocated valid C strings / arrays. + unsafe { + if libc::posix_spawn_file_actions_init(&raw mut actions) != 0 { + libc::_exit(10); + } + if posix_spawn_file_actions_addchdir_np(&raw mut actions, sub_c.as_ptr()) != 0 { + libc::_exit(11); + } + let mut grandchild: libc::pid_t = 0; + let rc = libc::posix_spawn( + &raw mut grandchild, + prog.as_ptr(), + &raw const actions, + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ); + let _ = libc::posix_spawn_file_actions_destroy(&raw mut actions); + if rc != 0 { + libc::_exit(12); + } + let mut gc_status: libc::c_int = 0; + if libc::waitpid(grandchild, &raw mut gc_status, 0) != grandchild + || !libc::WIFEXITED(gc_status) + || libc::WEXITSTATUS(gc_status) != 0 + { + libc::_exit(13); + } + libc::_exit(0); + } + } + 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, + "forked child failed with status {status:#x}" + ); + } + + stop.store(true, Ordering::Relaxed); + for worker in workers { + worker.join().unwrap(); + } + }) + .await?; + + assert_contains(&accesses, &script, PathAccess::Read); + assert_contains(&accesses, &marker, PathAccess::Read); + + Ok(()) +} diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index 667c87b78..2b5f7b102 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -72,6 +72,9 @@ Do not try to close these in this crate unless a real target requires it: - **Privileged / unsupported binaries.** `PR_SET_NO_NEW_PRIVS` is enabled for seccomp (so setuid/setgid and file-capability escalations do not apply), and ELF32 and `binfmt_misc` binaries are rejected with `ENOEXEC`. +- **Execute-only (`0111`) binaries.** Userland ELF mapping opens the executable + with `O_RDONLY` to validate headers and `mmap` segments, so execute-only + (`chmod 0111`) binaries cannot be mapped and fail with `EACCES`. - **Launcher path visibility across mount changes.** Every tracked `execve` re-enters the materialized freestanding launcher binary on disk. If a tracked process tree changes its mount namespace or root (`chroot`, `pivot_root`, or diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs index 32ef164c7..3d8185b00 100644 --- a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs +++ b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs @@ -1,6 +1,9 @@ -use std::sync::{ - Mutex, - atomic::{AtomicUsize, Ordering}, +use std::{ + cell::UnsafeCell, + sync::{ + Once, + atomic::{AtomicUsize, Ordering}, + }, }; use allocator_api2::vec::Vec as AllocVec; @@ -20,34 +23,140 @@ type PosixSpawnFn = unsafe extern "C" fn( envp: *const *mut c_char, ) -> c_int; +/// Initial capacity pre-allocated for [`SPAWN_CHDIRS`] outside the mutex. +const INITIAL_CAPACITY: usize = 64; + /// Number of `posix_spawn_file_actions_t` handles currently tracked in /// [`SPAWN_CHDIRS`]. Allows `posix_spawn(p)` and `destroy` to skip the mutex /// completely in the common case when no chdir action is active. static ACTIVE_CHDIRS: AtomicUsize = AtomicUsize::new(0); -/// Maps live `posix_spawn_file_actions_t` handle values (`*file_actions as usize`) -/// to their effective absolute working directory from `addchdir_np` / `addfchdir_np`. -static SPAWN_CHDIRS: Mutex)>> = Mutex::new(Vec::new()); +/// Fork-safe table mapping live `posix_spawn_file_actions_t` handle values +/// (`*file_actions as usize`) to their effective absolute working directory +/// from `addchdir_np` / `addfchdir_np`. +/// +/// Coordinated across `fork()` via `pthread_atfork`. No heap allocation or +/// deallocation ever runs while holding `mutex`, avoiding lock-order inversion +/// with libmalloc's own `atfork` handlers. +struct SpawnChdirTable { + mutex: UnsafeCell, + entries: UnsafeCell)>>, +} + +// SAFETY: `entries` is only accessed while holding `mutex`. +unsafe impl Sync for SpawnChdirTable {} + +static SPAWN_CHDIRS: SpawnChdirTable = SpawnChdirTable { + mutex: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER), + entries: UnsafeCell::new(Vec::new()), +}; +static ATFORK_INIT: Once = Once::new(); + +unsafe extern "C" fn atfork_prepare() { + // SAFETY: `SPAWN_CHDIRS.mutex` is statically initialized. + unsafe { libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()) }; +} + +unsafe extern "C" fn atfork_parent() { + // SAFETY: `atfork_prepare` acquired `SPAWN_CHDIRS.mutex` on this thread. + unsafe { libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()) }; +} + +unsafe extern "C" fn atfork_child() { + // SAFETY: `atfork_prepare` acquired `SPAWN_CHDIRS.mutex` on the forking + // thread, so the single-threaded child owns the lock and can unlock it. + unsafe { libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()) }; +} + +fn ensure_init() { + ATFORK_INIT.call_once(|| { + let prealloc = Vec::with_capacity(INITIAL_CAPACITY); + // SAFETY: `SPAWN_CHDIRS.mutex` is statically initialized; swap the + // pre-allocated buffer under the lock and drop the empty old `Vec` + // outside the lock, then register fork handlers. + let old = unsafe { + libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); + let old = core::mem::replace(&mut *SPAWN_CHDIRS.entries.get(), prealloc); + libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()); + libc::pthread_atfork(Some(atfork_prepare), Some(atfork_parent), Some(atfork_child)); + old + }; + drop(old); + }); +} + +fn set_spawn_chdir(key: usize, path: Box<[u8]>) { + ensure_init(); + let mut pending = Some(path); + let mut spare: Option)>> = None; + let mut to_drop_entry: Option> = None; + let mut to_drop_vec: Option)>> = None; -fn set_spawn_chdir(key: usize, path: Vec) { - let mut map = SPAWN_CHDIRS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some((_, existing)) = map.iter_mut().find(|(k, _)| *k == key) { - *existing = path; - } else { - map.push((key, path)); - ACTIVE_CHDIRS.store(map.len(), Ordering::Release); + loop { + // SAFETY: `SPAWN_CHDIRS.mutex` serializes all access to `entries`, and + // no allocation or deallocation occurs while the lock is held. + let need_capacity = unsafe { + libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); + let map = &mut *SPAWN_CHDIRS.entries.get(); + + let result = if let Some((_, existing)) = map.iter_mut().find(|(k, _)| *k == key) { + let new_path = pending.take().unwrap(); + to_drop_entry = Some(core::mem::replace(existing, new_path)); + None + } else if map.len() < map.capacity() { + map.push((key, pending.take().unwrap())); + ACTIVE_CHDIRS.store(map.len(), Ordering::Release); + None + } else if let Some(mut grown) = spare.take() + && grown.capacity() > map.len() + { + grown.append(map); + grown.push((key, pending.take().unwrap())); + let old_vec = core::mem::replace(map, grown); + ACTIVE_CHDIRS.store(map.len(), Ordering::Release); + to_drop_vec = Some(old_vec); + None + } else { + Some(map.capacity().max(INITIAL_CAPACITY).saturating_mul(2)) + }; + + libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()); + result + }; + + if let Some(cap) = need_capacity { + // Allocate outside `SPAWN_CHDIRS.mutex` so `malloc` never nests + // inside our `atfork`-locked mutex. + spare = Some(Vec::with_capacity(cap)); + } else { + break; + } } + + drop(to_drop_entry); + drop(to_drop_vec); + drop(spare); } fn remove_spawn_chdir(key: usize) { if ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 { return; } - let mut map = SPAWN_CHDIRS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some(pos) = map.iter().position(|(k, _)| *k == key) { - map.swap_remove(pos); - ACTIVE_CHDIRS.store(map.len(), Ordering::Release); - } + ensure_init(); + // SAFETY: `SPAWN_CHDIRS.mutex` serializes access to `entries`; the removed + // `Box<[u8]>` is dropped strictly after unlocking. + let removed = unsafe { + libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); + let map = &mut *SPAWN_CHDIRS.entries.get(); + let removed = map.iter().position(|(k, _)| *k == key).map(|pos| { + let entry = map.swap_remove(pos); + ACTIVE_CHDIRS.store(map.len(), Ordering::Release); + entry + }); + libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()); + removed + }; + drop(removed); } fn get_spawn_chdir_in( @@ -62,14 +171,37 @@ fn get_spawn_chdir_in( if key == 0 { return None; } - let map = SPAWN_CHDIRS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let out = map.iter().find(|(k, _)| *k == key).map(|(_, bytes)| { - let mut out = AllocVec::with_capacity_in(bytes.len(), allocator); - out.extend_from_slice(bytes); - out - }); - drop(map); - out + ensure_init(); + + // Pre-allocate outside `SPAWN_CHDIRS.mutex` (macOS PATH_MAX is 1024). + let mut out = AllocVec::with_capacity_in(1024, allocator); + loop { + // SAFETY: `SPAWN_CHDIRS.mutex` serializes access to `entries`, and + // copying into pre-allocated `out` performs no heap allocation. + let status = unsafe { + libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); + let map = &*SPAWN_CHDIRS.entries.get(); + let status = match map.iter().find(|(k, _)| *k == key) { + None => Ok(false), + Some((_, bytes)) if bytes.len() <= out.capacity() => { + out.clear(); + out.extend_from_slice(bytes); + Ok(true) + } + Some((_, bytes)) => Err(bytes.len()), + }; + libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()); + status + }; + + match status { + Ok(true) => return Some(out), + Ok(false) => return None, + Err(needed) => { + out.reserve(needed.saturating_sub(out.len())); + } + } + } } intercept!(posix_spawn_file_actions_addchdir_np: unsafe extern "C" fn( @@ -90,7 +222,7 @@ unsafe extern "C" fn posix_spawn_file_actions_addchdir_np( let c_path = unsafe { CStr::::from_ptr(path.cast()) }; let raw = c_path.count().as_units(); if raw.starts_with(b"/") { - set_spawn_chdir(key, raw.to_vec()); + set_spawn_chdir(key, Box::from(raw)); } else if !raw.is_empty() { let prev = get_spawn_chdir_in(file_actions.cast_const(), allocator_api2::alloc::Global); @@ -100,7 +232,7 @@ unsafe extern "C" fn posix_spawn_file_actions_addchdir_np( resolve_path_at(&arena, Some(CWD), c_path) .ok() .flatten() - .map(|p| p.as_units().to_vec()) + .map(|p| Box::from(p.as_units())) }, |base| { let mut joined = base.to_vec(); @@ -108,7 +240,7 @@ unsafe extern "C" fn posix_spawn_file_actions_addchdir_np( joined.push(b'/'); } joined.extend_from_slice(raw); - Some(joined) + Some(joined.into_boxed_slice()) }, ); if let Some(dir) = resolved { @@ -139,7 +271,7 @@ unsafe extern "C" fn posix_spawn_file_actions_addfchdir_np( if let Some(borrowed) = borrowed { let arena = fspy_nostd_alloc::pooled_bump(); if let Ok(Some(dir)) = fd_path(&arena, borrowed) { - set_spawn_chdir(key, dir.as_units().to_vec()); + set_spawn_chdir(key, Box::from(dir.as_units())); } } } diff --git a/crates/fspy_shared_unix/src/linux.rs b/crates/fspy_shared_unix/src/linux.rs index c40417e33..d2be98803 100644 --- a/crates/fspy_shared_unix/src/linux.rs +++ b/crates/fspy_shared_unix/src/linux.rs @@ -182,7 +182,17 @@ pub fn resolve_exec( } } } else { - let execfn = to_vec_in(&exec.program, allocator.clone()); + // Linux `fs/exec.c` (`do_execveat_common`) formats `AT_EXECFN` as + // `/dev/fd//` for non-`AT_FDCWD` relative `execveat`. + let execfn = if !exec.program.starts_with(b"/") + && let Some(fd) = dirfd + && fd.as_raw_fd() != CWD.as_raw_fd() + && let Ok(raw_fd) = u32::try_from(fd.as_raw_fd()) + { + format_dev_fd_rel(raw_fd, &exec.program, allocator.clone()) + } else { + to_vec_in(&exec.program, allocator.clone()) + }; (execfn, None, 0usize, dirfd, flags.contains(ExecAtFlags::SYMLINK_NOFOLLOW)) }; @@ -259,8 +269,7 @@ fn resolve_empty_path( 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 { + if let Some(p) = fd_path(allocator.clone(), fd)? { on_path_read(BStr::new(p.as_units())); } @@ -280,10 +289,9 @@ fn resolve_empty_path( 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, - ); + // Match Linux `fs/exec.c` (`do_execveat_common`): `AT_EMPTY_PATH` always + // sets `AT_EXECFN` to `/dev/fd/` for both binaries and `#!` scripts. + let execfn = format_dev_fd(raw_fd, allocator.clone()); let Some(shebang) = parse_shebang_bytes(&peek_buf[..n], ParseShebangOptions::linux(), allocator.clone())? @@ -337,6 +345,19 @@ fn format_dev_fd(fd: u32, allocator: A) -> Vec { out } +fn format_dev_fd_rel(fd: u32, rel: &[u8], allocator: A) -> Vec { + let mut buf = [0u8; 32]; + let proc_fd = format_proc_self_fd(&mut buf, fd).count().as_units(); + let digits = proc_fd.strip_prefix(b"/proc/self/fd/").unwrap_or(proc_fd); + let mut out = + Vec::with_capacity_in(b"/dev/fd/".len() + digits.len() + 1 + rel.len(), allocator); + out.extend_from_slice(b"/dev/fd/"); + out.extend_from_slice(digits); + out.push(b'/'); + out.extend_from_slice(rel); + out +} + #[cfg(all(test, target_os = "linux"))] mod tests { use std::{ @@ -518,5 +539,76 @@ mod tests { assert!(!fcntl_is_cloexec(extra.as_fd()).unwrap()); let expected_dev_fd = format!("/dev/fd/{}", extra.as_raw_fd()); assert_eq!(exec.args.last().unwrap().as_slice(), expected_dev_fd.as_bytes()); + assert_eq!( + resolved.execfn.as_slice(), + format!("/dev/fd/{}", o_path_owned.as_raw_fd()).as_bytes() + ); + } + + #[test] + fn resolve_exec_formats_execfn_matching_linux_kernel() { + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("bin"); + write_exec(&bin, b"\x7fELFdummy"); + let script = dir.path().join("script.sh"); + write_exec(&script, format!("#!{}\n", bin.display()).as_bytes()); + + // 1. `AT_EMPTY_PATH` on ELF binary -> `/dev/fd/`, while `on_path_read` + // still receives the resolved file path. + let bin_file = File::open(&bin).unwrap(); + // SAFETY: `bin_file` stays open for the call. + let bin_fd = unsafe { BorrowedFd::borrow_raw(bin_file.as_raw_fd()) }; + let mut seen = std::vec::Vec::new(); + let mut exec = make_exec(b"", &[b"bin"]); + let resolved = resolve_exec(&mut exec, Some(bin_fd), ExecAtFlags::EMPTY_PATH, |p| { + seen.push(p.to_vec()); + }) + .unwrap(); + assert_eq!( + resolved.execfn.as_slice(), + format!("/dev/fd/{}", bin_file.as_raw_fd()).as_bytes() + ); + assert!(seen.iter().any(|p| p.as_slice() == bin.as_os_str().as_bytes())); + + // 2. `AT_EMPTY_PATH` on non-CLOEXEC `#!` script -> `/dev/fd/`. + let script_c = bytes_to_cstring(script.as_os_str().as_bytes(), Global).unwrap(); + let script_owned = + openat(CWD, script_c.as_c_str().as_thin(), OFlags::RDONLY, Mode::empty()).unwrap(); + let mut exec = make_exec(b"", &[b"script"]); + let resolved = + resolve_exec(&mut exec, Some(script_owned.as_fd()), ExecAtFlags::EMPTY_PATH, |_| {}) + .unwrap(); + assert_eq!( + resolved.execfn.as_slice(), + format!("/dev/fd/{}", script_owned.as_raw_fd()).as_bytes() + ); + + // 3. Relative path with real `dirfd` -> `/dev/fd//` (both binary & script). + let dir_file = File::open(dir.path()).unwrap(); + // SAFETY: `dir_file` stays open for the call. + let dir_fd = unsafe { BorrowedFd::borrow_raw(dir_file.as_raw_fd()) }; + let mut exec = make_exec(b"bin", &[b"bin"]); + let resolved = resolve_exec(&mut exec, Some(dir_fd), ExecAtFlags::empty(), |_| {}).unwrap(); + assert_eq!( + resolved.execfn.as_slice(), + format!("/dev/fd/{}/bin", dir_file.as_raw_fd()).as_bytes() + ); + + let mut exec = make_exec(b"script.sh", &[b"script.sh"]); + let resolved = resolve_exec(&mut exec, Some(dir_fd), ExecAtFlags::empty(), |_| {}).unwrap(); + assert_eq!( + resolved.execfn.as_slice(), + format!("/dev/fd/{}/script.sh", dir_file.as_raw_fd()).as_bytes() + ); + + // 4. Absolute path (even with real `dirfd`) preserves `exec.program`. + let mut exec = make_exec(bin.as_os_str().as_bytes(), &[b"bin"]); + let resolved = resolve_exec(&mut exec, Some(dir_fd), ExecAtFlags::empty(), |_| {}).unwrap(); + assert_eq!(resolved.execfn.as_slice(), bin.as_os_str().as_bytes()); + + // 5. `AT_FDCWD` with relative path preserves `exec.program`. + let mut exec = make_exec(bin.as_os_str().as_bytes(), &[b"bin"]); + let resolved = resolve_exec(&mut exec, Some(CWD), ExecAtFlags::empty(), |_| {}).unwrap(); + assert_eq!(resolved.execfn.as_slice(), bin.as_os_str().as_bytes()); } } From 1ec1eb4a8d7871136fba5cc09741c8ca6393298b Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 01:16:40 +0800 Subject: [PATCH 19/48] fix(fspy): handle nested fspy fallback, creat, AT_FDCWD empty execveat, and deferred macOS spawn chdir Co-authored-by: Gemini 4 Neon --- crates/fspy/Cargo.toml | 2 +- crates/fspy/src/linux/mod.rs | 79 +++++- crates/fspy/tests/linux_hardening.rs | 103 +++++++ crates/fspy/tests/linux_syscalls.rs | 76 ++++-- crates/fspy/tests/macos_preload.rs | 132 +++++++++ crates/fspy_preload_linux/src/main.rs | 51 +++- .../src/interceptions/spawn/posix_spawn.rs | 253 ++++++++++++++---- crates/fspy_shared_unix/src/linux.rs | 20 +- 8 files changed, 628 insertions(+), 88 deletions(-) diff --git a/crates/fspy/Cargo.toml b/crates/fspy/Cargo.toml index 14d7e603c..cada19113 100644 --- a/crates/fspy/Cargo.toml +++ b/crates/fspy/Cargo.toml @@ -33,6 +33,7 @@ fspy_shared_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] +fspy_elf_loader = { workspace = true } linux-raw-sys = { workspace = true, features = ["general", "prctl", "ptrace"] } syscalls = { workspace = true } tracing = { workspace = true } @@ -68,7 +69,6 @@ nix = { workspace = true, features = ["fs"] } [target.'cfg(target_os = "linux")'.dev-dependencies] elf = { workspace = true } -fspy_elf_loader = { 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" } diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index d2022ab61..84e165507 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -10,10 +10,11 @@ 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, + prctl::{PR_GET_SECCOMP, 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_TRAP, SECCOMP_SET_MODE_FILTER, seccomp_data, sock_filter, sock_fprog, + BPF_ABS, BPF_JEQ, BPF_JMP, BPF_K, BPF_LD, BPF_RET, BPF_W, SECCOMP_MODE_FILTER, + SECCOMP_RET_ALLOW, SECCOMP_RET_TRAP, SECCOMP_SET_MODE_FILTER, seccomp_data, sock_filter, + sock_fprog, }, }; use syscalls::Sysno; @@ -47,6 +48,12 @@ impl SpyImpl { reason = "matches cross-platform SpyImpl::init() -> io::Result signature" )] pub fn init() -> io::Result { + if is_already_tracked_by_fspy() { + tracing::debug!( + "nested inside an active fspy tracker; delegating tracking to outer tracker" + ); + return Ok(Self { preload_path: RwLock::new(None), seccomp_available: false }); + } let seccomp_available = probe_seccomp_available(); let preload_path = if seccomp_available { let materialized = materialize_preload(); @@ -270,6 +277,72 @@ fn materialize_preload() -> Option> { .map(|p| p.as_path().into()) } +/// Detects whether the current process is already running inside an outer +/// `fspy` Linux launcher (`fspy_preload_linux`). +/// +/// Because `fspy_preload_linux` is linked at a fixed address in +/// [`fspy_elf_loader::LAUNCHER_REGION`], spawning another `fspy_preload_linux` +/// directly from inside a tracked process would collide with the outer +/// launcher's resident mappings (`EEXIST`). Falling back to untracked +/// execution lets the inner spawn succeed while the outer tracker records the +/// entire nested subtree. +fn is_already_tracked_by_fspy() -> bool { + #[cfg(target_arch = "x86_64")] + const NATIVE_MACHINE: u16 = 62; // EM_X86_64 + #[cfg(target_arch = "aarch64")] + const NATIVE_MACHINE: u16 = 183; // EM_AARCH64 + + // 1. Confirm seccomp filter mode (`SECCOMP_MODE_FILTER == 2`) is active. + // SAFETY: `PR_GET_SECCOMP` takes no pointer arguments and only queries + // the calling thread's seccomp mode. + let seccomp_mode = unsafe { syscalls::syscall!(Sysno::prctl, PR_GET_SECCOMP, 0, 0, 0, 0) }; + if seccomp_mode != Ok(SECCOMP_MODE_FILTER as usize) { + return false; + } + + // 2. Check whether `LAUNCHER_REGION.0` is mapped (read-only; `ENOMEM` + // means unmapped). + let region_base = fspy_elf_loader::LAUNCHER_REGION.0; + // SAFETY: `_SC_PAGESIZE` is a standard `sysconf` query. + let page_size = usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }) + .ok() + .filter(|&n| n > 0) + .unwrap_or(4096); + let mut vec: u8 = 0; + // SAFETY: `mincore` writes one residency byte per page (`1` page -> `vec`). + if unsafe { + libc::mincore(core::ptr::with_exposed_provenance_mut(region_base), page_size, &raw mut vec) + } != 0 + { + return false; + } + + // 3. Safely read the first 64 bytes at `LAUNCHER_REGION.0` via + // `process_vm_readv` (returns `EFAULT` without crashing if unreadable or + // `PROT_NONE`) and confirm it is a native little-endian ELF64 `ET_EXEC` + // header matching `fspy_preload_linux`. + let mut hdr = [0_u8; 64]; + let local = libc::iovec { iov_base: hdr.as_mut_ptr().cast(), iov_len: hdr.len() }; + let remote = libc::iovec { + iov_base: core::ptr::with_exposed_provenance_mut(region_base), + iov_len: hdr.len(), + }; + // SAFETY: `local` points to our writable 64-byte buffer and `remote` is + // validated by the kernel in `process_vm_readv`. + let n = unsafe { + libc::process_vm_readv(libc::getpid(), &raw const local, 1, &raw const remote, 1, 0) + }; + if n != hdr.len().cast_signed() { + return false; + } + + hdr[0..4] == *b"\x7fELF" + && hdr[4] == 2 // ELFCLASS64 + && hdr[5] == 1 // ELFDATA2LSB + && u16::from_le_bytes([hdr[16], hdr[17]]) == 2 // ET_EXEC + && u16::from_le_bytes([hdr[18], hdr[19]]) == NATIVE_MACHINE +} + /// Probes once on a dedicated short-lived OS thread whether /// `PR_SET_NO_NEW_PRIVS` and `seccomp(SECCOMP_SET_MODE_FILTER)` with /// `SECCOMP_RET_TRAP` are permitted in the current environment. diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs index 79cb144ad..10775679a 100644 --- a/crates/fspy/tests/linux_hardening.rs +++ b/crates/fspy/tests/linux_hardening.rs @@ -770,3 +770,106 @@ async fn posix_spawn_setsigdef_resets_child_sigsys_without_mutating_parent() -> assert_contains(&accesses, probe_path, fspy::PathAccess::Read); Ok(()) } + +#[test(tokio::test)] +async fn nested_fspy_falls_back_cleanly_while_outer_tracks_subtree() -> anyhow::Result<()> { + let probe_path = Path::new("/fspy-nested-inner-child-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)| { + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + rt.block_on(async move { + let mut inner_cmd = fspy::Command::new(&static_bin); + inner_cmd.args(["open_read", &probe_path]); + let termination = inner_cmd + .spawn(tokio_util::sync::CancellationToken::new()) + .await + .expect("nested fspy spawn must succeed via untracked fallback") + .wait_handle + .await + .expect("nested fspy child wait failed"); + assert!( + termination.status.success(), + "nested child exited unsuccessfully: {:?}", + termination.status + ); + assert!( + termination.path_accesses.is_err(), + "nested fspy must report TrackingIncomplete while delegating to outer tracker" + ); + }); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, probe_path, fspy::PathAccess::Read); + Ok(()) +} + +#[test(tokio::test)] +async fn execve_of_et_exec_overlapping_launcher_region_returns_eexist_cleanly() -> anyhow::Result<()> +{ + #[cfg(target_arch = "x86_64")] + const MACHINE: u16 = elf::abi::EM_X86_64; + #[cfg(target_arch = "aarch64")] + const MACHINE: u16 = elf::abi::EM_AARCH64; + + let survived_probe = Path::new("/fspy-overlap-et-exec-survived-probe"); + let tmp_dir = tempfile::tempdir()?; + let overlap_path = tmp_dir.path().canonicalize()?.join("overlap_et_exec"); + + // Construct a minimal valid native ELF64 `ET_EXEC` whose `PT_LOAD` overlaps + // `fspy_elf_loader::LAUNCHER_REGION`. + // SAFETY: `_SC_PAGESIZE` is a standard `sysconf` query. + let page = usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap(); + let vaddr = u64::try_from(fspy_elf_loader::LAUNCHER_REGION.0 + 4 * page).unwrap(); + + let mut bytes = vec![0_u8; 2 * page]; + bytes[0..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); + bytes[16..18].copy_from_slice(&elf::abi::ET_EXEC.to_le_bytes()); + bytes[18..20].copy_from_slice(&MACHINE.to_le_bytes()); + bytes[20..24].copy_from_slice(&1_u32.to_le_bytes()); + bytes[24..32].copy_from_slice(&(vaddr + 0x200).to_le_bytes()); + bytes[32..40].copy_from_slice(&64_u64.to_le_bytes()); // e_phoff + bytes[52..54].copy_from_slice(&64_u16.to_le_bytes()); // e_ehsize + bytes[54..56].copy_from_slice(&56_u16.to_le_bytes()); // e_phentsize + bytes[56..58].copy_from_slice(&1_u16.to_le_bytes()); // e_phnum + + let ph = &mut bytes[64..64 + 56]; + ph[0..4].copy_from_slice(&elf::abi::PT_LOAD.to_le_bytes()); + ph[4..8].copy_from_slice(&(elf::abi::PF_R | elf::abi::PF_X).to_le_bytes()); + ph[8..16].copy_from_slice(&0_u64.to_le_bytes()); // p_offset + ph[16..24].copy_from_slice(&vaddr.to_le_bytes()); // p_vaddr + ph[32..40].copy_from_slice(&u64::try_from(page).unwrap().to_le_bytes()); // p_filesz + ph[40..48].copy_from_slice(&u64::try_from(page).unwrap().to_le_bytes()); // p_memsz + ph[48..56].copy_from_slice(&u64::try_from(page).unwrap().to_le_bytes()); // p_align + + std::fs::write(&overlap_path, &bytes)?; + std::fs::set_permissions(&overlap_path, std::os::unix::fs::PermissionsExt::from_mode(0o755))?; + + let cmd = vt_subprocess_test::command_for_fn!( + (overlap_path.to_str().unwrap().to_owned(), survived_probe.to_str().unwrap().to_owned()), + |(overlap_path, survived_probe): (String, String)| { + use std::ffi::CString; + + let prog = CString::new(overlap_path).unwrap(); + let argv = [prog.as_ptr(), std::ptr::null()]; + let envp = [std::ptr::null::()]; + // SAFETY: valid NUL/NULL-terminated arrays; `execve` must fail with `EEXIST`. + let rc = unsafe { libc::execve(prog.as_ptr(), argv.as_ptr(), envp.as_ptr()) }; + assert_eq!(rc, -1, "overlapping ET_EXEC execve unexpectedly succeeded"); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::EEXIST), + "expected EEXIST (not ENOEXEC) for ET_EXEC overlapping LAUNCHER_REGION" + ); + + // Caller survived and syscall tracking remains healthy. + let _ = std::fs::File::open(&survived_probe); + } + ); + + let accesses = test_utils::spawn_command(cmd).await?; + assert_contains(&accesses, survived_probe, fspy::PathAccess::Read); + Ok(()) +} diff --git a/crates/fspy/tests/linux_syscalls.rs b/crates/fspy/tests/linux_syscalls.rs index d8a4fbb1d..d290e256c 100644 --- a/crates/fspy/tests/linux_syscalls.rs +++ b/crates/fspy/tests/linux_syscalls.rs @@ -238,6 +238,22 @@ async fn execveat_nofollow_dirfd_o_path_and_empty_path_scripts() -> anyhow::Resu }; assert_eq!(rc_cloexec, -1, "AT_EMPTY_PATH on CLOEXEC script should fail"); assert_eq!(errno(), libc::ENOENT); + + // 7. `execveat(AT_FDCWD, "", ..., AT_EMPTY_PATH)` refers to the current + // working directory and must return `EACCES` (matching Linux kernel). + // SAFETY: valid arguments to `execveat` expected to fail with `EACCES`. + let rc_cwd_empty = unsafe { + libc::syscall( + libc::SYS_execveat, + libc::AT_FDCWD, + c"".as_ptr(), + argv_empty_script.as_ptr(), + envp_empty.as_ptr(), + libc::AT_EMPTY_PATH, + ) + }; + assert_eq!(rc_cwd_empty, -1, "execveat(AT_FDCWD, \"\", AT_EMPTY_PATH) should fail"); + assert_eq!(errno(), libc::EACCES); }) .await?; @@ -539,11 +555,12 @@ async fn openat_rdonly_creat_trunc_and_renameat2_exchange() -> anyhow::Result<() #[cfg(target_arch = "x86_64")] #[test(tokio::test)] -async fn legacy_x86_64_open_stat_lstat_syscalls_are_tracked() -> anyhow::Result<()> { +async fn legacy_x86_64_open_creat_stat_lstat_syscalls_are_tracked() -> anyhow::Result<()> { let tmp_dir = tempfile::tempdir()?; let root = tmp_dir.path().canonicalize()?; let open_target = root.join("legacy_open"); + let creat_target = root.join("legacy_creat"); let stat_target = root.join("legacy_stat"); let lstat_target = root.join("legacy_lstat_link"); fs::write(&open_target, b"open")?; @@ -552,38 +569,49 @@ async fn legacy_x86_64_open_stat_lstat_syscalls_are_tracked() -> anyhow::Result< let args = ( open_target.to_str().unwrap().to_owned(), + creat_target.to_str().unwrap().to_owned(), stat_target.to_str().unwrap().to_owned(), lstat_target.to_str().unwrap().to_owned(), ); - let accesses = track_fn!(args, |(p_open, p_stat, p_lstat): (String, String, String)| { - use std::ffi::CString; + let accesses = + track_fn!(args, |(p_open, p_creat, p_stat, p_lstat): (String, String, String, String)| { + use std::ffi::CString; - #[repr(C, align(8))] - struct RawStatBuf([u8; 256]); + #[repr(C, align(8))] + struct RawStatBuf([u8; 256]); - let c_open = CString::new(p_open).unwrap(); - let c_stat = CString::new(p_stat).unwrap(); - let c_lstat = CString::new(p_lstat).unwrap(); + let c_open = CString::new(p_open).unwrap(); + let c_creat = CString::new(p_creat).unwrap(); + let c_stat = CString::new(p_stat).unwrap(); + let c_lstat = CString::new(p_lstat).unwrap(); - // SAFETY: valid C string; `SYS_open` takes `(path, flags, mode)`. - let fd = unsafe { libc::syscall(libc::SYS_open, c_open.as_ptr(), libc::O_RDONLY, 0) }; - assert!(fd >= 0, "SYS_open failed: {}", errno()); - // SAFETY: closing our owned descriptor. - unsafe { libc::close(libc::c_int::try_from(fd).unwrap()) }; - - let mut stat_buf = RawStatBuf([0; 256]); - // SAFETY: valid C string and 256-byte aligned buffer (>= x86_64 `struct stat`). - let rc_stat = unsafe { libc::syscall(libc::SYS_stat, c_stat.as_ptr(), &raw mut stat_buf) }; - assert_eq!(rc_stat, 0); - // SAFETY: valid C string and 256-byte aligned buffer (>= x86_64 `struct stat`). - let rc_lstat = - unsafe { libc::syscall(libc::SYS_lstat, c_lstat.as_ptr(), &raw mut stat_buf) }; - assert_eq!(rc_lstat, 0); - }) - .await?; + // SAFETY: valid C string; `SYS_open` takes `(path, flags, mode)`. + let fd = unsafe { libc::syscall(libc::SYS_open, c_open.as_ptr(), libc::O_RDONLY, 0) }; + assert!(fd >= 0, "SYS_open failed: {}", errno()); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(libc::c_int::try_from(fd).unwrap()) }; + + // SAFETY: valid C string; `SYS_creat` takes `(path, mode)`. + let creat_fd = unsafe { libc::syscall(libc::SYS_creat, c_creat.as_ptr(), 0o644) }; + assert!(creat_fd >= 0, "SYS_creat failed: {}", errno()); + // SAFETY: closing our owned descriptor. + unsafe { libc::close(libc::c_int::try_from(creat_fd).unwrap()) }; + + let mut stat_buf = RawStatBuf([0; 256]); + // SAFETY: valid C string and 256-byte aligned buffer (>= x86_64 `struct stat`). + let rc_stat = + unsafe { libc::syscall(libc::SYS_stat, c_stat.as_ptr(), &raw mut stat_buf) }; + assert_eq!(rc_stat, 0); + // SAFETY: valid C string and 256-byte aligned buffer (>= x86_64 `struct stat`). + let rc_lstat = + unsafe { libc::syscall(libc::SYS_lstat, c_lstat.as_ptr(), &raw mut stat_buf) }; + assert_eq!(rc_lstat, 0); + }) + .await?; assert_includes(&accesses, &open_target, PathAccess::Read); + assert_includes(&accesses, &creat_target, PathAccess::Write); assert_includes(&accesses, &stat_target, PathAccess::Read); assert_includes(&accesses, &lstat_target, PathAccess::Read); Ok(()) diff --git a/crates/fspy/tests/macos_preload.rs b/crates/fspy/tests/macos_preload.rs index 9acad7a70..be14f2be3 100644 --- a/crates/fspy/tests/macos_preload.rs +++ b/crates/fspy/tests/macos_preload.rs @@ -607,3 +607,135 @@ async fn posix_spawn_addchdir_np_is_fork_safe_under_concurrent_churn() -> anyhow Ok(()) } + +#[test(tokio::test)] +async fn posix_spawn_defers_relative_addchdir_and_addfchdir_resolution_to_spawn_time() +-> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + + let dir_a = root.join("dir_a"); + let dir_b = root.join("dir_b"); + let sub_a = dir_a.join("sub"); + let sub_b = dir_b.join("sub"); + fs::create_dir_all(&sub_a)?; + fs::create_dir_all(&sub_b)?; + + let marker_rel_a = sub_a.join("marker_rel_a"); + let marker_rel_b = sub_b.join("marker_rel_b"); + let marker_fd_a = dir_a.join("marker_fd_a"); + let marker_fd_b = dir_b.join("marker_fd_b"); + for m in [&marker_rel_a, &marker_rel_b, &marker_fd_a, &marker_fd_b] { + fs::write(m, "ok")?; + } + + let script_rel_a = sub_a.join("run.sh"); + let script_rel_b = sub_b.join("run.sh"); + let script_fd_a = dir_a.join("run_fd.sh"); + let script_fd_b = dir_b.join("run_fd.sh"); + write_executable(&script_rel_a, "#!/bin/sh\ncat marker_rel_a >/dev/null\n")?; + write_executable(&script_rel_b, "#!/bin/sh\ncat marker_rel_b >/dev/null\n")?; + write_executable(&script_fd_a, "#!/bin/sh\ncat marker_fd_a >/dev/null\n")?; + write_executable(&script_fd_b, "#!/bin/sh\ncat marker_fd_b >/dev/null\n")?; + + let args = (dir_a.to_str().unwrap().to_owned(), dir_b.to_str().unwrap().to_owned()); + let accesses = track_fn!(args, |(dir_a, dir_b): (String, String)| { + unsafe extern "C" { + fn posix_spawn_file_actions_addchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + path: *const libc::c_char, + ) -> libc::c_int; + fn posix_spawn_file_actions_addfchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + fd: libc::c_int, + ) -> libc::c_int; + } + + let spawn_and_wait = |prog: &std::ffi::CStr, actions: &libc::posix_spawn_file_actions_t| { + let argv = [prog.as_ptr().cast_mut(), std::ptr::null_mut()]; + let path_env = c"PATH=/bin:/usr/bin"; + let envp = [path_env.as_ptr().cast_mut(), std::ptr::null_mut()]; + let mut child: libc::pid_t = 0; + // SAFETY: all pointers are valid C strings/arrays and `actions` is initialized. + let rc = unsafe { + libc::posix_spawn( + &raw mut child, + prog.as_ptr(), + std::ptr::from_ref(actions), + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + assert_eq!(rc, 0, "posix_spawn({prog:?}) failed with errno {rc}"); + let mut status: libc::c_int = 0; + // SAFETY: `child` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(child, &raw mut status, 0) }, child); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "child for {prog:?} failed with raw status {status:#x}" + ); + }; + + // 1. Single `file_actions` with relative `addchdir_np("sub")` reused across `chdir`. + std::env::set_current_dir(&dir_a).unwrap(); + let mut rel_actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated relative path. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut rel_actions), 0); + assert_eq!( + posix_spawn_file_actions_addchdir_np(&raw mut rel_actions, c"sub".as_ptr()), + 0 + ); + } + spawn_and_wait(c"./run.sh", &rel_actions); + + std::env::set_current_dir(&dir_b).unwrap(); + spawn_and_wait(c"./run.sh", &rel_actions); + // SAFETY: destroying initialized `rel_actions`. + unsafe { assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut rel_actions), 0) }; + + // 2. Single `file_actions` with `addfchdir_np(fd)` where `dup2` retargets `fd` + // from `dir_a` to `dir_b` before the second spawn. + let dir_a_c = CString::new(dir_a.as_str()).unwrap(); + let dir_b_c = CString::new(dir_b.as_str()).unwrap(); + // SAFETY: valid C path strings for opening directory fds. + let fd_a = unsafe { libc::open(dir_a_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY) }; + assert!(fd_a >= 0, "open(dir_a) failed: {}", std::io::Error::last_os_error()); + // SAFETY: valid C path string. + let fd_b = unsafe { libc::open(dir_b_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY) }; + assert!(fd_b >= 0, "open(dir_b) failed: {}", std::io::Error::last_os_error()); + + let mut fd_actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and open directory descriptor `fd_a`. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut fd_actions), 0); + assert_eq!(posix_spawn_file_actions_addfchdir_np(&raw mut fd_actions, fd_a), 0); + } + spawn_and_wait(c"./run_fd.sh", &fd_actions); + + // Retarget `fd_a` to point at `dir_b` and spawn again with the same `fd_actions`. + // SAFETY: `fd_b` and `fd_a` are valid open descriptors. + assert_eq!(unsafe { libc::dup2(fd_b, fd_a) }, fd_a); + spawn_and_wait(c"./run_fd.sh", &fd_actions); + + // SAFETY: destroying initialized handle and closing owned descriptors. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut fd_actions), 0); + libc::close(fd_a); + libc::close(fd_b); + } + }) + .await?; + + assert_contains(&accesses, &script_rel_a, PathAccess::Read); + assert_contains(&accesses, &marker_rel_a, PathAccess::Read); + assert_contains(&accesses, &script_rel_b, PathAccess::Read); + assert_contains(&accesses, &marker_rel_b, PathAccess::Read); + assert_contains(&accesses, &script_fd_a, PathAccess::Read); + assert_contains(&accesses, &marker_fd_a, PathAccess::Read); + assert_contains(&accesses, &script_fd_b, PathAccess::Read); + assert_contains(&accesses, &marker_fd_b, PathAccess::Read); + + Ok(()) +} diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index 0b93a7391..4960d3318 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -110,6 +110,7 @@ mod runtime { Sysno::open, Sysno::openat, Sysno::openat2, + Sysno::creat, Sysno::getdents, Sysno::getdents64, Sysno::stat, @@ -282,7 +283,10 @@ mod runtime { ) } { Ok(never) => match never {}, - Err(err) => panic!("exec_elf failed: {err:?}"), + Err(err) => { + write_exec_error_stderr(err); + exit_group(127); + } } } } @@ -386,6 +390,49 @@ mod runtime { }; } + fn write_exec_error_stderr(err: Error) { + const PREFIX: &[u8] = b"fspy_preload_linux: exec_elf failed (errno="; + const SUFFIX: &[u8] = b")\n"; + let mut buf = [0_u8; 64]; + let mut len = PREFIX.len(); + buf[..len].copy_from_slice(PREFIX); + let code = err.raw_os_error(); + let abs = code.unsigned_abs(); + if code < 0 { + buf[len] = b'-'; + len += 1; + } + let mut digits = [0_u8; 10]; + let mut n = 0; + let mut rem = abs; + loop { + digits[n] = b'0' + (rem % 10) as u8; + n += 1; + rem /= 10; + if rem == 0 { + break; + } + } + for i in (0..n).rev() { + buf[len] = digits[i]; + len += 1; + } + buf[len..len + SUFFIX.len()].copy_from_slice(SUFFIX); + len += SUFFIX.len(); + + // SAFETY: fd 2 is standard error; errors on closed/unwritable stderr are ignored. + let stderr = unsafe { BorrowedFd::borrow_raw(2) }; + let mut written = 0; + while written < len { + match fspy_nostd::io::write(stderr, &buf[written..len]) { + Ok(0) => break, + Ok(k) => written += k, + Err(Error::INTR) => {} + Err(_) => break, + } + } + } + fn exit_group(code: i32) -> ! { // SAFETY: `exit_group` terminates the process immediately and never returns. let _ = unsafe { syscalls::syscall!(Sysno::exit_group, code) }; @@ -543,6 +590,8 @@ mod runtime { 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::creat => report_path_at(Some(CWD), a[0], AccessMode::Write, false), + #[cfg(target_arch = "x86_64")] Sysno::getdents => { if let Some(fd) = dirfd(0) { report_fd(fd, AccessMode::ReadDir); diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs index 3d8185b00..632dc4cb0 100644 --- a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs +++ b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs @@ -8,7 +8,7 @@ use std::{ use allocator_api2::vec::Vec as AllocVec; use fspy_nostd::{BorrowedFd, CStr, CWD, Thin}; -use fspy_nostd_alloc::fs::{fd_path, resolve_path_at}; +use fspy_nostd_alloc::fs::fd_path; use fspy_shared_unix::RawExec; use libc::{c_char, c_int}; @@ -31,16 +31,35 @@ const INITIAL_CAPACITY: usize = 64; /// completely in the common case when no chdir action is active. static ACTIVE_CHDIRS: AtomicUsize = AtomicUsize::new(0); +/// Base anchor for deferred `posix_spawn_file_actions_addchdir_np` / +/// `posix_spawn_file_actions_addfchdir_np` resolution. +/// +/// Resolved at `posix_spawn(p)` time rather than at `add*chdir_np` time so +/// reusing a `posix_spawn_file_actions_t` across `chdir(2)` or `dup2(2)` +/// matches kernel semantics. +enum ChdirBase { + Cwd, + Abs(Box<[u8]>), + Fd(c_int), +} + +struct SpawnChdir { + base: ChdirBase, + /// Relative components appended by subsequent relative `addchdir_np` + /// calls, joined by `/` without lexically collapsing `..`. + tail: Box<[u8]>, +} + /// Fork-safe table mapping live `posix_spawn_file_actions_t` handle values -/// (`*file_actions as usize`) to their effective absolute working directory -/// from `addchdir_np` / `addfchdir_np`. +/// (`*file_actions as usize`) to their deferred working-directory actions from +/// `addchdir_np` / `addfchdir_np`. /// /// Coordinated across `fork()` via `pthread_atfork`. No heap allocation or /// deallocation ever runs while holding `mutex`, avoiding lock-order inversion /// with libmalloc's own `atfork` handlers. struct SpawnChdirTable { mutex: UnsafeCell, - entries: UnsafeCell)>>, + entries: UnsafeCell>, } // SAFETY: `entries` is only accessed while holding `mutex`. @@ -85,12 +104,12 @@ fn ensure_init() { }); } -fn set_spawn_chdir(key: usize, path: Box<[u8]>) { +fn set_spawn_chdir(key: usize, entry: SpawnChdir) { ensure_init(); - let mut pending = Some(path); - let mut spare: Option)>> = None; - let mut to_drop_entry: Option> = None; - let mut to_drop_vec: Option)>> = None; + let mut pending = Some(entry); + let mut spare: Option> = None; + let mut to_drop_entry: Option = None; + let mut to_drop_vec: Option> = None; loop { // SAFETY: `SPAWN_CHDIRS.mutex` serializes all access to `entries`, and @@ -100,8 +119,8 @@ fn set_spawn_chdir(key: usize, path: Box<[u8]>) { let map = &mut *SPAWN_CHDIRS.entries.get(); let result = if let Some((_, existing)) = map.iter_mut().find(|(k, _)| *k == key) { - let new_path = pending.take().unwrap(); - to_drop_entry = Some(core::mem::replace(existing, new_path)); + let new_entry = pending.take().unwrap(); + to_drop_entry = Some(core::mem::replace(existing, new_entry)); None } else if map.len() < map.capacity() { map.push((key, pending.take().unwrap())); @@ -138,13 +157,99 @@ fn set_spawn_chdir(key: usize, path: Box<[u8]>) { drop(spare); } +fn append_relative_chdir(key: usize, rel: &[u8]) { + ensure_init(); + let mut scratch = Vec::with_capacity(256); + let mut spare: Option> = None; + let mut new_entry = Some(SpawnChdir { base: ChdirBase::Cwd, tail: Box::from(rel) }); + let mut new_tail: Option> = None; + let mut to_drop_tail: Option> = None; + let mut to_drop_vec: Option> = None; + + loop { + enum Action { + Done, + GrowVec(usize), + BuildJoinedTail(usize), + } + + // SAFETY: `SPAWN_CHDIRS.mutex` serializes all access to `entries`, and + // no allocation or deallocation occurs while the lock is held. + let action = unsafe { + libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); + let map = &mut *SPAWN_CHDIRS.entries.get(); + + let action = if let Some((_, existing)) = map.iter_mut().find(|(k, _)| *k == key) { + if new_tail.is_some() && existing.tail.as_ref() == scratch.as_slice() { + let joined = new_tail.take().unwrap(); + to_drop_tail = Some(core::mem::replace(&mut existing.tail, joined)); + Action::Done + } else if existing.tail.len() <= scratch.capacity() { + scratch.clear(); + scratch.extend_from_slice(&existing.tail); + Action::BuildJoinedTail(0) + } else { + Action::BuildJoinedTail(existing.tail.len()) + } + } else if map.len() < map.capacity() { + map.push((key, new_entry.take().unwrap())); + ACTIVE_CHDIRS.store(map.len(), Ordering::Release); + Action::Done + } else if let Some(mut grown) = spare.take() + && grown.capacity() > map.len() + { + grown.append(map); + grown.push((key, new_entry.take().unwrap())); + let old_vec = core::mem::replace(map, grown); + ACTIVE_CHDIRS.store(map.len(), Ordering::Release); + to_drop_vec = Some(old_vec); + Action::Done + } else { + Action::GrowVec(map.capacity().max(INITIAL_CAPACITY).saturating_mul(2)) + }; + + libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()); + action + }; + + // Drop replaced allocations strictly outside `SPAWN_CHDIRS.mutex`. + drop(to_drop_tail.take()); + drop(to_drop_vec.take()); + + match action { + Action::Done => break, + Action::GrowVec(cap) => { + spare = Some(Vec::with_capacity(cap)); + } + Action::BuildJoinedTail(min_cap) if min_cap > 0 => { + scratch.reserve(min_cap.saturating_sub(scratch.len())); + } + Action::BuildJoinedTail(_) => { + let mut joined = Vec::with_capacity(scratch.len() + 1 + rel.len()); + if !scratch.is_empty() { + joined.extend_from_slice(&scratch); + if joined.last() != Some(&b'/') { + joined.push(b'/'); + } + } + joined.extend_from_slice(rel); + new_tail = Some(joined.into_boxed_slice()); + } + } + } + + drop(new_entry); + drop(new_tail); + drop(spare); +} + fn remove_spawn_chdir(key: usize) { if ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 { return; } ensure_init(); // SAFETY: `SPAWN_CHDIRS.mutex` serializes access to `entries`; the removed - // `Box<[u8]>` is dropped strictly after unlocking. + // `SpawnChdir` is dropped strictly after unlocking. let removed = unsafe { libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); let map = &mut *SPAWN_CHDIRS.entries.get(); @@ -159,10 +264,21 @@ fn remove_spawn_chdir(key: usize) { drop(removed); } -fn get_spawn_chdir_in( +fn resolve_spawn_chdir_in( file_actions: *const libc::posix_spawn_file_actions_t, allocator: A, ) -> Option> { + enum SnapshotBase { + Cwd, + Abs, + Fd(c_int), + } + enum Status { + Missing, + Found(SnapshotBase), + NeedCap { base: usize, tail: usize }, + } + if file_actions.is_null() || ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 { return None; } @@ -174,34 +290,80 @@ fn get_spawn_chdir_in( ensure_init(); // Pre-allocate outside `SPAWN_CHDIRS.mutex` (macOS PATH_MAX is 1024). - let mut out = AllocVec::with_capacity_in(1024, allocator); - loop { + let mut base_buf = AllocVec::with_capacity_in(1024, allocator); + let mut tail_buf = AllocVec::with_capacity_in(256, allocator); + + let snapshot = loop { // SAFETY: `SPAWN_CHDIRS.mutex` serializes access to `entries`, and - // copying into pre-allocated `out` performs no heap allocation. + // copying into pre-allocated buffers performs no heap allocation. let status = unsafe { libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); let map = &*SPAWN_CHDIRS.entries.get(); let status = match map.iter().find(|(k, _)| *k == key) { - None => Ok(false), - Some((_, bytes)) if bytes.len() <= out.capacity() => { - out.clear(); - out.extend_from_slice(bytes); - Ok(true) + None => Status::Missing, + Some((_, entry)) => { + let abs_bytes = match &entry.base { + ChdirBase::Abs(b) => Some(b.as_ref()), + ChdirBase::Cwd | ChdirBase::Fd(_) => None, + }; + let need_base = abs_bytes.map_or(0, <[u8]>::len); + let need_tail = entry.tail.len(); + if need_base <= base_buf.capacity() && need_tail <= tail_buf.capacity() { + base_buf.clear(); + if let Some(b) = abs_bytes { + base_buf.extend_from_slice(b); + } + tail_buf.clear(); + tail_buf.extend_from_slice(&entry.tail); + let base_kind = match entry.base { + ChdirBase::Cwd => SnapshotBase::Cwd, + ChdirBase::Abs(_) => SnapshotBase::Abs, + ChdirBase::Fd(fd) => SnapshotBase::Fd(fd), + }; + Status::Found(base_kind) + } else { + Status::NeedCap { base: need_base, tail: need_tail } + } } - Some((_, bytes)) => Err(bytes.len()), }; libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()); status }; match status { - Ok(true) => return Some(out), - Ok(false) => return None, - Err(needed) => { - out.reserve(needed.saturating_sub(out.len())); + Status::Missing => return None, + Status::Found(base_kind) => break base_kind, + Status::NeedCap { base, tail } => { + base_buf.reserve(base.saturating_sub(base_buf.len())); + tail_buf.reserve(tail.saturating_sub(tail_buf.len())); } } + }; + + // Resolve the base anchor outside `SPAWN_CHDIRS.mutex` at `posix_spawn(p)` time. + match snapshot { + SnapshotBase::Abs => {} + SnapshotBase::Fd(fd) => { + // SAFETY: `fd` was accepted by `addfchdir_np`; invalid/closed fds yield `Ok(None)`. + let borrowed = unsafe { BorrowedFd::try_borrow_raw(fd) }?; + let dir = fd_path(allocator, borrowed).ok()??; + base_buf.clear(); + base_buf.extend_from_slice(dir.as_units()); + } + SnapshotBase::Cwd => { + let dir = fd_path(allocator, CWD).ok()??; + base_buf.clear(); + base_buf.extend_from_slice(dir.as_units()); + } } + + if !tail_buf.is_empty() { + if base_buf.last() != Some(&b'/') { + base_buf.push(b'/'); + } + base_buf.extend_from_slice(&tail_buf); + } + Some(base_buf) } intercept!(posix_spawn_file_actions_addchdir_np: unsafe extern "C" fn( @@ -222,30 +384,12 @@ unsafe extern "C" fn posix_spawn_file_actions_addchdir_np( let c_path = unsafe { CStr::::from_ptr(path.cast()) }; let raw = c_path.count().as_units(); if raw.starts_with(b"/") { - set_spawn_chdir(key, Box::from(raw)); - } else if !raw.is_empty() { - let prev = - get_spawn_chdir_in(file_actions.cast_const(), allocator_api2::alloc::Global); - let resolved = prev.map_or_else( - || { - let arena = fspy_nostd_alloc::pooled_bump(); - resolve_path_at(&arena, Some(CWD), c_path) - .ok() - .flatten() - .map(|p| Box::from(p.as_units())) - }, - |base| { - let mut joined = base.to_vec(); - if joined.last() != Some(&b'/') { - joined.push(b'/'); - } - joined.extend_from_slice(raw); - Some(joined.into_boxed_slice()) - }, + set_spawn_chdir( + key, + SpawnChdir { base: ChdirBase::Abs(Box::from(raw)), tail: Box::from([]) }, ); - if let Some(dir) = resolved { - set_spawn_chdir(key, dir); - } + } else if !raw.is_empty() { + append_relative_chdir(key, raw); } } } @@ -266,14 +410,7 @@ unsafe extern "C" fn posix_spawn_file_actions_addfchdir_np( // SAFETY: `original` succeeded on non-null `file_actions`. let key = (unsafe { *file_actions }) as usize; if key != 0 { - // SAFETY: `fd` was accepted by `addfchdir_np`. - let borrowed = unsafe { BorrowedFd::try_borrow_raw(fd) }; - if let Some(borrowed) = borrowed { - let arena = fspy_nostd_alloc::pooled_bump(); - if let Ok(Some(dir)) = fd_path(&arena, borrowed) { - set_spawn_chdir(key, Box::from(dir.as_units())); - } - } + set_spawn_chdir(key, SpawnChdir { base: ChdirBase::Fd(fd), tail: Box::from([]) }); } } ret @@ -316,7 +453,7 @@ unsafe fn handle_posix_spawn( .expect("posix_spawn(p) unexpectedly called before client initialized in ctor"); let arena = fspy_nostd_alloc::pooled_bump(); - let spawn_cwd = get_spawn_chdir_in(file_actions, &arena); + let spawn_cwd = resolve_spawn_chdir_in(file_actions, &arena); // SAFETY: file, argv, and envp are valid pointers forwarded from posix_spawn(p). let raw_command = match unsafe { client.handle_exec_in_dir( diff --git a/crates/fspy_shared_unix/src/linux.rs b/crates/fspy_shared_unix/src/linux.rs index d2be98803..9ae4bf066 100644 --- a/crates/fspy_shared_unix/src/linux.rs +++ b/crates/fspy_shared_unix/src/linux.rs @@ -226,7 +226,11 @@ pub fn resolve_exec( drop(file); // Preserve relative path as `script_arg` when relative to CWD (matching - // kernel `execve`), or substitute the resolved path for non-CWD `dirfd`. + // kernel `execve`), or substitute the resolved absolute path for + // non-CWD `dirfd`. We intentionally keep the resolved absolute path + // rather than `/dev/fd//` here because `send_path` filters + // `/dev/*` paths, so switching to `/dev/fd/...` would drop sibling-file + // tracking via `dirname "$0"`. 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()) @@ -261,6 +265,12 @@ fn resolve_empty_path( let Some(fd) = dirfd else { return Err(Error::BADF); }; + // Match Linux `execveat(AT_FDCWD, "", ..., AT_EMPTY_PATH)`: `AT_FDCWD` + // refers to the current working directory (not a regular file), so fail + // with `EACCES` rather than passing `AT_FDCWD` to `fstat` (`EBADF`). + if fd.as_raw_fd() == CWD.as_raw_fd() { + return Err(Error::ACCES); + } if !fstat(fd)?.is_regular_file() { return Err(Error::ACCES); } @@ -493,6 +503,14 @@ mod tests { ); assert_eq!(reads, 0); + // `AT_EMPTY_PATH` with `AT_FDCWD` refers to the current directory -> EACCES. + let mut exec = make_exec(b"", &[]); + assert_eq!( + resolve_exec(&mut exec, Some(CWD), ExecAtFlags::EMPTY_PATH, |_| reads += 1).err(), + Some(Error::ACCES) + ); + assert_eq!(reads, 0); + // SYMLINK_NOFOLLOW on symlink -> ELOOP. let mut exec = make_exec(link.as_os_str().as_bytes(), &[b"link"]); assert_eq!( From 6709cc81d8fce614e83d0376ce9a7bd5900890ad Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 01:30:37 +0800 Subject: [PATCH 20/48] fix(fspy): handle restricted process_vm_readv in nested probe and clarify launcher-vanished spawn error Co-authored-by: Gemini 4 Neon --- crates/fspy/src/linux/mod.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index 84e165507..646856e69 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -157,7 +157,12 @@ impl SpyImpl { Some(new_path) if new_path.as_bytes() == preload_path.as_bytes() => { tokio_command.spawn().map_err(SpawnError::OsSpawn)? } - _ => return Err(SpawnError::OsSpawn(err)), + _ => { + return Err(SpawnError::OsSpawn(io::Error::other(format!( + "fspy launcher vanished during spawn and could not be rematerialized at {}: {err}", + preload_path.as_os_str().to_string_lossy() + )))); + } } } Err(err) => return Err(SpawnError::OsSpawn(err)), @@ -332,6 +337,15 @@ fn is_already_tracked_by_fspy() -> bool { let n = unsafe { libc::process_vm_readv(libc::getpid(), &raw const local, 1, &raw const remote, 1, 0) }; + if n < 0 { + // Hardened container seccomp profiles may deny `process_vm_readv` + // (`EPERM`/`ENOSYS`). Since `PR_GET_SECCOMP == SECCOMP_MODE_FILTER` and + // `mincore` already confirmed `LAUNCHER_REGION.0` is mapped, fail safe + // as nested so inner `fspy` falls back to untracked instead of failing + // with `EEXIST`. + let err = io::Error::last_os_error().raw_os_error(); + return matches!(err, Some(libc::EPERM | libc::ENOSYS)); + } if n != hdr.len().cast_signed() { return false; } From 1028ac0944c8adbcc5a833f7324f68985b264aea Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 01:55:48 +0800 Subject: [PATCH 21/48] fix(fspy): handle unresolvable macOS spawn fchdir, re-probe kcmp, and document /proc/self/exe caveats - macOS posix_spawn: add `EncodedPayload::inject_env` and `ResolvedChdir::Unresolvable` so relative programs with an unresolvable `addfchdir_np(fd)` still inject tracking env and forward directly to `original` instead of resolving against the parent CWD; also rekey `SPAWN_CHDIRS` when libsystem reallocates `*file_actions` across subsequent `addopen`/`addclose`/`adddup2`/`addinherit_np`/`add*chdir_np` calls. - Linux preload: re-probe `kcmp(my_pid, my_pid, KCMP_VM)` on unexpected `shares_vm_with` errors and flip `KCMP_VM_AVAILABLE` off if blocked so subsequent `CLONE_VM` children fall back to `set_tid_address`. - `fspy_elf_loader`: document `/proc/self/exe` nuances for memfd/unlinked and in-place replaced targets in `README.md`. Co-authored-by: Gemini 4 Neon --- crates/fspy/tests/macos_preload.rs | 189 ++++++++++++++++ crates/fspy_elf_loader/README.md | 9 + crates/fspy_preload_linux/src/main.rs | 15 +- crates/fspy_preload_macos/src/client.rs | 12 +- .../src/interceptions/spawn/posix_spawn.rs | 206 +++++++++++++++--- crates/fspy_preload_macos/src/libc.rs | 5 + crates/fspy_shared_unix/src/macos.rs | 84 ++++++- 7 files changed, 482 insertions(+), 38 deletions(-) diff --git a/crates/fspy/tests/macos_preload.rs b/crates/fspy/tests/macos_preload.rs index be14f2be3..96b4ffcb6 100644 --- a/crates/fspy/tests/macos_preload.rs +++ b/crates/fspy/tests/macos_preload.rs @@ -739,3 +739,192 @@ async fn posix_spawn_defers_relative_addchdir_and_addfchdir_resolution_to_spawn_ Ok(()) } + +#[test(tokio::test)] +async fn posix_spawn_addfchdir_np_child_only_fd_and_realloc_actions() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let root = tmp_dir.path().canonicalize()?; + let sub = root.join("child_only_fd_dir"); + fs::create_dir(&sub)?; + + let marker = sub.join("marker_child_only_fd"); + fs::write(&marker, "ok")?; + + // Build a non-SIP relative `./helper` executable in `sub` by symlinking the + // test binary and passing `command_for_fn!`'s dispatch args. + let helper_cmd = + test_utils::command_for_fn!(marker.to_str().unwrap().to_owned(), |marker_path: String| { + assert_eq!(std::env::var("CUSTOM_ONLY").as_deref(), Ok("1")); + assert_eq!(fs::read(&marker_path).unwrap(), b"ok"); + }); + let helper_link = sub.join("helper"); + std::os::unix::fs::symlink(&helper_cmd.program, &helper_link)?; + let helper_args: Vec = + helper_cmd.args.into_iter().map(|s| s.into_string().unwrap()).collect(); + + // Place a decoy `./helper` in `root` (the parent's CWD) that fails if run, + // so we prove `ResolvedChdir::Unresolvable` never falls back to parent CWD. + write_executable(&root.join("helper"), "#!/bin/sh\nexit 99\n")?; + + let args = (root.to_str().unwrap().to_owned(), sub.to_str().unwrap().to_owned(), helper_args); + let accesses = + track_fn!(args, |(root_dir, sub_dir, helper_args): (String, String, Vec)| { + unsafe extern "C" { + fn posix_spawn_file_actions_addchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + path: *const libc::c_char, + ) -> libc::c_int; + fn posix_spawn_file_actions_addfchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + fd: libc::c_int, + ) -> libc::c_int; + } + + std::env::set_current_dir(&root_dir).unwrap(); + + // Pick an fd number that is not open in the parent so `addopen` + // creates it exclusively in the spawned child. + let child_fd = (40..200) + // SAFETY: `F_GETFD` on a candidate fd only queries descriptor state. + .find(|&fd| unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1) + .expect("no unused fd in 40..200"); + + let sub_c = CString::new(sub_dir.as_str()).unwrap(); + let prog = c"./helper"; + let c_args: Vec = + helper_args.iter().map(|s| CString::new(s.as_str()).unwrap()).collect(); + let mut argv: Vec<*mut libc::c_char> = Vec::with_capacity(c_args.len() + 2); + argv.push(prog.as_ptr().cast_mut()); + for arg in &c_args { + argv.push(arg.as_ptr().cast_mut()); + } + argv.push(std::ptr::null_mut()); + + // Explicit custom `envp` without inheriting `environ` (no `DYLD_INSERT_LIBRARIES` + // or `FSPY_PAYLOAD`); `fspy_preload_macos` must inject both into it. + let custom_env = c"CUSTOM_ONLY=1"; + let envp = [custom_env.as_ptr().cast_mut(), std::ptr::null_mut()]; + + // 1. `addopen(child_fd, sub)` + `addfchdir_np(child_fd)` + `addclose(child_fd)`. + // On current XNU, `PSFA_FCHDIR` checks the parent's fd table before + // `addopen` runs and returns `EBADF`; on a POSIX.1-2024 sequential + // kernel it succeeds in `sub`. Either way, fspy must not fail with + // spurious `ENOENT` or execute the decoy `./helper` in `root_dir`. + let mut actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated directory path. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut actions), 0); + assert_eq!( + libc::posix_spawn_file_actions_addopen( + &raw mut actions, + child_fd, + sub_c.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY, + 0, + ), + 0 + ); + assert_eq!(posix_spawn_file_actions_addfchdir_np(&raw mut actions, child_fd), 0); + assert_eq!(libc::posix_spawn_file_actions_addclose(&raw mut actions, child_fd), 0); + } + + let mut child: libc::pid_t = 0; + // SAFETY: all pointers are valid C strings/arrays and `actions` is initialized. + let rc = unsafe { + libc::posix_spawn( + &raw mut child, + prog.as_ptr(), + &raw const actions, + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + // SAFETY: destroying initialized `actions`. + unsafe { assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut actions), 0) }; + if rc == 0 { + let mut status: libc::c_int = 0; + // SAFETY: `child` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(child, &raw mut status, 0) }, child); + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "child failed with raw status {status:#x}" + ); + } else { + assert_eq!( + rc, + libc::EBADF, + "expected EBADF from XNU (or 0 on sequential kernels), not spurious errno {rc}" + ); + } + + // 2. `addchdir_np(sub)` followed by multiple file actions that force + // libsystem to `realloc` `*file_actions`, with explicit custom `envp`: + // verifies rekeying survives reallocation and child access is tracked. + let mut realloc_actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated paths. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut realloc_actions), 0); + assert_eq!( + posix_spawn_file_actions_addchdir_np(&raw mut realloc_actions, sub_c.as_ptr()), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_addopen( + &raw mut realloc_actions, + child_fd, + c"/dev/null".as_ptr(), + libc::O_RDONLY, + 0, + ), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_adddup2( + &raw mut realloc_actions, + child_fd, + child_fd + 1, + ), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_addclose(&raw mut realloc_actions, child_fd), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_addclose(&raw mut realloc_actions, child_fd + 1), + 0 + ); + } + let mut child2: libc::pid_t = 0; + // SAFETY: all pointers are valid C strings/arrays and `realloc_actions` is initialized. + let rc2 = unsafe { + libc::posix_spawn( + &raw mut child2, + prog.as_ptr(), + &raw const realloc_actions, + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + // SAFETY: destroying initialized `realloc_actions`. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut realloc_actions), 0); + } + assert_eq!(rc2, 0, "posix_spawn(./helper) after file_actions realloc failed: {rc2}"); + + let mut status2: libc::c_int = 0; + // SAFETY: `child2` is our child and `status2` is writable. + assert_eq!(unsafe { libc::waitpid(child2, &raw mut status2, 0) }, child2); + assert!( + libc::WIFEXITED(status2) && libc::WEXITSTATUS(status2) == 0, + "child2 failed with raw status {status2:#x}" + ); + }) + .await?; + + assert_contains(&accesses, &marker, PathAccess::Read); + + Ok(()) +} diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index 2b5f7b102..0247df1f9 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -75,6 +75,15 @@ Do not try to close these in this crate unless a real target requires it: - **Execute-only (`0111`) binaries.** Userland ELF mapping opens the executable with `O_RDONLY` to validate headers and `mmap` segments, so execute-only (`chmod 0111`) binaries cannot be mapped and fail with `EACCES`. +- **Deleted or replaced `/proc/self/exe` targets.** Virtualized `/proc/self/exe` + stores the target's path at load time rather than keeping an extra target fd + open (which would break clean FD-table invariants): + - When the target was a `memfd` or already unlinked at load time, `readlink` + still reports the `" (deleted)"` path, while path-following `open`/`stat`/ + `execve` on `/proc/self/exe` reach the launcher instead. + - When a target binary is replaced in place after load (e.g. via `rename`), + path-following calls on `/proc/self/exe` follow the saved path to the new + file rather than the original unlinked inode. - **Launcher path visibility across mount changes.** Every tracked `execve` re-enters the materialized freestanding launcher binary on disk. If a tracked process tree changes its mount namespace or root (`chroot`, `pivot_root`, or diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index 4960d3318..d1711256c 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -706,8 +706,19 @@ mod runtime { Ok(_) | Err(syscalls::Errno::ESRCH) => false, // Treat any other error (`EPERM`, `EINVAL`, `ENOSYS`, etc.) // conservatively as still sharing VM so a live `CLONE_VM` child's - // exec scratch is never freed prematurely. - Err(_) => true, + // exec scratch is never freed prematurely. If a self-probe now + // also fails (e.g. because the target installed a seccomp filter + // blocking `kcmp` after startup), flip `KCMP_VM_AVAILABLE` off so + // subsequent `CLONE_VM` children switch to `set_tid_address` + // instead of leaking unboundedly; nodes parked before the target + // installed its filter (or just before the flag flipped) stay + // boundedly leaked. + Err(_) => { + if kcmp_vm(my_pid, my_pid).is_err() { + KCMP_VM_AVAILABLE.store(false, Ordering::Relaxed); + } + true + } } } diff --git a/crates/fspy_preload_macos/src/client.rs b/crates/fspy_preload_macos/src/client.rs index 51ad776c0..f20bd8a06 100644 --- a/crates/fspy_preload_macos/src/client.rs +++ b/crates/fspy_preload_macos/src/client.rs @@ -5,7 +5,7 @@ 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 fspy_shared_unix::{Exec, RawExec, macos::EncodedPayload}; use libc::{c_char, c_int}; use crate::which; @@ -97,6 +97,16 @@ impl Client<'_> { })?; Ok(RawExec::from_exec(exec)) } + + /// Injects `DYLD_INSERT_LIBRARIES` and `FSPY_PAYLOAD` into `exec.envs` + /// without path resolution, shebang parsing, or SIP swapping. + /// + /// # Errors + /// + /// Returns [`Error::NOMEM`] if environment storage cannot be allocated. + pub fn inject_env(&self, exec: &mut Exec) -> Result<()> { + self.encoded_payload.inject_env(exec) + } } static CLIENT: OnceLock> = OnceLock::new(); diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs index 632dc4cb0..f6c382e66 100644 --- a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs +++ b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs @@ -243,6 +243,36 @@ fn append_relative_chdir(key: usize, rel: &[u8]) { drop(spare); } +fn rekey_spawn_chdir(old_key: usize, new_key: usize) { + if old_key == new_key + || old_key == 0 + || new_key == 0 + || ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 + { + return; + } + ensure_init(); + // SAFETY: `SPAWN_CHDIRS.mutex` serializes access to `entries`, and updating + // a key in place performs no heap allocation or deallocation. + unsafe { + libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); + let map = &mut *SPAWN_CHDIRS.entries.get(); + if let Some(entry) = map.iter_mut().find(|(k, _)| *k == old_key) { + entry.0 = new_key; + } + libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()); + } +} + +fn read_actions_key(file_actions: *const libc::posix_spawn_file_actions_t) -> usize { + if file_actions.is_null() { + 0 + } else { + // SAFETY: caller passed a non-null `file_actions` pointer. + (unsafe { *file_actions }) as usize + } +} + fn remove_spawn_chdir(key: usize) { if ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 { return; @@ -264,10 +294,20 @@ fn remove_spawn_chdir(key: usize) { drop(removed); } +enum ResolvedChdir { + /// No chdir action is registered on `file_actions`. + None, + /// Resolved absolute working directory for the child. + Dir(AllocVec), + /// A registered `addfchdir_np(fd)` could not be resolved in the parent + /// (for example, when an earlier `addopen` creates `fd` only in the child). + Unresolvable, +} + fn resolve_spawn_chdir_in( file_actions: *const libc::posix_spawn_file_actions_t, allocator: A, -) -> Option> { +) -> ResolvedChdir { enum SnapshotBase { Cwd, Abs, @@ -280,12 +320,12 @@ fn resolve_spawn_chdir_in( } if file_actions.is_null() || ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 { - return None; + return ResolvedChdir::None; } // SAFETY: caller passed a non-null `file_actions` pointer to `posix_spawn(p)`. let key = (unsafe { *file_actions }) as usize; if key == 0 { - return None; + return ResolvedChdir::None; } ensure_init(); @@ -331,7 +371,7 @@ fn resolve_spawn_chdir_in( }; match status { - Status::Missing => return None, + Status::Missing => return ResolvedChdir::None, Status::Found(base_kind) => break base_kind, Status::NeedCap { base, tail } => { base_buf.reserve(base.saturating_sub(base_buf.len())); @@ -341,17 +381,31 @@ fn resolve_spawn_chdir_in( }; // Resolve the base anchor outside `SPAWN_CHDIRS.mutex` at `posix_spawn(p)` time. + // Note: on current XNU, `PSFA_FCHDIR` resolves `fd` against the parent's + // descriptor table before `addopen`/`adddup2` actions run, matching + // `fd_path`. If a future kernel executes file actions sequentially and an + // earlier `addopen`/`adddup2` reuses a parent-open fd number for a + // different directory, `fd_path` would still see the parent's fd instead + // of the child's; for a child-only or closed fd, returning `Unresolvable` + // avoids resolving relative programs against the parent's CWD and preserves + // both env injection and the kernel's `EBADF`. match snapshot { SnapshotBase::Abs => {} SnapshotBase::Fd(fd) => { - // SAFETY: `fd` was accepted by `addfchdir_np`; invalid/closed fds yield `Ok(None)`. - let borrowed = unsafe { BorrowedFd::try_borrow_raw(fd) }?; - let dir = fd_path(allocator, borrowed).ok()??; + // SAFETY: `fd` was accepted by `addfchdir_np`; invalid/closed fds yield `None`. + let Some(borrowed) = (unsafe { BorrowedFd::try_borrow_raw(fd) }) else { + return ResolvedChdir::Unresolvable; + }; + let Ok(Some(dir)) = fd_path(allocator, borrowed) else { + return ResolvedChdir::Unresolvable; + }; base_buf.clear(); base_buf.extend_from_slice(dir.as_units()); } SnapshotBase::Cwd => { - let dir = fd_path(allocator, CWD).ok()??; + let Ok(Some(dir)) = fd_path(allocator, CWD) else { + return ResolvedChdir::None; + }; base_buf.clear(); base_buf.extend_from_slice(dir.as_units()); } @@ -363,7 +417,87 @@ fn resolve_spawn_chdir_in( } base_buf.extend_from_slice(&tail_buf); } - Some(base_buf) + ResolvedChdir::Dir(base_buf) +} + +intercept!(posix_spawn_file_actions_addopen: unsafe extern "C" fn( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: c_int, + path: *const c_char, + oflag: c_int, + mode: libc::mode_t, +) -> c_int); +unsafe extern "C" fn posix_spawn_file_actions_addopen( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: c_int, + path: *const c_char, + oflag: c_int, + mode: libc::mode_t, +) -> c_int { + let old_key = read_actions_key(file_actions); + // SAFETY: forwarding caller arguments to the original libc function. + let ret = unsafe { + posix_spawn_file_actions_addopen::original()(file_actions, filedes, path, oflag, mode) + }; + if ret == 0 { + // libsystem may `realloc` `*file_actions` as the action list grows. + rekey_spawn_chdir(old_key, read_actions_key(file_actions)); + } + ret +} + +intercept!(posix_spawn_file_actions_addclose: unsafe extern "C" fn( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: c_int, +) -> c_int); +unsafe extern "C" fn posix_spawn_file_actions_addclose( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: c_int, +) -> c_int { + let old_key = read_actions_key(file_actions); + // SAFETY: forwarding caller arguments to the original libc function. + let ret = unsafe { posix_spawn_file_actions_addclose::original()(file_actions, filedes) }; + if ret == 0 { + rekey_spawn_chdir(old_key, read_actions_key(file_actions)); + } + ret +} + +intercept!(posix_spawn_file_actions_adddup2: unsafe extern "C" fn( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: c_int, + newfiledes: c_int, +) -> c_int); +unsafe extern "C" fn posix_spawn_file_actions_adddup2( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: c_int, + newfiledes: c_int, +) -> c_int { + let old_key = read_actions_key(file_actions); + // SAFETY: forwarding caller arguments to the original libc function. + let ret = + unsafe { posix_spawn_file_actions_adddup2::original()(file_actions, filedes, newfiledes) }; + if ret == 0 { + rekey_spawn_chdir(old_key, read_actions_key(file_actions)); + } + ret +} + +intercept!(posix_spawn_file_actions_addinherit_np: unsafe extern "C" fn( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: c_int, +) -> c_int); +unsafe extern "C" fn posix_spawn_file_actions_addinherit_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: c_int, +) -> c_int { + let old_key = read_actions_key(file_actions); + // SAFETY: forwarding caller arguments to the original libc function. + let ret = unsafe { posix_spawn_file_actions_addinherit_np::original()(file_actions, filedes) }; + if ret == 0 { + rekey_spawn_chdir(old_key, read_actions_key(file_actions)); + } + ret } intercept!(posix_spawn_file_actions_addchdir_np: unsafe extern "C" fn( @@ -374,11 +508,12 @@ unsafe extern "C" fn posix_spawn_file_actions_addchdir_np( file_actions: *mut libc::posix_spawn_file_actions_t, path: *const c_char, ) -> c_int { + let old_key = read_actions_key(file_actions); // SAFETY: forwarding caller arguments to the original libc function. let ret = unsafe { posix_spawn_file_actions_addchdir_np::original()(file_actions, path) }; if ret == 0 && !file_actions.is_null() && !path.is_null() { - // SAFETY: `original` succeeded on non-null `file_actions`. - let key = (unsafe { *file_actions }) as usize; + let key = read_actions_key(file_actions); + rekey_spawn_chdir(old_key, key); if key != 0 { // SAFETY: non-null `path` is a valid NUL-terminated C string. let c_path = unsafe { CStr::::from_ptr(path.cast()) }; @@ -404,11 +539,12 @@ unsafe extern "C" fn posix_spawn_file_actions_addfchdir_np( file_actions: *mut libc::posix_spawn_file_actions_t, fd: c_int, ) -> c_int { + let old_key = read_actions_key(file_actions); // SAFETY: forwarding caller arguments to the original libc function. let ret = unsafe { posix_spawn_file_actions_addfchdir_np::original()(file_actions, fd) }; if ret == 0 && !file_actions.is_null() { - // SAFETY: `original` succeeded on non-null `file_actions`. - let key = (unsafe { *file_actions }) as usize; + let key = read_actions_key(file_actions); + rekey_spawn_chdir(old_key, key); if key != 0 { set_spawn_chdir(key, SpawnChdir { base: ChdirBase::Fd(fd), tail: Box::from([]) }); } @@ -453,18 +589,38 @@ unsafe fn handle_posix_spawn( .expect("posix_spawn(p) unexpectedly called before client initialized in ctor"); let arena = fspy_nostd_alloc::pooled_bump(); - let spawn_cwd = resolve_spawn_chdir_in(file_actions, &arena); - // SAFETY: file, argv, and envp are valid pointers forwarded from posix_spawn(p). - let raw_command = match unsafe { - client.handle_exec_in_dir( - search_path, - spawn_cwd.as_deref(), - RawExec { prog: file, argv: argv.cast(), envp: envp.cast() }, - &arena, - ) - } { - Ok(raw) => raw, - Err(err) => return err.raw_os_error(), + let raw_in = RawExec { prog: file, argv: argv.cast(), envp: envp.cast() }; + let raw_command = match resolve_spawn_chdir_in(file_actions, &arena) { + ResolvedChdir::Unresolvable + if file.addr() >= 4096 && { + // SAFETY: `file` is non-null and outside page 0, forwarded from `posix_spawn(p)`. + let file_bytes = unsafe { CStr::::from_ptr(file.cast()) }.count().as_units(); + !file_bytes.starts_with(b"/") && (!search_path || file_bytes.contains(&b'/')) + } => + { + // SAFETY: file, argv, and envp are valid pointers forwarded from posix_spawn(p). + let mut exec = match unsafe { raw_in.to_exec(&arena) } { + Ok(exec) => exec, + Err(err) => return err.raw_os_error(), + }; + if let Err(err) = client.inject_env(&mut exec) { + return err.raw_os_error(); + } + RawExec::from_exec(exec) + } + resolved => { + let spawn_cwd = match resolved { + ResolvedChdir::Dir(dir) => Some(dir), + ResolvedChdir::None | ResolvedChdir::Unresolvable => None, + }; + // SAFETY: file, argv, and envp are valid pointers forwarded from posix_spawn(p). + match unsafe { + client.handle_exec_in_dir(search_path, spawn_cwd.as_deref(), raw_in, &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. diff --git a/crates/fspy_preload_macos/src/libc.rs b/crates/fspy_preload_macos/src/libc.rs index 90465781e..b9880f8a1 100644 --- a/crates/fspy_preload_macos/src/libc.rs +++ b/crates/fspy_preload_macos/src/libc.rs @@ -67,4 +67,9 @@ unsafe extern "C" { file_actions: *mut posix_spawn_file_actions_t, fd: c_int, ) -> c_int; + + pub unsafe fn posix_spawn_file_actions_addinherit_np( + file_actions: *mut posix_spawn_file_actions_t, + filedes: c_int, + ) -> c_int; } diff --git a/crates/fspy_shared_unix/src/macos.rs b/crates/fspy_shared_unix/src/macos.rs index 5e113e84e..f7bde43b7 100644 --- a/crates/fspy_shared_unix/src/macos.rs +++ b/crates/fspy_shared_unix/src/macos.rs @@ -101,6 +101,21 @@ impl<'a> EncodedPayload<'a> { self.payload.ipc_channel_conf } + /// Injects `DYLD_INSERT_LIBRARIES` and `FSPY_PAYLOAD` into `exec.envs` + /// without running path resolution, shebang parsing, or SIP swapping. + /// + /// # Errors + /// + /// Returns [`Error::NOMEM`] if environment storage cannot be allocated. + pub fn inject_env(&self, exec: &mut Exec) -> Result<()> { + 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()) + } + /// 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`. @@ -210,16 +225,7 @@ impl<'a> EncodedPayload<'a> { }; 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(), - )?; + self.inject_env(exec)?; } else { remove_path_env( &mut exec.envs, @@ -436,4 +442,62 @@ mod tests { payload.prepare_exec(&mut exec, |_| {}).unwrap(); assert_eq!(exec.program.as_slice(), b"/tmp/fspy_bash"); } + + #[cfg(target_os = "macos")] + #[test] + fn inject_env_sets_dyld_and_payload_without_modifying_program() { + use allocator_api2::alloc::Global; + use fspy_shared::ipc::{IpcStr, channel::channel}; + + use super::{DYLD_INSERT_LIBRARIES, EncodedPayload, PAYLOAD_ENV_NAME, Payload}; + use crate::nostd_exec::{Exec, to_vec_in}; + + let receiver = channel(1 << 30, Global).unwrap(); + let preload = b"/tmp/fspy_preload.dylib"; + let payload = EncodedPayload::encode( + Payload { + ipc_channel_conf: receiver.conf(), + preload_path: IpcStr::from_bytes(preload), + bash_path: IpcStr::from_bytes(b"/tmp/fspy_bash"), + coreutils_path: IpcStr::from_bytes(b"/tmp/fspy_coreutils"), + }, + Global, + ); + + let mut envs = allocator_api2::vec::Vec::new_in(Global); + envs.push((to_vec_in(b"CUSTOM_ONLY", Global), Some(to_vec_in(b"1", Global)))); + let mut exec = Exec { + program: to_vec_in(b"./helper", Global), + args: allocator_api2::vec::Vec::new_in(Global), + envs, + }; + payload.inject_env(&mut exec).unwrap(); + assert_eq!(exec.program.as_slice(), b"./helper"); + let find_env = |key: &[u8]| { + exec.envs.iter().find(|(k, _)| k.as_slice() == key).and_then(|(_, v)| v.as_deref()) + }; + assert_eq!(find_env(b"CUSTOM_ONLY"), Some(b"1".as_slice())); + assert_eq!(find_env(DYLD_INSERT_LIBRARIES), Some(preload.as_slice())); + assert_eq!(find_env(PAYLOAD_ENV_NAME.as_bytes()), Some(payload.encoded_string.as_bytes())); + + // Existing user `DYLD_INSERT_LIBRARIES` is preserved with ours appended. + let mut envs = allocator_api2::vec::Vec::new_in(Global); + envs.push(( + to_vec_in(DYLD_INSERT_LIBRARIES, Global), + Some(to_vec_in(b"/tmp/user.dylib", Global)), + )); + let mut exec = Exec { + program: to_vec_in(b"/bin/sh", Global), + args: allocator_api2::vec::Vec::new_in(Global), + envs, + }; + payload.inject_env(&mut exec).unwrap(); + assert_eq!(exec.program.as_slice(), b"/bin/sh"); + let dyld = exec + .envs + .iter() + .find(|(k, _)| k.as_slice() == DYLD_INSERT_LIBRARIES) + .and_then(|(_, v)| v.as_deref()); + assert_eq!(dyld, Some(b"/tmp/user.dylib:/tmp/fspy_preload.dylib".as_slice())); + } } From 193adaf40e6c11b212d477741aa4ee8bd897a9d4 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 12:29:42 +0800 Subject: [PATCH 22/48] refactor(fspy): remove Linux-only nested fspy probe from #1029 Co-authored-by: Gemini 4 Neon --- crates/fspy/Cargo.toml | 2 +- crates/fspy/src/linux/mod.rs | 88 +--------------------------- crates/fspy/tests/linux_hardening.rs | 35 ----------- 3 files changed, 4 insertions(+), 121 deletions(-) diff --git a/crates/fspy/Cargo.toml b/crates/fspy/Cargo.toml index cada19113..14d7e603c 100644 --- a/crates/fspy/Cargo.toml +++ b/crates/fspy/Cargo.toml @@ -33,7 +33,6 @@ fspy_shared_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] -fspy_elf_loader = { workspace = true } linux-raw-sys = { workspace = true, features = ["general", "prctl", "ptrace"] } syscalls = { workspace = true } tracing = { workspace = true } @@ -69,6 +68,7 @@ nix = { workspace = true, features = ["fs"] } [target.'cfg(target_os = "linux")'.dev-dependencies] elf = { workspace = true } +fspy_elf_loader = { 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" } diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index 646856e69..e78d1c77a 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -10,11 +10,10 @@ 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_GET_SECCOMP, PR_SET_NO_NEW_PRIVS}, + prctl::PR_SET_NO_NEW_PRIVS, ptrace::{ - BPF_ABS, BPF_JEQ, BPF_JMP, BPF_K, BPF_LD, BPF_RET, BPF_W, SECCOMP_MODE_FILTER, - SECCOMP_RET_ALLOW, SECCOMP_RET_TRAP, SECCOMP_SET_MODE_FILTER, seccomp_data, sock_filter, - sock_fprog, + BPF_ABS, BPF_JEQ, BPF_JMP, BPF_K, BPF_LD, BPF_RET, BPF_W, SECCOMP_RET_ALLOW, + SECCOMP_RET_TRAP, SECCOMP_SET_MODE_FILTER, seccomp_data, sock_filter, sock_fprog, }, }; use syscalls::Sysno; @@ -48,12 +47,6 @@ impl SpyImpl { reason = "matches cross-platform SpyImpl::init() -> io::Result signature" )] pub fn init() -> io::Result { - if is_already_tracked_by_fspy() { - tracing::debug!( - "nested inside an active fspy tracker; delegating tracking to outer tracker" - ); - return Ok(Self { preload_path: RwLock::new(None), seccomp_available: false }); - } let seccomp_available = probe_seccomp_available(); let preload_path = if seccomp_available { let materialized = materialize_preload(); @@ -282,81 +275,6 @@ fn materialize_preload() -> Option> { .map(|p| p.as_path().into()) } -/// Detects whether the current process is already running inside an outer -/// `fspy` Linux launcher (`fspy_preload_linux`). -/// -/// Because `fspy_preload_linux` is linked at a fixed address in -/// [`fspy_elf_loader::LAUNCHER_REGION`], spawning another `fspy_preload_linux` -/// directly from inside a tracked process would collide with the outer -/// launcher's resident mappings (`EEXIST`). Falling back to untracked -/// execution lets the inner spawn succeed while the outer tracker records the -/// entire nested subtree. -fn is_already_tracked_by_fspy() -> bool { - #[cfg(target_arch = "x86_64")] - const NATIVE_MACHINE: u16 = 62; // EM_X86_64 - #[cfg(target_arch = "aarch64")] - const NATIVE_MACHINE: u16 = 183; // EM_AARCH64 - - // 1. Confirm seccomp filter mode (`SECCOMP_MODE_FILTER == 2`) is active. - // SAFETY: `PR_GET_SECCOMP` takes no pointer arguments and only queries - // the calling thread's seccomp mode. - let seccomp_mode = unsafe { syscalls::syscall!(Sysno::prctl, PR_GET_SECCOMP, 0, 0, 0, 0) }; - if seccomp_mode != Ok(SECCOMP_MODE_FILTER as usize) { - return false; - } - - // 2. Check whether `LAUNCHER_REGION.0` is mapped (read-only; `ENOMEM` - // means unmapped). - let region_base = fspy_elf_loader::LAUNCHER_REGION.0; - // SAFETY: `_SC_PAGESIZE` is a standard `sysconf` query. - let page_size = usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }) - .ok() - .filter(|&n| n > 0) - .unwrap_or(4096); - let mut vec: u8 = 0; - // SAFETY: `mincore` writes one residency byte per page (`1` page -> `vec`). - if unsafe { - libc::mincore(core::ptr::with_exposed_provenance_mut(region_base), page_size, &raw mut vec) - } != 0 - { - return false; - } - - // 3. Safely read the first 64 bytes at `LAUNCHER_REGION.0` via - // `process_vm_readv` (returns `EFAULT` without crashing if unreadable or - // `PROT_NONE`) and confirm it is a native little-endian ELF64 `ET_EXEC` - // header matching `fspy_preload_linux`. - let mut hdr = [0_u8; 64]; - let local = libc::iovec { iov_base: hdr.as_mut_ptr().cast(), iov_len: hdr.len() }; - let remote = libc::iovec { - iov_base: core::ptr::with_exposed_provenance_mut(region_base), - iov_len: hdr.len(), - }; - // SAFETY: `local` points to our writable 64-byte buffer and `remote` is - // validated by the kernel in `process_vm_readv`. - let n = unsafe { - libc::process_vm_readv(libc::getpid(), &raw const local, 1, &raw const remote, 1, 0) - }; - if n < 0 { - // Hardened container seccomp profiles may deny `process_vm_readv` - // (`EPERM`/`ENOSYS`). Since `PR_GET_SECCOMP == SECCOMP_MODE_FILTER` and - // `mincore` already confirmed `LAUNCHER_REGION.0` is mapped, fail safe - // as nested so inner `fspy` falls back to untracked instead of failing - // with `EEXIST`. - let err = io::Error::last_os_error().raw_os_error(); - return matches!(err, Some(libc::EPERM | libc::ENOSYS)); - } - if n != hdr.len().cast_signed() { - return false; - } - - hdr[0..4] == *b"\x7fELF" - && hdr[4] == 2 // ELFCLASS64 - && hdr[5] == 1 // ELFDATA2LSB - && u16::from_le_bytes([hdr[16], hdr[17]]) == 2 // ET_EXEC - && u16::from_le_bytes([hdr[18], hdr[19]]) == NATIVE_MACHINE -} - /// Probes once on a dedicated short-lived OS thread whether /// `PR_SET_NO_NEW_PRIVS` and `seccomp(SECCOMP_SET_MODE_FILTER)` with /// `SECCOMP_RET_TRAP` are permitted in the current environment. diff --git a/crates/fspy/tests/linux_hardening.rs b/crates/fspy/tests/linux_hardening.rs index 10775679a..cd55d65e2 100644 --- a/crates/fspy/tests/linux_hardening.rs +++ b/crates/fspy/tests/linux_hardening.rs @@ -771,41 +771,6 @@ async fn posix_spawn_setsigdef_resets_child_sigsys_without_mutating_parent() -> Ok(()) } -#[test(tokio::test)] -async fn nested_fspy_falls_back_cleanly_while_outer_tracks_subtree() -> anyhow::Result<()> { - let probe_path = Path::new("/fspy-nested-inner-child-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)| { - let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); - rt.block_on(async move { - let mut inner_cmd = fspy::Command::new(&static_bin); - inner_cmd.args(["open_read", &probe_path]); - let termination = inner_cmd - .spawn(tokio_util::sync::CancellationToken::new()) - .await - .expect("nested fspy spawn must succeed via untracked fallback") - .wait_handle - .await - .expect("nested fspy child wait failed"); - assert!( - termination.status.success(), - "nested child exited unsuccessfully: {:?}", - termination.status - ); - assert!( - termination.path_accesses.is_err(), - "nested fspy must report TrackingIncomplete while delegating to outer tracker" - ); - }); - } - ); - - let accesses = test_utils::spawn_command(cmd).await?; - assert_contains(&accesses, probe_path, fspy::PathAccess::Read); - Ok(()) -} - #[test(tokio::test)] async fn execve_of_et_exec_overlapping_launcher_region_returns_eexist_cleanly() -> anyhow::Result<()> { From 119b67a650ef2376a1ad041a84922036f2b5dc2d Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 12:47:00 +0800 Subject: [PATCH 23/48] fix(fspy_preload_macos): initialize spawn chdir atfork handler in ctor Co-authored-by: Gemini 4 Neon --- .../src/interceptions/spawn/posix_spawn.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs index f6c382e66..42887a6b8 100644 --- a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs +++ b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs @@ -104,6 +104,16 @@ fn ensure_init() { }); } +/// Register the `pthread_atfork` handler eagerly at dylib load time while the +/// process is single-threaded, so a concurrent `fork()` can never race with +/// the first `ATFORK_INIT.call_once(...)` and leave the `Once` stuck in an +/// in-progress state in the child. +#[cfg(not(test))] +#[ctor::ctor(unsafe)] +fn init_spawn_chdirs() { + ensure_init(); +} + fn set_spawn_chdir(key: usize, entry: SpawnChdir) { ensure_init(); let mut pending = Some(entry); From 8cde1a2e8112bdbb1dc621c180c2946f5566aabe Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 12:55:07 +0800 Subject: [PATCH 24/48] ci(benchmark): clean freestanding Linux artifact targets after baseline build Co-authored-by: Gemini 4 Neon --- .github/workflows/fspy-benchmark.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/fspy-benchmark.yml b/.github/workflows/fspy-benchmark.yml index db3ec05e4..fe653e5b7 100644 --- a/.github/workflows/fspy-benchmark.yml +++ b/.github/workflows/fspy-benchmark.yml @@ -94,8 +94,14 @@ jobs: [[ "$RUNNER_OS" == "Windows" ]] && exe=.exe cp "$CARGO_TARGET_DIR/release/fspy_benchmark_launcher$exe" "$RUNNER_TEMP/fspy-base-launcher$exe" # A baseline worktree created after the head can leave newer - # workspace artifacts that Cargo considers fresh for the head. + # workspace artifacts that Cargo considers fresh for the head, + # including cross-target artifact dependencies like fspy_preload_linux. cargo clean --release --workspace + for target in x86_64-unknown-none aarch64-unknown-none-softfloat; do + if [[ -d "$CARGO_TARGET_DIR/$target" ]]; then + cargo clean --release --workspace --target "$target" + fi + done - name: Run benchmark run: | From 85e8dd892cd8b8e7041b4d9eb44d84c9bb6cf7ab Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 13:07:38 +0800 Subject: [PATCH 25/48] test(fspy): synchronize script writes against spawns in shebang tests to prevent ETXTBSY Co-authored-by: Gemini 4 Neon --- crates/fspy/tests/shebang.rs | 43 +++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/crates/fspy/tests/shebang.rs b/crates/fspy/tests/shebang.rs index fdaccb0d2..c0204b694 100644 --- a/crates/fspy/tests/shebang.rs +++ b/crates/fspy/tests/shebang.rs @@ -12,6 +12,21 @@ use test_log::test; use test_utils::assert_contains; use tokio::fs; +/// Coordinates script creation (`O_WRONLY`) against concurrent `fork`/`vfork` +/// spawns across tests in this binary so no sibling spawn briefly inherits a +/// writable script descriptor and triggers a transient Linux `ETXTBSY`. +static SCRIPT_EXEC_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); + +async fn write_executable_script( + path: impl AsRef, + content: impl AsRef<[u8]>, +) -> anyhow::Result<()> { + let _write_guard = SCRIPT_EXEC_LOCK.write().await; + fs::write(path.as_ref(), content).await?; + fs::set_permissions(path.as_ref(), std::fs::Permissions::from_mode(0o755)).await?; + Ok(()) +} + #[test(tokio::test)] async fn spawn_sh_shebang() -> anyhow::Result<()> { let tmp_dir = tempfile::TempDir::new()?; @@ -19,12 +34,9 @@ async fn spawn_sh_shebang() -> anyhow::Result<()> { let shebang_script_path = tmp_dir.path().join("fspy_test_shebang_script.sh"); let shebang_script_path = shebang_script_path.into_os_string().into_string().unwrap(); - fs::write(&shebang_script_path, "#!/bin/sh\ncat hello\n").await?; - - let mut perms = fs::metadata(&shebang_script_path).await?.permissions(); - perms.set_mode(0o755); - fs::set_permissions(&shebang_script_path, perms).await?; + write_executable_script(&shebang_script_path, "#!/bin/sh\ncat hello\n").await?; + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; let accesses = track_fn!(shebang_script_path.clone(), |shebang_script_path: String| { let _ignored = Command::new(&shebang_script_path) .current_dir("/") @@ -61,10 +73,11 @@ async fn spawn_shebang_with_long_interpreter_path() -> anyhow::Result<()> { fs::symlink("/bin/sh", &interpreter).await?; let script_path = tmp_dir.path().join("long_shebang.sh"); - fs::write(&script_path, format!("#!{}\necho ok\n", interpreter.display())).await?; - fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).await?; + write_executable_script(&script_path, format!("#!{}\necho ok\n", interpreter.display())) + .await?; let script_path = script_path.into_os_string().into_string().unwrap(); + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; let accesses = track_fn!(script_path, |script_path: String| { let output = Command::new(&script_path).stdin(Stdio::null()).output(); // On macOS, fspy only swaps the arm64e `/bin/sh` for its own shell when @@ -94,8 +107,7 @@ async fn spawn_shebang_with_long_interpreter_path() -> anyhow::Result<()> { async fn shebang_argument_splitting_matches_platform() -> anyhow::Result<()> { let tmp_dir = tempfile::TempDir::new()?; let script_path = tmp_dir.path().canonicalize()?.join("split_args.sh"); - fs::write(&script_path, "#!/bin/echo foo bar\n").await?; - fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).await?; + write_executable_script(&script_path, "#!/bin/echo foo bar\n").await?; let script_str = script_path.to_str().unwrap().to_owned(); let expected = if cfg!(target_os = "macos") { @@ -103,6 +115,7 @@ async fn shebang_argument_splitting_matches_platform() -> anyhow::Result<()> { } else { format!("foo bar {script_str}\n") }; + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; let untraced = Command::new(&script_str).stdin(Stdio::null()).output()?; assert!(untraced.status.success()); assert_eq!(String::from_utf8_lossy(&untraced.stdout), expected); @@ -132,16 +145,14 @@ async fn chained_shebang_depth_matches_platform() -> anyhow::Result<()> { let mut scripts = Vec::new(); let base = root.join("hop1.sh"); - fs::write(&base, "#!/bin/sh\necho chained-ok\n").await?; - fs::set_permissions(&base, std::fs::Permissions::from_mode(0o755)).await?; + write_executable_script(&base, "#!/bin/sh\necho chained-ok\n").await?; scripts.push(base); let max_hops = if cfg!(target_os = "macos") { 2 } else { 6 }; for i in 2..=max_hops { let prev = scripts.last().unwrap(); let next = root.join(format!("hop{i}.sh")); - fs::write(&next, format!("#!{}\n", prev.display())).await?; - fs::set_permissions(&next, std::fs::Permissions::from_mode(0o755)).await?; + write_executable_script(&next, format!("#!{}\n", prev.display())).await?; scripts.push(next); } @@ -150,6 +161,7 @@ async fn chained_shebang_depth_matches_platform() -> anyhow::Result<()> { let expected_errno = if cfg!(target_os = "macos") { libc::ENOEXEC } else { libc::ELOOP }; let args = (max_ok, too_deep, expected_errno); + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; let accesses = track_fn!(args, |(max_ok, too_deep, expected_errno): (String, String, libc::c_int)| { let output = Command::new(&max_ok) @@ -204,13 +216,13 @@ async fn overlong_shebang_is_rejected_with_enoexec() -> anyhow::Result<()> { let script_path = tmp_dir.path().canonicalize()?.join("overlong.sh"); // Longer than both Linux's 256-byte and macOS's 512-byte kernel buffers. let content = format!("#!/{}\n", "a".repeat(520)); - fs::write(&script_path, content).await?; - fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).await?; + write_executable_script(&script_path, content).await?; let script_str = script_path.to_str().unwrap().to_owned(); // Use `posix_spawn` directly: `posix_spawnp` (used by `std::process::Command`) // falls back to `/bin/sh` on `ENOEXEC` on macOS. let c_script = std::ffi::CString::new(script_str.as_str())?; + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; assert_eq!(posix_spawn_errno(&c_script), libc::ENOEXEC); let accesses = track_fn!(script_str, |script_str: String| { @@ -235,6 +247,7 @@ async fn exec_fifo_does_not_block_and_returns_eacces() -> anyhow::Result<()> { assert_eq!(unsafe { libc::mkfifo(fifo_cstr.as_ptr(), 0o755) }, 0); let fifo_str = fifo_path.to_str().unwrap().to_owned(); + let _exec_guard = SCRIPT_EXEC_LOCK.read().await; let untraced_err = Command::new(&fifo_str).stdin(Stdio::null()).status().unwrap_err(); assert_eq!(untraced_err.raw_os_error(), Some(libc::EACCES)); From fab0d70db4e5c70afb6b52336d9a9b0ae3ca5795 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 16:39:19 +0800 Subject: [PATCH 26/48] fix(fspy_elf_loader): let signals interrupt a blocking creat replay On x86-64, creat is trapped for tracking but was replayed with all signals masked, so creat on a FIFO without a reader could not be interrupted by SIGALRM or Ctrl-C. Classify it as a potentially blocking open, like open/openat/openat2 without O_NONBLOCK. Co-Authored-By: Claude Opus 5.5 --- crates/fspy/tests/linux_syscalls.rs | 50 +++++++++++++++++++++++- crates/fspy_elf_loader/src/sigsys/mod.rs | 9 +++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/fspy/tests/linux_syscalls.rs b/crates/fspy/tests/linux_syscalls.rs index d290e256c..7b4082dc1 100644 --- a/crates/fspy/tests/linux_syscalls.rs +++ b/crates/fspy/tests/linux_syscalls.rs @@ -8,7 +8,8 @@ //! - `openat2` invalid `how_ptr` / invalid `size` (`EFAULT` / `EINVAL`) //! - `openat(O_RDONLY | O_CREAT)` / `openat(O_RDONLY | O_TRUNC)` recording `ReadWrite`, //! and `renameat2(RENAME_EXCHANGE)` recording both paths -//! - Legacy x86-64 `SYS_open`, `SYS_stat`, and `SYS_lstat` +//! - Legacy x86-64 `SYS_open`, `SYS_stat`, and `SYS_lstat`, and `SYS_creat` on a FIFO +//! interrupted by a signal #![cfg(target_os = "linux")] mod test_utils; @@ -617,6 +618,53 @@ async fn legacy_x86_64_open_creat_stat_lstat_syscalls_are_tracked() -> anyhow::R Ok(()) } +/// A signal interrupts `SYS_creat` blocked on a FIFO without a reader, as it +/// does natively. +#[cfg(target_arch = "x86_64")] +#[test(tokio::test)] +async fn legacy_x86_64_creat_on_fifo_is_interruptible_by_signal() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let fifo = tmp_dir.path().canonicalize()?.join("fifo"); + nix::unistd::mkfifo(&fifo, nix::sys::stat::Mode::S_IRWXU)?; + + let accesses = track_fn!(fifo.to_str().unwrap().to_owned(), |fifo: String| { + use std::{ffi::CString, ptr}; + + extern "C" fn on_alarm(_: libc::c_int) {} + + let c_fifo = CString::new(fifo).unwrap(); + let handler: extern "C" fn(libc::c_int) = on_alarm; + // SAFETY: a zeroed `sigaction` is valid. Without `SA_RESTART`, an + // interrupted `creat` fails with `EINTR`. + let rc = unsafe { + let mut action: libc::sigaction = std::mem::zeroed(); + action.sa_sigaction = handler as libc::sighandler_t; + libc::sigaction(libc::SIGALRM, &raw const action, ptr::null_mut()) + }; + assert_eq!(rc, 0); + // Raise `SIGALRM` every 10 ms so one arrives while `creat` waits for a reader. + let tick = libc::timeval { tv_sec: 0, tv_usec: 10_000 }; + let timer = libc::itimerval { it_interval: tick, it_value: tick }; + // SAFETY: `timer` is a valid `itimerval`. + let rc = unsafe { libc::setitimer(libc::ITIMER_REAL, &raw const timer, ptr::null_mut()) }; + assert_eq!(rc, 0); + + // SAFETY: valid C string; `SYS_creat` takes `(path, mode)`. + let fd = unsafe { libc::syscall(libc::SYS_creat, c_fifo.as_ptr(), 0o644) }; + let err = errno(); + let zero = libc::timeval { tv_sec: 0, tv_usec: 0 }; + let off = libc::itimerval { it_interval: zero, it_value: zero }; + // SAFETY: `off` is a valid `itimerval` that disarms the timer. + let rc = unsafe { libc::setitimer(libc::ITIMER_REAL, &raw const off, ptr::null_mut()) }; + assert_eq!(rc, 0); + assert_eq!((fd, err), (-1, libc::EINTR)); + }) + .await?; + + assert_includes(&accesses, &fifo, PathAccess::Write); + Ok(()) +} + #[test(tokio::test)] async fn execveat_sets_kernel_matching_at_execfn_while_preserving_proc_self_exe() -> anyhow::Result<()> { diff --git a/crates/fspy_elf_loader/src/sigsys/mod.rs b/crates/fspy_elf_loader/src/sigsys/mod.rs index 20bb4fbd4..9c39ac613 100644 --- a/crates/fspy_elf_loader/src/sigsys/mod.rs +++ b/crates/fspy_elf_loader/src/sigsys/mod.rs @@ -646,8 +646,8 @@ unsafe fn dispatch_phase1( } // 5. Return to the entry stack to replay the (possibly rewritten) syscall. - // Unmask signals for potentially blocking `open*` (e.g. FIFO without - // `O_NONBLOCK`) and directly-replayed `execve`/`execveat`, unless all + // Unmask signals for potentially blocking `open*`/`creat` (e.g. FIFO + // without `O_NONBLOCK`) and directly-replayed `execve`/`execveat`, unless all // maskable signals were already blocked by the caller. packet.inv = inv; // SAFETY: Inspects `openat2`'s `open_how` safely via `usermem` if not already prefetched. @@ -675,7 +675,7 @@ unsafe fn dispatch_phase1( /// Returns `true` if replaying `sysno` on the entry stack should temporarily /// restore the caller's signal mask (`open`/`openat`/`openat2` without -/// `O_NONBLOCK`/`O_PATH`, or `execve`/`execveat`). +/// `O_NONBLOCK`/`O_PATH`, `creat`, or `execve`/`execveat`). /// /// # Safety /// @@ -690,6 +690,9 @@ unsafe fn needs_unmasked_replay( match sysno { #[cfg(target_arch = "x86_64")] Sysno::open => ((inv.args[1] as u32) & NON_BLOCKING_FLAGS) == 0, + // `creat` is `open(O_CREAT | O_WRONLY | O_TRUNC)`, which blocks on a FIFO. + #[cfg(target_arch = "x86_64")] + Sysno::creat => true, Sysno::openat => ((inv.args[2] as u32) & NON_BLOCKING_FLAGS) == 0, Sysno::openat2 => { let how = if let Some(how) = prefetched_open_how { From 6c335ec514cf1515c85352226dec80710b56cc49 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 16:39:20 +0800 Subject: [PATCH 27/48] docs(fspy_elf_loader): document exec and SIGSYS virtualization limits List what userland exec and SIGSYS virtualization do not emulate: ETXTBSY write exclusion, effective-credential permission checks, extra signal frames on alternate stacks, glibc PC-checked thread cancellation, and the SIGSYS states outside rt_sigaction/rt_sigprocmask/rt_sigpending and masked waits. Co-Authored-By: Claude Opus 5.5 --- crates/fspy_elf_loader/README.md | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index 0247df1f9..aba5f0972 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -75,6 +75,15 @@ Do not try to close these in this crate unless a real target requires it: - **Execute-only (`0111`) binaries.** Userland ELF mapping opens the executable with `O_RDONLY` to validate headers and `mmap` segments, so execute-only (`chmod 0111`) binaries cannot be mapped and fail with `EACCES`. +- **Real-credential permission checks.** The executable and `PT_INTERP` `X_OK` + checks use `faccessat` with the real user and group IDs, so they do not + match kernel exec permission when real and effective IDs differ, including + IDs inherited from the parent. +- **No executable write protection.** The target is mapped from an ordinary + read-only descriptor rather than kernel-execed, so Linux's `ETXTBSY` write + exclusion does not apply. Opening a running target for writing succeeds, and + truncating or overwriting it can crash the process with `SIGBUS` or corrupt + its code. Executing a file that is still open for writing also succeeds. - **Deleted or replaced `/proc/self/exe` targets.** Virtualized `/proc/self/exe` stores the target's path at load time rather than keeping an extra target fd open (which would break clean FD-table invariants): @@ -89,6 +98,32 @@ Do not try to close these in this crate unless a real target requires it: process tree changes its mount namespace or root (`chroot`, `pivot_root`, or a private `/tmp` mount hiding the materialized launcher path), subsequent child `execve` calls fail with `ENOENT`. +- **Signal stacks.** A trapped syscall delivers `SIGSYS` on the current stack + before switching to a private one, so a handler that makes a trapped syscall + on a `sigaltstack` needs room for one more kernel signal frame (about + `AT_MINSIGSTKSZ`) plus trampoline headroom, or it overflows. The dispatcher + always uses `SA_ONSTACK`, so a forwarded target `SIGSYS` handler (including + `SIGSYS` from the target's own seccomp filter) runs on the alternate stack + even when installed without `SA_ONSTACK`. +- **Thread cancellation.** Trapped syscalls are replayed from launcher code, + outside glibc's PC-checked cancellation region, so `pthread_cancel` of a + thread blocked in a trapped syscall (such as an `open` waiting on a FIFO or + device) can hang instead of cancelling. +- **Virtualized `SIGSYS` state.** Only `rt_sigaction`, `rt_sigprocmask`, + `rt_sigpending`, and masked waits see the target's virtual `SIGSYS` blocked + and pending state: + - The `sigwait` family and `signalfd` cannot consume a virtually pending + `SIGSYS`. + - Another handler's `sa_mask` (including `sigfillset`) does not defer + `SIGSYS` while that handler runs. + - Shared-VM children (`vfork`, raw `clone(CLONE_VM)`) do not inherit the + virtual blocked bit, so `vfork` followed by `exec` starts with `SIGSYS` + unblocked (glibc `pthread_create` threads re-apply their mask). A custom + `SIGSYS` handler installed in a raw `CLONE_VM` child is replaced by the + fatal default. + - A virtually pending `SIGSYS` is lost across `exec`. + - A `SIGSYS` sent while virtually blocked can interrupt otherwise untrapped + blocking I/O with `EINTR`. - GNU properties, other arches, growable stack (fixed 8–64 MiB from `RLIMIT_STACK` + guard), and personality cleanup. From 9132ac5b7b76e43cb304bd7beec862fb72eb6ae7 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 17:26:12 +0800 Subject: [PATCH 28/48] fix(fspy_shared_unix): fail execveat of a script through a close-on-exec dirfd Linux runs a script reached by a relative path under a non-AT_FDCWD dirfd as /dev/fd//, and fails with ENOENT when that dirfd is FD_CLOEXEC because the interpreter could not open it. Tracked execveat substituted the absolute path and ran the script instead. Return ENOENT there too, and use non-CLOEXEC dirfds in the tests that expect success. Co-Authored-By: Claude Opus 5.5 --- crates/fspy/tests/linux_syscalls.rs | 25 +++++++++++++++++-- crates/fspy_shared_unix/src/linux.rs | 36 +++++++++++++++++++++++++--- 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/crates/fspy/tests/linux_syscalls.rs b/crates/fspy/tests/linux_syscalls.rs index 7b4082dc1..becaaa320 100644 --- a/crates/fspy/tests/linux_syscalls.rs +++ b/crates/fspy/tests/linux_syscalls.rs @@ -170,9 +170,30 @@ async fn execveat_nofollow_dirfd_o_path_and_empty_path_scripts() -> anyhow::Resu ]; assert_eq!(run_execveat_in_child(dirfd, c"rel_bin", &argv_rel_bin, 0), 0); - // 3. Non-CWD `dirfd` + relative `#!` script. + // 3. Non-CWD `dirfd` + relative `#!` script. The interpreter reaches the + // script as `/dev/fd//`, so the `dirfd` must survive exec: + // through the `O_CLOEXEC` `dirfd`, Linux fails with `ENOENT`. let argv_rel_script = [c"rel_script.sh".as_ptr(), std::ptr::null()]; - assert_eq!(run_execveat_in_child(dirfd, c"rel_script.sh", &argv_rel_script, 0), 0); + // SAFETY: valid arguments to `execveat` expected to fail with `ENOENT`. + let rc = unsafe { + libc::syscall( + libc::SYS_execveat, + dirfd, + c"rel_script.sh".as_ptr(), + argv_rel_script.as_ptr(), + envp_empty.as_ptr(), + 0, + ) + }; + assert_eq!(rc, -1, "execveat of a script through an O_CLOEXEC dirfd should fail"); + assert_eq!(errno(), libc::ENOENT); + // SAFETY: `dup` returns a non-`CLOEXEC` duplicate of the open `dirfd`. + let inheritable_dirfd = unsafe { libc::dup(dirfd) }; + assert!(inheritable_dirfd >= 0, "dup dirfd failed: {}", errno()); + assert_eq!( + run_execveat_in_child(inheritable_dirfd, c"rel_script.sh", &argv_rel_script, 0), + 0 + ); // 4. `O_PATH` + `AT_EMPTY_PATH` on an ELF executable. // SAFETY: valid path relative to `dirfd`. diff --git a/crates/fspy_shared_unix/src/linux.rs b/crates/fspy_shared_unix/src/linux.rs index 9ae4bf066..ff898838e 100644 --- a/crates/fspy_shared_unix/src/linux.rs +++ b/crates/fspy_shared_unix/src/linux.rs @@ -219,6 +219,16 @@ pub fn resolve_exec( if let Some(shebang) = parse_shebang_bytes(&peek_buf[..n], ParseShebangOptions::linux(), allocator.clone())? { + // Matches Linux `alloc_bprm` + `binfmt_script`: a script reached through + // a relative path under an `FD_CLOEXEC` `dirfd` is inaccessible to the + // interpreter as `/dev/fd//`, so exec fails with `ENOENT`. + if !is_abs + && let Some(d) = cur_dirfd + && d.as_raw_fd() != CWD.as_raw_fd() + && fcntl_is_cloexec(d)? + { + return Err(Error::NOENT); + } depth += 1; if depth > LINUX_MAX_RECURSION { return Err(Error::LOOP); @@ -537,6 +547,23 @@ mod tests { Some(Error::NOENT) ); + // Relative shebang script under a CLOEXEC non-CWD dirfd -> ENOENT; under + // a non-CLOEXEC dirfd it resolves. + let dir_file = File::open(dir.path()).unwrap(); // Rust opens with O_CLOEXEC. + // SAFETY: `dir_file` remains open for the call. + let cloexec_dirfd = unsafe { BorrowedFd::borrow_raw(dir_file.as_raw_fd()) }; + let mut exec = make_exec(b"script.sh", &[b"script.sh"]); + assert_eq!( + resolve_exec(&mut exec, Some(cloexec_dirfd), ExecAtFlags::empty(), |_| {}).err(), + Some(Error::NOENT) + ); + let plain_dirfd = fcntl_dupfd(cloexec_dirfd, 3).unwrap(); + let mut exec = make_exec(b"script.sh", &[b"script.sh"]); + assert!( + resolve_exec(&mut exec, Some(plain_dirfd.as_fd()), ExecAtFlags::empty(), |_| {}) + .is_ok() + ); + // AT_EMPTY_PATH on non-CLOEXEC O_PATH shebang script reopens readable // and passes `/dev/fd/` (non-CLOEXEC) to the interpreter. // Open directly via `openat(O_PATH)` because Rust's `OpenOptions::custom_flags` @@ -602,21 +629,24 @@ mod tests { ); // 3. Relative path with real `dirfd` -> `/dev/fd//` (both binary & script). + // The `dirfd` is non-`CLOEXEC` so the script stays reachable after exec. let dir_file = File::open(dir.path()).unwrap(); // SAFETY: `dir_file` stays open for the call. - let dir_fd = unsafe { BorrowedFd::borrow_raw(dir_file.as_raw_fd()) }; + let dir_owned = + fcntl_dupfd(unsafe { BorrowedFd::borrow_raw(dir_file.as_raw_fd()) }, 3).unwrap(); + let dir_fd = dir_owned.as_fd(); let mut exec = make_exec(b"bin", &[b"bin"]); let resolved = resolve_exec(&mut exec, Some(dir_fd), ExecAtFlags::empty(), |_| {}).unwrap(); assert_eq!( resolved.execfn.as_slice(), - format!("/dev/fd/{}/bin", dir_file.as_raw_fd()).as_bytes() + format!("/dev/fd/{}/bin", dir_fd.as_raw_fd()).as_bytes() ); let mut exec = make_exec(b"script.sh", &[b"script.sh"]); let resolved = resolve_exec(&mut exec, Some(dir_fd), ExecAtFlags::empty(), |_| {}).unwrap(); assert_eq!( resolved.execfn.as_slice(), - format!("/dev/fd/{}/script.sh", dir_file.as_raw_fd()).as_bytes() + format!("/dev/fd/{}/script.sh", dir_fd.as_raw_fd()).as_bytes() ); // 4. Absolute path (even with real `dirfd`) preserves `exec.program`. From 9359e1eafc1f4b6b5f401836df9542ab04de664c Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 17:26:14 +0800 Subject: [PATCH 29/48] docs(fspy_elf_loader): document auxv, shared FD table, and async SIGSYS limits Add /proc/self/auxv, CLONE_FILES descriptor leaks, kcmp-denied clear_child_tid, uc_sigmask edits that block SIGSYS, and asynchronous SIGSYS delivery to the list of exec and SIGSYS virtualization limits. Co-Authored-By: Claude Opus 5.5 --- crates/fspy_elf_loader/README.md | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index aba5f0972..65aca13ef 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -68,7 +68,10 @@ Do not try to close these in this crate unless a real target requires it: still works via mmap; leave brk alone. - **External `/proc` views.** `/proc/self/exe` and `/proc//exe` are virtualized inside the tracked process, while external `/proc//exe` - observers still see the launcher binary. + observers still see the launcher binary. `/proc/self/auxv` still holds the + kernel's vector for the launcher, so its `AT_PHDR`, `AT_PHNUM`, `AT_ENTRY`, + and `AT_BASE` differ from what `getauxval` and the startup stack report, and + inspecting program headers through it finds the launcher's. - **Privileged / unsupported binaries.** `PR_SET_NO_NEW_PRIVS` is enabled for seccomp (so setuid/setgid and file-capability escalations do not apply), and ELF32 and `binfmt_misc` binaries are rejected with `ENOEXEC`. @@ -98,6 +101,15 @@ Do not try to close these in this crate unless a real target requires it: process tree changes its mount namespace or root (`chroot`, `pivot_root`, or a private `/tmp` mount hiding the materialized launcher path), subsequent child `execve` calls fail with `ENOENT`. +- **Shared descriptor tables.** In a child that shares its parent's descriptor + table (`CLONE_FILES` without `CLONE_THREAD`, with or without `CLONE_VM`), the + descriptors a tracked `execve` opens stay open in the processes still sharing + the table after the exec, so repeated execs from such children can exhaust + descriptors (`EMFILE`). +- **`kcmp`-denied environments.** Where `kcmp` is denied, a shared-VM child + created with `CLONE_CHILD_CLEARTID` that execs does not have its + `clear_child_tid` word cleared and woken, so a parent waiting on that futex + can hang. - **Signal stacks.** A trapped syscall delivers `SIGSYS` on the current stack before switching to a private one, so a handler that makes a trapped syscall on a `sigaltstack` needs room for one more kernel signal frame (about @@ -122,8 +134,15 @@ Do not try to close these in this crate unless a real target requires it: `SIGSYS` handler installed in a raw `CLONE_VM` child is replaced by the fatal default. - A virtually pending `SIGSYS` is lost across `exec`. - - A `SIGSYS` sent while virtually blocked can interrupt otherwise untrapped - blocking I/O with `EINTR`. + - A handler that blocks `SIGSYS` by editing its `ucontext`'s `uc_sigmask` + (including with `sigfillset`) leaves the real `SIGSYS` blocked after it + returns, so the next trapped syscall terminates the process. + - An asynchronous, non-seccomp `SIGSYS` (from `kill`, `tgkill`, or a timer) + interrupts otherwise untrapped blocking syscalls with `EINTR` when it is + virtually blocked, when `SIGSYS` is ignored, and when the target's handler + was installed with `SA_RESTART`. A process-directed one can stay pending + indefinitely on a thread that virtually blocks it, even while another + thread has it unblocked. - GNU properties, other arches, growable stack (fixed 8–64 MiB from `RLIMIT_STACK` + guard), and personality cleanup. From 53e78e2af1963fad0ee9b2606f8c8b5d847611f4 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 18:07:48 +0800 Subject: [PATCH 30/48] fix(fspy): keep argv writes visible and run top-level /proc/self/exe natively The launcher now hands the target its own kernel argument strings when userland resolution left argv unchanged (nested execs always), so a process title or a scrubbed argument shows in /proc//cmdline as it does natively. A top-level /proc/self/exe (or /proc//exe) is resolved in the parent, where it names the spawning process's executable, instead of in the launcher, where it named the launcher. Co-Authored-By: Claude Opus 5.5 --- crates/fspy/src/linux/mod.rs | 27 +++++++++++++++++++-- crates/fspy/tests/linux_syscalls.rs | 13 ++++++++++ crates/fspy/tests/node_fs.rs | 34 +++++++++++++++++++++++++++ crates/fspy_preload_linux/src/main.rs | 24 +++++++++++++++++-- 4 files changed, 94 insertions(+), 4 deletions(-) diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index e78d1c77a..e2ea2e69e 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -1,7 +1,11 @@ use std::{ + ffi::OsStr, io, mem::offset_of, - os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd}, + os::{ + fd::{AsRawFd as _, FromRawFd as _, OwnedFd}, + unix::ffi::OsStrExt as _, + }, path::Path, sync::RwLock, }; @@ -115,7 +119,9 @@ impl SpyImpl { .map_err(SpawnError::OsSpawn)?; let write_raw_fd = write_end.as_raw_fd(); - let target_path: &IpcStr = command.target_program().into(); + let exe_link_target = resolve_process_exe_link(command.target_program()); + let target_path: &IpcStr = + exe_link_target.as_deref().map_or(command.target_program(), OsStr::new).into(); let bootstrap = Bootstrap { ipc_channel_conf: ipc_receiver.conf(), preload_path: &preload_path, @@ -262,6 +268,23 @@ fn spawn_untracked( }) } +/// Resolves a program that names this process's own executable link +/// (`/proc/self/exe`, `/proc/thread-self/exe`, or `/proc//exe`) to the +/// executable's path. Natively the forked child execs it before its image +/// changes, so it means this process's executable, while the launcher would +/// resolve it to itself. Other `/proc` paths keep resolving in the child, which +/// may depend on its setup (such as `/proc/self/cwd` after `current_dir`). +fn resolve_process_exe_link(program: &OsStr) -> Option { + let link = program.as_bytes().strip_prefix(b"/proc/")?.strip_suffix(b"/exe")?; + let is_own = link == b"self" + || link == b"thread-self" + || link == std::process::id().to_string().as_bytes(); + if !is_own { + return None; + } + std::fs::canonicalize(program).ok() +} + fn clone_ipc_str(s: &IpcStr) -> Box { Path::new(s.as_os_str()).into() } diff --git a/crates/fspy/tests/linux_syscalls.rs b/crates/fspy/tests/linux_syscalls.rs index becaaa320..8ed212481 100644 --- a/crates/fspy/tests/linux_syscalls.rs +++ b/crates/fspy/tests/linux_syscalls.rs @@ -801,3 +801,16 @@ async fn execveat_sets_kernel_matching_at_execfn_while_preserving_proc_self_exe( let _accesses = test_utils::spawn_command(cmd).await?; Ok(()) } + +/// A top-level `/proc/self/exe` names the spawning process's executable, as it +/// does when a forked child execs it natively, not the launcher's. +#[test(tokio::test)] +async fn top_level_proc_self_exe_runs_the_spawning_executable() -> anyhow::Result<()> { + let mut command = fspy::Command::new("/proc/self/exe"); + // libtest lists the tests and exits 0 without running them. + command.arg("--list").stdout(std::process::Stdio::null()); + let child = command.spawn(tokio_util::sync::CancellationToken::new()).await?; + let termination = child.wait_handle.await?; + assert!(termination.status.success(), "{:?}", termination.status); + Ok(()) +} diff --git a/crates/fspy/tests/node_fs.rs b/crates/fspy/tests/node_fs.rs index 4eed20a74..b9fec2527 100644 --- a/crates/fspy/tests/node_fs.rs +++ b/crates/fspy/tests/node_fs.rs @@ -235,3 +235,37 @@ fn fork_ipc(runtime: &str) -> anyhow::Result<()> { assert_contains(&accesses, &data_path, PathAccess::Read); Ok(()) } + +/// `process.title` overwrites the argv strings. The tracked program keeps the +/// kernel's argument strings, so `/proc/self/cmdline` shows the new title, both +/// when spawned directly and after a nested `exec`. +#[cfg(target_os = "linux")] +#[test] +#[ignore = "requires node"] +fn process_title_shows_in_proc_cmdline() -> anyhow::Result<()> { + let (node, path) = resolve_runtime("node")?; + let script = "process.title = 'fspy-title-probe'; \ + const cmdline = require('node:fs').readFileSync('/proc/self/cmdline', 'latin1'); \ + if (!cmdline.startsWith('fspy-title-probe\\0')) { \ + console.error(JSON.stringify(cmdline)); process.exit(1); \ + }"; + for nested in [false, true] { + let mut command = if nested { + let mut command = fspy::Command::new("/bin/sh"); + command.args(["-c", "exec \"$0\" -e \"$1\""]).arg(&node).arg(script); + command + } else { + let mut command = fspy::Command::new(&node); + command.arg("-e").arg(script); + command + }; + command.envs(vars_os()).env("PATH", &path); + tokio::runtime::Runtime::new()?.block_on(async { + let child = command.spawn(tokio_util::sync::CancellationToken::new()).await?; + let termination = child.wait_handle.await?; + assert!(termination.status.success(), "nested={nested}: {:?}", termination.status); + anyhow::Ok(()) + })?; + } + Ok(()) +} diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index d1711256c..3b2ad3747 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -165,6 +165,7 @@ mod runtime { } #[expect(clippy::needless_pass_by_value, reason = "signature required by fspy_nostd::main!")] + #[expect(clippy::too_many_lines, reason = "bootstrap decoding plus both target entry paths")] fn run(stack: InitialStack<'_>) -> ! { // SAFETY: `run` executes once in a fresh single-threaded process. let bump: &'static PageBump = unsafe { &*STARTUP_BUMP.0.get() }; @@ -220,9 +221,14 @@ mod runtime { }; let execfn = leak_cstr(&resolved.execfn, bump); + let argv_in_place = args_match_kernel(&exec.args, stack.args()); let mut argv = Vec::with_capacity_in(exec.args.len(), bump); - for arg in &exec.args { - argv.push(leak_cstr(arg, bump)); + if argv_in_place { + argv.extend(stack.args().iter().copied()); + } else { + for arg in &exec.args { + argv.push(leak_cstr(arg, bump)); + } } let on_ready = || { @@ -246,6 +252,7 @@ mod runtime { resolved.file, execfn, argv.into_iter(), + argv_in_place, filtered_envs, stack.auxv(), Some(INTERCEPTOR), @@ -275,7 +282,9 @@ mod runtime { fspy_elf_loader::try_exec_elf( file, execfn_cstr.as_c_str().as_thin(), + // The interceptor exec'd us with the target's final argv. stack.args().iter().copied(), + true, filtered_envs, stack.auxv(), Some(INTERCEPTOR), @@ -292,6 +301,17 @@ mod runtime { } } + /// Returns whether resolved `args` byte-match the kernel's argument strings + /// (no userland shebang expansion), so the target can keep using those and + /// writes to its argv show in `/proc//cmdline` as they do natively. + fn args_match_kernel>( + args: &[T], + kernel: &[CStr<'_, Thin>], + ) -> bool { + args.len() == kernel.len() + && args.iter().zip(kernel).all(|(arg, kernel)| **arg == *kernel.count().as_units()) + } + fn scrub_bootstrap_env(entries: &[(*mut u8, usize)]) { for &(ptr, len) in entries { for i in 0..len { From 25d208aa7a92112a0aaf0c1d748798be34f829ee Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 18:07:49 +0800 Subject: [PATCH 31/48] test(fspy): assert ELIBBAD for a top-level spawn with a text PT_INTERP Co-Authored-By: Claude Opus 5.5 --- crates/fspy/tests/spawn_errors.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/fspy/tests/spawn_errors.rs b/crates/fspy/tests/spawn_errors.rs index 79aaf2c2d..5124a1185 100644 --- a/crates/fspy/tests/spawn_errors.rs +++ b/crates/fspy/tests/spawn_errors.rs @@ -91,6 +91,31 @@ async fn top_level_spawn_exec_errors_return_os_spawn_with_expected_errno() -> an libc::EACCES, ); + // 5. ELF whose `PT_INTERP` names an executable text file -> ELIBBAD, not + // ENOEXEC (which `execvp` would retry with `/bin/sh`). musl test binaries + // are static, so there is no `PT_INTERP` to point elsewhere. + #[cfg(all(target_os = "linux", not(target_env = "musl")))] + { + let mut image = fs::read(std::env::current_exe()?)?; + let parsed = elf::ElfBytes::::minimal_parse(&image)?; + let interp = parsed + .segments() + .and_then(|segments| segments.iter().find(|ph| ph.p_type == elf::abi::PT_INTERP)) + .expect("the test binary is dynamically linked"); + let start = usize::try_from(interp.p_offset)?; + let end = start + usize::try_from(interp.p_filesz)?; + image[start..end].fill(0); + image[start..start + 5].copy_from_slice(b"itext"); + let bad_interp = root.join("bad_interp"); + fs::write(&bad_interp, image)?; + fs::set_permissions(&bad_interp, fs::Permissions::from_mode(0o755))?; + fs::write(root.join("itext"), format!("#!/bin/sh\n{}\n", "#".repeat(64)))?; + fs::set_permissions(root.join("itext"), fs::Permissions::from_mode(0o755))?; + let mut command = fspy::Command::new(&bad_interp); + command.current_dir(&root); + assert_os_spawn_errno(command.spawn(CancellationToken::new()).await, libc::ELIBBAD); + } + // Direct top-level spawns of a non-executable 0o644 file or a directory are // rejected during `resolve_program()` with `SpawnError::Which`. assert!(matches!( From f75814dcbb3d6296a8bf9c2b055592eac68b5d23 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 18:07:50 +0800 Subject: [PATCH 32/48] fix(fspy_preload_macos): keep spawn chdir across reallocating file-action calls libsystem can grow (and free) a posix_spawn file-action list and then fail, for example addchdir_np with an overlong path. The chdir entry was rekeyed only on success, so it stayed under the freed address, where a new list could pick it up while the original list lost it. Detach the entry before each add call and reinsert it under the resulting handle whatever the call returns. Co-Authored-By: Claude Opus 5.5 --- crates/fspy/tests/macos_preload.rs | 54 ++++++ .../src/interceptions/spawn/posix_spawn.rs | 164 +++++++++++------- 2 files changed, 153 insertions(+), 65 deletions(-) diff --git a/crates/fspy/tests/macos_preload.rs b/crates/fspy/tests/macos_preload.rs index 96b4ffcb6..333b28b93 100644 --- a/crates/fspy/tests/macos_preload.rs +++ b/crates/fspy/tests/macos_preload.rs @@ -921,6 +921,60 @@ async fn posix_spawn_addfchdir_np_child_only_fd_and_realloc_actions() -> anyhow: libc::WIFEXITED(status2) && libc::WEXITSTATUS(status2) == 0, "child2 failed with raw status {status2:#x}" ); + + // 3. A failing add can still grow (and move) the list: libsystem grows + // a full list before rejecting an overlong chdir path with + // `ENAMETOOLONG`. `addchdir_np(sub)` + `addopen` fill the initial + // two slots, so the chdir must follow the list through that call. + let overlong = + CString::new(vec![b'a'; usize::try_from(libc::PATH_MAX).unwrap()]).unwrap(); + let mut grown_actions: libc::posix_spawn_file_actions_t = std::ptr::null_mut(); + // SAFETY: valid uninitialized handle and NUL-terminated paths. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_init(&raw mut grown_actions), 0); + assert_eq!( + posix_spawn_file_actions_addchdir_np(&raw mut grown_actions, sub_c.as_ptr()), + 0 + ); + assert_eq!( + libc::posix_spawn_file_actions_addopen( + &raw mut grown_actions, + child_fd, + c"/dev/null".as_ptr(), + libc::O_RDONLY, + 0, + ), + 0 + ); + assert_eq!( + posix_spawn_file_actions_addchdir_np(&raw mut grown_actions, overlong.as_ptr()), + libc::ENAMETOOLONG + ); + } + let mut child3: libc::pid_t = 0; + // SAFETY: all pointers are valid C strings/arrays and `grown_actions` is initialized. + let rc3 = unsafe { + libc::posix_spawn( + &raw mut child3, + prog.as_ptr(), + &raw const grown_actions, + std::ptr::null(), + argv.as_ptr(), + envp.as_ptr(), + ) + }; + // SAFETY: destroying initialized `grown_actions`. + unsafe { + assert_eq!(libc::posix_spawn_file_actions_destroy(&raw mut grown_actions), 0); + } + assert_eq!(rc3, 0, "posix_spawn(./helper) after a failed growing add failed: {rc3}"); + let mut status3: libc::c_int = 0; + // SAFETY: `child3` is our child and `status3` is writable. + assert_eq!(unsafe { libc::waitpid(child3, &raw mut status3, 0) }, child3); + assert!( + libc::WIFEXITED(status3) && libc::WEXITSTATUS(status3) == 0, + "child3 failed with raw status {status3:#x}" + ); }) .await?; diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs index 42887a6b8..62de202b6 100644 --- a/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs +++ b/crates/fspy_preload_macos/src/interceptions/spawn/posix_spawn.rs @@ -253,25 +253,24 @@ fn append_relative_chdir(key: usize, rel: &[u8]) { drop(spare); } -fn rekey_spawn_chdir(old_key: usize, new_key: usize) { - if old_key == new_key - || old_key == 0 - || new_key == 0 - || ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 - { - return; - } - ensure_init(); - // SAFETY: `SPAWN_CHDIRS.mutex` serializes access to `entries`, and updating - // a key in place performs no heap allocation or deallocation. - unsafe { - libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); - let map = &mut *SPAWN_CHDIRS.entries.get(); - if let Some(entry) = map.iter_mut().find(|(k, _)| *k == old_key) { - entry.0 = new_key; +/// Runs a libc `posix_spawn_file_actions_*` call that may `realloc` (and so +/// free) `*file_actions`, even when it then fails. The list's chdir entry is +/// detached first and reinserted under the resulting handle afterwards, so no +/// entry ever names an address libc may have freed and handed to another list, +/// whose own entry could otherwise be confused with or overwritten by this one. +fn call_detaching_chdir( + file_actions: *const libc::posix_spawn_file_actions_t, + call: impl FnOnce() -> c_int, +) -> c_int { + let detached = take_spawn_chdir(read_actions_key(file_actions)); + let ret = call(); + if let Some(entry) = detached { + let key = read_actions_key(file_actions); + if key != 0 { + set_spawn_chdir(key, entry); } - libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()); } + ret } fn read_actions_key(file_actions: *const libc::posix_spawn_file_actions_t) -> usize { @@ -284,13 +283,18 @@ fn read_actions_key(file_actions: *const libc::posix_spawn_file_actions_t) -> us } fn remove_spawn_chdir(key: usize) { - if ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 { - return; + // The removed `SpawnChdir` is dropped strictly after unlocking. + drop(take_spawn_chdir(key)); +} + +fn take_spawn_chdir(key: usize) -> Option { + if key == 0 || ACTIVE_CHDIRS.load(Ordering::Acquire) == 0 { + return None; } ensure_init(); - // SAFETY: `SPAWN_CHDIRS.mutex` serializes access to `entries`; the removed - // `SpawnChdir` is dropped strictly after unlocking. - let removed = unsafe { + // SAFETY: `SPAWN_CHDIRS.mutex` serializes access to `entries`; removing an + // entry performs no heap allocation or deallocation. + unsafe { libc::pthread_mutex_lock(SPAWN_CHDIRS.mutex.get()); let map = &mut *SPAWN_CHDIRS.entries.get(); let removed = map.iter().position(|(k, _)| *k == key).map(|pos| { @@ -299,9 +303,8 @@ fn remove_spawn_chdir(key: usize) { entry }); libc::pthread_mutex_unlock(SPAWN_CHDIRS.mutex.get()); - removed - }; - drop(removed); + removed.map(|(_, entry)| entry) + } } enum ResolvedChdir { @@ -444,16 +447,12 @@ unsafe extern "C" fn posix_spawn_file_actions_addopen( oflag: c_int, mode: libc::mode_t, ) -> c_int { - let old_key = read_actions_key(file_actions); - // SAFETY: forwarding caller arguments to the original libc function. - let ret = unsafe { - posix_spawn_file_actions_addopen::original()(file_actions, filedes, path, oflag, mode) - }; - if ret == 0 { - // libsystem may `realloc` `*file_actions` as the action list grows. - rekey_spawn_chdir(old_key, read_actions_key(file_actions)); - } - ret + call_detaching_chdir(file_actions, || { + // SAFETY: forwarding caller arguments to the original libc function. + unsafe { + posix_spawn_file_actions_addopen::original()(file_actions, filedes, path, oflag, mode) + } + }) } intercept!(posix_spawn_file_actions_addclose: unsafe extern "C" fn( @@ -464,13 +463,10 @@ unsafe extern "C" fn posix_spawn_file_actions_addclose( file_actions: *mut libc::posix_spawn_file_actions_t, filedes: c_int, ) -> c_int { - let old_key = read_actions_key(file_actions); - // SAFETY: forwarding caller arguments to the original libc function. - let ret = unsafe { posix_spawn_file_actions_addclose::original()(file_actions, filedes) }; - if ret == 0 { - rekey_spawn_chdir(old_key, read_actions_key(file_actions)); - } - ret + call_detaching_chdir(file_actions, || { + // SAFETY: forwarding caller arguments to the original libc function. + unsafe { posix_spawn_file_actions_addclose::original()(file_actions, filedes) } + }) } intercept!(posix_spawn_file_actions_adddup2: unsafe extern "C" fn( @@ -483,14 +479,10 @@ unsafe extern "C" fn posix_spawn_file_actions_adddup2( filedes: c_int, newfiledes: c_int, ) -> c_int { - let old_key = read_actions_key(file_actions); - // SAFETY: forwarding caller arguments to the original libc function. - let ret = - unsafe { posix_spawn_file_actions_adddup2::original()(file_actions, filedes, newfiledes) }; - if ret == 0 { - rekey_spawn_chdir(old_key, read_actions_key(file_actions)); - } - ret + call_detaching_chdir(file_actions, || { + // SAFETY: forwarding caller arguments to the original libc function. + unsafe { posix_spawn_file_actions_adddup2::original()(file_actions, filedes, newfiledes) } + }) } intercept!(posix_spawn_file_actions_addinherit_np: unsafe extern "C" fn( @@ -501,13 +493,10 @@ unsafe extern "C" fn posix_spawn_file_actions_addinherit_np( file_actions: *mut libc::posix_spawn_file_actions_t, filedes: c_int, ) -> c_int { - let old_key = read_actions_key(file_actions); - // SAFETY: forwarding caller arguments to the original libc function. - let ret = unsafe { posix_spawn_file_actions_addinherit_np::original()(file_actions, filedes) }; - if ret == 0 { - rekey_spawn_chdir(old_key, read_actions_key(file_actions)); - } - ret + call_detaching_chdir(file_actions, || { + // SAFETY: forwarding caller arguments to the original libc function. + unsafe { posix_spawn_file_actions_addinherit_np::original()(file_actions, filedes) } + }) } intercept!(posix_spawn_file_actions_addchdir_np: unsafe extern "C" fn( @@ -518,12 +507,12 @@ unsafe extern "C" fn posix_spawn_file_actions_addchdir_np( file_actions: *mut libc::posix_spawn_file_actions_t, path: *const c_char, ) -> c_int { - let old_key = read_actions_key(file_actions); - // SAFETY: forwarding caller arguments to the original libc function. - let ret = unsafe { posix_spawn_file_actions_addchdir_np::original()(file_actions, path) }; + let ret = call_detaching_chdir(file_actions, || { + // SAFETY: forwarding caller arguments to the original libc function. + unsafe { posix_spawn_file_actions_addchdir_np::original()(file_actions, path) } + }); if ret == 0 && !file_actions.is_null() && !path.is_null() { let key = read_actions_key(file_actions); - rekey_spawn_chdir(old_key, key); if key != 0 { // SAFETY: non-null `path` is a valid NUL-terminated C string. let c_path = unsafe { CStr::::from_ptr(path.cast()) }; @@ -549,12 +538,12 @@ unsafe extern "C" fn posix_spawn_file_actions_addfchdir_np( file_actions: *mut libc::posix_spawn_file_actions_t, fd: c_int, ) -> c_int { - let old_key = read_actions_key(file_actions); - // SAFETY: forwarding caller arguments to the original libc function. - let ret = unsafe { posix_spawn_file_actions_addfchdir_np::original()(file_actions, fd) }; + let ret = call_detaching_chdir(file_actions, || { + // SAFETY: forwarding caller arguments to the original libc function. + unsafe { posix_spawn_file_actions_addfchdir_np::original()(file_actions, fd) } + }); if ret == 0 && !file_actions.is_null() { let key = read_actions_key(file_actions); - rekey_spawn_chdir(old_key, key); if key != 0 { set_spawn_chdir(key, SpawnChdir { base: ChdirBase::Fd(fd), tail: Box::from([]) }); } @@ -693,3 +682,48 @@ unsafe extern "C" fn posix_spawn( ) } } + +#[cfg(test)] +mod tests { + use core::cell::Cell; + + use allocator_api2::alloc::Global; + + use super::*; + + fn abs_chdir(path: &[u8]) -> SpawnChdir { + SpawnChdir { base: ChdirBase::Abs(Box::from(path)), tail: Box::from([]) } + } + + fn resolved_dir(handle: usize) -> Option> { + let handle = handle as libc::posix_spawn_file_actions_t; + match resolve_spawn_chdir_in(&raw const handle, Global) { + ResolvedChdir::Dir(dir) => Some(dir.to_vec()), + ResolvedChdir::None | ResolvedChdir::Unresolvable => None, + } + } + + /// A libc call may free list A's storage and hand that address to a new + /// list B before failing. A's entry follows A to its new address, and B's + /// entry at the old address stays B's own. + #[test] + fn chdir_entry_follows_reallocated_list_without_touching_reused_address() { + const A_OLD: usize = 0x5eed_0000; + const A_NEW: usize = 0x5eed_1000; + set_spawn_chdir(A_OLD, abs_chdir(b"/a")); + + let handle = Cell::new(A_OLD as libc::posix_spawn_file_actions_t); + let ret = call_detaching_chdir(handle.as_ptr(), || { + // B is created at A's freed address and records its own chdir. + set_spawn_chdir(A_OLD, abs_chdir(b"/b")); + handle.set(A_NEW as libc::posix_spawn_file_actions_t); + libc::ENAMETOOLONG + }); + + assert_eq!(ret, libc::ENAMETOOLONG); + assert_eq!(resolved_dir(A_NEW).as_deref(), Some(b"/a".as_slice())); + assert_eq!(resolved_dir(A_OLD).as_deref(), Some(b"/b".as_slice())); + remove_spawn_chdir(A_NEW); + remove_spawn_chdir(A_OLD); + } +} From 82d69d8655d8eeba3c1cd8a2bfb0ace65f24443e Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 18:07:51 +0800 Subject: [PATCH 33/48] fix(fspy_shared_unix): parse macOS shebang lines like XNU XNU needs '\n' or '#' within its window and then reads the line as a C string, so a NUL ends the interpreter and its arguments (and whitespace right before it yields one empty argument). NUL ended the line on macOS too, so a script XNU rejects ran under tracking. Co-Authored-By: Claude Opus 5.5 --- .../src/nostd_exec/shebang.rs | 91 +++++++++++++------ 1 file changed, 62 insertions(+), 29 deletions(-) diff --git a/crates/fspy_shared_unix/src/nostd_exec/shebang.rs b/crates/fspy_shared_unix/src/nostd_exec/shebang.rs index 0c31856cf..7e6750978 100644 --- a/crates/fspy_shared_unix/src/nostd_exec/shebang.rs +++ b/crates/fspy_shared_unix/src/nostd_exec/shebang.rs @@ -66,13 +66,11 @@ const fn trim_sp_tab(mut bytes: &[u8]) -> &[u8] { #[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, + /// Whether to parse like XNU (see [`parse_xnu_shebang_line`]) rather than + /// Linux `binfmt_script`. + pub xnu: bool, } impl ParseShebangOptions { @@ -82,12 +80,7 @@ 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, - } + Self { max_line_len: MACOS_MAX_LINE_LEN, xnu: true } } #[cfg_attr( @@ -96,12 +89,7 @@ impl ParseShebangOptions { )] #[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, - } + Self { max_line_len: LINUX_MAX_LINE_LEN, xnu: false } } } @@ -119,12 +107,12 @@ pub fn parse_shebang_bytes( let Some(line) = buf.strip_prefix(b"#!") else { return Ok(None); }; + if options.xnu { + return parse_xnu_shebang_line(line, allocator).map(Some); + } - 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) { + let line = if let Some(line_end) = line.find_byteset(b"\n\0") { &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 @@ -144,21 +132,49 @@ pub fn parse_shebang_bytes( if interpreter.is_empty() { return Err(Error::NOEXEC); } - let arguments_buf = trim_sp_tab_start(&line[interpreter.len()..]).as_bstr(); - + // Linux passes everything after the interpreter as one argument. + let arguments_buf = trim_sp_tab_start(&line[interpreter.len()..]); 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() { + if !arguments_buf.is_empty() { arguments.push(to_vec_in(arguments_buf, allocator.clone())); } Ok(Some(Shebang { interpreter: to_vec_in(interpreter, allocator), arguments })) } +/// Parses the bytes after `#!` like XNU `exec_shell_imgact`: the line must end +/// with `\n` or `#` within the window, and trailing spaces and tabs are +/// stripped from it. XNU then reads it as a C string, so a NUL cuts it short, +/// and splits it on spaces and tabs into the interpreter and its arguments, +/// where a space or tab right before that NUL yields one empty argument. +fn parse_xnu_shebang_line(line: &[u8], allocator: A) -> Result> { + let Some(line_end) = line.find_byteset(b"\n#") else { + return Err(Error::NOEXEC); + }; + let line = trim_sp_tab(&line[..line_end]); + let mut rest = line.find_byte(0).map_or(line, |nul| &line[..nul]); + let mut interpreter = None; + let mut arguments = Vec::new_in(allocator.clone()); + loop { + let len = rest.iter().position(|ch| is_whitespace(*ch)).unwrap_or(rest.len()); + let token = to_vec_in(&rest[..len], allocator.clone()); + if interpreter.is_none() { + interpreter = Some(token); + } else { + arguments.push(token); + } + if len == rest.len() { + break; + } + rest = trim_sp_tab_start(&rest[len + 1..]); + } + let interpreter = interpreter.unwrap_or_else(|| Vec::new_in(allocator)); + if interpreter.is_empty() { + return Err(Error::NOEXEC); + } + Ok(Shebang { interpreter, arguments }) +} + /// Rewrites `exec` for a parsed `#!` hop, inserting `shebang.interpreter`, /// `shebang.arguments`, and `script_arg` at the front of `exec.args`. /// @@ -230,6 +246,23 @@ mod tests { assert_eq!(parse(b"#! \n", ParseShebangOptions::linux()).unwrap_err(), Error::NOEXEC); assert!(parse(b"\x7fELF", ParseShebangOptions::linux()).unwrap().is_none()); + // XNU needs `\n` or `#` within its window even after a NUL, then reads + // the line as a C string: the NUL ends both the interpreter and the + // arguments, and a space right before it yields one empty argument. + let macos = ParseShebangOptions::macos(); + assert_eq!(parse(b"#!/bin/sh\0", macos).unwrap_err(), Error::NOEXEC); + let nul = parse(b"#!/bin/sh\0ignored\n", macos).unwrap().unwrap(); + assert_eq!(nul.interpreter.as_slice(), b"/bin/sh"); + assert!(nul.arguments.is_empty()); + let nul_arg = parse(b"#!helper one\0junk two\n", macos).unwrap().unwrap(); + assert_eq!(nul_arg.interpreter.as_slice(), b"helper"); + assert_eq!(nul_arg.arguments, [b"one"]); + let nul_empty = parse(b"#!helper \0x\n", macos).unwrap().unwrap(); + assert_eq!(nul_empty.arguments, [b""]); + let split = parse(b"#! /bin/sh -e -x \n", macos).unwrap().unwrap(); + assert_eq!(split.interpreter.as_slice(), b"/bin/sh"); + assert_eq!(split.arguments, [b"-e".as_slice(), b"-x"]); + // 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"); From ef8944968f27b6b143743d21bb0100e73ce54e02 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 18:07:52 +0800 Subject: [PATCH 34/48] docs(fspy_elf_loader): document fd-relative programs, copied argv, and short rt_sigpending Co-Authored-By: Claude Opus 5.5 --- crates/fspy_elf_loader/README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index 65aca13ef..32d66dfaf 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -101,6 +101,17 @@ Do not try to close these in this crate unless a real target requires it: process tree changes its mount namespace or root (`chroot`, `pivot_root`, or a private `/tmp` mount hiding the materialized launcher path), subsequent child `execve` calls fail with `ENOENT`. +- **Process-relative top-level programs.** A top-level program named through + an `FD_CLOEXEC` descriptor (`/proc/self/fd/` or `/dev/fd/`) fails with + `ENOENT`, because exec'ing the launcher closes the descriptor before the + target is resolved. A non-`CLOEXEC` descriptor works, `/proc/self/exe` is + resolved before spawning, and execs inside tracked processes resolve such + paths before exec'ing the launcher. +- **Copied argv after shebang expansion.** The target keeps the launcher's + kernel argument strings, so writes to its `argv` (a process title, a + scrubbed secret) show in `/proc//cmdline`. When userland shebang + expansion changes a top-level task's argv, the target gets copies instead, + and `/proc//cmdline` keeps the original arguments for its lifetime. - **Shared descriptor tables.** In a child that shares its parent's descriptor table (`CLONE_FILES` without `CLONE_THREAD`, with or without `CLONE_VM`), the descriptors a tracked `execve` opens stay open in the processes still sharing @@ -134,6 +145,8 @@ Do not try to close these in this crate unless a real target requires it: `SIGSYS` handler installed in a raw `CLONE_VM` child is replaced by the fatal default. - A virtually pending `SIGSYS` is lost across `exec`. + - A successful raw `rt_sigpending` with a `sigsetsize` shorter than 8 + bytes omits a virtually pending `SIGSYS` (libc always passes 8). - A handler that blocks `SIGSYS` by editing its `ucontext`'s `uc_sigmask` (including with `sigfillset`) leaves the real `SIGSYS` blocked after it returns, so the next trapped syscall terminates the process. From 421c3fcdbfcca4a1ac66533477833dd28ab2b1cc Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 18:09:40 +0800 Subject: [PATCH 35/48] style(fspy): use map_or_else for the exe-link fallback Co-Authored-By: Claude Opus 5.5 --- crates/fspy/src/linux/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index e2ea2e69e..ee01d494d 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -121,7 +121,7 @@ impl SpyImpl { let exe_link_target = resolve_process_exe_link(command.target_program()); let target_path: &IpcStr = - exe_link_target.as_deref().map_or(command.target_program(), OsStr::new).into(); + exe_link_target.as_deref().map_or_else(|| command.target_program(), OsStr::new).into(); let bootstrap = Bootstrap { ipc_channel_conf: ipc_receiver.conf(), preload_path: &preload_path, From 664daf907e7891ad5ce74b8951b4edf151a6fc8e Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 19:04:01 +0800 Subject: [PATCH 36/48] fix(fspy): close round of Linux launcher fidelity gaps - Keep the target's envp on the launcher's kernel strings, so a program that overwrites a getenv result also clears it from /proc//environ. - Report a lost access when a path or descriptor that the syscall uses can't be resolved (for example when the program denies readlinkat), instead of returning a trace that looks complete without it. - Track paths under /dev/shm, an ordinary tmpfs that can hold a workspace. - Read trapped path arguments up to PATH_MAX, as the kernel does, so an unterminated path fails with ENAMETOOLONG instead of crashing. - Materialize the launcher at an absolute path, so a relative TMPDIR keeps working after a tracked process changes directory. - Parse #! lines exactly like binfmt_script (trailing whitespace before a NUL or end of file is kept), fail execveat(AT_EMPTY_PATH) on a symlink descriptor with ELOOP, and pass an O_PATH script descriptor to the interpreter as is instead of through an extra duplicate. Co-Authored-By: Claude Opus 5.5 --- crates/fspy/src/linux/mod.rs | 10 +- crates/fspy/tests/linux_syscalls.rs | 72 +++++++++++ crates/fspy/tests/untracked_fallback.rs | 90 ++++++++++++++ crates/fspy_elf_loader/src/lib.rs | 20 +-- crates/fspy_elf_loader/src/sigsys/mod.rs | 11 +- crates/fspy_elf_loader/src/sigsys/usermem.rs | 21 +--- crates/fspy_nostd/src/fs/linux.rs | 1 + crates/fspy_nostd/src/fs/mac.rs | 1 + crates/fspy_nostd/src/fs/unix.rs | 7 ++ crates/fspy_preload_linux/src/main.rs | 67 ++++++---- crates/fspy_shared_unix/src/linux.rs | 117 +++++++++++------- .../src/nostd_exec/shebang.rs | 113 +++++++++++------ 12 files changed, 381 insertions(+), 149 deletions(-) diff --git a/crates/fspy/src/linux/mod.rs b/crates/fspy/src/linux/mod.rs index ee01d494d..c358caa17 100644 --- a/crates/fspy/src/linux/mod.rs +++ b/crates/fspy/src/linux/mod.rs @@ -290,12 +290,10 @@ fn clone_ipc_str(s: &IpcStr) -> Box { } fn materialize_preload() -> Option> { - PRELOAD_LINUX - .materialize() - .executable() - .at_user_temp_dir("vp_run") - .ok() - .map(|p| p.as_path().into()) + let path = PRELOAD_LINUX.materialize().executable().at_user_temp_dir("vp_run").ok()?; + // Every tracked exec re-enters the launcher by this path, so a relative + // `TMPDIR` must not be resolved against a tracked process's own cwd. + std::path::absolute(&path).ok().map(|path| path.as_path().into()) } /// Probes once on a dedicated short-lived OS thread whether diff --git a/crates/fspy/tests/linux_syscalls.rs b/crates/fspy/tests/linux_syscalls.rs index 8ed212481..09dc71b3c 100644 --- a/crates/fspy/tests/linux_syscalls.rs +++ b/crates/fspy/tests/linux_syscalls.rs @@ -814,3 +814,75 @@ async fn top_level_proc_self_exe_runs_the_spawning_executable() -> anyhow::Resul assert!(termination.status.success(), "{:?}", termination.status); Ok(()) } + +/// Files under `/dev/shm`, an ordinary tmpfs that can hold a workspace, are +/// tracked like any other path. +#[test(tokio::test)] +async fn dev_shm_paths_are_tracked() -> anyhow::Result<()> { + let shm_dir = tempfile::tempdir_in("/dev/shm")?; + let input = shm_dir.path().join("input"); + fs::write(&input, b"shm")?; + + let accesses = track_fn!(input.to_str().unwrap().to_owned(), |input: String| { + assert_eq!(fs::read(input).unwrap(), b"shm"); + }) + .await?; + assert_contains(&accesses, &input, PathAccess::Read); + Ok(()) +} + +/// A path with no NUL within `PATH_MAX`, ending at an unreadable page, fails +/// with `ENAMETOOLONG` as it does natively instead of crashing the tracker. +#[test(tokio::test)] +async fn unterminated_path_fails_with_enametoolong() -> anyhow::Result<()> { + let _accesses = track_fn!((), |()| { + const PAGE: usize = 1 << 16; // at least the page size on every Linux target + // SAFETY: maps two fresh anonymous regions of `PAGE` bytes. + let base = unsafe { + libc::mmap( + std::ptr::null_mut(), + 2 * PAGE, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + assert_ne!(base, libc::MAP_FAILED); + // Fill the bytes right before the guard with non-NUL bytes. + let start = PAGE - 4096; + // SAFETY: `base..base + PAGE` is writable, and the guard region after + // it becomes unreadable. + let rc = unsafe { + std::ptr::write_bytes(base.cast::().add(start), b'a', 4096); + libc::mprotect(base.cast::().add(PAGE).cast(), PAGE, libc::PROT_NONE) + }; + assert_eq!(rc, 0); + // SAFETY: the path's 4096 bytes are readable; the kernel stops there. + let fd = unsafe { libc::open(base.cast::().add(start).cast(), libc::O_RDONLY) }; + assert_eq!((fd, errno()), (-1, libc::ENAMETOOLONG)); + }) + .await?; + Ok(()) +} + +/// The tracked program keeps the kernel's environment strings, so overwriting +/// a value it got from `getenv` (scrubbing a secret) changes +/// `/proc/self/environ`, as it does natively. +#[test(tokio::test)] +async fn environment_writes_show_in_proc_environ() -> anyhow::Result<()> { + let mut cmd = test_utils::command_for_fn!((), |()| { + // SAFETY: the literal is NUL-terminated. + let value = unsafe { libc::getenv(c"FSPY_TEST_SCRUBBED_SECRET".as_ptr()) }; + assert!(!value.is_null()); + // SAFETY: `getenv` returned this process's own writable value string. + unsafe { std::ptr::write_bytes(value, b'x', libc::strlen(value)) }; + let environ = fs::read("/proc/self/environ").unwrap(); + let entries: Vec<&[u8]> = environ.split(|&byte| byte == 0).collect(); + assert!(entries.contains(&b"FSPY_TEST_SCRUBBED_SECRET=xxxxxx".as_slice())); + assert!(!entries.contains(&b"FSPY_TEST_SCRUBBED_SECRET=secret".as_slice())); + }); + cmd.envs.insert("FSPY_TEST_SCRUBBED_SECRET".into(), "secret".into()); + let _accesses = test_utils::spawn_command(cmd).await?; + Ok(()) +} diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs index 2c111bacd..cbd664c18 100644 --- a/crates/fspy/tests/untracked_fallback.rs +++ b/crates/fspy/tests/untracked_fallback.rs @@ -115,3 +115,93 @@ fn seccomp_blocked_sandbox_falls_back_to_untracked() { String::from_utf8_lossy(&output.stderr), ); } + +/// When a descriptor-relative path can't be resolved (here because the program +/// denies `readlinkat`, which resolving its directory descriptor needs), the +/// access still happens, so the trace is reported incomplete instead of +/// complete without it. +#[test(tokio::test)] +async fn unresolvable_relative_path_reports_tracking_incomplete() { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + fs::write(dir.path().join("input"), "data").expect("failed to write input"); + let cmd = command_for_fn!(dir.path().to_str().unwrap().to_owned(), |dir: String| { + use std::os::fd::AsRawFd as _; + + let dir = fs::File::open(dir).unwrap(); + #[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::readlinkat 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 tracked + // process, which already runs with `no_new_privs`. + 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(); + } + // SAFETY: valid directory descriptor and NUL-terminated relative path. + let fd = unsafe { libc::openat(dir.as_raw_fd(), c"input".as_ptr(), libc::O_RDONLY) }; + assert!(fd >= 0, "openat(dirfd, input) failed"); + }); + let tracked = fspy::Command::from(cmd) + .spawn(CancellationToken::new()) + .await + .expect("failed to spawn the child"); + let termination = tracked.wait_handle.await.expect("failed to wait for the child"); + assert!(termination.status.success(), "the child failed: {:?}", termination.status); + assert!(matches!(termination.path_accesses, Err(TrackingIncomplete))); +} + +/// A relative `TMPDIR` names the launcher relative to the parent's directory, +/// so tracked processes that change directory keep executing commands. +#[test] +fn relative_temp_dir_survives_cd_in_tracked_process() { + let tmp_dir = tempfile::tempdir().expect("failed to create temp dir"); + let cmd = command_for_fn!(tmp_dir.path().to_str().unwrap().to_owned(), |dir: String| { + std::env::set_current_dir(&dir).unwrap(); + fs::create_dir("relativetmp").unwrap(); + fs::create_dir("child").unwrap(); + // SAFETY: this test subprocess is still single-threaded, and `fspy` + // reads `TMPDIR` only on first spawn. + unsafe { std::env::set_var("TMPDIR", "relativetmp") }; + + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + rt.block_on(async { + let mut command = fspy::Command::new("/bin/sh"); + command.args(["-c", "cd child && /bin/true"]).stdin(Stdio::null()); + let tracked = command.spawn(CancellationToken::new()).await.unwrap(); + let termination = tracked.wait_handle.await.unwrap(); + assert!(termination.status.success(), "{:?}", termination.status); + }); + }); + + let output = std::process::Command::from(cmd).output().expect("failed to run TMPDIR test"); + assert!( + output.status.success(), + "relative TMPDIR subprocess failed: stdout={}, stderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); +} diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 50cdfdaef..8f5b138e0 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -168,24 +168,26 @@ pub struct SyscallInterceptor { pub on_vfork_return: Option, } -/// Borrows a NUL-terminated C string directly from a trapped syscall's user -/// pointer. +/// Borrows a trapped syscall's path argument from its user pointer, scanning +/// at most `PATH_MAX` bytes for the NUL as the kernel does. /// /// # Errors /// /// Returns [`fspy_nostd::Error::FAULT`] if `addr` is in the first page (such as -/// `NULL`). +/// `NULL`), and [`fspy_nostd::Error::NAMETOOLONG`] if no NUL appears within +/// `PATH_MAX` bytes. /// /// # Safety /// -/// Any other `addr` must point to a readable NUL-terminated string valid for -/// `'a`. Like the macOS and Windows preloads, the runtime assumes the pointers -/// programs pass to syscalls are valid; a bad one crashes the process instead -/// of failing with `EFAULT`. +/// Any other `addr` must be readable up to its NUL or `PATH_MAX` bytes, +/// whichever comes first, and stay unchanged for `'a`. Like the macOS and +/// Windows preloads, the runtime assumes the pointers programs pass to +/// syscalls are valid; a pointer into an unmapped page crashes the process +/// instead of failing with `EFAULT`. #[cfg(any(target_os = "linux", target_os = "none"))] -pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { +pub unsafe fn user_path<'a>(addr: usize) -> Result> { // SAFETY: forwarded from caller contract. - unsafe { sigsys::user_cstr(addr) } + unsafe { sigsys::user_path(addr) } } /// Copies a `Copy` value from a trapped syscall's user pointer. diff --git a/crates/fspy_elf_loader/src/sigsys/mod.rs b/crates/fspy_elf_loader/src/sigsys/mod.rs index 9c39ac613..500fec2cb 100644 --- a/crates/fspy_elf_loader/src/sigsys/mod.rs +++ b/crates/fspy_elf_loader/src/sigsys/mod.rs @@ -50,14 +50,17 @@ pub fn handler_addr() -> usize { (sigsys_trampoline as *const ()).addr() } -/// Borrows a user C string directly from `addr`. +/// Borrows a user path from `addr`, scanning at most `PATH_MAX` bytes as the +/// kernel does. /// /// # Safety /// -/// See [`usermem::user_cstr`]. -pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { +/// See [`usermem::user_cstr_bounded`]. +pub unsafe fn user_path<'a>(addr: usize) -> Result> { // SAFETY: forwarded from caller contract. - unsafe { usermem::user_cstr(addr) } + let path = unsafe { usermem::user_cstr_bounded(addr, fspy_nostd::fs::PATH_MAX) }?; + // SAFETY: `path` is followed by its NUL terminator and valid for `'a`. + Ok(unsafe { CStr::::from_ptr(path.as_ptr()) }) } /// Copies a user `Copy` value. diff --git a/crates/fspy_elf_loader/src/sigsys/usermem.rs b/crates/fspy_elf_loader/src/sigsys/usermem.rs index ee18ef3e4..c87da3a2b 100644 --- a/crates/fspy_elf_loader/src/sigsys/usermem.rs +++ b/crates/fspy_elf_loader/src/sigsys/usermem.rs @@ -16,7 +16,7 @@ use core::{mem::size_of, ptr, slice}; -use fspy_nostd::{CStr, Error, Result, Thin}; +use fspy_nostd::{Error, Result}; /// Minimum valid user-space address (page 0 is never mapped on Linux). const MIN_USER_ADDR: usize = 4096; @@ -78,25 +78,6 @@ pub unsafe fn write_user_bytes(addr: usize, src: &[u8]) -> Result<()> { Ok(()) } -/// Borrows a NUL-terminated C string directly from user address `addr`, -/// returning [`Error::FAULT`] if `addr` is in the first page (such as `NULL`). -/// -/// Prefer [`user_cstr_bounded`] for pathname inspection so malformed or -/// unterminated strings cannot scan arbitrarily far past `PATH_MAX`. -/// -/// # Safety -/// -/// Any other `addr` must point to a readable NUL-terminated C string that -/// remains valid and unmodified for `'a`. -pub unsafe fn user_cstr<'a>(addr: usize) -> Result> { - if addr < MIN_USER_ADDR { - return Err(Error::FAULT); - } - // SAFETY: caller guarantees `addr` points to a readable NUL-terminated C - // string valid for `'a`. - Ok(unsafe { CStr::::from_ptr(ptr::with_exposed_provenance(addr)) }) -} - /// Scans at most `max_len` bytes starting at user address `addr` for a NUL /// terminator and returns the byte slice preceding the NUL. /// diff --git a/crates/fspy_nostd/src/fs/linux.rs b/crates/fspy_nostd/src/fs/linux.rs index 589b435ad..bea7baa7a 100644 --- a/crates/fspy_nostd/src/fs/linux.rs +++ b/crates/fspy_nostd/src/fs/linux.rs @@ -19,6 +19,7 @@ pub(super) const S_IRUSR: ModeBits = linux_raw_sys::general::S_IRUSR; pub(super) const S_IWUSR: ModeBits = linux_raw_sys::general::S_IWUSR; pub(super) const S_IFMT: ModeBits = linux_raw_sys::general::S_IFMT; pub(super) const S_IFREG: ModeBits = linux_raw_sys::general::S_IFREG; +pub(super) const S_IFLNK: ModeBits = linux_raw_sys::general::S_IFLNK; fn raw_fd_from_syscall(fd: usize) -> Result { RawFd::try_from(fd).map_err(|_| Error::OVERFLOW) diff --git a/crates/fspy_nostd/src/fs/mac.rs b/crates/fspy_nostd/src/fs/mac.rs index ebfa2c7f0..db63dee0a 100644 --- a/crates/fspy_nostd/src/fs/mac.rs +++ b/crates/fspy_nostd/src/fs/mac.rs @@ -21,6 +21,7 @@ pub(super) const S_IRUSR: ModeBits = libc::S_IRUSR; pub(super) const S_IWUSR: ModeBits = libc::S_IWUSR; pub(super) const S_IFMT: ModeBits = libc::S_IFMT; pub(super) const S_IFREG: ModeBits = libc::S_IFREG; +pub(super) const S_IFLNK: ModeBits = libc::S_IFLNK; #[expect(clippy::needless_pass_by_value, reason = "CStr is a borrowed value type")] pub(super) fn faccessat( diff --git a/crates/fspy_nostd/src/fs/unix.rs b/crates/fspy_nostd/src/fs/unix.rs index a4f65112c..6a1104381 100644 --- a/crates/fspy_nostd/src/fs/unix.rs +++ b/crates/fspy_nostd/src/fs/unix.rs @@ -70,6 +70,13 @@ impl Stat { pub const fn is_regular_file(&self) -> bool { (self.st_mode & imp::S_IFMT) == imp::S_IFREG } + + /// Returns `true` when the file is a symbolic link (`S_ISLNK`), as an + /// `O_PATH | O_NOFOLLOW` descriptor of one is. + #[must_use] + pub const fn is_symlink(&self) -> bool { + (self.st_mode & imp::S_IFMT) == imp::S_IFLNK + } } /// The platform's maximum pathname size, including the terminating NUL. diff --git a/crates/fspy_preload_linux/src/main.rs b/crates/fspy_preload_linux/src/main.rs index 3b2ad3747..84a45b3dd 100644 --- a/crates/fspy_preload_linux/src/main.rs +++ b/crates/fspy_preload_linux/src/main.rs @@ -90,10 +90,9 @@ mod runtime { used_set_tid_address: bool, arena: UnsafeCell>, duped_fd: UnsafeCell, - extra_fd: UnsafeCell, } - // SAFETY: `arena`, `duped_fd`, and `extra_fd` are mutated only by the + // SAFETY: `arena` and `duped_fd` are mutated only by the // exec'ing thread before it leaves the VM or sets `active_tid` to `0` // (`Release`), and dropped by a reclaimer only after confirming the child // is gone (via `on_vfork_return`, `kcmp(KCMP_VM) != 0`, or `active_tid == 0` @@ -254,6 +253,8 @@ mod runtime { argv.into_iter(), argv_in_place, filtered_envs, + // The kernel's own strings, minus the bootstrap entry. + true, stack.auxv(), Some(INTERCEPTOR), on_ready, @@ -286,6 +287,7 @@ mod runtime { stack.args().iter().copied(), true, filtered_envs, + true, stack.auxv(), Some(INTERCEPTOR), || scrub_bootstrap_env(&bootstrap_entries), @@ -463,7 +465,9 @@ mod runtime { fn send_path(mode: AccessMode, path: &BStr) { let bytes: &[u8] = path.as_ref(); - if bytes.starts_with(b"/dev/") + // `/dev/shm` is an ordinary tmpfs that can hold a workspace. + let dev_shm = bytes == b"/dev/shm" || bytes.starts_with(b"/dev/shm/"); + if (bytes.starts_with(b"/dev/") && !dev_shm) || bytes.starts_with(b"/proc/") || bytes.starts_with(b"/sys/") { @@ -511,8 +515,10 @@ mod runtime { } return; } + // A path with no NUL within `PATH_MAX` fails with `ENAMETOOLONG`, so + // the syscall accesses nothing. // SAFETY: `path_ptr` is the trapped syscall's path argument. - let Ok(c_path) = (unsafe { fspy_elf_loader::user_cstr(path_ptr) }) else { + let Ok(c_path) = (unsafe { fspy_elf_loader::user_path(path_ptr) }) else { return; }; let raw = c_path.count().as_units(); @@ -527,15 +533,34 @@ mod runtime { 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())); + match resolve_path_at(&arena, dirfd, c_path) { + Ok(Some(resolved)) => send_path(mode, BStr::new(resolved.as_units())), + // The syscall fails with `EBADF` and accesses nothing. + Ok(None) if dirfd.is_none_or(|fd| !is_open_fd(fd)) => {} + // The access happens, but its path is unknown (for example a cwd + // longer than `PATH_MAX`), so the trace is incomplete. + Ok(None) | Err(_) => report_loss(), } } 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())); + match fd_path(&arena, fd) { + Ok(Some(resolved)) => send_path(mode, BStr::new(resolved.as_units())), + Ok(None) if !is_open_fd(fd) => {} + Ok(None) | Err(_) => report_loss(), + } + } + + fn is_open_fd(fd: BorrowedFd<'_>) -> bool { + fspy_nostd::fs::fcntl_is_cloexec(fd).is_ok() + } + + /// Marks the trace incomplete, so the run is reported as untracked + /// instead of cached with a missing access. + fn report_loss() { + if let Some(sender) = runtime().sender.as_ref() { + sender.report_loss(); } } @@ -829,7 +854,7 @@ mod runtime { if reclaimable { // SAFETY: The child left this memory (or failure cleanup // released the node), so nothing references `cur`. Its - // `duped_fd` / `extra_fd` belonged to the child's descriptor table. + // `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. @@ -844,19 +869,13 @@ mod runtime { 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`/`extra_fd` are open in its - // descriptor table. + // 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)); } - let extra = *(*node).extra_fd.get(); - *(*node).extra_fd.get() = -1; - if extra >= 0 { - drop(OwnedFd::from_raw_fd(extra)); - } if (*node).parked { // Already published: release its arena and mark reclaimable. if (*node).used_set_tid_address { @@ -902,12 +921,11 @@ mod runtime { used_set_tid_address: false, arena: UnsafeCell::new(Some(page_bump())), duped_fd: UnsafeCell::new(-1), - extra_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, extra_fd) = match prepare_exec_in( + let (raw_out, duped_fd) = match prepare_exec_in( dirfd, prog_ptr, argv_ptr, @@ -927,7 +945,6 @@ mod runtime { // SAFETY: the node is owned by this thread until published below. unsafe { *(*node).duped_fd.get() = duped_fd; - *(*node).extra_fd.get() = extra_fd; if is_shared_vm_child { let use_set_tid = !KCMP_VM_AVAILABLE.load(Ordering::Relaxed); (*node).owner_pid = current_pid(); @@ -963,7 +980,7 @@ mod runtime { sigmask: u64, sigsys_ignored: bool, arena: &'static PageBump, - ) -> Result<(RawExec, RawFd, RawFd)> { + ) -> Result<(RawExec, RawFd)> { let raw = RawExec { prog: ptr::with_exposed_provenance(prog_ptr), argv: ptr::with_exposed_provenance(argv_ptr), @@ -979,9 +996,9 @@ mod runtime { // 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 - // (and any `resolved.extra_fd`) automatically; once handed back as raw - // fds, `cleanup_exec_scratch` closes them on `SYS_execve` failure while - // a successful exec transfers them to the child. + // automatically; once handed back as a raw fd, `cleanup_exec_scratch` + // 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(); @@ -1002,9 +1019,7 @@ mod runtime { 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(); - let extra_raw = resolved.extra_fd.as_ref().map_or(-1, OwnedFd::as_raw_fd); core::mem::forget(duped_fd); - core::mem::forget(resolved.extra_fd); - Ok((raw_out, duped_raw, extra_raw)) + Ok((raw_out, duped_raw)) } } diff --git a/crates/fspy_shared_unix/src/linux.rs b/crates/fspy_shared_unix/src/linux.rs index ff898838e..4e04c4db3 100644 --- a/crates/fspy_shared_unix/src/linux.rs +++ b/crates/fspy_shared_unix/src/linux.rs @@ -7,13 +7,12 @@ use bstr::BStr; use fspy_nostd::{ BorrowedFd, CStr, CWD, Error, OwnedFd, RawFd, Result, Thin, fs::{ - AccessFlags, Mode, OFlags, faccessat, fcntl_dupfd, fcntl_dupfd_cloexec, fcntl_is_cloexec, - fstat, openat, + AccessFlags, Mode, OFlags, faccessat, fcntl_dupfd_cloexec, fcntl_is_cloexec, fstat, openat, }, }; use fspy_nostd_alloc::{ CString, - fs::{fd_path, format_proc_self_fd, resolve_path_at}, + fs::{fd_path, format_proc_thread_self_fd, resolve_path_at}, }; use fspy_shared::ipc::{IpcStr, channel::ChannelConf}; use wincode::{SchemaRead, SchemaWrite}; @@ -50,16 +49,11 @@ bitflags! { /// Output of [`resolve_exec`]. /// -/// Contains the open final binary descriptor, the original execution name for -/// `AT_EXECFN`, and any extra non-`CLOEXEC` readable script descriptor opened -/// when `execveat(..., AT_EMPTY_PATH)` targeted an `O_PATH` `#!` script. +/// Contains the open final binary descriptor and the original execution name +/// for `AT_EXECFN`. pub struct ResolvedExec { pub file: OwnedFd, pub execfn: Vec, - /// Readable non-`CLOEXEC` duplicate of an `O_PATH` shebang script passed to - /// the interpreter as `/dev/fd/`. Kept open across `SYS_execve` and - /// closed on exec failure. - pub extra_fd: Option, } /// What the freshly exec'd `fspy_preload_linux` binary should load and run. @@ -170,16 +164,13 @@ pub fn resolve_exec( let allocator = exec.allocator().clone(); let mut peek_buf = [0u8; LINUX_MAX_LINE_LEN]; - let (execfn, extra_fd, mut depth, mut cur_dirfd, mut cur_nofollow) = if exec.program.is_empty() - { + 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, extra_fd } => { - (execfn, extra_fd, 1usize, Some(CWD), false) - } + EmptyPathStep::Shebang { execfn } => (execfn, 1usize, Some(CWD), false), } } else { // Linux `fs/exec.c` (`do_execveat_common`) formats `AT_EXECFN` as @@ -193,7 +184,7 @@ pub fn resolve_exec( } else { to_vec_in(&exec.program, allocator.clone()) }; - (execfn, None, 0usize, dirfd, flags.contains(ExecAtFlags::SYMLINK_NOFOLLOW)) + (execfn, 0usize, dirfd, flags.contains(ExecAtFlags::SYMLINK_NOFOLLOW)) }; loop { @@ -256,13 +247,13 @@ pub fn resolve_exec( continue; } - return Ok(ResolvedExec { file, execfn, extra_fd }); + return Ok(ResolvedExec { file, execfn }); } } enum EmptyPathStep { Resolved(ResolvedExec), - Shebang { execfn: Vec, extra_fd: Option }, + Shebang { execfn: Vec }, } fn resolve_empty_path( @@ -281,22 +272,28 @@ fn resolve_empty_path( if fd.as_raw_fd() == CWD.as_raw_fd() { return Err(Error::ACCES); } - if !fstat(fd)?.is_regular_file() { + let stat = fstat(fd)?; + // An `O_PATH | O_NOFOLLOW` descriptor of a symlink fails like the + // symlink itself would under `AT_SYMLINK_NOFOLLOW`. + if stat.is_symlink() { + return Err(Error::LOOP); + } + if !stat.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); + let proc_fd = format_proc_thread_self_fd(&mut proc_buf, raw_fd); faccessat(CWD, proc_fd, AccessFlags::X_OK)?; if let Some(p) = fd_path(allocator.clone(), fd)? { on_path_read(BStr::new(p.as_units())); } - let (file, n, reopened_from_o_path) = match pread_header(fd, peek_buf) { - Ok(n) => (fcntl_dupfd_cloexec(fd, 0)?, n, false), + 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`. + // `fd` may have been opened with `O_PATH`; reopen read-only via `/proc/thread-self/fd`. let reopened = openat( CWD, proc_fd, @@ -304,7 +301,7 @@ fn resolve_empty_path( Mode::empty(), )?; let n = pread_header(reopened.as_fd(), peek_buf)?; - (reopened, n, true) + (reopened, n) } Err(err) => return Err(err), }; @@ -316,7 +313,7 @@ fn resolve_empty_path( let Some(shebang) = parse_shebang_bytes(&peek_buf[..n], ParseShebangOptions::linux(), allocator.clone())? else { - return Ok(EmptyPathStep::Resolved(ResolvedExec { file, execfn, extra_fd: None })); + return Ok(EmptyPathStep::Resolved(ResolvedExec { file, execfn })); }; // Matches Linux `binfmt_script`: an `FD_CLOEXEC` script fd cannot be @@ -325,21 +322,12 @@ fn resolve_empty_path( return Err(Error::NOENT); } - // If `fd` was opened with `O_PATH`, the interpreter cannot read through - // `/dev/fd/` (`EBADF`); hand it a non-`CLOEXEC` duplicate of the - // readable descriptor we reopened above instead. - let (script_fd_num, extra_fd) = if reopened_from_o_path { - let readable = fcntl_dupfd(file.as_fd(), 3)?; - drop(file); - let readable_num = u32::try_from(readable.as_raw_fd()).map_err(|_| Error::BADF)?; - (readable_num, Some(readable)) - } else { - drop(file); - (raw_fd, None) - }; - let script_arg = format_dev_fd(script_fd_num, allocator); + // The interpreter opens `/dev/fd/` itself, which reopens the + // file even when `fd` was opened with `O_PATH`. + drop(file); + let script_arg = format_dev_fd(raw_fd, allocator); apply_shebang(exec, shebang, script_arg); - Ok(EmptyPathStep::Shebang { execfn, extra_fd }) + Ok(EmptyPathStep::Shebang { execfn }) } /// Copies `bytes` into a NUL-terminated [`CString`], rejecting interior NULs @@ -357,8 +345,8 @@ fn bytes_to_cstring( fn format_dev_fd(fd: u32, allocator: A) -> Vec { let mut buf = [0u8; 32]; - let proc_fd = format_proc_self_fd(&mut buf, fd).count().as_units(); - let digits = proc_fd.strip_prefix(b"/proc/self/fd/").unwrap_or(proc_fd); + let proc_fd = format_proc_thread_self_fd(&mut buf, fd).count().as_units(); + let digits = proc_fd.strip_prefix(b"/proc/thread-self/fd/").unwrap_or(proc_fd); let mut out = Vec::with_capacity_in(b"/dev/fd/".len() + digits.len(), allocator); out.extend_from_slice(b"/dev/fd/"); out.extend_from_slice(digits); @@ -367,8 +355,8 @@ fn format_dev_fd(fd: u32, allocator: A) -> Vec { fn format_dev_fd_rel(fd: u32, rel: &[u8], allocator: A) -> Vec { let mut buf = [0u8; 32]; - let proc_fd = format_proc_self_fd(&mut buf, fd).count().as_units(); - let digits = proc_fd.strip_prefix(b"/proc/self/fd/").unwrap_or(proc_fd); + let proc_fd = format_proc_thread_self_fd(&mut buf, fd).count().as_units(); + let digits = proc_fd.strip_prefix(b"/proc/thread-self/fd/").unwrap_or(proc_fd); let mut out = Vec::with_capacity_in(b"/dev/fd/".len() + digits.len() + 1 + rel.len(), allocator); out.extend_from_slice(b"/dev/fd/"); @@ -391,6 +379,7 @@ mod tests { }; use allocator_api2::alloc::Global; + use fspy_nostd::fs::fcntl_dupfd; use fspy_shared::ipc::channel::channel; use super::*; @@ -564,8 +553,8 @@ mod tests { .is_ok() ); - // AT_EMPTY_PATH on non-CLOEXEC O_PATH shebang script reopens readable - // and passes `/dev/fd/` (non-CLOEXEC) to the interpreter. + // AT_EMPTY_PATH on a non-CLOEXEC O_PATH shebang script passes + // `/dev/fd/` to the interpreter. // Open directly via `openat(O_PATH)` because Rust's `OpenOptions::custom_flags` // masks off `O_ACCMODE`, which on musl includes `O_PATH` (`O_SEARCH`). let script_c = bytes_to_cstring(script.as_os_str().as_bytes(), Global).unwrap(); @@ -580,10 +569,42 @@ mod tests { let resolved = resolve_exec(&mut exec, Some(o_path_owned.as_fd()), ExecAtFlags::EMPTY_PATH, |_| {}) .unwrap(); - let extra = resolved.extra_fd.as_ref().expect("expected reopened readable script fd"); - assert!(!fcntl_is_cloexec(extra.as_fd()).unwrap()); - let expected_dev_fd = format!("/dev/fd/{}", extra.as_raw_fd()); + // The interpreter reopens `/dev/fd/` itself, which works for an + // `O_PATH` descriptor too, so no duplicate is needed. + let expected_dev_fd = format!("/dev/fd/{}", o_path_owned.as_raw_fd()); assert_eq!(exec.args.last().unwrap().as_slice(), expected_dev_fd.as_bytes()); + + // `AT_EMPTY_PATH` on an `O_PATH | O_NOFOLLOW` descriptor of a symlink + // -> ELOOP, with or without `AT_SYMLINK_NOFOLLOW`; a directory -> EACCES. + let script_link = dir.path().join("script_link"); + symlink(&script, &script_link).unwrap(); + let link_c = bytes_to_cstring(script_link.as_os_str().as_bytes(), Global).unwrap(); + let link_fd = openat( + CWD, + link_c.as_c_str().as_thin(), + OFlags::from_bits_retain( + linux_raw_sys::general::O_PATH | linux_raw_sys::general::O_NOFOLLOW, + ), + Mode::empty(), + ) + .unwrap(); + for flags in + [ExecAtFlags::EMPTY_PATH, ExecAtFlags::EMPTY_PATH | ExecAtFlags::SYMLINK_NOFOLLOW] + { + let mut exec = make_exec(b"", &[]); + assert_eq!( + resolve_exec(&mut exec, Some(link_fd.as_fd()), flags, |_| {}).err(), + Some(Error::LOOP) + ); + } + let dir_file = File::open(dir.path()).unwrap(); + // SAFETY: `dir_file` remains open for the call. + let dir_fd = unsafe { BorrowedFd::borrow_raw(dir_file.as_raw_fd()) }; + let mut exec = make_exec(b"", &[]); + assert_eq!( + resolve_exec(&mut exec, Some(dir_fd), ExecAtFlags::EMPTY_PATH, |_| {}).err(), + Some(Error::ACCES) + ); assert_eq!( resolved.execfn.as_slice(), format!("/dev/fd/{}", o_path_owned.as_raw_fd()).as_bytes() diff --git a/crates/fspy_shared_unix/src/nostd_exec/shebang.rs b/crates/fspy_shared_unix/src/nostd_exec/shebang.rs index 7e6750978..7f17d9a69 100644 --- a/crates/fspy_shared_unix/src/nostd_exec/shebang.rs +++ b/crates/fspy_shared_unix/src/nostd_exec/shebang.rs @@ -25,10 +25,6 @@ pub const MACOS_MAX_RECURSION: usize = 1; 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)] @@ -66,8 +62,6 @@ const fn trim_sp_tab(mut bytes: &[u8]) -> &[u8] { #[derive(Clone, Copy, Debug)] pub struct ParseShebangOptions { - /// How many bytes of the file the kernel reads to find the shebang line. - pub max_line_len: usize, /// Whether to parse like XNU (see [`parse_xnu_shebang_line`]) rather than /// Linux `binfmt_script`. pub xnu: bool, @@ -80,7 +74,7 @@ impl ParseShebangOptions { )] #[must_use] pub const fn macos() -> Self { - Self { max_line_len: MACOS_MAX_LINE_LEN, xnu: true } + Self { xnu: true } } #[cfg_attr( @@ -89,13 +83,13 @@ impl ParseShebangOptions { )] #[must_use] pub const fn linux() -> Self { - Self { max_line_len: LINUX_MAX_LINE_LEN, xnu: false } + Self { xnu: false } } } -/// Parses the shebang line from an already-peeked file prefix (`buf.len() <= -/// options.max_line_len`), copying the interpreter and arguments into -/// `allocator`. +/// Parses the shebang line from an already-peeked file prefix (at most +/// [`LINUX_MAX_LINE_LEN`] or [`MACOS_MAX_LINE_LEN`] bytes), copying the +/// interpreter and arguments into `allocator`. /// /// Returns [`Error::NOEXEC`] where the kernel would refuse the script instead /// of running a truncated interpreter path. @@ -110,36 +104,63 @@ pub fn parse_shebang_bytes( if options.xnu { return parse_xnu_shebang_line(line, allocator).map(Some); } + parse_linux_shebang_line(buf, allocator).map(Some) +} - let line = if let Some(line_end) = line.find_byteset(b"\n\0") { - &line[..line_end] - } 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] +/// Parses a `#!` line exactly like Linux `binfmt_script`, which works on the +/// file's first [`LINUX_MAX_LINE_LEN`] bytes in a zero-padded buffer: +/// . +/// +/// The line ends at the first `\n` before any NUL. Without one, it runs to the +/// buffer's last byte, provided the interpreter is followed by a space, tab, or +/// NUL (otherwise it may be cut off). Trailing spaces and tabs are then +/// trimmed, which keeps those right before padding NULs, so `#!/bin/sh x ` +/// at EOF passes `"x "`. Everything after the interpreter and its separator +/// is one argument, read up to its NUL. +fn parse_linux_shebang_line(buf: &[u8], allocator: A) -> Result> { + let mut kbuf = [0u8; LINUX_MAX_LINE_LEN]; + let len = buf.len().min(LINUX_MAX_LINE_LEN); + kbuf[..len].copy_from_slice(&buf[..len]); + let buf_end = LINUX_MAX_LINE_LEN - 1; + let next_non_spacetab = + |kbuf: &[u8], first: usize, last: usize| (first..=last).find(|&i| !is_whitespace(kbuf[i])); + let next_terminator = |kbuf: &[u8], first: usize, last: usize| { + (first..=last).find(|&i| is_whitespace(kbuf[i]) || kbuf[i] == 0) }; - 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 mut i_end = + if let Some(newline) = kbuf.iter().take_while(|&&ch| ch != 0).position(|&ch| ch == b'\n') { + newline + } else { + let first = next_non_spacetab(&kbuf, 2, buf_end).ok_or(Error::NOEXEC)?; + next_terminator(&kbuf, first, buf_end).ok_or(Error::NOEXEC)?; + buf_end + }; + // `kbuf[1]` is `!`, so trimming stops before the `#!` prefix. + while is_whitespace(kbuf[i_end - 1]) { + i_end -= 1; } - // Linux passes everything after the interpreter as one argument. - let arguments_buf = trim_sp_tab_start(&line[interpreter.len()..]); - let mut arguments = Vec::new_in(allocator.clone()); - if !arguments_buf.is_empty() { - arguments.push(to_vec_in(arguments_buf, allocator.clone())); + let i_name = next_non_spacetab(&kbuf, 2, i_end) + .filter(|&i_name| i_name != i_end) + .ok_or(Error::NOEXEC)?; + let i_sep = next_terminator(&kbuf, i_name, i_end); + let i_arg = i_sep + .filter(|&i_sep| kbuf[i_sep] != 0) + .and_then(|i_sep| next_non_spacetab(&kbuf, i_sep, i_end)); + kbuf[i_end] = 0; + if let (Some(i_sep), Some(_)) = (i_sep, i_arg) { + kbuf[i_sep] = 0; } - Ok(Some(Shebang { interpreter: to_vec_in(interpreter, allocator), arguments })) + let c_string_at = |start: usize| { + let bytes = &kbuf[start..]; + &bytes[..bytes.find_byte(0).unwrap_or(bytes.len())] + }; + let mut arguments = Vec::new_in(allocator.clone()); + if let Some(i_arg) = i_arg { + arguments.push(to_vec_in(c_string_at(i_arg), allocator.clone())); + } + Ok(Shebang { interpreter: to_vec_in(c_string_at(i_name), allocator), arguments }) } /// Parses the bytes after `#!` like XNU `exec_shell_imgact`: the line must end @@ -202,7 +223,8 @@ mod tests { use super::*; fn parse(content: &[u8], options: ParseShebangOptions) -> Result>> { - let len = content.len().min(options.max_line_len); + let max_line_len = if options.xnu { MACOS_MAX_LINE_LEN } else { LINUX_MAX_LINE_LEN }; + let len = content.len().min(max_line_len); parse_shebang_bytes(&content[..len], options, Global) } @@ -263,6 +285,25 @@ mod tests { assert_eq!(split.interpreter.as_slice(), b"/bin/sh"); assert_eq!(split.arguments, [b"-e".as_slice(), b"-x"]); + // Linux trims trailing spaces only where `binfmt_script` does: before a + // newline, or at the end of a full buffer, but not before the padding + // NULs after a short file or before an embedded NUL. + let linux = ParseShebangOptions::linux(); + assert_eq!(parse(b"#!/bin/sh x \n", linux).unwrap().unwrap().arguments, [b"x"]); + assert_eq!(parse(b"#!/bin/sh x ", linux).unwrap().unwrap().arguments, [b"x "]); + assert_eq!(parse(b"#!/bin/sh ", linux).unwrap().unwrap().arguments, [b""]); + assert_eq!(parse(b"#!/bin/sh x \0junk\n", linux).unwrap().unwrap().arguments, [b"x "]); + assert!(parse(b"#!/bin/sh\n", linux).unwrap().unwrap().arguments.is_empty()); + let padded = |len: usize| { + let mut script = b"#!/bin/sh ".to_vec(); + script.resize(len - 1, b'a'); + script.push(b' '); + script + }; + let arg = |len| parse(&padded(len), linux).unwrap().unwrap().arguments[0].clone(); + assert_eq!(arg(254).last(), Some(&b' '), "254-byte EOF keeps the trailing space"); + assert_eq!(arg(255).last(), Some(&b'a'), "255-byte EOF trims it"); + // 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"); From 995d8ffc10e631218af1f1dede999abdb0470ce4 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Sat, 28 Nov 2026 19:11:31 +0800 Subject: [PATCH 37/48] fix(fspy_preload_macos): retry PATH candidates and keep execvp's shell fallback Exec preparation picked the first executable PATH candidate before trying it, so a candidate that then failed (its #! interpreter missing) stopped the search, and execvp/execlp returned ENOEXEC for a file without #! instead of running it with /bin/sh. Search PATH the way Darwin's execvP and posix_spawnp do: prepare and try each candidate, move on after ENOENT/ENOTDIR/ELOOP/ENAMETOOLONG (and remember EACCES), and for execvp/execlp run an ENOEXEC candidate with /bin/sh through the same preparation, so SIP substitution and tracking still apply. Co-Authored-By: Claude Opus 5.5 --- crates/fspy/tests/macos_preload.rs | 80 ++++++++++- crates/fspy_preload_macos/README.md | 3 + crates/fspy_preload_macos/src/client.rs | 20 +-- .../src/interceptions/spawn/exec/mod.rs | 76 ++++++++-- .../src/interceptions/spawn/posix_spawn.rs | 74 ++++++---- crates/fspy_preload_macos/src/which.rs | 130 +++++++++--------- 6 files changed, 261 insertions(+), 122 deletions(-) diff --git a/crates/fspy/tests/macos_preload.rs b/crates/fspy/tests/macos_preload.rs index 333b28b93..b8d59b0b3 100644 --- a/crates/fspy/tests/macos_preload.rs +++ b/crates/fspy/tests/macos_preload.rs @@ -191,17 +191,38 @@ async fn which_path_search_handles_unset_empty_and_directory_entries() -> anyhow &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", empty_marker.display()), )?; + // A `broken_tool` whose interpreter is missing in the first PATH entry, a + // working one in the second, and a script without `#!`, which `execvp` + // (unlike `posix_spawnp`) runs with `/bin/sh`. + let dir_with_broken = root.join("dir_with_broken"); + fs::create_dir(&dir_with_broken)?; + write_executable(&dir_with_broken.join("broken_tool"), "#!/nonexistent/fspy-interpreter\n")?; + let broken_skip_marker = root.join("marker_broken_skip"); + fs::write(&broken_skip_marker, "ok")?; + write_executable( + &dir_with_real.join("broken_tool"), + &format!("#!/bin/sh\ncat \"{}\" >/dev/null\n", broken_skip_marker.display()), + )?; + let no_shebang_marker = root.join("marker_no_shebang"); + fs::write(&no_shebang_marker, "ok")?; + write_executable( + &dir_with_real.join("no_shebang"), + &format!("cat \"{}\" >/dev/null\n", no_shebang_marker.display()), + )?; + let args = ( dir_with_subdir.to_str().unwrap().to_owned(), dir_with_real.to_str().unwrap().to_owned(), empty_entry_cwd.to_str().unwrap().to_owned(), + dir_with_broken.to_str().unwrap().to_owned(), ); - let accesses = track_fn!(args, |(dir_with_subdir, dir_with_real, empty_entry_cwd): ( - String, - String, - String - )| { + let accesses = track_fn!(args, |( + dir_with_subdir, + dir_with_real, + empty_entry_cwd, + dir_with_broken, + ): (String, String, String, String)| { // 1. Directory on PATH is skipped in favor of a later regular executable. run_in_fork(|| { let path = format!("{dir_with_subdir}:{dir_with_real}:/bin:/usr/bin"); @@ -252,11 +273,60 @@ async fn which_path_search_handles_unset_empty_and_directory_entries() -> anyhow // SAFETY: `prog` and `argv` are valid. unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; }); + + // 5. A candidate that fails to exec (its interpreter is missing) moves on + // to the next PATH entry, for `execvp` and `posix_spawnp` alike. + let broken_path = format!("{dir_with_broken}:{dir_with_real}:/bin:/usr/bin"); + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", &broken_path) }; + let prog = c"broken_tool"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", &broken_path) }; + let prog = c"broken_tool"; + let argv = [prog.as_ptr().cast_mut(), std::ptr::null_mut()]; + let mut pid: libc::pid_t = 0; + // SAFETY: all pointers are valid, and `environ` is this process's environment. + let rc = unsafe { + libc::posix_spawnp( + &raw mut pid, + prog.as_ptr(), + null(), + null(), + argv.as_ptr(), + (*libc::_NSGetEnviron()).cast_const(), + ) + }; + assert_eq!(rc, 0, "posix_spawnp(broken_tool) failed: {rc}"); + let mut status = 0; + // SAFETY: `pid` is our child and `status` is writable. + assert_eq!(unsafe { libc::waitpid(pid, &raw mut status, 0) }, pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); + // SAFETY: exit the forked child cleanly. + unsafe { libc::_exit(0) }; + }); + + // 6. `execvp` runs an executable without a recognized format with `/bin/sh`. + run_in_fork(|| { + // SAFETY: single-threaded forked child. + unsafe { std::env::set_var("PATH", &dir_with_real) }; + let prog = c"no_shebang"; + let argv = [prog.as_ptr(), null()]; + // SAFETY: `prog` and `argv` are valid. + unsafe { libc::execvp(prog.as_ptr(), argv.as_ptr()) }; + }); }) .await?; assert_contains(&accesses, &skipped_marker, PathAccess::Read); assert_contains(&accesses, &empty_marker, PathAccess::Read); + assert_contains(&accesses, &broken_skip_marker, PathAccess::Read); + assert_contains(&accesses, &no_shebang_marker, PathAccess::Read); Ok(()) } diff --git a/crates/fspy_preload_macos/README.md b/crates/fspy_preload_macos/README.md index 64fe600a8..8c3037f02 100644 --- a/crates/fspy_preload_macos/README.md +++ b/crates/fspy_preload_macos/README.md @@ -2,3 +2,6 @@ Dynamic library (`cdylib`) injected into traced macOS processes via `DYLD_INSERT_LIBRARIES` using dyld's `__DATA,__interpose` section. + +Exec calls are prepared in userland, reading the program to resolve `#!`, so +execute-only (`chmod 0111`) programs fail with `EACCES` under tracking. diff --git a/crates/fspy_preload_macos/src/client.rs b/crates/fspy_preload_macos/src/client.rs index f20bd8a06..db9bf899f 100644 --- a/crates/fspy_preload_macos/src/client.rs +++ b/crates/fspy_preload_macos/src/client.rs @@ -8,8 +8,6 @@ use fspy_shared::ipc::{AccessMode, IpcPath, channel::Sender}; use fspy_shared_unix::{Exec, RawExec, macos::EncodedPayload}; use libc::{c_char, c_int}; -use crate::which; - pub struct Client<'a> { encoded_payload: EncodedPayload<'a>, ipc_sender: Option, @@ -44,7 +42,8 @@ impl Client<'_> { ipc_sender.send(&mode.with_path(IpcPath::from_bytes(bytes))); } - /// Resolves and prepares an exec call, optionally searching `PATH` first. + /// Prepares an exec call for an already chosen program (callers search + /// `PATH` with [`crate::which::try_path_candidates`]). /// /// # Safety /// @@ -53,16 +52,14 @@ impl Client<'_> { /// /// # Errors /// - /// Returns OS-compatible `errno` values from `PATH` lookup or exec - /// preparation. + /// Returns OS-compatible `errno` values from 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. - unsafe { self.handle_exec_in_dir(search_path, None, raw_exec, allocator) } + unsafe { self.handle_exec_in_dir(None, raw_exec, allocator) } } /// Resolves and prepares an exec call, resolving relative paths against @@ -76,22 +73,15 @@ impl Client<'_> { /// /// # Errors /// - /// Returns OS-compatible `errno` values from `PATH` lookup or exec - /// preparation. + /// Returns OS-compatible `errno` values from exec preparation. pub unsafe fn handle_exec_in_dir( &self, - search_path: bool, cwd: Option<&[u8]>, 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, cwd, allocator, |candidate| { - self.send_path(AccessMode::Read, candidate); - })?; - } self.encoded_payload.prepare_exec_in_dir(&mut exec, cwd, |path| { self.send_path(AccessMode::Read, path); })?; diff --git a/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs b/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs index cb5c09df5..d1dc4a0b1 100644 --- a/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs +++ b/crates/fspy_preload_macos/src/interceptions/spawn/exec/mod.rs @@ -1,12 +1,15 @@ use std::{ffi::VaList, ptr::null}; use allocator_api2::{alloc::Allocator, vec::Vec}; +use fspy_nostd::{CStr, Error, Result, Thin}; +use fspy_shared::ipc::AccessMode; use fspy_shared_unix::RawExec; use libc::{c_char, c_int}; use crate::{ client::{global_client, set_errno}, macros::intercept, + which, }; unsafe fn environ() -> *const *const c_char { @@ -45,18 +48,69 @@ fn handle_exec( ) -> 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; - } + let allocator = &allocator; + // Prepares and runs one candidate; returns only when the exec fails. + let exec_program = |prog: *const c_char, argv: *const *const c_char| -> Result<()> { + // SAFETY: prog, argv, and envp are forwarded from the interposed exec call. + let raw = unsafe { client.handle_exec(RawExec { prog, argv, envp }, allocator) }?; + // SAFETY: `raw` points into `allocator`, which outlives this call. + unsafe { execve::original()(raw.prog, raw.argv, raw.envp) }; + Err(Error::last_os_error()) + }; + let err = if search_path && !prog.is_null() { + // SAFETY: a non-null `prog` is the caller's NUL-terminated file name. + let file = unsafe { CStr::::from_ptr(prog.cast()) }.count(); + let result = which::try_path_candidates( + file.as_units(), + None, + allocator, + |candidate| client.send_path(AccessMode::Read, candidate), + |candidate| exec_program(candidate.as_ptr().cast(), argv), + // Like Darwin `execvp`, run a file without a recognized format with + // `/bin/sh`, through the same preparation (SIP copy, tracking). + |candidate| { + // SAFETY: `argv` is the caller's NULL-terminated argument array. + let shell_argv = unsafe { shell_argv(allocator, candidate, argv) }; + exec_program(c"/bin/sh".as_ptr(), shell_argv.as_ptr()) + }, + ); + result.err().unwrap_or(Error::NOENT) + } else { + exec_program(prog, argv).err().unwrap_or(Error::NOENT) }; - // SAFETY: `raw_command` points into `allocator`, which outlives this call. - unsafe { execve::original()(raw_command.prog, raw_command.argv, raw_command.envp) } + set_errno(err); + -1 +} + +/// Builds `sh