| // Copyright 2026 The Fuchsia Authors | |
| // | |
| // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| // This file may not be copied, modified, or distributed except according to | |
| // those terms. | |
| //! Hermetic Nix/CAS split-store and ELF `DT_RUNPATH` simulation helpers. | |
| //! | |
| //! Tests split C/toolchain runtimes (`PT_INTERP`, `DT_RUNPATH` vs. `DT_RPATH`, | |
| //! symlinked DSOs, and cross-package Nix `symlinkJoin` Lean stdlib trees) | |
| //! under `<root>/store/` without mutating or requiring host `/nix/store`. | |
| use std::ffi::OsStr; | |
| use std::fs; | |
| use std::path::{Path, PathBuf}; | |
| use crate::TestResult; | |
| use crate::process::{Invocation, ProcessOutcome}; | |
| use crate::workspace::StagedWorkspace; | |
| mod elf; | |
| mod layout; | |
| #[cfg(all(test, target_os = "linux"))] | |
| mod tests; | |
| pub use self::elf::{ | |
| Elf64Info, Elf64Spec, build_elf64_image, inspect_elf64, | |
| resolve_elf64_dependency_closure, | |
| }; | |
| pub use self::layout::{ElfStoreBuilder, ElfStoreCell, FiveCellElfLayout}; | |
| #[cfg(all(test, target_os = "linux"))] | |
| use self::{elf::vaddr_to_offset, layout::write_exec}; | |
| #[cfg(all(test, target_os = "linux"))] | |
| use crate::workspace::WorkspaceBuilder; | |
| /// Configuration for running an executable inside an unprivileged Linux `bwrap` | |
| /// namespace with `<store_dir>` bound read-only at `/nix/store`. | |
| #[derive(Clone, Debug)] | |
| pub struct SimulatedStoreConfig { | |
| pub extra_ro_binds: Vec<(PathBuf, PathBuf)>, | |
| pub environment: Vec<(String, String)>, | |
| } | |
| impl Default for SimulatedStoreConfig { | |
| fn default() -> Self { | |
| Self { | |
| extra_ro_binds: Vec::new(), | |
| environment: vec![("PATH".into(), "/usr/bin:/bin".into())], | |
| } | |
| } | |
| } | |
| /// Execute `exe` with `args` inside an unprivileged Linux `bubblewrap` mount | |
| /// namespace binding `staged.store_dir()` read-only at `/nix/store` and | |
| /// `staged.work_dir()` writable at `/work`. | |
| /// | |
| /// If `exe` resides outside `/usr`, `/bin`, `/lib`, `/lib64`, or `/nix/store`, | |
| /// it is also read-only mounted at its canonical path inside the namespace so | |
| /// workspace-compiled test binaries can run as the simulated child target. | |
| pub fn run_in_simulated_nix_store( | |
| staged: &StagedWorkspace, | |
| exe: &Path, | |
| args: &[&OsStr], | |
| config: &SimulatedStoreConfig, | |
| ) -> TestResult<ProcessOutcome> { | |
| #[cfg(not(target_os = "linux"))] | |
| { | |
| let _ = (staged, exe, args, config); | |
| return Err( | |
| "run_in_simulated_nix_store requires Linux bubblewrap user/mount namespaces".into(), | |
| ); | |
| } | |
| #[cfg(target_os = "linux")] | |
| { | |
| let bwrap = Path::new("/usr/bin/bwrap"); | |
| if !bwrap.is_file() { | |
| return Err("bubblewrap (/usr/bin/bwrap) is required for simulated /nix/store".into()); | |
| } | |
| let canon_store = fs::canonicalize(staged.store_dir()) | |
| .map_err(|e| format!("canonicalize store_dir: {e}"))?; | |
| let canon_work = fs::canonicalize(staged.work_dir()) | |
| .map_err(|e| format!("canonicalize work_dir: {e}"))?; | |
| // Allow callers to invoke binaries staged directly under `/nix/store/` | |
| // without host canonicalization so `/nix/store`-relative `$ORIGIN` is | |
| // preserved inside the mount namespace. | |
| let (exec_in_sandbox, bind_host_exe) = if let Ok(rel) = exe.strip_prefix("/nix/store") { | |
| if rel.as_os_str().is_empty() | |
| || rel | |
| .components() | |
| .any(|c| matches!(c, std::path::Component::ParentDir)) | |
| { | |
| return Err(format!( | |
| "simulated /nix/store executable path must be clean: {}", | |
| exe.display() | |
| )); | |
| } | |
| let host_target = canon_store.join(rel); | |
| let canon_target = fs::canonicalize(&host_target).map_err(|e| { | |
| format!("canonicalize staged store executable {}: {e}", exe.display()) | |
| })?; | |
| if !canon_target.starts_with(&canon_store) { | |
| return Err(format!( | |
| "staged store executable escapes store_dir: {}", | |
| exe.display() | |
| )); | |
| } | |
| (exe.to_path_buf(), None) | |
| } else { | |
| let canon_exe = fs::canonicalize(exe) | |
| .map_err(|e| format!("canonicalize target executable {}: {e}", exe.display()))?; | |
| let already_mounted = ["/usr", "/bin", "/lib", "/lib64", "/nix/store"] | |
| .into_iter() | |
| .any(|prefix| canon_exe.starts_with(prefix)); | |
| let extra_bind = (!already_mounted).then(|| canon_exe.clone()); | |
| (canon_exe, extra_bind) | |
| }; | |
| let mut inv = Invocation::new( | |
| bwrap, | |
| &[ | |
| "--unshare-all", | |
| "--die-with-parent", | |
| "--new-session", | |
| "--clearenv", | |
| "--cap-drop", | |
| "ALL", | |
| "--tmpfs", | |
| "/", | |
| "--dev", | |
| "/dev", | |
| "--proc", | |
| "/proc", | |
| "--ro-bind", | |
| "/usr", | |
| "/usr", | |
| "--ro-bind-try", | |
| "/bin", | |
| "/bin", | |
| "--ro-bind-try", | |
| "/lib", | |
| "/lib", | |
| "--ro-bind-try", | |
| "/lib64", | |
| "/lib64", | |
| "--ro-bind-try", | |
| "/etc/ld.so.cache", | |
| "/etc/ld.so.cache", | |
| ], | |
| ); | |
| inv = inv | |
| .arg("--ro-bind") | |
| .arg(&canon_store) | |
| .arg("/nix/store") | |
| .arg("--dir") | |
| .arg("/work") | |
| .arg("--bind") | |
| .arg(&canon_work) | |
| .arg("/work") | |
| .arg("--chdir") | |
| .arg("/work"); | |
| if let Some(host_exe) = &bind_host_exe { | |
| inv = inv.arg("--ro-bind").arg(host_exe).arg(host_exe); | |
| } | |
| for (src, dst) in &config.extra_ro_binds { | |
| inv = inv.arg("--ro-bind").arg(src).arg(dst); | |
| } | |
| for (k, v) in &config.environment { | |
| inv = inv.arg("--setenv").arg(k).arg(v); | |
| } | |
| inv = inv.arg("--").arg(&exec_in_sandbox); | |
| for arg in args { | |
| inv = inv.arg(arg); | |
| } | |
| let log_dir = staged.next_command_log_dir(); | |
| staged | |
| .supervisor() | |
| .run(&inv, staged.work_dir(), &log_dir, staged.root_dir()) | |
| } | |
| } |