#![deny(clippy::all)]
#![allow(clippy::uninlined_format_args)]
#![allow(
unexpected_cfgs,
reason = "`fbcode_build` is supplied by the internal Buck build"
)]
mod analyze;
mod backends;
mod bisect;
mod clean;
mod cli_owned_lifecycle;
mod container;
mod dap_adapter;
#[cfg(test)]
mod exec_stop_launch_tests;
mod gdb_client;
mod gdb_watch_helper;
mod global_opts;
mod host_capabilities;
mod host_seccomp;
mod image;
mod instruction_map;
mod inventory;
mod list;
mod logdiff;
mod manifest;
#[cfg(feature = "native-exec")]
mod native_exec_artifacts;
#[cfg(feature = "native-exec")]
mod native_exec_cli;
#[cfg(feature = "native-exec")]
mod native_exec_coordinator;
#[cfg(feature = "native-exec")]
mod native_exec_inputs;
#[cfg(feature = "native-exec")]
mod native_exec_maps;
#[cfg(feature = "native-exec")]
mod native_exec_observer;
#[cfg(feature = "native-exec")]
mod native_exec_provider;
#[cfg(feature = "native-exec")]
mod native_exec_run;
#[cfg(feature = "native-exec")]
mod native_exec_setup;
mod oci;
mod owned_container;
mod podman_store;
mod record;
mod record_envelope;
mod record_start;
mod remove;
mod replay;
mod run;
mod run_config;
mod run_timeout;
mod schedule_search;
mod strace;
mod tracing;
mod verify;
mod verify_inputs;
mod verify_run;
mod version;
use std::fs::File;
use std::io;
use std::os::fd::AsRawFd;
use std::os::fd::BorrowedFd;
use std::os::fd::FromRawFd;
use std::path::Path;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering;
const STDIN_UNCAPTURED: i32 = i32::MIN;
const STDIN_TAKEN: i32 = i32::MIN + 1;
static STARTUP_STDIN: AtomicI32 = AtomicI32::new(STDIN_UNCAPTURED);
unsafe extern "C" fn capture_startup_stdin() {
let fd = unsafe { libc::fcntl(libc::STDIN_FILENO, libc::F_DUPFD_CLOEXEC, 3) };
let value = if fd >= 0 {
fd
} else {
let errno = unsafe { *libc::__errno_location() };
-errno - 1
};
STARTUP_STDIN.store(value, Ordering::Relaxed);
}
#[used]
#[unsafe(link_section = ".preinit_array")]
static CAPTURE_STARTUP_STDIN: unsafe extern "C" fn() = capture_startup_stdin;
fn startup_stdin() -> io::Result<Option<File>> {
let value = STARTUP_STDIN.swap(STDIN_TAKEN, Ordering::AcqRel);
if value >= 0 {
return Ok(Some(unsafe { File::from_raw_fd(value) }));
}
if value == STDIN_UNCAPTURED || value == STDIN_TAKEN {
return Err(io::Error::other(
"startup stdin was not captured exactly once",
));
}
let errno = -value - 1;
if errno == libc::EBADF {
Ok(None)
} else {
Err(io::Error::from_raw_os_error(errno))
}
}
fn retire_inherited_descriptors(owned: &[BorrowedFd<'_>]) -> io::Result<()> {
let saved_stdin = STARTUP_STDIN.load(Ordering::Acquire);
if saved_stdin == STDIN_UNCAPTURED || saved_stdin == STDIN_TAKEN {
return Err(io::Error::other(
"startup stdin reservation is unavailable at CLI entry",
));
}
let stdin_owner = (saved_stdin >= 3).then_some(saved_stdin as u32);
let mut first = 3;
loop {
let next_owner = stdin_owner
.into_iter()
.chain(owned.iter().map(|fd| fd.as_raw_fd() as u32))
.filter(|fd| *fd >= first)
.min();
let last = next_owner.map_or(u32::MAX, |fd| fd - 1);
if first <= last {
if unsafe { libc::syscall(libc::SYS_close_range, first, last, 0u32) } < 0 {
return Err(io::Error::last_os_error());
}
}
match next_owner {
Some(fd) => first = fd + 1,
None => return Ok(()),
}
}
}
use clap::ArgMatches;
use clap::CommandFactory;
use clap::FromArgMatches;
use clap::Parser;
use clap::parser::ValueSource;
use colored::*;
use hermit::BackendUnavailable;
use hermit::Error;
use hermit::ExitStatus;
use hermit::HERMIT_INTERNAL_FAILURE_EXIT;
use self::analyze::AnalyzeOpts;
use self::bisect::BisectOpts;
use self::container::ContainerChildExit;
use self::container::ContainerChildPanic;
use self::container::LogCapExceeded;
use self::container::PolicyRefusal;
use self::container::RunTimeoutMarker;
use self::container::SignalDeath;
use self::global_opts::GlobalOpts;
use self::host_capabilities::HostCapabilitiesOpts;
use self::instruction_map::InstructionMapOpts;
use self::logdiff::LogDiffCLIOpts;
use self::oci::OciOpts;
use self::record::RecordOpts;
use self::replay::ReplayOpts;
use self::run::GuestProgramFault;
use self::run::RunOpts;
use self::strace::StraceOpts;
use self::verify::write_pending_verification_json;
use self::version::Version;
use self::version::VersionOpts;
#[derive(Debug, Parser)]
#[clap(
name = "hermit",
version = Version::get(),
)]
struct Args {
#[clap(flatten)]
global: GlobalOpts,
#[clap(subcommand)]
command: Subcommand,
}
fn args_from_matches_with_clock(
matches: &ArgMatches,
capture_now: impl FnOnce() -> std::time::SystemTime,
) -> Result<Args, clap::Error> {
let run_matches = matches.subcommand_matches("run").or_else(|| {
matches
.subcommand_matches("oci")
.and_then(|oci| oci.subcommand_matches("run"))
});
let run_epoch_source = run_matches.and_then(|run| run.value_source("epoch"));
let mut args = Args::from_arg_matches(matches)?;
if let Some(run_matches) = run_matches {
match &mut args.command {
Subcommand::Run(run) => run.capture_max_timeslice_source(run_matches),
Subcommand::Oci(oci) => oci.capture_max_timeslice_source(run_matches),
_ => unreachable!("only run subcommands carry a maximum timeslice"),
}
}
if let (Some(backend), Some(run)) = (args.global.backend, run_matches)
&& run.get_flag("namespace_only")
{
return Err(Args::command().error(
clap::error::ErrorKind::ArgumentConflict,
format!(
"the argument '--backend={}' cannot be used with '--namespace-only': \
namespace-only mode bypasses instrumentation, so the backend would be \
ignored. Drop `--backend` to run namespace-only, or drop \
`--namespace-only` to run under the {} backend.",
backend.as_str(),
backend.as_str()
),
));
}
if run_epoch_source == Some(ValueSource::DefaultValue) {
match &mut args.command {
Subcommand::Run(run) => run.capture_default_epoch(capture_now),
Subcommand::Oci(oci) => oci.capture_default_run_epoch(capture_now),
_ => unreachable!("only run subcommands carry an epoch"),
}
}
if let (Subcommand::Run(run), Some(run_matches)) =
(&mut args.command, matches.subcommand_matches("run"))
{
match run_config::capture(&Args::command(), matches, run_matches) {
Ok(config) => run.set_config_capture(config),
Err(error) if run.saves_config() => {
return Err(Args::command().error(
clap::error::ErrorKind::ValueValidation,
format!("{error:#}"),
));
}
Err(_) => {}
}
}
if let Subcommand::Replay(replay) = &mut args.command {
let tokens = run_config::global_tokens(&Args::command(), matches).map_err(|error| {
Args::command().error(
clap::error::ErrorKind::ValueValidation,
format!("{error:#}"),
)
})?;
replay.set_global_argv(tokens);
}
Ok(args)
}
fn redirect_misplaced_backend(error: clap::Error, argv: &[std::ffi::OsString]) -> clap::Error {
use clap::builder::StyledStr;
use clap::error::ContextKind;
use clap::error::ContextValue;
use clap::error::ErrorKind;
let Some(invalid) = misplaced_backend_argument(&error) else {
return error;
};
let mut command = Args::command();
let mut redirected = clap::Error::new(ErrorKind::UnknownArgument).with_cmd(&command);
redirected.insert(ContextKind::InvalidArg, ContextValue::String(invalid));
redirected.insert(
ContextKind::Usage,
ContextValue::StyledStr(command.render_usage()),
);
let corrected = globally_placed_backend(argv)
.unwrap_or_else(|| "hermit --backend=<BACKEND> <SUBCOMMAND> [OPTIONS]".to_owned());
redirected.insert(
ContextKind::Suggested,
ContextValue::StyledStrs(vec![StyledStr::from(format!(
"`--backend` is a global option and must come before the subcommand: `{corrected}`"
))]),
);
redirected
}
pub(crate) fn misplaced_backend_argument(error: &clap::Error) -> Option<String> {
use clap::error::ContextKind;
use clap::error::ContextValue;
use clap::error::ErrorKind;
if error.kind() != ErrorKind::UnknownArgument {
return None;
}
match error.get(ContextKind::InvalidArg) {
Some(ContextValue::String(invalid))
if invalid == "--backend" || invalid.starts_with("--backend=") =>
{
Some(invalid.clone())
}
_ => None,
}
}
fn globally_placed_backend(argv: &[std::ffi::OsString]) -> Option<String> {
let args = argv
.iter()
.map(|arg| arg.to_str())
.collect::<Option<Vec<_>>>()?;
let (program, rest) = args.split_first()?;
let options_end = rest
.iter()
.position(|arg| *arg == "--")
.unwrap_or(rest.len());
let mut positions = rest[..options_end]
.iter()
.enumerate()
.filter(|(_, arg)| **arg == "--backend" || arg.starts_with("--backend="))
.map(|(index, _)| index);
let index = positions.next()?;
if positions.next().is_some() {
return None;
}
let mut remaining = rest.to_vec();
let backend = if remaining[index] == "--backend" {
if index + 1 >= options_end {
return None;
}
let value = remaining.remove(index + 1);
remaining.remove(index);
value
} else {
remaining.remove(index).strip_prefix("--backend=")?
};
if backend.is_empty() || backend.starts_with('-') {
return None;
}
let flag = format!("--backend={backend}");
let words = std::iter::once(*program)
.chain(std::iter::once(flag.as_str()))
.chain(remaining.iter().copied())
.map(|word| {
let plain = !word.is_empty()
&& word
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"-_./:=,@%+".contains(&byte));
if plain {
word.to_owned()
} else {
shell_words::quote(word).into_owned()
}
})
.collect::<Vec<_>>();
Some(words.join(" "))
}
#[derive(Debug, Parser)]
enum Subcommand {
#[clap(name = "host-capabilities")]
HostCapabilities(HostCapabilitiesOpts),
#[clap(name = "version")]
Version(VersionOpts),
#[clap(name = "run", trailing_var_arg = true)]
Run(Box<RunOpts>),
#[clap(name = "strace")]
Strace(StraceOpts),
#[clap(name = "record", trailing_var_arg = true)]
Record(Box<RecordOpts>),
#[clap(name = "replay")]
Replay(ReplayOpts),
#[clap(name = "list")]
List(inventory::ListOpts),
#[clap(name = "show")]
Show(inventory::ShowOpts),
#[clap(verbatim_doc_comment)]
LogDiff(LogDiffCLIOpts),
Analyze(Box<AnalyzeOpts>),
#[clap(name = "bisect", trailing_var_arg = true)]
Bisect(Box<BisectOpts>),
#[clap(name = "instruction-map")]
InstructionMap(InstructionMapOpts),
#[clap(name = "oci")]
Oci(Box<OciOpts>),
#[clap(name = "verify-inputs", hide = true)]
VerifyInputs(verify_inputs::VerifyInputsOpts),
}
impl Subcommand {
fn validate_backend_scope(&self, backend: Option<hermit::Backend>) -> Result<(), Error> {
let runs_trials = matches!(self, Subcommand::Analyze(_) | Subcommand::Bisect(_));
if backend == Some(hermit::Backend::Sabre)
&& !matches!(self, Subcommand::Strace(_) | Subcommand::Run(_))
{
anyhow::bail!(
"the SaBRe backend is available only through `hermit --backend sabre run` \
and `hermit --backend sabre strace`"
);
}
let starts_e9patch_guest = matches!(self, Subcommand::Run(_))
|| matches!(self, Subcommand::Record(record) if record.starts_recording());
if backend == Some(hermit::Backend::E9patch) && !starts_e9patch_guest {
anyhow::bail!(
"the e9patch preprocessor is available only through `hermit --backend e9patch \
run` and `hermit --backend e9patch record`; other subcommands, including \
`analyze` and `bisect`, do not preprocess their guest"
);
}
if let Some(backend) = backend.filter(|backend| backend.is_in_guest_liteinst())
&& !matches!(self, Subcommand::Run(_))
{
anyhow::bail!(
"the LiteInst preload backend is available only through `hermit --backend \
{backend} run`; other subcommands, including `analyze` and `bisect`, do not \
use the preload runtime",
backend = backend.as_str()
);
}
if backend == Some(hermit::Backend::Kvm)
&& !(matches!(self, Subcommand::Run(_)) || runs_trials)
{
anyhow::bail!(
"the KVM backend is available only through `hermit --backend kvm run`, \
`hermit --backend kvm analyze` and `hermit --backend kvm bisect`; record and \
replay require the ptrace runtime's sequentialized scheduler"
);
}
if backend == Some(hermit::Backend::Dbt) && !matches!(self, Subcommand::Run(_)) {
anyhow::bail!(
"the DBT backend is available only through `hermit --backend dbt run`; record \
and replay use the ptrace runtime, and `analyze` and `bisect` bind a \
workspace into every trial, which DBT cannot apply"
);
}
Ok(())
}
fn starts_guest(&self) -> bool {
match self {
Subcommand::Run(_)
| Subcommand::Strace(_)
| Subcommand::Replay(_)
| Subcommand::Analyze(_)
| Subcommand::Bisect(_) => true,
Subcommand::Record(record) => record.starts_recording(),
Subcommand::Oci(oci) => oci.starts_guest(),
Subcommand::HostCapabilities(_)
| Subcommand::List(_)
| Subcommand::Show(_)
| Subcommand::Version(_)
| Subcommand::LogDiff(_)
| Subcommand::InstructionMap(_)
| Subcommand::VerifyInputs(_) => false,
}
}
fn verification_json_path(&self) -> Option<&Path> {
match self {
Subcommand::Run(run) => run.verify_json_path(),
Subcommand::Record(record) => record.verify_json_path(),
Subcommand::Oci(oci) => oci.verify_json_path(),
_ => None,
}
}
fn main(&mut self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
self.main_with_host_admission(global, host_seccomp::admit)
}
fn main_with_host_admission(
&mut self,
global: &GlobalOpts,
admit_host: impl FnOnce(bool) -> Result<(), Error>,
) -> Result<ExitStatus, Error> {
if let Some(path) = self.verification_json_path() {
write_pending_verification_json(path)?;
}
match self {
Subcommand::Run(run) => run.refuse_unready_exec_stop()?,
Subcommand::Oci(oci) => oci.refuse_unready_exec_stop()?,
_ => (),
}
self.validate_backend_scope(global.backend)?;
if self.starts_guest() {
admit_host(global.unsafe_ignore_host_seccomp)?;
}
match self {
Subcommand::HostCapabilities(x) => x.main(),
Subcommand::Version(x) => x.main(),
Subcommand::Run(x) => x.main(global),
Subcommand::Strace(x) => x.main(global),
Subcommand::Record(x) => x.main(global),
Subcommand::Replay(x) => x.main(global),
Subcommand::List(x) => x.main(),
Subcommand::Show(x) => x.main(),
Subcommand::LogDiff(x) => x.run(global),
Subcommand::Analyze(x) => x.main(global),
Subcommand::Bisect(x) => x.main(global),
Subcommand::InstructionMap(x) => x.main(global),
Subcommand::Oci(x) => x.main(global),
Subcommand::VerifyInputs(x) => x.main(),
}
}
}
#[fbinit::main]
fn main() {
hermit::launch_on_calling_thread();
if let Some(status) = cli_owned_lifecycle::maybe_run() {
std::process::exit(status);
}
if let Some(result) = gdb_watch_helper::maybe_run() {
match result {
Ok(()) => return,
Err(error) => {
display_entry_error("GDB helper failed", &error);
std::process::exit(125);
}
}
}
let entry_argv = std::env::args_os().collect::<Vec<_>>();
if let Err(error) = verify_inputs::retire_inherited_keeping_shared_inputs(
&entry_argv,
retire_inherited_descriptors,
) {
std::process::exit(refuse_entry_descriptor_failure(error, &entry_argv));
}
container::open_parent_pidfd_for_container_inits();
detcore::util::init_shared_stderr_deadline_origin();
let argv = std::env::args_os().collect::<Vec<_>>();
let (argv, config_applied) = match run_config::expand_argv(&Args::command(), &argv) {
Ok(Some(expanded)) => (expanded, true),
Ok(None) => (argv, false),
Err(error) => Args::command()
.error(
clap::error::ErrorKind::ValueValidation,
format!("{error:#}"),
)
.exit(),
};
let matches = Args::command()
.try_get_matches_from(&argv)
.unwrap_or_else(|error| {
let error = redirect_misplaced_backend(error, &argv);
if config_applied && error.use_stderr() {
let _ = error.print();
eprintln!(
"note: the options of the --config file count as given on the command \
line, and an option given on the command line replaces the file's value"
);
std::process::exit(error.exit_code());
}
error.exit()
});
let Args {
mut global,
mut command,
} = args_from_matches_with_clock(&matches, std::time::SystemTime::now)
.unwrap_or_else(|error| error.exit());
if global.max_log_bytes.is_some() {
self::tracing::enable_log_cap_exit_bound();
}
let result = global
.prepare_log_budget()
.map(|()| self::tracing::register_invocation_log_budget(global.log_budget()))
.and_then(|()| global.open_log_file())
.and_then(|()| command.main(&global));
let status = result.unwrap_or_else(|error| {
let status = ExitStatus::Exited(failure_exit_code(&error));
display_error(error);
status
});
block_write_signals_until_exit();
let _ = std::io::Write::flush(&mut std::io::stdout());
verify::write_queued_signal_reports();
status.raise_or_exit();
}
fn stamp_entry_descriptor_failure(argv: &[std::ffi::OsString]) -> Result<(), Error> {
let expanded = run_config::expand_argv(&Args::command(), argv)?;
let argv = expanded.as_deref().unwrap_or(argv);
let matches = Args::command().try_get_matches_from(argv)?;
let args = args_from_matches_with_clock(&matches, std::time::SystemTime::now)?;
if let Some(path) = args.command.verification_json_path() {
write_pending_verification_json(path)?;
}
Ok(())
}
fn refuse_entry_descriptor_failure(error: io::Error, argv: &[std::ffi::OsString]) -> i32 {
block_write_signals_until_exit();
let stamp = stamp_entry_descriptor_failure(argv);
display_entry_error(
"Inherited descriptor cleanup failed; use a Linux environment that allows close_range",
&error.into(),
);
if let Err(secondary) = stamp {
display_entry_error("Entry-failure verification stamp failed", &secondary);
}
HERMIT_INTERNAL_FAILURE_EXIT
}
fn display_entry_error(context: &str, error: &Error) {
block_write_signals_until_exit();
let report = format!("{context}: {error:#}\n");
hermit::nonwaiting_write::write_without_waiting(libc::STDERR_FILENO, report.as_bytes());
}
fn block_write_signals_until_exit() {
unsafe {
let mut blocked: libc::sigset_t = std::mem::zeroed();
libc::sigemptyset(&mut blocked);
libc::sigaddset(&mut blocked, libc::SIGXFSZ);
libc::sigaddset(&mut blocked, libc::SIGPIPE);
libc::pthread_sigmask(libc::SIG_BLOCK, &blocked, std::ptr::null_mut());
}
}
fn failure_exit_code(error: &Error) -> i32 {
if error.downcast_ref::<hermit::SkidOvershootError>().is_some() {
return detcore_model::HERMIT_POLICY_REFUSAL_EXIT;
}
if error.downcast_ref::<PolicyRefusal>().is_some() {
return detcore_model::HERMIT_POLICY_REFUSAL_EXIT;
}
if let Some(SignalDeath(signal)) = error.downcast_ref::<SignalDeath>() {
return detcore_model::signal_exit_status(*signal);
}
if error.downcast_ref::<RunTimeoutMarker>().is_some() {
return 124;
}
if error.downcast_ref::<LogCapExceeded>().is_some() {
return hermit::HERMIT_LOG_CAP_EXIT;
}
match error.downcast_ref::<GuestProgramFault>() {
Some(fault) => fault.exit_code(),
None => HERMIT_INTERNAL_FAILURE_EXIT,
}
}
fn classify_failure(error: &Error) -> String {
if let Some(overshoot) = error.downcast_ref::<hermit::SkidOvershootError>() {
return format!(
"HERMIT_POLICY_REFUSAL class=policy-refusal cause=skid-overshoot count={}",
overshoot.count()
);
}
if error.downcast_ref::<PolicyRefusal>().is_some() {
return "HERMIT_POLICY_REFUSAL class=policy-refusal".to_string();
}
if let Some(SignalDeath(signal)) = error.downcast_ref::<SignalDeath>() {
return format!("HERMIT_SIGNAL_DEATH class=signal-death signal={}", signal);
}
if error.downcast_ref::<RunTimeoutMarker>().is_some() {
return "HERMIT_RUN_TIMEOUT class=run-timeout".to_string();
}
if error.downcast_ref::<LogCapExceeded>().is_some() {
return "HERMIT_LOG_CAP class=log-cap".to_string();
}
if let Some(ContainerChildExit(status)) = error.downcast_ref::<ContainerChildExit>() {
return format!("HERMIT_INTERNAL_FAILURE class=container-child-exit status={status:?}");
}
if let Some(fault) = error.downcast_ref::<GuestProgramFault>() {
return format!("HERMIT_INTERNAL_FAILURE class={}", fault.class());
}
if let Some(unavailable) = error.downcast_ref::<BackendUnavailable>() {
return format!(
"HERMIT_INTERNAL_FAILURE class=backend-unavailable backend={}",
unavailable.backend().as_str()
);
}
if error.downcast_ref::<ContainerChildPanic>().is_some() {
return "HERMIT_INTERNAL_FAILURE class=container-child-panic".to_string();
}
"HERMIT_INTERNAL_FAILURE class=cli-error".to_string()
}
fn display_error(error: Error) {
use std::io::Write;
if error.downcast_ref::<LogCapExceeded>().is_some() {
let mut report = classify_failure(&error);
report.push('\n');
for (index, cause) in error.chain().enumerate() {
report.push_str(&if index == 0 {
format!("{}: {}\n", "Error".red().bold(), cause)
} else {
format!(" {} {}\n", ">".dimmed().bold(), cause)
});
}
self::tracing::report_log_cap_without_waiting(&report);
return;
}
let mut out = detcore::util::RetryingStderr;
let _ = writeln!(out, "{}", classify_failure(&error));
let mut chain = error.chain();
if let Some(error) = chain.next() {
let _ = writeln!(out, "{}: {}", "Error".red().bold(), error);
}
for cause in chain {
let _ = writeln!(out, " {} {}", ">".dimmed().bold(), cause);
}
}
#[cfg(all(test, feature = "native-exec"))]
use detcore_model::liteinst_native_exec_runtime as runtime_packet;
#[cfg(all(test, feature = "native-exec"))]
fn qualify_config(_: &detcore::Config) -> std::io::Result<()> {
panic!("completion fixture must not qualify an image")
}
#[cfg(all(test, feature = "native-exec"))]
mod exec_initial {
pub(crate) unsafe fn restore_dispatch_sequence(_: u64) -> std::io::Result<()> {
panic!("completion fixture must not restore an image")
}
}
#[cfg(test)]
#[cfg(feature = "native-exec")]
#[path = "../../../../detcore-liteinst/src/exec_native/consumer.rs"]
mod native_exec_consumer;
#[cfg(test)]
#[cfg(feature = "native-exec")]
#[path = "../../../../detcore-liteinst/src/exec_native/provider.rs"]
mod native_exec_guest_provider;
#[cfg(all(test, feature = "native-exec"))]
mod native_exec_provider_connect_tests;
#[cfg(test)]
mod tests {
use clap::CommandFactory;
use clap::Parser;
use hermit::Backend;
use hermit::BackendUnavailable;
use hermit::Error;
use super::Args;
use super::Subcommand;
use super::args_from_matches_with_clock;
use super::classify_failure;
use super::failure_exit_code;
#[derive(Debug, PartialEq, Eq)]
struct EntryFdSnapshot {
device: libc::dev_t,
inode: libc::ino_t,
mode: libc::mode_t,
descriptor_flags: i32,
file_flags: i32,
offset: libc::off_t,
}
fn entry_fd_snapshot(fd: i32) -> Option<EntryFdSnapshot> {
let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();
unsafe {
if libc::fstat(fd, stat.as_mut_ptr()) < 0 {
return None;
}
let stat = stat.assume_init();
let descriptor_flags = libc::fcntl(fd, libc::F_GETFD);
let file_flags = libc::fcntl(fd, libc::F_GETFL);
if descriptor_flags < 0 || file_flags < 0 {
return None;
}
Some(EntryFdSnapshot {
device: stat.st_dev,
inode: stat.st_ino,
mode: stat.st_mode,
descriptor_flags,
file_flags,
offset: libc::lseek(fd, 0, libc::SEEK_CUR),
})
}
}
fn entry_fd_is_closed(fd: i32) -> bool {
(unsafe { libc::fcntl(fd, libc::F_GETFD) }) < 0
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::EBADF)
}
fn check_single_threaded_entry_child(check: impl FnOnce() -> i32) {
let pid = unsafe { libc::fork() };
assert!(
pid >= 0,
"fork entry check: {}",
std::io::Error::last_os_error()
);
if pid == 0 {
let status = check();
unsafe { libc::_exit(status) };
}
let mut status = 0;
loop {
let waited = unsafe { libc::waitpid(pid, &mut status, 0) };
if waited < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINTR) {
continue;
}
assert_eq!(waited, pid);
break;
}
assert_eq!(status, 0, "entry check child returned raw status {status}");
}
#[test]
fn entry_retires_unsolicited_fds_and_preserves_owned_streams() {
use std::io::Seek;
use std::os::fd::AsFd;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::unix::net::UnixStream;
let mut streams = [
tempfile::tempfile().unwrap(),
tempfile::tempfile().unwrap(),
tempfile::tempfile().unwrap(),
];
for (index, file) in streams.iter_mut().enumerate() {
file.seek(std::io::SeekFrom::Start(7 + index as u64))
.unwrap();
}
let (control, peer) = UnixStream::pair().unwrap();
let pidfd = unsafe { libc::syscall(libc::SYS_pidfd_open, libc::getpid(), 0u32) } as i32;
assert!(
pidfd >= 0,
"pidfd_open: {}",
std::io::Error::last_os_error()
);
let parent = unsafe { std::os::fd::OwnedFd::from_raw_fd(pidfd) };
let unsolicited = [tempfile::tempfile().unwrap(), tempfile::tempfile().unwrap()];
let parent_fds = [
streams[0].as_raw_fd(),
streams[1].as_raw_fd(),
streams[2].as_raw_fd(),
control.as_raw_fd(),
peer.as_raw_fd(),
parent.as_raw_fd(),
unsolicited[0].as_raw_fd(),
unsolicited[1].as_raw_fd(),
];
let parent_before = parent_fds.map(entry_fd_snapshot);
assert!(parent_before.iter().all(Option::is_some));
check_single_threaded_entry_child(|| {
for (fd, file) in streams.iter().enumerate() {
if unsafe { libc::dup2(file.as_raw_fd(), fd as i32) } < 0 {
return 1;
}
if unsafe {
libc::fcntl(
fd as i32,
libc::F_SETFD,
if fd == 1 { libc::FD_CLOEXEC } else { 0 },
)
} < 0
{
return 2;
}
}
unsafe { super::capture_startup_stdin() };
let saved = super::STARTUP_STDIN.load(std::sync::atomic::Ordering::Acquire);
if saved < 3 {
return 3;
}
let stdio_before = [0, 1, 2].map(entry_fd_snapshot);
let kept = [saved, control.as_raw_fd(), parent.as_raw_fd()];
let kept_before = kept.map(entry_fd_snapshot);
if kept_before.iter().any(Option::is_none) {
return 4;
}
if super::retire_inherited_descriptors(&[parent.as_fd(), control.as_fd()]).is_err() {
return 5;
}
if super::STARTUP_STDIN.load(std::sync::atomic::Ordering::Acquire) != saved
|| [0, 1, 2].map(entry_fd_snapshot) != stdio_before
|| kept.map(entry_fd_snapshot) != kept_before
{
return 6;
}
let removed = [
streams[0].as_raw_fd(),
streams[1].as_raw_fd(),
streams[2].as_raw_fd(),
peer.as_raw_fd(),
unsolicited[0].as_raw_fd(),
unsolicited[1].as_raw_fd(),
];
if removed.into_iter().any(|fd| !entry_fd_is_closed(fd)) {
return 7;
}
match super::startup_stdin() {
Ok(Some(file))
if file.as_raw_fd() == saved && entry_fd_snapshot(saved) == kept_before[0] =>
{
0
}
_ => 8,
}
});
assert_eq!(parent_fds.map(entry_fd_snapshot), parent_before);
}
#[test]
fn entry_leaves_captured_stdin_errors_for_the_original_consumer() {
use std::os::fd::AsRawFd;
let unsolicited = tempfile::tempfile().unwrap();
for closed in [true, false] {
check_single_threaded_entry_child(|| {
let changed = unsafe {
if libc::dup2(unsolicited.as_raw_fd(), 0) < 0 {
return 1;
}
if closed {
libc::close(0)
} else {
let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
if libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) < 0 {
return 1;
}
let mut limit = limit.assume_init();
limit.rlim_cur = 3;
libc::setrlimit(libc::RLIMIT_NOFILE, &limit)
}
};
if changed < 0 {
return 2;
}
unsafe { super::capture_startup_stdin() };
let saved = super::STARTUP_STDIN.load(std::sync::atomic::Ordering::Acquire);
let expected_errno = if closed { libc::EBADF } else { libc::EINVAL };
if saved != -expected_errno - 1 {
return 3;
}
if super::retire_inherited_descriptors(&[]).is_err()
|| super::STARTUP_STDIN.load(std::sync::atomic::Ordering::Acquire) != saved
|| !entry_fd_is_closed(unsolicited.as_raw_fd())
|| (closed && !entry_fd_is_closed(0))
{
return 4;
}
match super::startup_stdin() {
Ok(None) if closed => 0,
Err(error) if !closed && error.raw_os_error() == Some(expected_errno) => 0,
_ => 5,
}
});
}
assert!(entry_fd_snapshot(unsolicited.as_raw_fd()).is_some());
}
#[test]
fn entry_descriptor_failure_can_stamp_no_result_without_running_a_guest() {
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::os::unix::process::CommandExt;
use std::process::Command;
use std::process::Stdio;
use std::time::Duration;
use std::time::Instant;
const REPORT: &str = "HERMIT_TEST_ENTRY_DESCRIPTOR_REPORT";
const MODE: &str = "HERMIT_TEST_ENTRY_DESCRIPTOR_MODE";
if let Some(report) = std::env::var_os(REPORT) {
let error = super::retire_inherited_descriptors(&[]).unwrap_err();
assert_eq!(error.raw_os_error(), Some(libc::EPERM));
let argv = if std::env::var(MODE).unwrap() == "help" {
vec!["hermit".into(), "--help".into()]
} else {
vec![
"hermit".into(),
"run".into(),
"--verify".into(),
"--verify-json".into(),
report,
"--".into(),
"/bin/true".into(),
]
};
std::process::exit(super::refuse_entry_descriptor_failure(error, &argv));
}
let directory = tempfile::tempdir().unwrap();
let report = directory.path().join("verification.json");
for mode in ["verify", "help"] {
std::fs::write(&report, b"{\"verified\":true}").unwrap();
let mut pipe = [-1; 2];
assert_eq!(
unsafe { libc::pipe2(pipe.as_mut_ptr(), libc::O_CLOEXEC) },
0
);
let reader = unsafe { OwnedFd::from_raw_fd(pipe[0]) };
let writer = unsafe { OwnedFd::from_raw_fd(pipe[1]) };
let flags = unsafe { libc::fcntl(writer.as_raw_fd(), libc::F_GETFL) };
assert!(flags >= 0);
if mode == "verify" {
assert_eq!(
unsafe {
libc::fcntl(writer.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK)
},
0
);
let bytes = [0u8; 4096];
loop {
let result = unsafe {
libc::write(writer.as_raw_fd(), bytes.as_ptr().cast(), bytes.len())
};
if result < 0 {
assert_eq!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::EAGAIN)
);
break;
}
}
assert_eq!(
unsafe { libc::fcntl(writer.as_raw_fd(), libc::F_SETFL, flags) },
0
);
} else {
drop(reader);
}
let mut command = Command::new(std::env::current_exe().unwrap());
command
.args([
"--exact",
"tests::entry_descriptor_failure_can_stamp_no_result_without_running_a_guest",
"--nocapture",
"--test-threads=1",
])
.env(REPORT, &report)
.env(MODE, mode)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(writer.try_clone().unwrap()));
unsafe {
command.pre_exec(|| {
let mut filter = [
libc::sock_filter {
code: (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16,
jt: 0,
jf: 0,
k: 0,
},
libc::sock_filter {
code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16,
jt: 0,
jf: 1,
k: libc::SYS_close_range as u32,
},
libc::sock_filter {
code: (libc::BPF_RET | libc::BPF_K) as u16,
jt: 0,
jf: 0,
k: libc::SECCOMP_RET_ERRNO | libc::EPERM as u32,
},
libc::sock_filter {
code: (libc::BPF_RET | libc::BPF_K) as u16,
jt: 0,
jf: 0,
k: libc::SECCOMP_RET_ALLOW,
},
];
let program = libc::sock_fprog {
len: filter.len() as u16,
filter: filter.as_mut_ptr(),
};
if libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0
|| libc::prctl(libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER, &program)
< 0
{
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
let mut child = command.spawn().unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
let outcome = loop {
match child.try_wait() {
Ok(Some(status)) => break Ok(status),
Ok(None) if Instant::now() < deadline => {
std::thread::sleep(Duration::from_millis(10))
}
Ok(None) => {
break Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"entry refusal did not terminate",
));
}
Err(error) => break Err(error),
}
};
let status = outcome.unwrap_or_else(|error| {
let _ = child.kill();
let _ = child.wait();
panic!("entry refusal: {error}");
});
assert_eq!(status.code(), Some(hermit::HERMIT_INTERNAL_FAILURE_EXIT));
assert_eq!(
unsafe { libc::fcntl(writer.as_raw_fd(), libc::F_GETFL) },
flags
);
let actual: serde_json::Value =
serde_json::from_slice(&std::fs::read(&report).unwrap()).unwrap();
if mode == "verify" {
assert_eq!(actual["verdict"], "no_result");
assert_eq!(actual["verified"], false);
} else {
assert_eq!(actual, serde_json::json!({"verified": true}));
}
}
}
#[test]
fn clap_configuration_is_valid() {
Args::command().debug_assert();
}
fn command_without_epoch_env() -> clap::Command {
Args::command()
.mut_subcommand("run", |run| {
run.mut_arg("epoch", |arg| arg.env(None::<&str>))
})
.mut_subcommand("oci", |oci| {
oci.mut_subcommand("run", |run| {
run.mut_arg("epoch", |arg| arg.env(None::<&str>))
})
})
}
fn parse_at<const N: usize>(argv: [&str; N], now: std::time::SystemTime) -> Args {
let matches = command_without_epoch_env()
.try_get_matches_from(argv)
.unwrap();
args_from_matches_with_clock(&matches, || now).unwrap()
}
#[test]
fn omitted_run_epoch_is_captured_once_at_parse_boundary() {
let now = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_933_135_628);
let args = parse_at(["hermit", "run", "/bin/true"], now);
let Subcommand::Run(run) = args.command else {
panic!("expected run")
};
assert_eq!(
run.epoch_capture_for_test(),
("2031-04-05T06:07:08+00:00".to_owned(), true)
);
}
#[test]
fn explicit_run_epoch_is_preserved_instead_of_reading_host_time() {
let matches = command_without_epoch_env()
.try_get_matches_from([
"hermit",
"run",
"--epoch=2000-12-31T23:59:59.123456789Z",
"/bin/true",
])
.unwrap();
let args = args_from_matches_with_clock(&matches, || {
panic!("an explicit epoch must not read the host clock")
})
.unwrap();
let Subcommand::Run(run) = args.command else {
panic!("expected run")
};
let (epoch, captured) = run.epoch_capture_for_test();
assert_eq!(epoch, "2000-12-31T23:59:59.123456789+00:00");
assert!(!captured);
}
#[test]
fn nonvirtualized_run_epoch_does_not_read_the_host_clock() {
let matches = command_without_epoch_env()
.try_get_matches_from([
"hermit",
"run",
"--no-virtualize-time",
"--no-virtualize-metadata",
"/bin/true",
])
.unwrap();
let args = args_from_matches_with_clock(&matches, || {
panic!("a nonvirtualized run must not capture a virtual epoch")
})
.unwrap();
let Subcommand::Run(run) = args.command else {
panic!("expected run")
};
assert!(!run.epoch_capture_for_test().1);
}
#[test]
fn namespace_only_run_epoch_is_neither_captured_nor_reported() {
let matches = command_without_epoch_env()
.try_get_matches_from(["hermit", "run", "--namespace-only", "/bin/true"])
.unwrap();
let args = args_from_matches_with_clock(&matches, || {
panic!("namespace-only bypasses Detcore and must not capture host time")
})
.unwrap();
let Subcommand::Run(run) = args.command else {
panic!("expected run")
};
assert!(!run.epoch_capture_for_test().1);
assert!(!run.reports_virtual_epoch_for_test());
}
#[test]
fn strace_only_run_epoch_is_neither_captured_nor_reported() {
let matches = command_without_epoch_env()
.try_get_matches_from(["hermit", "run", "--strace-only", "/bin/true"])
.unwrap();
let args = args_from_matches_with_clock(&matches, || {
panic!("strace-only disables virtual time and must not sample the host clock")
})
.unwrap();
let Subcommand::Run(run) = args.command else {
panic!("expected run")
};
assert!(!run.epoch_capture_for_test().1);
assert!(!run.reports_virtual_epoch_for_test());
}
#[test]
fn omitted_oci_run_epoch_is_captured_once_with_host_provenance() {
let now = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_933_135_628);
let args = parse_at(
[
"hermit",
"oci",
"run",
"example.invalid/image:tag",
"--",
"/bin/true",
],
now,
);
let Subcommand::Oci(oci) = args.command else {
panic!("expected oci")
};
assert_eq!(
oci.run_epoch_capture_for_test(),
("2031-04-05T06:07:08+00:00".to_owned(), true, true)
);
}
#[test]
fn explicit_oci_run_epoch_preserves_explicit_provenance() {
let matches = command_without_epoch_env()
.try_get_matches_from([
"hermit",
"oci",
"run",
"example.invalid/image:tag",
"--epoch=2000-12-31T23:59:59Z",
"--",
"/bin/true",
])
.unwrap();
let args = args_from_matches_with_clock(&matches, || {
panic!("an explicit OCI epoch must not read the host clock")
})
.unwrap();
let Subcommand::Oci(oci) = args.command else {
panic!("expected oci")
};
assert_eq!(
oci.run_epoch_capture_for_test(),
("2000-12-31T23:59:59+00:00".to_owned(), false, true)
);
}
#[test]
fn invalid_run_epoch_is_rejected_by_the_cli() {
assert!(
command_without_epoch_env()
.try_get_matches_from(["hermit", "run", "--epoch=not-a-time", "/bin/true"])
.is_err()
);
}
#[test]
fn run_epoch_help_describes_capture_instead_of_the_fixture_default() {
let mut command = command_without_epoch_env();
let run = command.find_subcommand_mut("run").unwrap();
let help = run.render_long_help().to_string();
assert!(help.contains("host wall-clock sample"), "{help}");
assert!(!help.contains("[default: 2026-01-01T00:00:00Z]"), "{help}");
}
#[test]
fn top_level_help_states_what_the_defaults_actually_are() {
let mut command = command_without_epoch_env();
let help = command
.render_long_help()
.to_string()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
for stale in [
"networking is disallowed",
"bitwise identical",
"~/.hermit",
"content addressible",
"Record mode has no `--network` flag",
] {
assert!(!help.contains(stale), "stale claim {stale:?} in:\n{help}");
}
for claim in [
"functions of their controlled inputs",
"`hermit run` starts it at the host's current time",
"--epoch=2026-01-01T00:00:00Z",
"In run and record mode, by default (`--network=local`)",
"only a loopback interface",
"A recording stores its choice",
"`hermit record start --verify-with-gdbex` defaults to, and requires, `--network=host`",
"The DBT backend does not apply `--network` yet",
"`$XDG_CACHE_HOME/hermit`, which is `~/.cache/hermit`",
"`--data-dir` or `HERMIT_DATA_DIR`",
] {
assert!(help.contains(claim), "missing {claim:?} in:\n{help}");
}
let run = command.find_subcommand_mut("run").unwrap();
let network = run
.get_arguments()
.find(|arg| arg.get_id() == "network")
.expect("run --network");
assert_eq!(network.get_default_values(), ["local"]);
fn network_args(command: &clap::Command) -> Vec<String> {
let mut found: Vec<String> = command
.get_arguments()
.filter(|arg| arg.get_long() == Some("network"))
.map(|_| command.get_name().to_string())
.collect();
for sub in command.get_subcommands() {
found.extend(network_args(sub));
}
found
}
let record = command.find_subcommand("record").unwrap();
assert_eq!(network_args(record), ["record", "start"]);
assert_eq!(
network_args(command.find_subcommand("run").unwrap()),
["run"]
);
}
#[test]
fn run_epoch_environment_and_cli_precedence() {
const CHILD: &str = "HERMIT_EPOCH_PRECEDENCE_TEST_CHILD";
const ENV_EPOCH: &str = "2000-12-31T23:59:59.123456789Z";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"tests::run_epoch_environment_and_cli_precedence",
"--nocapture",
])
.env(CHILD, "1")
.env("HERMIT_EPOCH", ENV_EPOCH)
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
return;
}
assert_eq!(std::env::var("HERMIT_EPOCH").unwrap(), ENV_EPOCH);
for oci in [false, true] {
for explicit in [None, Some("2026-01-01T00:00:00Z")] {
let mut argv = vec!["hermit"];
if oci {
argv.extend(["oci", "run", "example.invalid/image:tag"]);
} else {
argv.push("run");
}
if let Some(epoch) = explicit {
argv.extend(["--epoch", epoch]);
}
argv.extend(["--", "/bin/true"]);
let matches = Args::command().try_get_matches_from(argv).unwrap();
let args = args_from_matches_with_clock(&matches, || {
panic!("CLI/environment epochs must not sample the host clock")
})
.unwrap();
let (epoch, captured) = match args.command {
Subcommand::Run(run) => run.epoch_capture_for_test(),
Subcommand::Oci(oci) => {
let (epoch, captured, reported) = oci.run_epoch_capture_for_test();
assert!(reported);
(epoch, captured)
}
_ => panic!("expected run"),
};
assert_eq!(
epoch,
if explicit.is_some() {
"2026-01-01T00:00:00+00:00"
} else {
"2000-12-31T23:59:59.123456789+00:00"
}
);
assert!(!captured);
}
}
}
#[test]
fn run_epoch_reproducer_retains_default_and_fractional_inputs_once() {
for epoch in ["2026-01-01T00:00:00Z", "2000-12-31T23:59:59.123456789Z"] {
let mut original = super::run::RunOpts::parse_from([
"run",
"--epoch",
epoch,
"--seed=71",
"/bin/true",
]);
original.validate_args().unwrap();
let rendered = original.to_string();
assert_eq!(rendered.matches("--epoch=").count(), 1, "{rendered}");
let mut argv = vec!["hermit".to_owned(), "run".to_owned()];
argv.extend(shell_words::split(&rendered).unwrap());
let matches = command_without_epoch_env()
.try_get_matches_from(argv)
.unwrap();
assert_eq!(
matches
.subcommand_matches("run")
.unwrap()
.value_source("epoch"),
Some(clap::parser::ValueSource::CommandLine)
);
let args = args_from_matches_with_clock(&matches, || {
panic!("a concrete reproducer must not capture a replacement epoch")
})
.unwrap();
let Subcommand::Run(reparsed) = args.command else {
panic!("expected run")
};
assert_eq!(
reparsed.epoch_capture_for_test().0,
original.epoch_capture_for_test().0
);
assert!(!reparsed.epoch_capture_for_test().1);
assert_eq!(reparsed.det_opts.det_config.seed, 71);
}
}
#[test]
fn backend_unavailability_is_classified_by_type_not_message() {
let typed = Error::new(BackendUnavailable::new(Backend::Dbt, "SDK absent"));
assert_eq!(
classify_failure(&typed),
"HERMIT_INTERNAL_FAILURE class=backend-unavailable backend=dbt"
);
let prose_only = Error::msg("backend `dbt` is unavailable: SDK absent");
assert_eq!(
classify_failure(&prose_only),
"HERMIT_INTERNAL_FAILURE class=cli-error",
"changing only prose must not manufacture the typed class"
);
}
#[test]
fn skid_overshoot_uses_the_policy_refusal_exit_and_marker() {
let error = Error::new(hermit::SkidOvershootError::new(2));
assert_eq!(
failure_exit_code(&error),
detcore_model::HERMIT_POLICY_REFUSAL_EXIT
);
assert_eq!(
classify_failure(&error),
"HERMIT_POLICY_REFUSAL class=policy-refusal cause=skid-overshoot count=2"
);
}
fn plant_previous_green(path: &std::path::Path) {
std::fs::write(
path,
"{\"verified\":true,\"bitwise_parity\":true,\"verdict\":\"matched\"}\n",
)
.unwrap();
let planted: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
assert_eq!(planted["verified"], serde_json::json!(true));
}
fn read_verdict(path: &std::path::Path) -> serde_json::Value {
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
fn assert_no_result(path: &std::path::Path, context: &str) {
let now = read_verdict(path);
assert_eq!(now["verdict"], serde_json::json!("no_result"), "{context}");
assert_eq!(now["verified"], serde_json::json!(false), "{context}");
assert_eq!(now["bitwise_parity"], serde_json::json!(false), "{context}");
}
#[test]
fn exec_stop_refusal_stamps_no_result_before_host_admission() {
let file = tempfile::NamedTempFile::new().unwrap();
plant_previous_green(file.path());
let mut args = Args::try_parse_from([
"hermit",
"--backend=in-guest-trap",
"run",
"--in-guest-exec-stop",
"--verify",
"--verify-json",
file.path().to_str().unwrap(),
"--",
"/nonexistent/hermit-exec-stop-guest",
])
.unwrap();
let host_called = std::cell::Cell::new(false);
let error = args
.command
.main_with_host_admission(&args.global, |_| {
host_called.set(true);
Err(Error::msg("host admission must not run"))
})
.unwrap_err();
assert!(
!host_called.get(),
"host probe preceded exec-stop admission"
);
assert_eq!(
failure_exit_code(&error),
detcore_model::HERMIT_POLICY_REFUSAL_EXIT
);
assert_eq!(
classify_failure(&error),
"HERMIT_POLICY_REFUSAL class=policy-refusal"
);
assert!(
error.to_string().contains("exec-stop-runtime-not-ready"),
"{error:#}"
);
assert_no_result(file.path(), "exec-stop prelaunch refusal");
}
#[test]
fn oci_exec_stop_refuses_before_host_or_image_access_and_replaces_stale_verdict() {
let file = tempfile::NamedTempFile::new().unwrap();
plant_previous_green(file.path());
let mut args = Args::try_parse_from([
"hermit",
"oci",
"run",
"--pull",
"unresolvable.invalid/must-not-fetch",
"--in-guest-exec-stop",
"--verify",
"--verify-json",
file.path().to_str().unwrap(),
"--",
"/nonexistent/guest",
])
.unwrap();
let error = args
.command
.main_with_host_admission(&args.global, |_| {
panic!("pending OCI launcher must not probe the host or start image access")
})
.unwrap_err();
assert!(
error.to_string().contains("exec-stop-runtime-not-ready"),
"{error:#}"
);
assert_no_result(file.path(), "OCI exec-stop prelaunch refusal");
let Subcommand::Oci(oci) = &mut args.command else {
unreachable!()
};
let error = oci.main(&args.global).unwrap_err();
assert!(
error.to_string().contains("exec-stop-runtime-not-ready"),
"{error:#}"
);
}
#[test]
fn exec_stop_pending_run_does_not_capture_a_host_epoch() {
let matches = command_without_epoch_env()
.try_get_matches_from([
"hermit",
"run",
"--in-guest-exec-stop",
"--",
"/nonexistent/hermit-exec-stop-guest",
])
.unwrap();
let args = args_from_matches_with_clock(&matches, || {
panic!("a pending exec-stop request must not sample the host clock")
})
.unwrap();
let Subcommand::Run(run) = args.command else {
unreachable!()
};
assert!(!run.epoch_capture_for_test().1);
assert!(
run.refuse_unready_exec_stop()
.unwrap_err()
.to_string()
.contains("exec-stop-runtime-not-ready")
);
}
#[test]
fn no_exec_stop_flag_preserves_host_admission_and_verdict_stamp() {
for prefix in [
vec!["hermit", "run"],
vec!["hermit", "oci", "run", "test-image"],
] {
let file = tempfile::NamedTempFile::new().unwrap();
plant_previous_green(file.path());
let mut argv = prefix;
argv.extend([
"--verify",
"--verify-json",
file.path().to_str().unwrap(),
"--",
"/nonexistent/hermit-exec-stop-guest",
]);
let mut args = Args::try_parse_from(argv).unwrap();
let host_called = std::cell::Cell::new(false);
let error = args
.command
.main_with_host_admission(&args.global, |_| {
host_called.set(true);
Err(Error::new(std::io::Error::from_raw_os_error(libc::EACCES)))
})
.unwrap_err();
assert!(host_called.get());
assert_eq!(
error
.downcast_ref::<std::io::Error>()
.and_then(std::io::Error::raw_os_error),
Some(libc::EACCES)
);
assert_no_result(file.path(), "ordinary host admission failure");
}
}
fn assert_top_level_exit_leaves_no_result(argv: &[&str], context: &str) {
let file = tempfile::NamedTempFile::new().unwrap();
let path = file.path().to_path_buf();
plant_previous_green(&path);
let json = format!("--verify-json={}", path.display());
let mut full: Vec<&str> = argv.to_vec();
full.push(&json);
full.push("--");
full.push("/nonexistent/hermit-test-guest");
let mut args = Args::try_parse_from(full).expect("argv should parse");
let result = args.command.main(&args.global);
assert!(result.is_err(), "{context}: expected a non-verdict exit");
assert_no_result(&path, context);
}
#[test]
fn main_preflight_exit_leaves_an_invocation_bound_no_result() {
assert_top_level_exit_leaves_no_result(
&["hermit", "--backend", "kvm", "record", "--verify"],
"backend-scope preflight",
);
}
#[test]
fn dbt_verification_joins_the_generic_verify_dispatch() {
let source = include_str!("run.rs");
let sole_offset = |needle: &str| -> usize {
let hits: Vec<_> = source
.match_indices(needle)
.map(|(offset, _)| offset)
.collect();
assert_eq!(
hits.len(),
1,
"expected one production occurrence of {needle:?}"
);
hits[0]
};
let ordinary = sole_offset("if backend == Backend::Dbt && !self.verify");
let saved = sole_offset("return invocation.verify_run(");
let physical = sole_offset("return invocation.run(");
let verify = sole_offset("self.verify(global, dbt_verification_stdin)");
assert!(ordinary < saved && saved < physical && physical < verify);
let common = source
.split_once(" fn verify(")
.unwrap()
.1
.split_once(" /// The `--bind`s")
.unwrap()
.0;
assert!(common.contains("self.dbt_invocation()?.verification(_dbt_stdin)"));
assert_eq!(common.matches("options.run_verify(").count(), 1);
assert_eq!(common.matches(" execute(").count(), 2);
assert_eq!(common.matches("&run1_options,").count(), 1);
assert_eq!(common.matches("&run2_options,").count(), 1);
assert_eq!(
common
.matches("let outcome = conclude_verification(")
.count(),
1
);
let conclusion = source
.split_once("pub(super) fn conclude_verification(")
.unwrap()
.1
.split_once("\n#[cfg(test)]\nmod tests {")
.expect("run.rs has a test module")
.0;
assert_eq!(
conclusion
.matches("let mut outcome = compare_two_runs(")
.count(),
1
);
let physical = include_str!("backends.rs")
.split_once("impl DbtVerification {")
.unwrap()
.1
.split_once("/// Stats are consumed")
.unwrap()
.0;
assert!(!physical.contains("compare_two_runs("));
assert!(source.contains("self.verify_run(directory, global)"));
}
#[test]
fn dbt_arm_has_a_channel_to_publish_a_verdict() {
let source = include_str!("run.rs");
let common = source
.split_once(" fn verify(")
.unwrap()
.1
.split_once(" /// The `--bind`s")
.unwrap()
.0;
for run in ["Run1", "Run2"] {
let label = format!("VerificationRun::{run}");
assert!(common.contains(&label));
}
assert!(common.contains("publish_run_failure(self.verify_json.as_deref()"));
let conclusion = source
.split_once("pub(super) fn conclude_verification(")
.unwrap()
.1;
assert!(conclusion.contains("write_verification_json(path, &outcome)"));
let physical = source
.split_once(" fn run_verify(")
.unwrap()
.1
.split_once(" fn merge_from_env_settings")
.unwrap()
.0;
assert!(physical.contains("return dbt.run("));
assert!(physical.contains("self.verify_json.as_deref()"));
}
#[test]
fn dbt_verdict_names_a_canonical_record_envelope() {
let common = include_str!("run.rs");
let options = common
.split_once(" fn verification_comparison_options(")
.unwrap()
.1
.split_once(" /// The `--verify-json`")
.unwrap()
.0;
let block = options;
let source = include_str!("backends.rs");
let record_envelope_literal = || {
block
.lines()
.find_map(|line| line.trim().strip_prefix("record_envelope:"))
.map(|value| value.trim().trim_end_matches(',').to_string())
.expect(
"the DBT comparison must state its record envelope; an unnamed selection \
is exactly the undisclosed filtering the envelope exists to prevent",
)
};
assert_eq!(
record_envelope_literal(),
"RecordEnvelope::all_records_v1()",
"the DBT adapter compares every authenticated evidence record, initialization \
records included at their stream positions, and also compares the initialization \
count as a typed dimension. Changing this envelope changes which records are \
compared, so update the adapter and its evidence together, not just this literal"
);
let materialize = source
.find("fn materialize_dbt_comparison_log")
.expect("DBT comparison log materialization");
let body = &source[materialize..];
let body = &body[..body.find("\n}\n").expect("materialization body end")];
assert!(
body.contains("detcore::logdiff::write_canonical_info(path, &mut std::io::sink())"),
"the DBT comparison log must be materialized unfiltered; filtering here would \
contradict the envelope the verdict publishes"
);
assert!(
!body.contains("write_canonical_info_with_filter"),
"filtering at the DBT boundary would apply an undisclosed second policy"
);
assert!(
crate::record_envelope::RecordEnvelope::all_records_v1()
.policy()
.is_canonical(),
"all_records_v1 must remain canonical or DBT verdicts silently lose \
bitwise-parity eligibility"
);
assert_eq!(
crate::record_envelope::RecordEnvelope::all_records_v1()
.policy()
.as_str(),
"all_records_v1"
);
}
#[test]
fn dbt_backend_divergence_overrides_a_log_match_for_retention() {
let source = include_str!("backends.rs");
let comparison = source
.split_once("impl DbtVerificationComparison {")
.unwrap()
.1
.split_once("/// Where DynamoRIO")
.unwrap()
.0;
let normalized = comparison.split_whitespace().collect::<Vec<_>>().join(" ");
assert!(normalized.contains(
"let mismatch = !self.branches.matched() || self.summary.requires_log_retention();"
));
assert_eq!(
normalized.matches("options.keep_logs |= mismatch;").count(),
1
);
assert_eq!(
normalized
.matches("options.match_overridden |= mismatch;")
.count(),
1
);
assert!(normalized.contains("self.summary.apply(outcome)"));
assert!(normalized.contains("record_dbt_branch_clock_comparison(outcome, self.branches)"));
let common = include_str!("run.rs")
.split_once("pub(super) fn conclude_verification(")
.unwrap()
.1;
assert!(
common
.find("comparison.configure(&mut comparison_options)")
.unwrap()
< common.find("let mut outcome = compare_two_runs(").unwrap()
);
assert!(
common.find("comparison.apply(&mut outcome)").unwrap()
< common
.find("write_verification_json(path, &outcome)")
.unwrap()
);
}
#[test]
fn namespace_only_cannot_carry_a_verdict_artifact() {
let parsed = Args::try_parse_from([
"hermit",
"run",
"--verify",
"--namespace-only",
"--",
"/bin/true",
]);
assert!(
parsed.is_err(),
"--verify with --namespace-only must remain a parse-time conflict; if this now \
parses, --namespace-only bypasses verify() and needs the pending stamp too"
);
}
#[test]
fn run_preflight_exit_leaves_an_invocation_bound_no_result() {
assert_top_level_exit_leaves_no_result(
&[
"hermit",
"--log",
"warn",
"--backend=ptrace",
"run",
"--verify",
],
"RunOpts::main log-level preflight",
);
}
#[test]
fn record_start_prevalidation_exit_leaves_an_invocation_bound_no_result() {
assert_top_level_exit_leaves_no_result(
&["hermit", "--log", "warn", "record", "start", "--verify"],
"record start log-level pre-validation",
);
}
#[test]
fn subcommands_without_verify_json_have_no_verdict_path() {
for argv in [
vec!["hermit", "run", "--", "/bin/true"],
vec!["hermit", "record", "start", "--", "/bin/true"],
vec!["hermit", "run", "--verify", "--", "/bin/true"],
] {
let args = Args::try_parse_from(argv.clone()).expect("argv should parse");
assert!(
args.command.verification_json_path().is_none(),
"{argv:?} should carry no verification-json path"
);
}
}
#[test]
fn every_verdict_producing_spelling_reports_its_verdict_path() {
for argv in [
vec![
"hermit",
"oci",
"run",
"test-image",
"--verify",
"--verify-json=/tmp/v.json",
"--",
"/bin/true",
],
vec![
"hermit",
"run",
"--verify",
"--verify-json=/tmp/v.json",
"--",
"/bin/true",
],
vec![
"hermit",
"record",
"--verify",
"--verify-json=/tmp/v.json",
"--",
"/bin/true",
],
vec![
"hermit",
"record",
"start",
"--verify",
"--verify-json=/tmp/v.json",
"--",
"/bin/true",
],
] {
let args = Args::try_parse_from(argv.clone()).expect("argv should parse");
assert_eq!(
args.command.verification_json_path(),
Some(std::path::Path::new("/tmp/v.json")),
"{argv:?} must report its verdict path to the stamp"
);
}
}
#[test]
fn replay_accepts_an_optional_id_and_options() {
let args = Args::try_parse_from([
"hermit",
"replay",
"--autopilot",
"--data-dir",
"/tmp/recordings",
"0123456789abcdef0123456789abcdef",
])
.unwrap();
assert!(matches!(args.command, Subcommand::Replay(_)));
}
#[test]
fn replay_accepts_serve_only_for_an_external_debugger() {
let args =
Args::try_parse_from(["hermit", "replay", "--serve-only", "--gdbserver-port=2345"])
.unwrap();
assert!(matches!(args.command, Subcommand::Replay(_)));
}
#[test]
fn replay_serve_only_rejects_gdb_commands() {
let error =
Args::try_parse_from(["hermit", "replay", "--serve-only", "--gdbex=break main"])
.unwrap_err();
assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
}
#[test]
fn bisect_accepts_schedule_endpoints_and_run_args() {
let args = Args::try_parse_from([
"hermit",
"bisect",
"--good",
"good.json",
"--bad",
"bad.json",
"--",
"--max-timeslice=disabled",
"/bin/true",
])
.unwrap();
assert!(matches!(args.command, Subcommand::Bisect(_)));
}
#[test]
fn backend_parses_in_global_position() {
use hermit::Backend;
let args = Args::try_parse_from(["hermit", "--backend", "kvm", "run", "prog"])
.expect("global-position --backend should parse");
assert_eq!(args.global.backend, Some(Backend::Kvm));
assert!(matches!(args.command, Subcommand::Run(_)));
}
#[test]
fn analyze_and_bisect_scope_is_limited_to_backends_whose_trials_run() {
for (backend, in_scope) in [
("ptrace", true),
("kvm", true),
("dbt", false),
("liteinst", false),
("sabre", false),
("e9patch", false),
] {
for argv in [
vec!["hermit", "--backend", backend, "analyze", "--", "/bin/true"],
vec![
"hermit",
"--backend",
backend,
"bisect",
"--good=g.json",
"--bad=b.json",
"--",
"/bin/true",
],
] {
let args = Args::try_parse_from(&argv)
.unwrap_or_else(|error| panic!("{argv:?} should parse: {error}"));
let scope = args.command.validate_backend_scope(args.global.backend);
if in_scope {
scope.unwrap_or_else(|error| panic!("{argv:?} must be in scope: {error:#}"));
} else {
let error =
scope.expect_err("a backend whose trials cannot run must be refused");
assert!(
error
.to_string()
.contains(&format!("hermit --backend {backend} run")),
"{argv:?}: refusal does not name the working path: {error:#}"
);
}
}
if backend != "ptrace" {
let args = Args::try_parse_from(["hermit", "--backend", backend, "record", "list"])
.unwrap();
assert!(
args.command
.validate_backend_scope(args.global.backend)
.is_err(),
"--backend {backend} record list must stay out of scope"
);
}
}
}
fn os_args(args: &[&str]) -> Vec<std::ffi::OsString> {
args.iter().map(std::ffi::OsString::from).collect()
}
#[test]
fn subcommand_level_backend_is_a_usage_error_naming_the_global_form() {
use clap::error::ErrorKind;
for (argv, corrected) in [
(
&["hermit", "run", "--backend=ptrace", "--", "/bin/true"][..],
"hermit --backend=ptrace run -- /bin/true",
),
(
&[
"hermit",
"record",
"start",
"--backend",
"e9patch",
"--",
"a b",
][..],
"hermit --backend=e9patch record start -- 'a b'",
),
] {
let argv = os_args(argv);
let error = Args::command()
.try_get_matches_from(&argv)
.expect_err("a subcommand-level --backend must not parse");
let error = super::redirect_misplaced_backend(error, &argv);
assert_eq!(error.kind(), ErrorKind::UnknownArgument);
assert_eq!(error.exit_code(), 2);
let rendered = error.render().to_string();
assert!(
rendered.contains(&format!("must come before the subcommand: `{corrected}`")),
"{rendered}"
);
assert!(
rendered.contains("Usage: hermit [OPTIONS] <COMMAND>"),
"{rendered}"
);
}
let argv = os_args(&["hermit", "run", "--backend-engagement-jsn=x", "prog"]);
let error = Args::command().try_get_matches_from(&argv).unwrap_err();
let untouched = error.render().to_string();
let error = super::redirect_misplaced_backend(error, &argv);
assert_eq!(error.render().to_string(), untouched);
assert!(
untouched.contains("--backend-engagement-json"),
"{untouched}"
);
}
#[test]
fn misplaced_backend_is_only_moved_when_unambiguous() {
use super::globally_placed_backend;
assert_eq!(
globally_placed_backend(&os_args(&["h", "--log", "info", "run", "--backend", "kvm"]))
.as_deref(),
Some("h --backend=kvm --log info run")
);
assert_eq!(
globally_placed_backend(&os_args(&[
"h",
"run",
"--backend=dbt",
"--",
"prog",
"--backend",
]))
.as_deref(),
Some("h --backend=dbt run -- prog --backend")
);
for argv in [
&["h", "--backend=kvm", "run", "--backend=dbt", "--", "p"][..],
&["h", "run", "--backend"][..],
&["h", "run", "--backend", "--", "p"][..],
&["h", "run", "--backend", "--strict", "--", "p"][..],
&["h", "run", "--backend=", "--", "p"][..],
&["h", "run", "--backend=-x", "--", "p"][..],
] {
assert_eq!(globally_placed_backend(&os_args(argv)), None, "{argv:?}");
}
}
#[test]
fn global_backend_with_namespace_only_is_a_usage_error() {
use clap::error::ErrorKind;
for argv in [
&[
"hermit",
"--backend=ptrace",
"run",
"--namespace-only",
"prog",
][..],
&[
"hermit",
"--backend=kvm",
"oci",
"run",
"--namespace-only",
"img",
"p",
][..],
] {
let matches = Args::command().try_get_matches_from(argv).unwrap();
let error = args_from_matches_with_clock(&matches, || {
panic!("a refused command must not capture host time")
})
.expect_err("--backend with --namespace-only must be refused");
assert_eq!(error.kind(), ErrorKind::ArgumentConflict, "{argv:?}");
assert_eq!(error.exit_code(), 2);
let rendered = error.render().to_string();
assert!(rendered.contains("--namespace-only"), "{rendered}");
assert!(rendered.contains("Drop `--backend`"), "{rendered}");
}
let matches = Args::command()
.try_get_matches_from(["hermit", "run", "--namespace-only", "prog"])
.unwrap();
assert!(args_from_matches_with_clock(&matches, || panic!("no clock")).is_ok());
}
#[test]
fn e9patch_is_allowed_for_recording_but_rejected_for_management_and_replay() {
use hermit::Backend;
for command in [
vec![
"hermit",
"--backend",
"e9patch",
"record",
"start",
"--",
"/bin/true",
],
vec![
"hermit",
"--backend",
"e9patch",
"record",
"--",
"/bin/true",
],
] {
let args = Args::try_parse_from(command).unwrap();
args.command
.validate_backend_scope(Some(Backend::E9patch))
.unwrap();
}
for command in [
vec!["hermit", "--backend", "e9patch", "record", "list"],
vec![
"hermit",
"--backend",
"e9patch",
"replay",
"0123456789abcdef0123456789abcdef",
],
] {
let args = Args::try_parse_from(command).unwrap();
let error = args
.command
.validate_backend_scope(Some(Backend::E9patch))
.unwrap_err();
assert!(error.to_string().contains("only through"));
}
}
#[test]
fn liteinst_is_rejected_outside_run() {
use hermit::Backend;
let args = Args::try_parse_from([
"hermit",
"--backend",
"liteinst",
"record",
"list",
"--json",
])
.unwrap();
let error = args
.command
.validate_backend_scope(Some(Backend::Liteinst))
.unwrap_err();
assert!(error.to_string().contains("only through"));
}
#[test]
fn in_guest_trap_is_rejected_outside_run() {
use hermit::Backend;
let args = Args::try_parse_from([
"hermit",
"--backend",
"in-guest-trap",
"record",
"list",
"--json",
])
.unwrap();
let error = args
.command
.validate_backend_scope(Some(Backend::InGuestTrap))
.unwrap_err();
assert!(
error
.to_string()
.contains("only through `hermit --backend in-guest-trap run`"),
"{error}"
);
}
#[test]
fn kvm_is_rejected_outside_run_instead_of_silently_recording_with_ptrace() {
use hermit::Backend;
let args = Args::try_parse_from([
"hermit",
"--backend",
"kvm",
"record",
"start",
"--",
"/bin/true",
])
.unwrap();
let error = args
.command
.validate_backend_scope(Some(Backend::Kvm))
.unwrap_err();
assert!(error.to_string().contains("require the ptrace runtime"));
}
#[test]
fn dbt_is_rejected_outside_run_instead_of_silently_recording_with_ptrace() {
use hermit::Backend;
let run =
Args::try_parse_from(["hermit", "--backend", "dbt", "run", "--", "/bin/true"]).unwrap();
run.command
.validate_backend_scope(Some(Backend::Dbt))
.expect("DBT run is the supported DBT execution path");
let record = Args::try_parse_from([
"hermit",
"--backend",
"dbt",
"record",
"start",
"--",
"/bin/true",
])
.unwrap();
let error = record
.command
.validate_backend_scope(Some(Backend::Dbt))
.expect_err("DBT record must not silently execute through ptrace");
assert!(error.to_string().contains("use the ptrace runtime"));
}
#[test]
fn record_accepts_strict_direct_and_start_forms() {
for args in [
vec!["hermit", "record", "--strict", "--", "/bin/echo", "hello"],
vec![
"hermit",
"record",
"start",
"--strict",
"--",
"/bin/echo",
"hello",
],
] {
let parsed = Args::try_parse_from(args).expect("record --strict should parse");
assert!(matches!(parsed.command, Subcommand::Record(_)));
}
}
#[test]
fn sabre_scope_admits_exactly_run_and_strace() {
use hermit::Backend;
for sub in ["run", "strace"] {
let args = Args::try_parse_from([
"hermit",
"--backend",
"sabre",
sub,
"--",
"/bin/echo",
"hi",
])
.unwrap_or_else(|e| panic!("`--backend sabre {sub}` should parse: {e}"));
assert_eq!(args.global.backend, Some(Backend::Sabre));
args.command
.validate_backend_scope(args.global.backend)
.unwrap_or_else(|e| panic!("`--backend sabre {sub}` must be in scope: {e}"));
}
let args = Args::try_parse_from([
"hermit",
"--backend",
"sabre",
"log-diff",
"/dev/null",
"/dev/null",
])
.expect("log-diff should parse");
let err = args
.command
.validate_backend_scope(args.global.backend)
.expect_err("`--backend sabre log-diff` must be rejected");
let text = err.to_string();
assert!(text.contains("sabre run"), "message must name run: {text}");
assert!(
text.contains("sabre strace"),
"message must name strace: {text}"
);
}
#[test]
fn sabre_strace_command_parses_in_requested_form() {
use hermit::Backend;
let args = Args::try_parse_from([
"hermit",
"--backend",
"sabre",
"strace",
"--",
"/bin/echo",
"hello",
])
.expect("requested SaBRe strace form should parse");
assert_eq!(args.global.backend, Some(Backend::Sabre));
assert!(matches!(args.command, Subcommand::Strace(_)));
}
#[test]
fn sabre_strace_rejects_run_options_it_does_not_honor() {
for option in [
"--namespace-only",
"--verify",
"--strict",
"--env=SHOULD_NOT_BE_IGNORED=1",
"--workdir=/tmp",
] {
let result = Args::try_parse_from([
"hermit",
"--backend",
"sabre",
"strace",
option,
"--",
"/bin/true",
]);
assert!(
result.is_err(),
"SaBRe strace unexpectedly accepted unsupported option {option}"
);
}
}
#[test]
fn record_accepts_a_positive_timeout() {
Args::try_parse_from([
"hermit",
"record",
"start",
"--record-timeout=1",
"--",
"/bin/true",
])
.unwrap();
}
#[test]
fn record_rejects_a_zero_timeout() {
assert!(
Args::try_parse_from([
"hermit",
"record",
"start",
"--record-timeout=0",
"--",
"/bin/true",
])
.is_err()
);
}
#[test]
fn instruction_map_accepts_binary_and_cache_directory() {
let args = Args::try_parse_from([
"hermit",
"instruction-map",
"--cache-dir",
"/tmp/instruction-maps",
"/bin/ls",
])
.unwrap();
assert!(matches!(args.command, Subcommand::InstructionMap(_)));
}
}