use std::collections::BTreeSet;
use std::ffi::OsString;
use std::fmt;
use std::num::NonZeroU32;
use std::num::NonZeroU64;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::SystemTime;
use chrono::DateTime;
use chrono::Utc;
use clap::Parser;
use reverie::BackendCapabilities;
use serde::Deserialize;
use serde::Serialize;
use crate::happens_before::HappensBeforeProgram;
use crate::network_trace::NetworkTraceConfig;
use crate::pid::DetTid;
use crate::schedule::SigWrapper;
use crate::time::NANOS_PER_RCB;
use crate::time::NANOS_PER_SCHED;
use crate::time::RcbTimeMultiplier;
const fn default_backend_capabilities() -> BackendCapabilities {
DEFAULT_BACKEND_CAPABILITIES
}
pub const DEFAULT_BACKEND_CAPABILITIES: BackendCapabilities = {
let mut backend = BackendCapabilities::PTRACE;
set_kernel_signal_facts(&mut backend, false);
backend.delivers_preemption_timer_events = false;
backend.runs_guest_code_between_injections = false;
backend.reports_sigreturns = false;
backend.hardware_watchpoints = 0;
backend.rcb_clock_contract = None;
backend
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RcbClockClaim {
#[default]
Unset,
Known(reverie::pmu_config::ClockKey),
BackendLocal(&'static str),
}
pub const fn set_kernel_signal_facts(backend: &mut BackendCapabilities, on: bool) {
backend.supports_blocked_wait_signal_interruption = on;
backend.kernel_signal_state_is_guests = on;
backend.kernel_signal_targets_are_predictable = on;
backend.host_task_reads_reach_guest_threads = on;
backend.host_timed_signals_are_physical = on;
}
#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
pub struct MountInfoRootRewrite {
pub raw_mount_id: u64,
pub deterministic_root: Vec<u8>,
#[serde(default)]
pub raw_root_prefix: Option<Vec<u8>>,
#[serde(default)]
pub deterministic_root_prefix: Option<Vec<u8>>,
#[serde(default)]
pub raw_mountpoint_prefix: Option<Vec<u8>>,
#[serde(default)]
pub deterministic_mountpoint_prefix: Option<Vec<u8>>,
}
#[derive(
Clone,
Copy,
Debug,
Default,
PartialEq,
Eq,
Hash,
Serialize,
Deserialize
)]
pub enum InheritedSeccomp {
#[default]
Unknown,
Disabled,
Strict,
Filter(Option<u32>),
}
impl InheritedSeccomp {
pub fn measure() -> Self {
std::fs::read_to_string("/proc/thread-self/status")
.map_or(Self::Unknown, |status| Self::parse(&status))
}
pub fn parse(status: &str) -> Self {
let field = |name: &str| {
status
.lines()
.find_map(|line| line.strip_prefix(name)?.strip_prefix(':'))
.map(str::trim)
};
match field("Seccomp") {
Some("0") => Self::Disabled,
Some("1") => Self::Strict,
Some("2") => Self::Filter(field("Seccomp_filters").and_then(|n| n.parse().ok())),
_ => Self::Unknown,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LaunchImage {
pub exe: Option<PathBuf>,
pub launcher: Option<PathBuf>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct MountNamespaceIdentity {
pub id: Option<u64>,
pub device: u64,
pub inode: u64,
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Serialize,
Deserialize,
clap::ValueEnum
)]
pub enum DetlogAnon {
Mappings,
Pages,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PropertySnapshot {
pub guest_dir: PathBuf,
pub copy_dir: PathBuf,
#[serde(default)]
pub live_files: Vec<PropertyFile>,
#[serde(default)]
pub uncopied_files: Vec<PropertyFile>,
#[serde(default)]
pub consistent_cut: bool,
}
impl PropertySnapshot {
pub fn live_file(&self, dev: u64, ino: u64) -> Option<&PropertyFile> {
self.live_files
.iter()
.find(|file| (file.dev, file.ino) == (dev, ino))
}
pub fn known_live_file(&self, dev: u64, ino: u64) -> Option<&PropertyFile> {
self.live_file(dev, ino).or_else(|| {
self.uncopied_files
.iter()
.find(|file| (file.dev, file.ino) == (dev, ino))
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PropertyFile {
pub dev: u64,
pub ino: u64,
pub name: String,
}
#[derive(Debug, Serialize, Deserialize, Clone, Parser)]
pub struct Config {
#[clap(long = "no-virtualize-time", action = clap::ArgAction::SetFalse)]
pub virtualize_time: bool,
#[clap(long = "no-virtualize-cpuid", action = clap::ArgAction::SetFalse)]
pub virtualize_cpuid: bool,
#[clap(long, value_enum, default_value = "auto", env = "HERMIT_CPU_PROFILE", long_help = crate::cpu_profile::CPU_PROFILE_LONG_HELP)]
#[serde(default)]
pub cpu_profile: crate::cpu_profile::CpuProfile,
#[clap(skip)]
#[serde(default)]
pub rewrite_exclusives_in_memory: bool,
#[clap(skip)]
#[serde(default)]
pub count_store_exclusives: bool,
#[clap(skip)]
#[serde(default)]
pub rewrite_exclusives_overlay: Vec<PathBuf>,
#[clap(skip)]
#[serde(default)]
pub rewrite_exclusives_overlay_requested: bool,
#[clap(skip)]
#[serde(default)]
pub cpu_profile_host: Option<crate::cpu_profile::HostXstate>,
#[clap(skip)]
#[serde(default)]
pub cpu_profile_source: Option<usize>,
#[serde(default = "default_backend_capabilities")]
#[clap(skip = DEFAULT_BACKEND_CAPABILITIES)]
pub backend: BackendCapabilities,
#[serde(skip)]
#[clap(skip)]
pub rcb_clock_claim: RcbClockClaim,
#[serde(default)]
#[clap(skip)]
pub guest_may_inherit_a_terminal: bool,
#[serde(default)]
#[clap(skip)]
pub in_guest_detlog_forward_policy: Option<String>,
#[serde(default)]
#[clap(skip)]
pub in_guest_site_patching_off: bool,
#[serde(default)]
#[clap(skip)]
pub in_guest_reserved_signals: u64,
#[serde(default)]
#[clap(skip)]
pub in_guest_refuses_host_timed_producers: bool,
#[serde(default)]
#[clap(skip)]
pub launch_image: Option<LaunchImage>,
#[serde(skip)]
#[clap(skip)]
pub launch_namespace_mounts: crate::host_input::LaunchNamespaceMounts,
#[serde(default)]
#[clap(skip)]
pub rewrite_exclusives_unmarked: Vec<std::path::PathBuf>,
#[serde(default)]
#[clap(skip)]
pub inherited_seccomp: InheritedSeccomp,
#[clap(
long,
env = "HERMIT_EPOCH",
value_name = "YYYY-MM-DDThh:mm:ssZ",
default_value = DEFAULT_EPOCH_STR,
hide_default_value = true
)]
pub epoch: DateTime<Utc>,
#[clap(
long = "seed",
env = "HERMIT_PRNG",
default_value = "0",
value_name = "uint64"
)]
pub seed: u64,
#[clap(long, value_name = "uint64")]
pub rng_seed: Option<u64>,
#[clap(long, value_name = "uint64")]
pub fuzz_seed: Option<u64>,
#[clap(long, value_name = "float")]
pub clock_multiplier: Option<f64>,
#[clap(long = "no-virtualize-metadata", action = clap::ArgAction::SetFalse)]
pub virtualize_metadata: bool,
#[serde(default)]
#[clap(skip)]
pub mountinfo_root_rewrites: Vec<MountInfoRootRewrite>,
#[serde(default)]
#[clap(skip)]
pub mountinfo_device_rewrites: Vec<(u64, u64)>,
#[serde(default)]
#[clap(skip)]
pub mountinfo_mount_ids: Vec<u64>,
#[serde(default)]
#[clap(skip)]
pub mountinfo_mount_ids_captured: bool,
#[serde(default)]
#[clap(skip)]
pub mountinfo_mount_namespace: Option<MountNamespaceIdentity>,
#[serde(default)]
#[clap(skip)]
pub mount_id_assignment_order: Vec<u64>,
#[serde(default)]
#[clap(skip)]
pub container_mount_table: Option<crate::container_mounts::ContainerMountTable>,
#[serde(default)]
#[clap(skip)]
pub directory_placeholder: Option<PathBuf>,
#[serde(default)]
#[clap(skip)]
pub container_procfs: bool,
#[clap(long)]
pub sequentialize_threads: bool,
#[serde(default)]
#[clap(long, default_value = "child", value_name = "child|parent|random")]
pub runs_post_fork: RunsPostFork,
#[serde(default)]
#[clap(long)]
pub passthru_opt: bool,
#[serde(default)]
#[clap(long)]
pub untrap_passthrough_syscalls: bool,
#[clap(long)]
pub imprecise_timers: bool,
#[serde(default)]
#[clap(long)]
pub eager_lone_preemptions: bool,
#[serde(default = "signal_state_copy_default")]
#[clap(long = "no-signal-state-copy", action = clap::ArgAction::SetFalse)]
pub signal_state_copy: bool,
#[serde(default)]
#[clap(skip)]
pub signal_delivery_check_fatal: bool,
#[serde(default)]
#[clap(skip)]
pub strict_binder: bool,
#[clap(long, long_help = chaos_long_help())]
pub chaos: bool,
#[serde(default)]
#[clap(
long,
value_name = "MIN..MAX",
requires = "chaos",
conflicts_with = "target_timeslice"
)]
pub chaos_timeslice_range: Option<TimesliceRange>,
#[serde(default)]
#[clap(
long,
value_enum,
default_value_t,
requires = "chaos",
requires_if("slice", "chaos_timeslice_range"),
conflicts_with = "target_timeslice",
long_help = chaos_timeslice_draw_long_help()
)]
pub chaos_timeslice_draw: ChaosTimesliceDraw,
#[serde(default)]
#[clap(skip)]
pub chaos_timeslice: Option<NonZeroU64>,
#[clap(long)]
pub fuzz_futexes: bool,
#[clap(long)]
pub chaos_target_races: bool,
#[clap(long)]
pub chaos_per_thread_slowdown: bool,
#[clap(long, default_value = "10.0", value_name = "double")]
pub chaos_slowdown_max_factor: f64,
#[clap(long, default_value = "0", value_name = "nanos")]
pub chaos_epoch_length_ns: u64,
#[serde(default)]
#[clap(long, default_value = "0", value_name = "instructions")]
pub chaos_instruction_offset: u64,
#[clap(long)]
pub record_preemptions: bool,
#[serde(default)]
#[clap(long)]
pub strict_schedule_boundaries: bool,
#[clap(long, value_name = "filepath")]
pub record_preemptions_to: Option<PathBuf>,
#[clap(long, value_name = "filepath", conflicts_with = "replay_schedule_from")]
pub replay_preemptions_from: Option<PathBuf>,
#[clap(
long,
value_name = "filepath",
conflicts_with = "replay_preemptions_from"
)]
pub replay_schedule_from: Option<PathBuf>,
#[clap(long)]
pub replay_exhausted_panic: bool,
#[serde(default)]
#[clap(skip)]
pub lenient_replay: bool,
#[clap(long = "die-on-desync", hide = true)]
pub die_on_desync: bool,
#[serde(default)]
#[clap(long, requires = "replay_preemptions_from")]
pub replay_edited_preemptions: bool,
#[clap(
long,
requires = "replay_schedule_from",
conflicts_with_all = ["chaos", "replay_exhausted_panic"]
)]
#[serde(default)]
pub replay_continue_fairly: bool,
#[clap(long,
short = 's',
value_name = "index[,path]",
value_parser = parse_index_with_path)]
pub stacktrace_event: Vec<(u64, Option<PathBuf>)>,
#[serde(default)]
#[clap(
long,
hide = true,
requires = "replay_schedule_from",
conflicts_with = "strict_schedule_boundaries"
)]
pub stacktrace_at_schedule_positions: bool,
#[clap(long, value_name = "signame")]
pub stacktrace_signal: Option<SigWrapper>,
#[serde(default)]
#[clap(long = "record-access-trace-to", value_name = "path")]
pub access_trace: Option<PathBuf>,
#[serde(default)]
#[clap(long, value_name = "event", default_value = "0")]
pub access_trace_from: u64,
#[serde(default)]
#[clap(long, value_name = "records")]
pub access_trace_max_records: Option<u64>,
#[serde(default)]
#[clap(long, value_name = "bytes")]
pub access_trace_max_bytes: Option<u64>,
#[serde(default)]
#[clap(long = "watch", value_name = "addr[:len][:w|rw]")]
pub watch: Vec<crate::watch::WatchArg>,
#[serde(default)]
#[clap(long, value_name = "event", default_value = "0")]
pub watch_from: u64,
#[clap(long)]
pub preemption_stacktrace: bool,
#[clap(long, value_name = "filepath")]
pub preemption_stacktrace_log_file: Option<PathBuf>,
#[clap(long)]
pub deterministic_io: bool,
#[clap(long)]
pub panic_on_unsupported_syscalls: bool,
#[serde(default)]
#[clap(skip)]
pub exit_on_unsupported_syscall: bool,
#[serde(default)]
#[clap(skip)]
pub shutdown_on_unsupported_syscall: bool,
#[serde(default)]
#[clap(skip)]
pub unsupported_syscall_report_fd: Option<i32>,
#[serde(default)]
#[clap(
long = "panic-on-rbc-overshoot",
visible_alias = "panic-on-rcb-overshoot"
)]
pub panic_on_rcb_overshoot: bool,
#[clap(skip)]
pub has_uts_namespace: bool,
#[serde(default)]
#[clap(skip)]
pub notice_host_network_abstract_binds: bool,
#[serde(default)]
#[clap(skip)]
pub guest_ids: crate::pid::GuestIds,
#[serde(default)]
#[clap(skip)]
pub standard_stream_aliases: Option<[u8; 3]>,
#[clap(skip)]
pub replay_data: Option<PathBuf>,
#[clap(long)]
pub kill_daemons: bool,
#[clap(long)]
pub gdbserver: bool,
#[clap(long, value_name = "uint16", default_value = "1234")]
pub gdbserver_port: u16,
#[serde(alias = "preemption_timeout")]
#[clap(
long,
visible_alias = "preemption-timeout",
value_name = "uint64|'disabled'",
default_value = "200000000",
value_parser = parse_timeslice)]
pub max_timeslice: MaybeTimeslice,
#[serde(default)]
#[clap(long, value_name = "virtual-nanoseconds")]
pub target_timeslice: Option<NonZeroU64>,
#[serde(default)]
#[clap(long, requires = "target_timeslice")]
pub target_timeslice_syscalls_only: bool,
#[serde(default)]
#[clap(long)]
pub futex_wake_yields: bool,
#[serde(default)]
#[clap(long, value_name = "nanos")]
pub pipe_wake_latency: Option<u64>,
#[serde(default)]
#[clap(long, value_enum, value_name = "each|once")]
pub expired_wait_charge: Option<ExpiredWaitCharge>,
#[serde(default)]
#[clap(long, value_enum, value_name = "first-pass|when-chosen")]
pub sleep_registration: Option<SleepRegistration>,
#[serde(default)]
#[clap(long, value_name = "path")]
pub work_span_report: Option<std::path::PathBuf>,
#[serde(default)]
#[clap(long, value_name = "virtual-nanoseconds")]
pub scheduler_turn_cost: Option<NonZeroU64>,
#[serde(default)]
#[clap(long)]
pub cap_preemption_charge: bool,
#[serde(default)]
#[clap(long, value_name = "virtual-nanoseconds")]
pub virtual_timeout: Option<NonZeroU64>,
#[clap(long)]
pub sigint_instakill: bool,
#[clap(long)]
pub warn_non_zero_binds: bool,
#[clap(long, default_value = "none", value_name = "str")]
pub sched_heuristic: SchedHeuristic,
#[clap(long, env = "HERMIT_SCHED_SEED", value_name = "uint64")]
pub sched_seed: Option<u64>,
#[serde(default)]
#[clap(skip)]
pub network_trace: NetworkTraceConfig,
#[clap(long, default_value = "0.0", value_name = "double")]
pub sched_sticky_random_param: f64,
#[clap(skip = false)]
pub recordreplay_modes: bool,
#[serde(default)]
#[clap(skip = false)]
pub replaying: bool,
#[clap(long, value_name = "turn_N")]
pub stop_after_turn: Option<u64>,
#[clap(long, value_name = "iter_N")]
pub stop_after_iter: Option<u64>,
#[clap(long, value_name = "turn=N:SIGNAL", value_parser = parse_signal_at)]
#[serde(default)]
pub signal_at: Option<SignalAt>,
#[clap(
long,
value_name = "uint64|'default'|'off'",
default_value = "off",
value_parser = parse_post_crash_timeslice
)]
#[serde(default)]
pub post_crash_timeslice: MaybeTimeslice,
#[clap(long)]
pub debug_externalize_sockets: bool,
#[clap(
long,
value_name = "precise|polling|external",
default_value = "precise"
)]
pub debug_futex_mode: BlockingMode,
#[clap(long)]
pub no_rcb_time: bool,
#[clap(long)]
pub detlog_heap: bool,
#[clap(long)]
pub detlog_stack: bool,
#[clap(
long,
value_enum,
value_name = "pages",
num_args = 0..=1,
require_equals = true,
default_missing_value = "mappings"
)]
#[serde(default)]
pub detlog_anon: Option<DetlogAnon>,
#[clap(long)]
pub detlog_regs: bool,
#[clap(long = "no-detlog-io-buffers", action = clap::ArgAction::SetFalse)]
pub detlog_io_buffers: bool,
#[clap(long, default_value = "1", value_name = "uint64")]
pub detlog_regs_cadence: u64,
#[clap(long, default_value = "120", value_name = "uint64")]
pub sysinfo_uptime_offset: u64,
#[clap(long, default_value = "1GB", value_parser = try_parse_memory, value_name = "bytesize")]
pub memory: u64,
#[serde(default)]
#[clap(long, value_name = "count", value_parser = parse_virtual_cpus)]
pub virtual_cpus: Option<NonZeroU32>,
#[serde(default)]
#[clap(
long = "proc",
default_value = "minimal",
value_name = "minimal|standard"
)]
pub proc_level: ProcLevel,
#[clap(long, value_name = "tid:rcbs", value_parser = try_parse_numbers_with_colon)]
pub interrupt_at: Vec<(DetTid, u64)>,
#[serde(skip)]
#[clap(skip)]
pub happens_before: Option<HappensBeforeProgram>,
#[serde(default)]
#[clap(skip)]
pub record_host_inputs: bool,
#[serde(skip)]
#[clap(skip)]
pub host_input_log: Option<PathBuf>,
#[serde(skip)]
#[clap(skip)]
pub host_input_snapshots: Vec<crate::host_input::HostInputSnapshot>,
#[serde(default)]
#[clap(skip)]
pub property_snapshot: Option<PropertySnapshot>,
#[serde(skip)]
#[clap(skip)]
pub untraced_code_range: Option<(u64, u64)>,
#[serde(skip)]
#[clap(skip)]
pub fatal_core_capture: Option<FatalCoreCapture>,
#[serde(default)]
#[clap(skip)]
pub in_guest_signal_delivery: bool,
#[serde(default)]
#[clap(skip)]
pub annotated_priority_replay: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FatalCoreCapture {
pub dir: PathBuf,
pub file_prefix: String,
pub max_core_bytes: u64,
pub max_total_bytes: u64,
pub time_limit: std::time::Duration,
}
fn try_parse_numbers_with_colon(from_str: &str) -> anyhow::Result<(DetTid, u64)> {
if let Some((thread_id_str, time_str)) = from_str.split_once(':') {
Ok((
thread_id_str
.parse::<DetTid>()
.map_err(anyhow::Error::msg)?,
time_str.parse::<u64>().map_err(anyhow::Error::msg)?,
))
} else {
anyhow::bail!(
"unable to parse <thread_id>:<logical_time> from '{}'",
from_str
)
}
}
fn try_parse_memory(from_str: &str) -> anyhow::Result<u64> {
<bytesize::ByteSize as FromStr>::from_str(from_str)
.map(|res| res.as_u64())
.map_err(anyhow::Error::msg)
}
pub const MAX_VIRTUAL_CPUS: u32 = 128;
fn parse_virtual_cpus(value: &str) -> Result<NonZeroU32, String> {
value
.parse::<u32>()
.ok()
.filter(|count| (1..=MAX_VIRTUAL_CPUS).contains(count))
.and_then(NonZeroU32::new)
.ok_or_else(|| {
format!(
"expected a CPU count from 1 to {MAX_VIRTUAL_CPUS}, for example --virtual-cpus 4"
)
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RewriteExclusivesRefusal {
HostLacksLseAtomics,
ThreadsNotSequentialized,
}
impl std::fmt::Display for RewriteExclusivesRefusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::HostLacksLseAtomics => write!(
f,
"rewriting exclusive loops in the guest's memory rewrites them into FEAT_LSE \
atomic instructions, which this host does not execute (no HWCAP_ATOMICS); \
the rewritten image would raise SIGILL"
),
Self::ThreadsNotSequentialized => write!(
f,
"rewriting exclusive loops in the guest's memory writes code that another \
thread could be running; run with threads sequentialized"
),
}
}
}
impl Config {
pub fn virtual_cpu_count(&self) -> u32 {
self.virtual_cpus.map_or(1, NonZeroU32::get)
}
pub fn models_signal_targets(&self) -> bool {
self.sequentialize_threads && self.backend.kernel_signal_targets_are_predictable
}
pub fn reads_sleeper_signal_state(&self) -> bool {
self.models_signal_targets() || self.in_guest_signal_delivery
}
pub fn reserves_in_guest_signal(&self, signal: i64) -> bool {
(1..=64).contains(&signal) && self.in_guest_reserved_signals & (1_u64 << (signal - 1)) != 0
}
pub fn with_backend(mut self, change: impl FnOnce(&mut BackendCapabilities)) -> Self {
change(&mut self.backend);
self
}
pub fn has_default_epoch(&self) -> bool {
self.epoch == DEFAULT_EPOCH_STR.parse::<DateTime<Utc>>().unwrap()
}
pub fn capture_epoch_from_host_time(&mut self, now: SystemTime) {
self.epoch = epoch_from_host_time(now);
}
pub fn largest_nanos_per_rcb(&self) -> f64 {
let slowdown = if self.chaos && self.chaos_per_thread_slowdown {
self.chaos_slowdown_max_factor
} else {
1.0
};
NANOS_PER_RCB * (self.clock_multiplier.unwrap_or(1.0) * slowdown)
}
pub fn minimum_max_timeslice_nanos(&self) -> u64 {
(self.largest_nanos_per_rcb().ceil() as u64).max(NANOS_PER_RCB as u64)
}
pub fn validate_invariants(&self) {
assert!(self.sched_sticky_random_param >= 0.0);
assert!(self.sched_sticky_random_param <= 1.0);
assert!(
self.chaos_slowdown_max_factor.is_finite()
&& self.chaos_slowdown_max_factor >= 1.0
&& self.chaos_slowdown_max_factor <= RcbTimeMultiplier::MAX,
"chaos_slowdown_max_factor must be finite and in [1.0, {}], got {}",
RcbTimeMultiplier::MAX,
self.chaos_slowdown_max_factor
);
if let Some(multiplier) = self.clock_multiplier {
assert!(
multiplier.is_finite() && multiplier > 0.0,
"clock_multiplier must be finite and positive"
);
}
let minimum_max_timeslice = self.minimum_max_timeslice_nanos();
assert!(
self.max_timeslice
.is_none_or(|timeslice| u64::from(timeslice) >= minimum_max_timeslice),
"max_timeslice must be at least one RCB ({} virtual nanoseconds)",
minimum_max_timeslice
);
}
pub fn rewrite_exclusives_in_memory_refusal(
&self,
host_has_lse_atomics: bool,
) -> Option<RewriteExclusivesRefusal> {
if !self.rewrite_exclusives_in_memory {
return None;
}
if !self.sequentialize_threads {
return Some(RewriteExclusivesRefusal::ThreadsNotSequentialized);
}
if !host_has_lse_atomics {
return Some(RewriteExclusivesRefusal::HostLacksLseAtomics);
}
None
}
pub fn validate(&mut self) {
self.validate_invariants();
if self.die_on_desync {
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
eprintln!(
"warning: --die-on-desync is retired and has no effect; replay is strict by default"
);
});
self.die_on_desync = false;
}
if self.record_preemptions_to.is_some() {
self.record_preemptions = true;
}
if self.replay_schedule_from.is_some() && self.replay_preemptions_from.is_some() {
panic!("Cannot set both --replay-preemptions-from and --replay-schedule-from!!");
}
if self.chaos {
self.sequentialize_threads = true;
}
if self.replay_preemptions_from.is_some() && self.imprecise_timers {
eprintln!(
"WARNING: Setting --imprecise timers with --replay-preemptions-from is probably not what you want. They won't replay precisely."
);
}
if self.stop_after_turn.is_some() && !self.sequentialize_threads {
eprintln!(
"WARNING: --stop-after-turn will have no effect if --no-sequentialize-threads is enabled"
);
self.stop_after_turn = None;
}
if self.stop_after_iter.is_some() && !self.sequentialize_threads {
eprintln!(
"WARNING: --stop-after-iter will have no effect if --no-sequentialize-threads is enabled"
);
self.stop_after_iter = None;
}
if self.signal_at.is_some() && !self.sequentialize_threads {
eprintln!(
"WARNING: --signal-at will have no effect if --no-sequentialize-threads is enabled"
);
self.signal_at = None;
}
if self.debug_externalize_sockets && !self.sequentialize_threads {
eprintln!(
"WARNING: --debug-externalize-sockets will have no effect if --no-sequentialize-threads is enabled"
);
self.debug_externalize_sockets = false;
}
if !self.stacktrace_event.is_empty()
&& !self.record_preemptions
&& self.replay_schedule_from.is_none()
{
eprintln!(
"WARNING: -s/--stacktrace-event has no effect if not recording/replaying events!"
);
}
if self.preemption_stacktrace_log_file.is_some() {
self.preemption_stacktrace = true;
}
}
pub fn use_preemption_timer(&self) -> bool {
self.max_timeslice.is_some() && self.backend.delivers_preemption_timer_events
}
pub fn replays_lone_preemptions(&self) -> bool {
!self.eager_lone_preemptions
&& self.use_preemption_timer()
&& self.use_rcb_time()
&& self.sequentialize_threads
&& !self.imprecise_timers
&& !self.chaos_per_thread_slowdown
&& !self.strict_schedule_boundaries
&& self.target_timeslice.is_none()
&& !self.preemption_stacktrace
&& self.stacktrace_event.is_empty()
&& self.stop_after_turn.is_none()
&& self.stop_after_iter.is_none()
&& self.signal_at.is_none()
&& self.happens_before.is_none()
&& self.interrupt_at.is_empty()
&& !self.slice_ends_need_a_stop()
&& !self.gdbserver
}
pub fn use_rcb_time(&self) -> bool {
self.max_timeslice.is_some() && !self.no_rcb_time
}
pub fn slice_ends_need_a_stop(&self) -> bool {
self.chaos && self.chaos_instruction_offset > 0
}
pub fn chaos_draws_schedule(&self) -> bool {
self.chaos && self.replay_schedule_from.is_none()
}
pub fn yields_after_futex_wake(&self, woken: u64) -> bool {
self.futex_wake_yields && woken > 0
}
pub fn scheduler_turn_charge(&self) -> Result<u64, String> {
let multiplier = self.clock_multiplier.unwrap_or(1.0);
let Some(cost) = self.scheduler_turn_cost else {
return Ok((NANOS_PER_SCHED * multiplier) as u64);
};
let cost = u64::from(cost);
if cost > MAX_SCHEDULER_TURN_COST {
return Err(format!(
"--scheduler-turn-cost must be at most {MAX_SCHEDULER_TURN_COST} virtual \
nanoseconds (received {cost})"
));
}
let charge = cost as f64 * multiplier;
if !(1.0..=MAX_SCHEDULER_TURN_COST as f64).contains(&charge) {
return Err(format!(
"--scheduler-turn-cost {cost} at --clock-multiplier {multiplier} charges {charge} \
virtual nanoseconds per scheduler turn; the charge must be at least 1, so that \
timed waits keep advancing, and at most {MAX_SCHEDULER_TURN_COST}"
));
}
Ok(charge as u64)
}
pub fn post_crash_timeslice_refusal(&self) -> Option<String> {
let bound = self.post_crash_timeslice?;
if self.post_crash_timeslice_in_effect().is_some() {
return None;
}
Some(if !self.sequentialize_threads {
"the switch needs sequentialized threads".to_owned()
} else {
match self.max_timeslice {
None => "the switch needs a --max-timeslice".to_owned(),
Some(max) => format!(
"a bound of {bound} is not above --max-timeslice={max}; replay with the \
recording's --max-timeslice"
),
}
})
}
pub fn post_crash_timeslice_in_effect(&self) -> Option<NonZeroU64> {
let bound = self.post_crash_timeslice?;
let run = self.max_timeslice?;
(self.sequentialize_threads && bound > run).then_some(bound)
}
pub fn pipe_wake_latency_in_effect(&self) -> Option<u64> {
self.pipe_wake_latency.filter(|_| {
self.use_nonblocking_sockets()
&& !self.recordreplay_modes
&& self.sched_heuristic.is_priority_ordered()
})
}
pub fn expired_wait_runs_charged_once(&self) -> bool {
!self.recordreplay_modes
&& match self.expired_wait_charge {
Some(charge) => charge == ExpiredWaitCharge::Once,
None => !self.chaos && self.sched_heuristic.is_priority_ordered(),
}
}
pub fn queued_sleeps_registered_at_first_pass(&self) -> bool {
!self.recordreplay_modes
&& match self.sleep_registration {
Some(registration) => registration == SleepRegistration::FirstPass,
None => {
!self.chaos
&& self.sched_heuristic.is_priority_ordered()
&& self.reads_sleeper_signal_state()
}
}
}
pub fn untyped_descriptor_settings(&self) -> Vec<String> {
let mut settings = Vec::new();
if !self.virtualize_metadata {
settings.push("--no-virtualize-metadata".to_string());
}
settings
}
pub fn use_nonblocking_sockets(&self) -> bool {
self.sequentialize_threads && !self.debug_externalize_sockets
}
pub fn should_trace_schedevent(&self) -> bool {
self.record_preemptions || self.replay_schedule_from.is_some()
}
pub fn observes_schedevents(&self) -> bool {
self.should_trace_schedevent() || self.annotated_priority_replay
}
pub fn annotated_priority_replay_unqualified(&self) -> Option<&'static str> {
if !self.backend.delivers_preemption_timer_events {
Some("cannot deliver Detcore preemption timer events")
} else if !self.sequentialize_threads {
Some("does not sequentialize threads (--no-sequentialize-threads)")
} else if self.max_timeslice.is_none() {
Some("has its preemption timer disabled (--max-timeslice=disabled)")
} else if self.imprecise_timers {
Some("requests imprecise timers (--imprecise-timers)")
} else if self.no_rcb_time {
Some("requests logical time without RCBs (--no-rcb-time)")
} else {
None
}
}
pub fn interrupts_for_thread(&self, thread_id: DetTid) -> BTreeSet<u64> {
self.interrupt_at
.iter()
.filter_map(|(tid, time)| {
if tid.eq(&thread_id) {
Some(*time)
} else {
None
}
})
.collect::<BTreeSet<u64>>()
}
}
impl fmt::Display for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if !self.virtualize_time {
write!(f, " --no-virtualize-time")?;
}
if !self.virtualize_cpuid {
write!(f, " --no-virtualize-cpuid")?;
}
if self.cpu_profile != crate::cpu_profile::CpuProfile::Auto {
write!(f, " --cpu-profile={}", self.cpu_profile)?;
}
if !self.virtualize_metadata {
write!(f, " --no-virtualize-metadata")?;
}
if self.passthru_opt {
write!(f, " --passthru-opt")?;
}
if self.untrap_passthrough_syscalls {
write!(f, " --untrap-passthrough-syscalls")?;
}
match self.runs_post_fork {
RunsPostFork::Child => {}
RunsPostFork::Parent => write!(f, " --runs-post-fork=parent")?,
RunsPostFork::Random => write!(f, " --runs-post-fork=random")?,
}
if !self.has_default_epoch() {
write!(f, " --epoch={}", self.epoch.to_rfc3339())?;
}
if self.seed != 0 {
write!(f, " --seed={}", self.seed)?;
}
if let Some(rng_seed) = self.rng_seed {
write!(f, " --rng-seed={}", rng_seed)?;
}
if let Some(fuzz_seed) = self.fuzz_seed {
write!(f, " --fuzz-seed={}", fuzz_seed)?;
}
if self.fuzz_futexes {
write!(f, " --fuzz-futexes")?;
}
if self.chaos_target_races {
write!(f, " --chaos-target-races")?;
}
if self.chaos_per_thread_slowdown {
write!(f, " --chaos-per-thread-slowdown")?;
write!(
f,
" --chaos-slowdown-max-factor={}",
self.chaos_slowdown_max_factor
)?;
if self.chaos_epoch_length_ns > 0 {
write!(f, " --chaos-epoch-length-ns={}", self.chaos_epoch_length_ns)?;
}
}
if self.chaos_instruction_offset > 0 {
write!(
f,
" --chaos-instruction-offset={}",
self.chaos_instruction_offset
)?;
}
if let Some(m) = self.clock_multiplier {
write!(f, " --clock-multiplier={}", m)?;
}
if self.imprecise_timers {
write!(f, " --imprecise-timers")?;
}
if self.eager_lone_preemptions {
write!(f, " --eager-lone-preemptions")?;
}
if !self.signal_state_copy {
write!(f, " --no-signal-state-copy")?;
}
if self.chaos {
write!(f, " --chaos")?;
}
if let Some(range) = self.chaos_timeslice_range {
write!(f, " --chaos-timeslice-range={range}")?;
}
if self.chaos_timeslice_draw == ChaosTimesliceDraw::Run {
write!(f, " --chaos-timeslice-draw=run")?;
}
if self.strict_schedule_boundaries {
write!(f, " --strict-schedule-boundaries")?;
}
if self.record_preemptions {
write!(f, " --record-preemptions")?;
}
if let Some(p) = &self.record_preemptions_to {
let s = p.to_str().expect("valid unicode path");
write!(f, " --record-preemptions-to={}", shell_words::quote(s))?;
}
if let Some(p) = &self.replay_preemptions_from {
let s = p.to_str().expect("valid unicode path");
write!(f, " --replay-preemptions-from={}", shell_words::quote(s))?;
}
if let Some(p) = &self.replay_schedule_from {
let s = p.to_str().expect("valid unicode path");
write!(f, " --replay-schedule-from={}", shell_words::quote(s))?;
}
if self.replay_exhausted_panic {
write!(f, " --replay-exhausted-panic")?;
}
if self.replay_edited_preemptions {
write!(f, " --replay-edited-preemptions")?;
}
if self.replay_continue_fairly {
write!(f, " --replay-continue-fairly")?;
}
for (index, path) in &self.stacktrace_event {
write!(f, " --stacktrace-event={}", index)?;
if let Some(p) = path {
let s = p.to_str().expect("valid unicode path");
write!(f, ",{}", shell_words::quote(s))?;
}
}
if let Some(p) = &self.access_trace {
let s = p.to_str().expect("valid unicode path");
write!(f, " --record-access-trace-to={}", shell_words::quote(s))?;
}
if self.access_trace_from != 0 {
write!(f, " --access-trace-from={}", self.access_trace_from)?;
}
if let Some(records) = self.access_trace_max_records {
write!(f, " --access-trace-max-records={}", records)?;
}
if let Some(bytes) = self.access_trace_max_bytes {
write!(f, " --access-trace-max-bytes={}", bytes)?;
}
if self.stacktrace_at_schedule_positions {
write!(f, " --stacktrace-at-schedule-positions")?;
}
for watch in &self.watch {
write!(f, " --watch={}", watch)?;
}
if self.watch_from != 0 {
write!(f, " --watch-from={}", self.watch_from)?;
}
if self.preemption_stacktrace {
write!(f, " --preemption-stacktrace")?;
}
if self.panic_on_unsupported_syscalls {
write!(f, " --panic-on-unsupported-syscalls")?;
}
if self.panic_on_rcb_overshoot {
write!(f, " --panic-on-rbc-overshoot")?;
}
if self.kill_daemons {
write!(f, " --kill-daemons")?;
}
if self.gdbserver {
write!(f, " --gdbserver")?;
}
if self.gdbserver_port != 1234u16 {
write!(f, " --gdbserver-port={}", self.gdbserver_port)?;
}
match &self.max_timeslice {
Some(x)
if self.chaos_timeslice_range.is_some()
&& (self.chaos_timeslice_range.map(|range| range.max) == Some(*x)
|| self.chaos_timeslice == Some(*x)) => {}
Some(x) => {
if *x != NonZeroU64::new(200_000_000).unwrap() {
write!(f, " --max-timeslice={}", x)?;
}
}
None => {
write!(f, " --max-timeslice=disabled")?;
}
}
if let Some(target_timeslice) = self.target_timeslice {
write!(f, " --target-timeslice={}", target_timeslice)?;
}
if self.target_timeslice_syscalls_only {
write!(f, " --target-timeslice-syscalls-only")?;
}
if self.futex_wake_yields {
write!(f, " --futex-wake-yields")?;
}
if let Some(latency) = self.pipe_wake_latency {
write!(f, " --pipe-wake-latency={}", latency)?;
}
if let Some(charge) = self.expired_wait_charge {
write!(f, " --expired-wait-charge={}", charge.as_str())?;
}
if let Some(registration) = self.sleep_registration {
write!(f, " --sleep-registration={}", registration.as_str())?;
}
if let Some(report) = &self.work_span_report {
write!(f, " --work-span-report={}", report.display())?;
}
if let Some(cost) = self.scheduler_turn_cost {
write!(f, " --scheduler-turn-cost={}", cost)?;
}
if self.cap_preemption_charge {
write!(f, " --cap-preemption-charge")?;
}
if let Some(bound) = self.virtual_timeout {
write!(f, " --virtual-timeout={}", bound)?;
}
if self.sigint_instakill {
write!(f, " --sigint-instakill")?;
}
if self.warn_non_zero_binds {
write!(f, " --warn-non-zero-binds")?;
}
match &self.sched_heuristic {
SchedHeuristic::None => {}
SchedHeuristic::ConnectBind => {
write!(f, " --sched-heuristic=connectbind")?;
}
SchedHeuristic::Random => {
write!(f, " --sched-heuristic=random")?;
}
SchedHeuristic::StickyRandom => {
write!(f, " --sched-heuristic=stickyrandom")?;
}
}
if let Some(s) = self.sched_seed {
write!(f, " --sched-seed={}", s)?;
}
if self.sched_sticky_random_param != 0.0 {
write!(
f,
" --sched-sticky-random-param={}",
self.sched_sticky_random_param
)?;
}
if let Some(t) = self.stop_after_turn {
write!(f, " --stop-after-turn={}", t)?;
}
if let Some(i) = self.stop_after_iter {
write!(f, " --stop-after-iter={}", i)?;
}
if let Some(at) = self.signal_at {
write!(f, " --signal-at={}", at)?;
}
if let Some(bound) = self.post_crash_timeslice {
write!(f, " --post-crash-timeslice={}", bound)?;
}
if self.debug_externalize_sockets {
write!(f, " --debug-externalize-sockets")?;
}
match &self.debug_futex_mode {
BlockingMode::External => {
write!(f, " --debug-futex-mode=external")?;
}
BlockingMode::Polling => {
write!(f, " --debug-futex-mode=polling")?;
}
BlockingMode::Precise => { }
}
if self.no_rcb_time {
write!(f, " --no-rcb-time")?;
}
if self.detlog_heap {
write!(f, " --detlog-heap")?;
}
if self.detlog_stack {
write!(f, " --detlog-stack")?;
}
match self.detlog_anon {
Some(DetlogAnon::Mappings) => write!(f, " --detlog-anon")?,
Some(DetlogAnon::Pages) => write!(f, " --detlog-anon=pages")?,
None => {}
}
if self.detlog_regs {
write!(f, " --detlog-regs")?;
}
if self.detlog_regs_cadence != 1 {
write!(f, " --detlog-regs-cadence={}", self.detlog_regs_cadence)?;
}
if !self.detlog_io_buffers {
write!(f, " --no-detlog-io-buffers")?;
}
if self.sysinfo_uptime_offset != 120 {
write!(f, " --sysinfo-uptime-offset={}", self.sysinfo_uptime_offset)?;
}
if self.memory != 1_000_000_000 {
write!(f, " --memory={}", self.memory)?;
}
if let Some(cpus) = self.virtual_cpus {
write!(f, " --virtual-cpus={cpus}")?;
}
match self.proc_level {
ProcLevel::Minimal => {}
ProcLevel::Standard => write!(f, " --proc=standard")?,
}
for (tid, rcb) in &self.interrupt_at {
write!(f, " --interrupt-at={}:{}", tid, rcb)?;
}
Ok(())
}
}
#[derive(
Debug,
Default,
Clone,
Copy,
Serialize,
Deserialize,
Parser,
PartialEq,
Eq,
PartialOrd,
Ord
)]
pub enum ProcLevel {
#[default]
Minimal,
Standard,
}
impl FromStr for ProcLevel {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"minimal" => Ok(Self::Minimal),
"standard" => Ok(Self::Standard),
_ => Err(format!(
"Expected minimal|standard, could not parse: {:?}",
s
)),
}
}
}
#[derive(
Debug,
Default,
Clone,
Copy,
Serialize,
Deserialize,
Parser,
PartialEq,
Eq
)]
pub enum RunsPostFork {
#[default]
Child,
Parent,
Random,
}
impl FromStr for RunsPostFork {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"child" => Ok(Self::Child),
"parent" => Ok(Self::Parent),
"random" => Ok(Self::Random),
_ => Err(format!(
"Expected Child|Parent|Random, could not parse: {:?}",
s
)),
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Parser, PartialEq, Eq)]
pub enum BlockingMode {
External,
Polling,
Precise,
}
impl FromStr for BlockingMode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"polling" => Ok(BlockingMode::Polling),
"precise" => Ok(BlockingMode::Precise),
"external" => Ok(BlockingMode::External),
_ => Err(format!(
"Expected Polling|Precise|External, could not parse: {:?}",
s
)),
}
}
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Hash,
Serialize,
Deserialize,
clap::ValueEnum
)]
#[serde(rename_all = "lowercase")]
pub enum ExpiredWaitCharge {
Each,
Once,
}
impl ExpiredWaitCharge {
pub fn from_charged_once(once: bool) -> Self {
if once { Self::Once } else { Self::Each }
}
pub fn as_str(self) -> &'static str {
match self {
Self::Each => "each",
Self::Once => "once",
}
}
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Hash,
Serialize,
Deserialize,
clap::ValueEnum
)]
#[serde(rename_all = "kebab-case")]
pub enum SleepRegistration {
FirstPass,
WhenChosen,
}
impl SleepRegistration {
pub fn from_registered_at_first_pass(first_pass: bool) -> Self {
if first_pass {
Self::FirstPass
} else {
Self::WhenChosen
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::FirstPass => "first-pass",
Self::WhenChosen => "when-chosen",
}
}
}
#[derive(
Debug,
Default,
Clone,
Copy,
Serialize,
Deserialize,
Parser,
PartialEq,
Eq
)]
pub enum SchedHeuristic {
#[default]
None,
ConnectBind,
Random,
StickyRandom,
}
impl SchedHeuristic {
pub fn is_priority_ordered(self) -> bool {
matches!(self, SchedHeuristic::None | SchedHeuristic::ConnectBind)
}
}
impl FromStr for SchedHeuristic {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"none" | "roundrobin" => Ok(SchedHeuristic::None),
"connectbind" => Ok(SchedHeuristic::ConnectBind),
"random" => Ok(SchedHeuristic::Random),
"stickyrandom" => Ok(SchedHeuristic::StickyRandom),
_ => Err(format!(
"Expected None|ConnectBind|Random|StickyRandom, could not parse: {:?}",
s
)),
}
}
}
pub type MaybeTimeslice = Option<NonZeroU64>;
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Default,
Serialize,
Deserialize,
clap::ValueEnum
)]
#[serde(rename_all = "kebab-case")]
pub enum ChaosTimesliceDraw {
#[default]
Slice,
Run,
}
pub const RECOMMENDED_CHAOS_TIMESLICE_RANGE: TimesliceRange = TimesliceRange {
min: NonZeroU64::new(1_000).unwrap(),
max: NonZeroU64::new(200_000_000).unwrap(),
};
pub fn chaos_long_help() -> String {
let range = RECOMMENDED_CHAOS_TIMESLICE_RANGE;
format!(
"Schedule threads chaotically.\n\n\
The behavior of this flag is subject to change. Current behavior is to randomize thread \
priorities at every logical timeslice. Other randomization strategies are possible with \
`--sched-heuristic`.\n\n\
Thread scheduling remains deterministic, determined by the random seed.\n\n\
By default, every chaos slice's mean is the run's `--max-timeslice` (200000000 virtual \
nanoseconds unless given), so one seed sweep explores mostly one slice scale. For race \
discovery, sweep seeds with `--chaos-timeslice-draw=run`: each run draws its \
`--max-timeslice` once, log-uniformly from the recommended range {range} virtual \
nanoseconds (or from `--chaos-timeslice-range`), as a pure function of the scheduler \
seed. Fine draws explore short preemption windows, but can take orders of magnitude \
longer: size time limits for them. A replay adopts a recorded drawn maximum without \
drawing again. See `--chaos-timeslice-draw`."
)
}
pub fn chaos_timeslice_draw_long_help() -> String {
let range = RECOMMENDED_CHAOS_TIMESLICE_RANGE;
format!(
"How a chaos run draws its timeslice. Requires `--chaos`.\n\n\
`run` (the discovery mode) draws the run's `--max-timeslice` once, log-uniformly from \
`--chaos-timeslice-range`, or from the recommended range {range} virtual nanoseconds \
(1 us to 200 ms) without an explicit range. The draw is a pure function of the scheduler \
seed; the run is then an ordinary chaos run under it, so a seed sweep spreads its seeds \
over the range, each seed at one scale. Without a seed, every run uses seed 0 and draws \
the same value. Fine draws can be much slower: size time limits for the fine end.\n\n\
Fine draws also incur frequent scheduler-turn charges in guest-visible time, which can \
trigger a guest's own watchdogs. See `--cap-preemption-charge` for the explicit option \
that caps expired-timeslice charges. The range parser requires MIN to be at least \
10 virtual nanoseconds and no larger than MAX.\n\n\
`--summary-json` reports the drawn value (`preemption.max_timeslice_ns`), and a \
`--record-preemptions-to` record stores it. A replay adopts a recorded drawn maximum \
without drawing again; it needs no timeslice option. A legacy record with no drawn \
value does not override the requested draw policy. `hermit analyze` and `hermit bisect` \
take a recorded value and refuse `run` in their run arguments, since all trials must \
share one maximum.\n\n\
`slice` (the default) draws each slice's mean from an explicitly supplied range; it is \
what a range alone does. Without a range or an explicit `run` draw, the ordinary fixed \
maximum remains unchanged."
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct TimesliceRange {
pub min: NonZeroU64,
pub max: NonZeroU64,
}
impl TimesliceRange {
pub fn log_uniform(&self, u: f64) -> f64 {
let (low, high) = ((self.min.get() as f64).ln(), (self.max.get() as f64).ln());
(low + u * (high - low))
.exp()
.clamp(self.min.get() as f64, self.max.get() as f64)
}
}
impl FromStr for TimesliceRange {
type Err = String;
fn from_str(src: &str) -> Result<Self, Self::Err> {
let (min, max) = src
.split_once("..")
.ok_or_else(|| format!("expected MIN..MAX virtual nanoseconds, got {src:?}"))?;
let bound = |text: &str| -> Result<NonZeroU64, String> {
let value = text
.parse::<u64>()
.map_err(|error| format!("{text:?} is not a number of nanoseconds: {error}"))?;
if value < NANOS_PER_RCB as u64 {
return Err(format!(
"{value} ns is below one RCB ({} virtual nanoseconds), the shortest PMU-backed \
timeslice",
NANOS_PER_RCB as u64
));
}
Ok(NonZeroU64::new(value).expect("at least one RCB"))
};
let (min, max) = (bound(min)?, bound(max)?);
if min > max {
return Err(format!("the range {min}..{max} is empty: MIN exceeds MAX"));
}
Ok(Self { min, max })
}
}
impl TryFrom<String> for TimesliceRange {
type Error = String;
fn try_from(text: String) -> Result<Self, Self::Error> {
text.parse()
}
}
impl From<TimesliceRange> for String {
fn from(range: TimesliceRange) -> Self {
range.to_string()
}
}
impl std::fmt::Display for TimesliceRange {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..{}", self.min, self.max)
}
}
#[deprecated(note = "use MaybeTimeslice")]
pub type MaybePreemptionTimeout = MaybeTimeslice;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignalAt {
pub turn: u64,
pub signal: i32,
}
impl std::fmt::Display for SignalAt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "turn={}:{}", self.turn, self.signal)
}
}
fn parse_signal_at(src: &str) -> Result<SignalAt, String> {
let rest = src
.strip_prefix("turn=")
.ok_or_else(|| format!("expected turn=N:SIGNAL, got {src:?}"))?;
let (turn, signal) = rest
.split_once(':')
.ok_or_else(|| format!("expected turn=N:SIGNAL, got {src:?}"))?;
let turn = turn
.parse::<u64>()
.map_err(|e| format!("the turn in {src:?} is not a non-negative integer: {e}"))?;
let signal = match signal.parse::<i32>() {
Ok(number) => nix::sys::signal::Signal::try_from(number),
Err(_) => signal.parse::<nix::sys::signal::Signal>(),
}
.map_err(|_| format!("{signal:?} in {src:?} names no signal"))?;
if matches!(
signal,
nix::sys::signal::Signal::SIGKILL | nix::sys::signal::Signal::SIGSTOP
) {
return Err(format!(
"{signal} in {src:?} cannot be caught or blocked; --signal-at sends only \
signals the guest can handle"
));
}
Ok(SignalAt {
turn,
signal: signal as i32,
})
}
fn parse_timeslice(src: &str) -> Result<MaybeTimeslice, ParseTimesliceError> {
if let Ok(n) = src.parse::<u64>() {
if n != 0 && n < NANOS_PER_RCB as u64 {
Err(ParseTimesliceError::new(
"PMU-backed timeslices must be at least one RCB (10 virtual nanoseconds)",
))
} else {
Ok(NonZeroU64::new(n))
}
} else {
match src {
"disabled" => Ok(None),
_ => Err(ParseTimesliceError::new(
"Unable to parse timeslice, expected disabled or a non-negative integer",
)),
}
}
}
pub const DEFAULT_MAX_TIMESLICE: u64 = 200_000_000;
fn parse_post_crash_timeslice(src: &str) -> Result<MaybeTimeslice, ParseTimesliceError> {
match src {
"off" => Ok(None),
"default" => Ok(NonZeroU64::new(DEFAULT_MAX_TIMESLICE)),
_ => match parse_timeslice(src) {
Ok(Some(bound)) => Ok(Some(bound)),
_ => Err(ParseTimesliceError::new(
"expected off, default, or a timeslice of at least one RCB (10 virtual \
nanoseconds)",
)),
},
}
}
fn parse_index_with_path(src: &str) -> Result<(u64, Option<PathBuf>), String> {
let convert = |e| format!("Failed to parse int index before comma: {e}");
if let Some((index_str, path)) = src.split_once(',') {
let ix = index_str.parse::<u64>().map_err(convert)?;
let pathbuf = PathBuf::from_str(path).map_err(|_| "the impossible happened")?;
Ok((ix, Some(pathbuf)))
} else {
let ix = src.parse::<u64>().map_err(convert)?;
Ok((ix, None))
}
}
#[derive(Debug)]
struct ParseTimesliceError {
details: String,
}
impl fmt::Display for ParseTimesliceError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.details)
}
}
impl ParseTimesliceError {
fn new(msg: &str) -> ParseTimesliceError {
ParseTimesliceError {
details: msg.to_string(),
}
}
}
impl std::error::Error for ParseTimesliceError {
fn description(&self) -> &str {
&self.details
}
}
pub static DEFAULT_EPOCH_STR: &str = "2026-01-01T00:00:00Z";
pub use crate::canonical_test_epoch::CANONICAL_TEST_EPOCH;
pub use crate::canonical_test_epoch::CANONICAL_TEST_EPOCH_ARG;
pub fn epoch_from_host_time(now: SystemTime) -> DateTime<Utc> {
DateTime::<Utc>::from(now)
}
impl Config {
pub fn from_env() -> Self {
let args: [OsString; 2] = [
OsString::from("CMD"), OsString::from(format!("--epoch={}", DEFAULT_EPOCH_STR)),
];
Config::parse_from(args.iter())
}
pub fn rng_seed(&self) -> u64 {
self.rng_seed.unwrap_or(self.seed)
}
pub fn fuzz_seed(&self) -> u64 {
self.fuzz_seed.unwrap_or(self.seed)
}
pub fn sched_seed(&self) -> u64 {
self.sched_seed.unwrap_or(self.seed)
}
}
pub const MAX_SCHEDULER_TURN_COST: u64 = 1_000_000_000;
pub const CONFIG_FINGERPRINT_ENV: &str = "REVERIE_SABRE_HERMIT_CONFIG_FINGERPRINT";
pub const LITEINST_CONFIG_FINGERPRINT_ENV: &str = "HERMIT_LITEINST_CONFIG_FINGERPRINT";
const CONFIG_DEFINITION_SOURCES: &[&[u8]] = &[
include_bytes!("config.rs"),
include_bytes!("fd.rs"),
include_bytes!("happens_before.rs"),
include_bytes!("network_trace.rs"),
include_bytes!("pid.rs"),
include_bytes!("schedule.rs"),
include_bytes!("time.rs"),
include_bytes!("watch.rs"),
];
fn config_wire_default() -> Config {
let mut config = Config::parse_from([
"config-wire-fingerprint",
&format!("--epoch={DEFAULT_EPOCH_STR}"),
"--seed=0",
"--sched-seed=0",
"--cpu-profile=x86-64-v2",
]);
config.sched_seed = None;
config.backend = BackendCapabilities::KVM;
config.backend.rcb_clock_contract = BackendCapabilities::PTRACE.rcb_clock_contract;
config
}
pub fn config_wire_fingerprint() -> String {
let config = config_wire_default();
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy())
.expect("canonical Config wire default must encode with Reverie's bincode configuration");
let named_shape = serde_json::to_string(&config)
.expect("canonical Config wire default must encode as JSON for field-name checking");
fingerprint_of_config_material(&wire, &named_shape, CONFIG_DEFINITION_SOURCES)
}
pub fn config_fingerprint_mismatch(expected: &std::ffi::OsStr) -> Option<String> {
let ours = config_wire_fingerprint();
(expected.to_str() != Some(ours.as_str())).then(|| {
format!(
"its configuration and clock RPC fingerprint is {ours}, Hermit's is {}",
expected.to_string_lossy()
)
})
}
fn fingerprint_of_config_material(
wire: &[u8],
named_shape: &str,
definition_sources: &[&[u8]],
) -> String {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
let mut update = |domain: u8, bytes: &[u8]| {
for byte in std::iter::once(&domain)
.chain((bytes.len() as u64).to_le_bytes().iter())
.chain(bytes.iter())
{
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x1000_0000_01b3);
}
};
update(0, wire);
update(1, named_shape.as_bytes());
for source in definition_sources {
update(2, source);
}
format!("{hash:016x}")
}
fn signal_state_copy_default() -> bool {
true
}
impl Default for Config {
fn default() -> Self {
let v: Vec<String> = vec![];
Config::parse_from(v.iter())
}
}
pub fn to_legacy_backend_json(config: &Config) -> serde_json::Result<String> {
if config.strict_schedule_boundaries {
return Err(serde::ser::Error::custom(
"strict schedule boundaries cannot be represented by the legacy backend configuration",
));
}
let mut json = Vec::with_capacity(4096);
let mut serializer = serde_json::Serializer::new(&mut json);
config.serialize(legacy_backend_json::ConfigSerializer {
inner: &mut serializer,
config,
})?;
String::from_utf8(json).map_err(serde::ser::Error::custom)
}
fn legacy_backend_keys(config: &Config) -> [(&'static str, bool); 15] {
let backend = &config.backend;
[
("cpuid_virtualized_by_backend", false),
("backend_supports_madvise", true),
(
"discover_live_file_metadata",
backend.tool_shares_guest_descriptor_table,
),
(
"detect_host_clock_futex_timeouts",
backend.guest_clock_reads_bypass_backend,
),
("syscall_clobbers_virtualized_by_backend", false),
(
"cancel_killed_thread_rpcs",
backend.needs_killed_thread_rpc_cancellation,
),
(
"backend_reports_physical_process_exits",
backend.reports_physical_process_exits,
),
(
"backend_tracks_process_children",
backend.tracks_process_children,
),
(
"backend_runs_exit_robust_list",
backend.runs_exit_robust_list,
),
(
"backend_requires_thread_directed_process_signals",
backend.requires_thread_directed_process_signals,
),
("backend_is_kvm", backend.provides_process_signal_control),
(
"kvm_shared_dequeue_timers",
backend.provides_process_signal_control && config.sequentialize_threads,
),
(
"backend_supports_parked_write_signal_interruption",
backend.supports_parked_write_signal_interruption,
),
("backend_virtualizes_capability_prctls", false),
("backend_defers_vfork_child_registration", false),
]
}
pub fn from_legacy_backend_json(json: &str) -> serde_json::Result<Config> {
let mut deserializer = serde_json::Deserializer::from_str(json);
let (mut config, legacy) = serde::Deserializer::deserialize_struct(
&mut deserializer,
"Config",
&[],
legacy_backend_json::LegacyConfigVisitor,
)?;
deserializer.end()?;
if legacy.cpuid_virtualized_by_backend {
return Err(<serde_json::Error as serde::de::Error>::custom(
"cpuid_virtualized_by_backend is true, but no backend installs a CPUID \
policy of its own; the key must be false or absent",
));
}
if legacy.backend_virtualizes_capability_prctls {
return Err(<serde_json::Error as serde::de::Error>::custom(
"backend_virtualizes_capability_prctls is true, but no backend answers the \
capability prctls itself; the key must be false or absent",
));
}
let controlled = legacy.backend_is_kvm && config.sequentialize_threads;
if legacy.kvm_shared_dequeue_timers != controlled {
return Err(<serde_json::Error as serde::de::Error>::custom(
format_args!(
"kvm_shared_dequeue_timers is {} but backend_is_kvm && \
sequentialize_threads is {controlled}; the key is no longer an \
independent setting and must equal that conjunction",
legacy.kvm_shared_dequeue_timers,
),
));
}
config.backend = legacy.capabilities();
Ok(config)
}
pub fn encode_backend_config_json(
legacy_json: String,
backend: BackendCapabilities,
) -> serde_json::Result<String> {
if from_legacy_backend_json(&legacy_json)?.backend == backend {
return Ok(legacy_json);
}
serde_json::to_string(&VersionedBackendConfig {
dbt_config_version: 1,
config: serde_json::from_str(&legacy_json)?,
backend,
})
}
pub fn decode_backend_config_json(json: &str) -> serde_json::Result<Config> {
if let Ok(config) = from_legacy_backend_json(json) {
return Ok(config);
}
let envelope: VersionedBackendConfig<'_> = serde_json::from_str(json)?;
if envelope.dbt_config_version != 1 {
return Err(<serde_json::Error as serde::de::Error>::custom(
format_args!(
"unsupported DBT configuration version {}",
envelope.dbt_config_version
),
));
}
let named: EnvelopeBackendKeys = serde_json::from_str(json)?;
let expected = serde_json::to_value(envelope.backend)?;
if let Some(missing) = expected
.as_object()
.into_iter()
.flat_map(|capabilities| capabilities.keys())
.find(|capability| !named.backend.contains_key(capability.as_str()))
{
return Err(<serde_json::Error as serde::de::Error>::custom(
format_args!("missing field `{missing}` in the envelope's backend"),
));
}
let mut config = from_legacy_backend_json(envelope.config.get())?;
config.backend = envelope.backend;
Ok(config)
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct VersionedBackendConfig<'a> {
dbt_config_version: u32,
#[serde(borrow)]
config: &'a serde_json::value::RawValue,
backend: BackendCapabilities,
}
#[derive(Deserialize)]
struct EnvelopeBackendKeys {
backend: serde_json::Map<String, serde_json::Value>,
}
const LEGACY_BACKEND_KEY_NAMES: [&str; 15] = [
"cpuid_virtualized_by_backend",
"backend_supports_madvise",
"discover_live_file_metadata",
"detect_host_clock_futex_timeouts",
"syscall_clobbers_virtualized_by_backend",
"cancel_killed_thread_rpcs",
"backend_reports_physical_process_exits",
"backend_tracks_process_children",
"backend_runs_exit_robust_list",
"backend_requires_thread_directed_process_signals",
"backend_is_kvm",
"kvm_shared_dequeue_timers",
"backend_supports_parked_write_signal_interruption",
"backend_virtualizes_capability_prctls",
"backend_defers_vfork_child_registration",
];
const fn legacy_backend_key_default_true() -> bool {
true
}
#[derive(Deserialize)]
struct LegacyBackendKeys {
#[serde(default)]
cpuid_virtualized_by_backend: bool,
#[expect(
dead_code,
reason = "read only to refuse a repeated key; its value is ignored"
)]
#[serde(default = "legacy_backend_key_default_true")]
backend_supports_madvise: bool,
#[serde(default)]
discover_live_file_metadata: bool,
#[serde(default)]
detect_host_clock_futex_timeouts: bool,
#[expect(
dead_code,
reason = "read only to refuse a repeated key; its value is ignored"
)]
#[serde(default)]
syscall_clobbers_virtualized_by_backend: bool,
#[serde(default)]
cancel_killed_thread_rpcs: bool,
#[serde(default)]
backend_reports_physical_process_exits: bool,
#[serde(default = "legacy_backend_key_default_true")]
backend_tracks_process_children: bool,
#[serde(default = "legacy_backend_key_default_true")]
backend_runs_exit_robust_list: bool,
#[serde(default)]
backend_requires_thread_directed_process_signals: bool,
#[serde(default)]
backend_is_kvm: bool,
#[serde(default)]
kvm_shared_dequeue_timers: bool,
#[serde(default = "legacy_backend_key_default_true")]
backend_supports_parked_write_signal_interruption: bool,
#[serde(default)]
backend_virtualizes_capability_prctls: bool,
#[expect(
dead_code,
reason = "read only to refuse a repeated key; its value is ignored"
)]
#[serde(default)]
backend_defers_vfork_child_registration: bool,
}
impl LegacyBackendKeys {
fn capabilities(&self) -> BackendCapabilities {
let mut backend = BackendCapabilities::PTRACE;
backend.tool_shares_guest_descriptor_table = self.discover_live_file_metadata;
backend.rediscovers_descriptors_after_exec = self.discover_live_file_metadata;
backend.loopback_pollers_yield_to_peers = self.discover_live_file_metadata;
backend.guest_clock_reads_bypass_backend = self.detect_host_clock_futex_timeouts;
backend.needs_killed_thread_rpc_cancellation = self.cancel_killed_thread_rpcs;
backend.reports_child_exit_publication = !self.cancel_killed_thread_rpcs;
backend.reports_kernel_child_exit_signals = backend.reports_child_exit_publication;
backend.reports_physical_process_exits = self.backend_reports_physical_process_exits;
backend.tracks_process_children = self.backend_tracks_process_children;
backend.runs_exit_robust_list = self.backend_runs_exit_robust_list;
backend.requires_thread_directed_process_signals =
self.backend_requires_thread_directed_process_signals;
backend.supports_parked_write_signal_interruption =
self.backend_supports_parked_write_signal_interruption;
backend.provides_process_signal_control = self.backend_is_kvm;
backend.emulates_child_waits = self.backend_is_kvm;
backend.promotes_open_files_before_native_lifecycle =
self.backend_requires_thread_directed_process_signals;
set_kernel_signal_facts(&mut backend, false);
backend.reports_sigreturns = false;
backend.delivers_preemption_timer_events = false;
backend.runs_guest_code_between_injections = false;
backend.kernel_never_walks_robust_lists = false;
backend.provides_guest_backtraces = true;
backend.places_orphans = false;
backend.publishable_parent_death_signals = 0;
backend.hardware_watchpoints = 0;
backend.rcb_clock_contract = None;
backend
}
}
mod legacy_backend_json {
use std::fmt;
use serde::Deserialize;
use serde::Serialize;
use serde::de;
use serde::de::DeserializeSeed;
use serde::de::IgnoredAny;
use serde::de::MapAccess;
use serde::de::SeqAccess;
use serde::de::Visitor;
use serde::de::value::BoolDeserializer;
use serde::de::value::MapAccessDeserializer;
use serde::de::value::MapDeserializer;
use serde::de::value::SeqAccessDeserializer;
use serde::de::value::StringDeserializer;
use serde::de::value::U64Deserializer;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::SerializeStruct;
use serde::ser::Serializer;
use super::BackendCapabilities;
use super::Config;
use super::LEGACY_BACKEND_KEY_NAMES;
use super::LegacyBackendKeys;
use super::legacy_backend_keys;
const FIELDS_WITHOUT_A_LEGACY_KEY: [&str; 61] = [
"backend",
"strict_schedule_boundaries",
"record_host_inputs",
"guest_may_inherit_a_terminal",
"in_guest_detlog_forward_policy",
"in_guest_site_patching_off",
"in_guest_reserved_signals",
"in_guest_refuses_host_timed_producers",
"launch_image",
"target_timeslice_syscalls_only",
"futex_wake_yields",
"pipe_wake_latency",
"expired_wait_charge",
"sleep_registration",
"replaying",
"scheduler_turn_cost",
"cap_preemption_charge",
"virtual_timeout",
"inherited_seccomp",
"cpu_profile",
"cpu_profile_host",
"cpu_profile_source",
"signal_state_copy",
"container_mount_table",
"mountinfo_mount_namespace",
"directory_placeholder",
"container_procfs",
"signal_delivery_check_fatal",
"strict_binder",
"work_span_report",
"signal_at",
"post_crash_timeslice",
"in_guest_signal_delivery",
"annotated_priority_replay",
"virtual_cpus",
"notice_host_network_abstract_binds",
"replay_edited_preemptions",
"lenient_replay",
"eager_lone_preemptions",
"chaos_timeslice_range",
"chaos_timeslice_draw",
"chaos_timeslice",
"guest_ids",
"detlog_anon",
"access_trace",
"access_trace_from",
"access_trace_max_records",
"access_trace_max_bytes",
"replay_continue_fairly",
"standard_stream_aliases",
"rewrite_exclusives_unmarked",
"rewrite_exclusives_in_memory",
"rewrite_exclusives_overlay",
"rewrite_exclusives_overlay_requested",
"count_store_exclusives",
"stacktrace_at_schedule_positions",
"property_snapshot",
"watch",
"watch_from",
"chaos_instruction_offset",
"untrap_passthrough_syscalls",
];
pub(super) struct LegacyConfigVisitor;
impl<'de> Visitor<'de> for LegacyConfigVisitor {
type Value = (Config, LegacyBackendKeys);
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("struct Config")
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
let mut legacy = Vec::new();
let config = Config::deserialize(MapAccessDeserializer::new(LegacyKeys {
inner: map,
legacy: &mut legacy,
}))?;
Ok((config, legacy_backend_keys_from(legacy)?))
}
fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
let fields = config_field_order().map_err(<A::Error as de::Error>::custom)?;
let mut legacy = Vec::new();
let config = Config::deserialize(SeqAccessDeserializer::new(LegacyPositions {
inner: seq,
fields: fields.iter(),
legacy: &mut legacy,
}))?;
Ok((config, legacy_backend_keys_from(legacy)?))
}
}
fn legacy_backend_keys_from<E: de::Error>(
legacy: Vec<(&'static str, bool)>,
) -> Result<LegacyBackendKeys, E> {
LegacyBackendKeys::deserialize(MapDeserializer::<_, E>::new(legacy.into_iter()))
}
struct LegacyKeys<'l, A> {
inner: A,
legacy: &'l mut Vec<(&'static str, bool)>,
}
impl<'de, A: MapAccess<'de>> MapAccess<'de> for LegacyKeys<'_, A> {
type Error = A::Error;
fn next_key_seed<K: DeserializeSeed<'de>>(
&mut self,
seed: K,
) -> Result<Option<K::Value>, A::Error> {
while let Some(key) = self.inner.next_key::<String>()? {
if let Some(name) = LEGACY_BACKEND_KEY_NAMES
.into_iter()
.find(|name| *name == key)
{
let value = self.inner.next_value::<bool>()?;
self.legacy.push((name, value));
} else if FIELDS_WITHOUT_A_LEGACY_KEY.contains(&key.as_str()) {
self.inner.next_value::<IgnoredAny>()?;
} else {
return seed.deserialize(StringDeserializer::new(key)).map(Some);
}
}
Ok(None)
}
fn next_value_seed<V: DeserializeSeed<'de>>(
&mut self,
seed: V,
) -> Result<V::Value, A::Error> {
self.inner.next_value_seed(seed)
}
}
struct LegacyPositions<'f, 'l, A> {
inner: A,
fields: std::slice::Iter<'f, String>,
legacy: &'l mut Vec<(&'static str, bool)>,
}
impl<'de, A: SeqAccess<'de>> SeqAccess<'de> for LegacyPositions<'_, '_, A> {
type Error = A::Error;
fn next_element_seed<T: DeserializeSeed<'de>>(
&mut self,
seed: T,
) -> Result<Option<T::Value>, A::Error> {
match self.fields.next().map(String::as_str) {
Some("backend") => {
for name in LEGACY_BACKEND_KEY_NAMES {
match self.inner.next_element::<bool>()? {
Some(value) => self.legacy.push((name, value)),
None => break,
}
}
let placeholder = serde_json::to_value(BackendCapabilities::PTRACE)
.map_err(<A::Error as de::Error>::custom)?;
seed.deserialize(placeholder)
.map(Some)
.map_err(<A::Error as de::Error>::custom)
}
Some(
"strict_schedule_boundaries"
| "record_host_inputs"
| "guest_may_inherit_a_terminal"
| "in_guest_site_patching_off"
| "in_guest_refuses_host_timed_producers"
| "in_guest_signal_delivery"
| "annotated_priority_replay"
| "target_timeslice_syscalls_only"
| "futex_wake_yields"
| "cap_preemption_charge"
| "replaying"
| "signal_delivery_check_fatal"
| "container_procfs"
| "notice_host_network_abstract_binds"
| "replay_edited_preemptions"
| "lenient_replay"
| "eager_lone_preemptions"
| "replay_continue_fairly"
| "strict_binder"
| "rewrite_exclusives_in_memory"
| "rewrite_exclusives_overlay_requested"
| "count_store_exclusives"
| "stacktrace_at_schedule_positions"
| "untrap_passthrough_syscalls",
) => seed.deserialize(BoolDeserializer::new(false)).map(Some),
Some("rewrite_exclusives_overlay" | "rewrite_exclusives_unmarked") => seed
.deserialize(serde_json::Value::Array(Vec::new()))
.map(Some)
.map_err(<A::Error as de::Error>::custom),
Some(
"in_guest_reserved_signals"
| "access_trace_from"
| "watch_from"
| "chaos_instruction_offset",
) => seed.deserialize(U64Deserializer::new(0)).map(Some),
Some("watch") => seed
.deserialize(serde_json::Value::Array(Vec::new()))
.map(Some)
.map_err(<A::Error as de::Error>::custom),
Some("signal_state_copy") => {
seed.deserialize(BoolDeserializer::new(true)).map(Some)
}
Some(
"in_guest_detlog_forward_policy"
| "launch_image"
| "detlog_anon"
| "scheduler_turn_cost"
| "virtual_timeout"
| "pipe_wake_latency"
| "expired_wait_charge"
| "sleep_registration"
| "container_mount_table"
| "mountinfo_mount_namespace"
| "directory_placeholder"
| "work_span_report"
| "signal_at"
| "virtual_cpus"
| "chaos_timeslice_range"
| "chaos_timeslice"
| "access_trace"
| "access_trace_max_records"
| "access_trace_max_bytes"
| "standard_stream_aliases"
| "post_crash_timeslice"
| "property_snapshot",
) => seed
.deserialize(serde_json::Value::Null)
.map(Some)
.map_err(<A::Error as de::Error>::custom),
Some("chaos_timeslice_draw") => {
let slice = serde_json::to_value(super::ChaosTimesliceDraw::Slice)
.map_err(<A::Error as de::Error>::custom)?;
seed.deserialize(slice)
.map(Some)
.map_err(<A::Error as de::Error>::custom)
}
Some("cpu_profile") => {
let v2 = serde_json::to_value(crate::cpu_profile::CpuProfile::X86_64V2)
.map_err(<A::Error as de::Error>::custom)?;
seed.deserialize(v2)
.map(Some)
.map_err(<A::Error as de::Error>::custom)
}
Some("cpu_profile_host" | "cpu_profile_source") => seed
.deserialize(serde_json::Value::Null)
.map(Some)
.map_err(<A::Error as de::Error>::custom),
Some("guest_ids") => {
let namespace = serde_json::to_value(crate::pid::GuestIds::Namespace)
.map_err(<A::Error as de::Error>::custom)?;
seed.deserialize(namespace)
.map(Some)
.map_err(<A::Error as de::Error>::custom)
}
Some("inherited_seccomp") => {
let unknown = serde_json::to_value(super::InheritedSeccomp::Unknown)
.map_err(<A::Error as de::Error>::custom)?;
seed.deserialize(unknown)
.map(Some)
.map_err(<A::Error as de::Error>::custom)
}
_ => self.inner.next_element_seed(seed),
}
}
}
fn config_field_order() -> serde_json::Result<Vec<String>> {
let config = environment_free_config().map_err(<serde_json::Error as de::Error>::custom)?;
let json = serde_json::to_string(&config)?;
Ok(serde_json::from_str::<KeyOrder>(&json)?.0)
}
fn environment_free_config() -> Result<Config, clap::Error> {
use clap::CommandFactory;
use clap::FromArgMatches;
let matches = Config::command()
.mut_args(|arg| arg.env(None::<&'static str>))
.try_get_matches_from(["config-field-order"])?;
Config::from_arg_matches(&matches)
}
pub(super) struct KeyOrder(pub(super) Vec<String>);
impl<'de> Deserialize<'de> for KeyOrder {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct KeyOrderVisitor;
impl<'de> Visitor<'de> for KeyOrderVisitor {
type Value = KeyOrder;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a JSON object")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<KeyOrder, A::Error> {
let mut keys = Vec::new();
while let Some(key) = map.next_key::<String>()? {
map.next_value::<IgnoredAny>()?;
keys.push(key);
}
Ok(KeyOrder(keys))
}
}
deserializer.deserialize_map(KeyOrderVisitor)
}
}
pub(super) struct ConfigSerializer<'c, S> {
pub(super) inner: S,
pub(super) config: &'c Config,
}
pub(super) struct ConfigFields<'c, S> {
inner: S,
config: &'c Config,
wrote_backend_keys: bool,
}
fn not_a_config<E: serde::ser::Error>() -> E {
E::custom("the legacy backend JSON encoding applies only to a Detcore Config")
}
impl<'c, S: Serializer> Serializer for ConfigSerializer<'c, S> {
type Ok = S::Ok;
type Error = S::Error;
type SerializeSeq = Impossible<S::Ok, S::Error>;
type SerializeTuple = Impossible<S::Ok, S::Error>;
type SerializeTupleStruct = Impossible<S::Ok, S::Error>;
type SerializeTupleVariant = Impossible<S::Ok, S::Error>;
type SerializeMap = Impossible<S::Ok, S::Error>;
type SerializeStruct = ConfigFields<'c, S::SerializeStruct>;
type SerializeStructVariant = Impossible<S::Ok, S::Error>;
fn is_human_readable(&self) -> bool {
self.inner.is_human_readable()
}
fn serialize_struct(
self,
name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct, S::Error> {
let len = len + legacy_backend_keys(self.config).len() - 2;
Ok(ConfigFields {
inner: self.inner.serialize_struct(name, len)?,
config: self.config,
wrote_backend_keys: false,
})
}
fn serialize_bool(self, _: bool) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_i8(self, _: i8) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_i16(self, _: i16) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_i32(self, _: i32) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_i64(self, _: i64) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_u8(self, _: u8) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_u16(self, _: u16) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_u32(self, _: u32) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_u64(self, _: u64) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_f32(self, _: f32) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_f64(self, _: f64) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_char(self, _: char) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_str(self, _: &str) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_bytes(self, _: &[u8]) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_none(self) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_some<T: ?Sized + Serialize>(self, _: &T) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_unit(self) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_unit_struct(self, _: &'static str) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_unit_variant(
self,
_: &'static str,
_: u32,
_: &'static str,
) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_newtype_struct<T: ?Sized + Serialize>(
self,
_: &'static str,
_: &T,
) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_newtype_variant<T: ?Sized + Serialize>(
self,
_: &'static str,
_: u32,
_: &'static str,
_: &T,
) -> Result<S::Ok, S::Error> {
Err(not_a_config())
}
fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, S::Error> {
Err(not_a_config())
}
fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, S::Error> {
Err(not_a_config())
}
fn serialize_tuple_struct(
self,
_: &'static str,
_: usize,
) -> Result<Self::SerializeTupleStruct, S::Error> {
Err(not_a_config())
}
fn serialize_tuple_variant(
self,
_: &'static str,
_: u32,
_: &'static str,
_: usize,
) -> Result<Self::SerializeTupleVariant, S::Error> {
Err(not_a_config())
}
fn serialize_map(self, _: Option<usize>) -> Result<Self::SerializeMap, S::Error> {
Err(not_a_config())
}
fn serialize_struct_variant(
self,
_: &'static str,
_: u32,
_: &'static str,
_: usize,
) -> Result<Self::SerializeStructVariant, S::Error> {
Err(not_a_config())
}
}
impl<S: SerializeStruct> SerializeStruct for ConfigFields<'_, S> {
type Ok = S::Ok;
type Error = S::Error;
fn serialize_field<T: ?Sized + Serialize>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), S::Error> {
match key {
"backend" => {
for (legacy_key, legacy_value) in legacy_backend_keys(self.config) {
self.inner.serialize_field(legacy_key, &legacy_value)?;
}
self.wrote_backend_keys = true;
Ok(())
}
"strict_schedule_boundaries"
| "record_host_inputs"
| "guest_may_inherit_a_terminal"
| "in_guest_detlog_forward_policy"
| "in_guest_site_patching_off"
| "in_guest_reserved_signals"
| "in_guest_refuses_host_timed_producers"
| "launch_image"
| "target_timeslice_syscalls_only"
| "futex_wake_yields"
| "pipe_wake_latency"
| "expired_wait_charge"
| "sleep_registration"
| "replaying"
| "scheduler_turn_cost"
| "cap_preemption_charge"
| "virtual_timeout"
| "inherited_seccomp"
| "cpu_profile"
| "cpu_profile_host"
| "cpu_profile_source"
| "signal_state_copy"
| "container_mount_table"
| "mountinfo_mount_namespace"
| "directory_placeholder"
| "container_procfs"
| "signal_delivery_check_fatal"
| "strict_binder"
| "work_span_report"
| "signal_at"
| "post_crash_timeslice"
| "in_guest_signal_delivery"
| "annotated_priority_replay"
| "virtual_cpus"
| "notice_host_network_abstract_binds"
| "replay_edited_preemptions"
| "lenient_replay"
| "eager_lone_preemptions"
| "chaos_timeslice_range"
| "chaos_timeslice_draw"
| "chaos_timeslice"
| "guest_ids"
| "detlog_anon"
| "standard_stream_aliases"
| "rewrite_exclusives_unmarked" => Ok(()),
"access_trace"
| "access_trace_from"
| "access_trace_max_records"
| "access_trace_max_bytes"
| "rewrite_exclusives_in_memory"
| "rewrite_exclusives_overlay"
| "rewrite_exclusives_overlay_requested"
| "count_store_exclusives"
| "stacktrace_at_schedule_positions"
| "property_snapshot"
| "watch"
| "watch_from"
| "chaos_instruction_offset"
| "untrap_passthrough_syscalls" => Ok(()),
"replay_continue_fairly" => Ok(()),
_ => self.inner.serialize_field(key, value),
}
}
fn skip_field(&mut self, key: &'static str) -> Result<(), S::Error> {
self.inner.skip_field(key)
}
fn end(self) -> Result<S::Ok, S::Error> {
if !self.wrote_backend_keys {
return Err(S::Error::custom(
"Config serialized no `backend` field to replace with the legacy backend keys",
));
}
self.inner.end()
}
}
}
#[cfg(test)]
mod tests {
use super::parse_post_crash_timeslice;
#[test]
fn a_post_crash_bound_is_refused_where_it_would_not_take_effect() {
let nz = std::num::NonZeroU64::new;
let config = |bound: u64, max: Option<u64>, sequentialize: bool| super::Config {
post_crash_timeslice: nz(bound),
max_timeslice: max.and_then(nz),
sequentialize_threads: sequentialize,
..Default::default()
};
assert_eq!(
config(200, Some(100), true).post_crash_timeslice_refusal(),
None
);
assert_eq!(
super::Config::default().post_crash_timeslice_refusal(),
None,
"not set"
);
for (max, sequentialize, why) in [
(Some(200), true, "not above --max-timeslice=200"),
(Some(300), true, "not above --max-timeslice=300"),
(None, true, "needs a --max-timeslice"),
(Some(100), false, "needs sequentialized threads"),
] {
let refusal = config(200, max, sequentialize)
.post_crash_timeslice_refusal()
.unwrap();
assert!(refusal.contains(why), "{refusal}");
}
}
#[test]
fn post_crash_timeslice_parses_off_default_and_bounds() {
assert_eq!(parse_post_crash_timeslice("off").unwrap(), None);
assert_eq!(
parse_post_crash_timeslice("default").unwrap(),
std::num::NonZeroU64::new(super::DEFAULT_MAX_TIMESLICE)
);
assert_eq!(
parse_post_crash_timeslice("5000000").unwrap(),
std::num::NonZeroU64::new(5_000_000)
);
for bad in ["0", "5", "disabled", "fast"] {
assert!(parse_post_crash_timeslice(bad).is_err(), "{bad}");
}
}
use super::*;
fn range_max(config: &Config) -> NonZeroU64 {
config.chaos_timeslice_range.unwrap().max
}
#[test]
fn a_chaos_timeslice_range_is_min_to_max_nanoseconds_drawn_log_uniformly() {
let range: TimesliceRange = "1000..1000000000".parse().unwrap();
assert_eq!((range.min.get(), range.max.get()), (1_000, 1_000_000_000));
assert_eq!(range.to_string(), "1000..1000000000");
assert_eq!("10..10".parse::<TimesliceRange>().unwrap().max.get(), 10);
for refused in ["1000", "9..1000", "2000..1000", "a..b", "1000..", "..1000"] {
assert!(refused.parse::<TimesliceRange>().is_err(), "{refused}");
}
assert!(
Config::try_parse_from(["config", "--chaos-timeslice-range=1000..2000"]).is_err(),
"a range without --chaos was accepted"
);
let config =
Config::try_parse_from(["config", "--chaos", "--chaos-timeslice-range=1000..2000"])
.unwrap();
assert_eq!(
config.chaos_timeslice_range,
Some("1000..2000".parse().unwrap())
);
assert!(
Config::try_parse_from([
"config",
"--chaos",
"--chaos-timeslice-range=1000..2000",
"--target-timeslice=1000",
])
.is_err(),
"a range beside --target-timeslice was accepted"
);
let mut resolved = config.clone();
resolved.max_timeslice = Some(range_max(&config));
let rendered = resolved.to_string();
assert!(
rendered.contains(" --chaos-timeslice-range=1000..2000"),
"{rendered}"
);
assert!(!rendered.contains("--max-timeslice"), "{rendered}");
let reparsed = Config::parse_from(
std::iter::once("detcore".to_string())
.chain(rendered.split_whitespace().map(String::from)),
);
assert_eq!(reparsed.chaos_timeslice_range, config.chaos_timeslice_range);
assert_eq!(
serde_json::to_value(config.chaos_timeslice_range).unwrap(),
"1000..2000"
);
assert!(serde_json::from_str::<TimesliceRange>("\"2000..1000\"").is_err());
assert_eq!(config.chaos_timeslice_draw, ChaosTimesliceDraw::Slice);
assert_eq!(config.chaos_timeslice, None);
let config = Config::try_parse_from([
"config",
"--chaos",
"--chaos-timeslice-range=1000..2000",
"--chaos-timeslice-draw=run",
])
.unwrap();
assert_eq!(config.chaos_timeslice_draw, ChaosTimesliceDraw::Run);
let bare =
Config::try_parse_from(["config", "--chaos", "--chaos-timeslice-draw=run"]).unwrap();
assert_eq!(bare.chaos_timeslice_draw, ChaosTimesliceDraw::Run);
assert_eq!(
bare.chaos_timeslice_range, None,
"the CLI resolves the range"
);
assert_eq!(
Config::default().chaos_timeslice_draw,
ChaosTimesliceDraw::Slice
);
for args in [
vec!["config", "--chaos-timeslice-draw=run"],
vec!["config", "--chaos", "--chaos-timeslice-draw=slice"],
vec!["config", "--chaos", "--chaos-timeslice-draw=fixed"],
vec![
"config",
"--chaos",
"--chaos-timeslice-draw=run",
"--target-timeslice=1000",
],
] {
assert!(Config::try_parse_from(&args).is_err(), "{args:?}");
}
let rendered = bare.to_string();
assert!(
rendered.contains(" --chaos-timeslice-draw=run"),
"{rendered}"
);
assert!(!rendered.contains("--chaos-timeslice-range"), "{rendered}");
let reparsed =
Config::parse_from(std::iter::once("detcore").chain(rendered.split_whitespace()));
assert_eq!(reparsed.chaos_timeslice_draw, ChaosTimesliceDraw::Run);
assert_eq!(reparsed.chaos_timeslice_range, None);
assert_eq!(
RECOMMENDED_CHAOS_TIMESLICE_RANGE,
"1000..200000000".parse().unwrap()
);
let command = <Config as clap::CommandFactory>::command();
for id in ["chaos", "chaos_timeslice_draw"] {
let text = command
.get_arguments()
.find(|arg| arg.get_id() == id)
.unwrap()
.get_long_help()
.unwrap()
.to_string();
assert!(
text.contains(&RECOMMENDED_CHAOS_TIMESLICE_RANGE.to_string()),
"{text}"
);
assert!(text.contains("time limits"), "{text}");
}
let mut drawn = config.clone();
drawn.max_timeslice = NonZeroU64::new(1234);
drawn.chaos_timeslice = NonZeroU64::new(1234);
let rendered = drawn.to_string();
assert!(
rendered.contains(" --chaos-timeslice-range=1000..2000 --chaos-timeslice-draw=run"),
"{rendered}"
);
assert!(!rendered.contains("--max-timeslice"), "{rendered}");
let reparsed = Config::parse_from(
std::iter::once("detcore".to_string())
.chain(rendered.split_whitespace().map(String::from)),
);
assert_eq!(reparsed.chaos_timeslice_range, config.chaos_timeslice_range);
assert_eq!(reparsed.chaos_timeslice_draw, ChaosTimesliceDraw::Run);
for k in 0..=6 {
let expected = 10f64.powi(3 + k);
let point = range.log_uniform(f64::from(k) / 6.0);
assert!((point / expected - 1.0).abs() < 1e-9, "{k}: {point}");
}
let point: TimesliceRange = "4321..4321".parse().unwrap();
assert_eq!(point.log_uniform(0.7), 4321.0);
}
#[test]
fn only_a_chaos_instruction_offset_needs_a_stop_at_every_slice_end() {
let mut config = Config::default();
assert!(!config.slice_ends_need_a_stop());
config.chaos_instruction_offset = 8;
assert!(!config.slice_ends_need_a_stop());
config.chaos = true;
assert!(config.slice_ends_need_a_stop());
config.chaos_instruction_offset = 0;
assert!(!config.slice_ends_need_a_stop());
}
#[test]
fn split_signal_facts_equal_their_former_bundle_on_every_backend() {
let backends = [
("ptrace", BackendCapabilities::PTRACE, true),
("e9patch", BackendCapabilities::E9PATCH, true),
("liteinst", BackendCapabilities::LITEINST_IN_GUEST, false),
("sabre", BackendCapabilities::SABRE, false),
("dbt", BackendCapabilities::DBT, false),
("kvm", BackendCapabilities::KVM, false),
("unprepared", DEFAULT_BACKEND_CAPABILITIES, false),
];
for (name, backend, expected) in backends {
assert_eq!(
backend.supports_blocked_wait_signal_interruption, expected,
"{name}"
);
assert_eq!(backend.kernel_signal_state_is_guests, expected, "{name}");
assert_eq!(
backend.kernel_signal_targets_are_predictable, expected,
"{name}"
);
assert_eq!(
backend.host_task_reads_reach_guest_threads, expected,
"{name}"
);
assert_eq!(backend.host_timed_signals_are_physical, expected, "{name}");
let mut flipped = backend;
flipped.supports_blocked_wait_signal_interruption = !expected;
flipped.kernel_signal_state_is_guests = !expected;
flipped.kernel_signal_targets_are_predictable = !expected;
flipped.host_task_reads_reach_guest_threads = !expected;
flipped.host_timed_signals_are_physical = !expected;
let mut toggled = backend;
set_kernel_signal_facts(&mut toggled, !expected);
assert_eq!(toggled, flipped, "{name}");
set_kernel_signal_facts(&mut toggled, expected);
assert_eq!(toggled, backend, "{name}");
for sequentialize_threads in [false, true] {
let cfg = Config {
sequentialize_threads,
backend,
..Config::default()
};
assert_eq!(
cfg.models_signal_targets(),
sequentialize_threads && expected,
"{name}, sequentialize_threads={sequentialize_threads}"
);
}
}
}
#[test]
fn default_epoch_is_2026() {
assert_eq!(DEFAULT_EPOCH_STR, "2026-01-01T00:00:00Z");
let epoch = DEFAULT_EPOCH_STR.parse::<DateTime<Utc>>().unwrap();
assert_eq!(epoch.timestamp(), 1_767_225_600);
}
#[test]
fn resolved_epoch_is_serialized_as_an_exact_config_input() {
let epoch = "2000-12-31T23:59:59.123456789Z"
.parse::<DateTime<Utc>>()
.unwrap();
let config = Config {
epoch,
..Config::default()
};
let encoded = serde_json::to_value(&config).unwrap();
assert_eq!(
encoded["epoch"],
serde_json::json!("2000-12-31T23:59:59.123456789Z")
);
let decoded: Config = serde_json::from_value(encoded).unwrap();
assert_eq!(decoded.epoch, epoch);
}
#[test]
fn default_backend_capabilities_match_instrumented_backends() {
let config = Config::default();
assert_eq!(config.backend, DEFAULT_BACKEND_CAPABILITIES);
assert!(!config.backend.reports_physical_process_exits);
assert!(config.backend.tracks_process_children);
assert!(config.backend.runs_exit_robust_list);
assert!(!config.backend.requires_thread_directed_process_signals);
assert!(config.backend.supports_parked_write_signal_interruption);
assert!(!config.sequentialize_threads);
assert!(
legacy_backend_keys(&config).contains(&("kvm_shared_dequeue_timers", false)),
"the default configuration must not write a controlled-run legacy key"
);
assert!(!config.backend.supports_blocked_wait_signal_interruption);
assert!(!config.backend.kernel_signal_state_is_guests);
assert!(!config.backend.kernel_signal_targets_are_predictable);
assert!(!config.backend.host_task_reads_reach_guest_threads);
assert!(!config.backend.host_timed_signals_are_physical);
assert!(!config.backend.delivers_preemption_timer_events);
assert!(!config.backend.runs_guest_code_between_injections);
assert!(config.backend.rcb_clock_contract.is_none());
assert_eq!(config.rcb_clock_claim, RcbClockClaim::Unset);
assert!(!config.guest_may_inherit_a_terminal);
assert!(config.in_guest_detlog_forward_policy.is_none());
assert!(!config.in_guest_site_patching_off);
assert_eq!(config.in_guest_reserved_signals, 0);
assert!(!config.reserves_in_guest_signal(libc::SIGSYS.into()));
assert!(!config.in_guest_refuses_host_timed_producers);
assert!(!config.in_guest_signal_delivery);
assert!(config.launch_image.is_none());
}
#[test]
fn a_config_without_backend_capabilities_deserializes_as_ptrace() {
let mut encoded = serde_json::to_value(Config::default()).unwrap();
let fields = encoded.as_object_mut().unwrap();
assert!(fields.remove("backend").is_some());
assert!(!fields.contains_key("shared_dequeue_timers"));
let decoded: Config = serde_json::from_value(encoded).unwrap();
assert_eq!(decoded.backend, DEFAULT_BACKEND_CAPABILITIES);
}
#[test]
fn a_saved_shared_dequeue_timers_field_is_ignored() {
let baseline = serde_json::to_string(&Config::default()).unwrap();
for extra in [
r#""shared_dequeue_timers":false"#,
r#""shared_dequeue_timers":true"#,
r#""shared_dequeue_timers":"yes""#,
r#""shared_dequeue_timers":true,"shared_dequeue_timers":false"#,
] {
let edited = baseline.replacen('{', &format!("{{{extra},"), 1);
let decoded: Config = serde_json::from_str(&edited).unwrap();
assert_eq!(
serde_json::to_string(&decoded).unwrap(),
baseline,
"{edited}"
);
}
}
fn ptrace_without_exit_transitions() -> BackendCapabilities {
let mut backend = BackendCapabilities::PTRACE;
backend.runs_exit_robust_list = false;
backend.supports_parked_write_signal_interruption = false;
backend
}
fn legacy_expressible(mut backend: BackendCapabilities) -> BackendCapabilities {
backend.process_exits_complete_asynchronously = false;
backend.virtualizes_guest_sigalrm = false;
set_kernel_signal_facts(&mut backend, false);
backend.delivers_preemption_timer_events = false;
backend.runs_guest_code_between_injections = false;
backend.reports_sigreturns = false;
backend.kernel_never_walks_robust_lists = false;
backend.provides_guest_backtraces = true;
backend.places_orphans = false;
backend.publishable_parent_death_signals = 0;
backend.reports_kernel_child_exit_signals = backend.reports_child_exit_publication;
backend.rediscovers_descriptors_after_exec = backend.tool_shares_guest_descriptor_table;
backend.promotes_open_files_before_native_lifecycle =
backend.requires_thread_directed_process_signals;
backend.loopback_pollers_yield_to_peers = backend.tool_shares_guest_descriptor_table;
backend.hardware_watchpoints = 0;
backend.rcb_clock_contract = None;
backend
}
#[test]
fn legacy_backend_json_round_trips_every_backend_capabilities_constant() {
for (name, backend) in [
("PTRACE", BackendCapabilities::PTRACE),
("E9PATCH", BackendCapabilities::E9PATCH),
(
"ptrace without exit transitions",
ptrace_without_exit_transitions(),
),
("LITEINST_IN_GUEST", BackendCapabilities::LITEINST_IN_GUEST),
("SABRE", BackendCapabilities::SABRE),
("DBT", BackendCapabilities::DBT),
("KVM", BackendCapabilities::KVM),
] {
for sequentialize_threads in [false, true] {
let sent = Config {
backend,
sequentialize_threads,
cpu_profile: crate::cpu_profile::CpuProfile::X86_64V2,
..Config::default()
};
let json = to_legacy_backend_json(&sent).unwrap();
let received = from_legacy_backend_json(&json).unwrap();
assert_eq!(received.backend, legacy_expressible(backend), "{name}");
assert_eq!(
received.sequentialize_threads, sequentialize_threads,
"{name}"
);
assert_controlled_key(&json, &backend, sequentialize_threads, name);
let expressible = Config {
backend: legacy_expressible(backend),
..sent.clone()
};
assert_eq!(
serde_json::to_string(&received).unwrap(),
serde_json::to_string(&expressible).unwrap(),
"{name}"
);
assert_eq!(to_legacy_backend_json(&received).unwrap(), json, "{name}");
assert_controlled_key_is_checked(&json, &sent, name);
}
}
}
#[test]
fn backend_config_json_preserves_every_backend_and_representable_bytes() {
for (name, backend, needs_envelope) in [
("PTRACE", BackendCapabilities::PTRACE, true),
("E9PATCH", BackendCapabilities::E9PATCH, true),
(
"LITEINST_IN_GUEST",
BackendCapabilities::LITEINST_IN_GUEST,
true,
),
("SABRE", BackendCapabilities::SABRE, true),
("DBT", BackendCapabilities::DBT, true),
("KVM", BackendCapabilities::KVM, true),
] {
for sequentialize_threads in [false, true] {
let sent = Config {
backend,
sequentialize_threads,
cpu_profile: crate::cpu_profile::CpuProfile::X86_64V2,
..Config::default()
};
let legacy = to_legacy_backend_json(&sent).unwrap();
let encoded = encode_backend_config_json(legacy.clone(), backend).unwrap();
assert_eq!(encoded != legacy, needs_envelope, "{name}");
assert_eq!(
from_legacy_backend_json(&encoded).is_err(),
needs_envelope,
"{name}: an envelope must not be accepted as a legacy config"
);
let received = decode_backend_config_json(&encoded).unwrap();
assert_eq!(received.backend, backend, "{name}");
assert_eq!(
serde_json::to_string(&received).unwrap(),
serde_json::to_string(&sent).unwrap(),
"{name}"
);
}
}
}
#[test]
fn backend_config_json_round_trips_each_independent_capability() {
let baseline = serde_json::to_value(BackendCapabilities::DBT).unwrap();
for (name, value) in baseline.as_object().unwrap() {
let mut edited = baseline.clone();
edited[name] = match name.as_str() {
"hardware_watchpoints" => serde_json::Value::from(1u8),
"publishable_parent_death_signals" => serde_json::Value::from(
BackendCapabilities::KVM.publishable_parent_death_signals,
),
"rcb_clock_contract" => {
assert!(value.is_null(), "DBT states no RCB clock contract");
serde_json::to_value(BackendCapabilities::PTRACE.rcb_clock_contract).unwrap()
}
_ => serde_json::Value::Bool(!value.as_bool().unwrap()),
};
let backend = serde_json::from_value(edited).unwrap();
let sent = Config {
backend,
..Config::default()
};
let legacy = to_legacy_backend_json(&sent).unwrap();
let encoded = encode_backend_config_json(legacy, backend).unwrap();
let received = decode_backend_config_json(&encoded).unwrap();
assert_eq!(received.backend, backend, "{name}");
}
}
#[test]
fn every_backend_constant_states_a_listed_rcb_clock_contract() {
use reverie::RcbClockContract;
const RCB_CLOCK_CONTRACTS: [Option<RcbClockContract>; 2] = [
None,
Some(RcbClockContract::PerfCounterOnTargetThreadUserOnly),
];
for backend in [
BackendCapabilities::PTRACE,
BackendCapabilities::E9PATCH,
BackendCapabilities::LITEINST_IN_GUEST,
BackendCapabilities::SABRE,
BackendCapabilities::DBT,
BackendCapabilities::KVM,
] {
assert!(
RCB_CLOCK_CONTRACTS.contains(&backend.rcb_clock_contract),
"{backend:?}"
);
}
assert_eq!(
BackendCapabilities::PTRACE.rcb_clock_contract,
Some(RcbClockContract::PerfCounterOnTargetThreadUserOnly)
);
let sent = Config {
backend: BackendCapabilities::LITEINST_IN_GUEST,
..Config::default()
};
let encoded =
encode_backend_config_json(to_legacy_backend_json(&sent).unwrap(), sent.backend)
.unwrap();
let mut unnamed: serde_json::Value = serde_json::from_str(&encoded).unwrap();
unnamed["backend"]["rcb_clock_contract"] = "PerfCounterOnSomeOtherThread".into();
assert!(decode_backend_config_json(&unnamed.to_string()).is_err());
}
#[test]
fn backend_config_json_requires_each_typed_capability_once() {
let sent = Config {
backend: BackendCapabilities::LITEINST_IN_GUEST,
..Config::default()
};
let encoded =
encode_backend_config_json(to_legacy_backend_json(&sent).unwrap(), sent.backend)
.unwrap();
let envelope: serde_json::Value = serde_json::from_str(&encoded).unwrap();
for (name, value) in envelope["backend"].as_object().unwrap() {
let mut missing = envelope.clone();
missing["backend"].as_object_mut().unwrap().remove(name);
assert!(
decode_backend_config_json(&missing.to_string()).is_err(),
"missing {name}"
);
let backend = serde_json::to_string(&sent.backend).unwrap();
let duplicate = backend.replacen('{', &format!("{{\"{name}\":{value},"), 1);
let duplicate = encoded.replace(&backend, &duplicate);
assert_ne!(duplicate, encoded);
assert!(
decode_backend_config_json(&duplicate).is_err(),
"duplicate {name}"
);
}
}
#[test]
fn backend_config_json_keeps_legacy_object_and_array_semantics() {
let legacy = to_legacy_backend_json(&Config::default()).unwrap();
let unknown_duplicates = legacy.replacen(
'{',
r#"{"unrecognized":1,"unrecognized":null,"backend":null,"backend":true,"dbt_config_version":null,"dbt_config_version":2,"#,
1,
);
let known_duplicate = legacy.replacen('{', r#"{"seed":1,"#, 1);
let mistyped = legacy.replacen("\"backend_is_kvm\":false", "\"backend_is_kvm\":null", 1);
assert_ne!(mistyped, legacy);
for json in [
legacy.clone(),
positional(&legacy),
unknown_duplicates,
known_duplicate,
mistyped,
format!("{legacy} trailing"),
"[]".to_owned(),
] {
let old = from_legacy_backend_json(&json);
let new = decode_backend_config_json(&json);
match (old, new) {
(Ok(old), Ok(new)) => assert_eq!(
serde_json::to_string(&old).unwrap(),
serde_json::to_string(&new).unwrap()
),
(Err(_), Err(_)) => {}
_ => panic!("legacy parse outcome changed for {json}"),
}
}
}
fn assert_controlled_key_is_checked(json: &str, sent: &Config, name: &str) {
let controlled = sent.backend.provides_process_signal_control && sent.sequentialize_threads;
let written = format!("\"kvm_shared_dequeue_timers\":{controlled}");
assert_eq!(json.matches(&written).count(), 1, "{name}");
for value in [None, Some(false), Some(true)] {
let edited = match value {
None => json.replacen(&format!(",{written}"), "", 1),
Some(value) => json.replacen(
&written,
&format!("\"kvm_shared_dequeue_timers\":{value}"),
1,
),
};
assert_eq!(
edited.contains("kvm_shared_dequeue_timers"),
value.is_some(),
"{name} {value:?}"
);
let case = format!(
"{name} sequentialize_threads={} key={value:?}",
sent.sequentialize_threads
);
match from_legacy_backend_json(&edited) {
Ok(received) => {
assert_eq!(value.unwrap_or(false), controlled, "{case} was accepted");
let expressible = Config {
backend: legacy_expressible(sent.backend),
..sent.clone()
};
assert_eq!(
serde_json::to_string(&received).unwrap(),
serde_json::to_string(&expressible).unwrap(),
"{case}"
);
}
Err(error) => {
assert_ne!(value.unwrap_or(false), controlled, "{case}: {error}");
assert!(
error.to_string().contains("kvm_shared_dequeue_timers"),
"{case}: {error}"
);
}
}
}
}
#[test]
fn a_controlled_key_that_contradicts_the_capabilities_fails_the_parse() {
let kvm = Config {
backend: BackendCapabilities::KVM,
sequentialize_threads: true,
..Config::default()
};
let kvm_json = to_legacy_backend_json(&kvm).unwrap();
assert!(from_legacy_backend_json(&kvm_json).is_ok());
let dbt = Config {
backend: BackendCapabilities::DBT,
sequentialize_threads: true,
..Config::default()
};
let dbt_json = to_legacy_backend_json(&dbt).unwrap();
assert!(from_legacy_backend_json(&dbt_json).is_ok());
for edited in [
kvm_json.replacen(
r#""kvm_shared_dequeue_timers":true"#,
r#""kvm_shared_dequeue_timers":false"#,
1,
),
kvm_json.replacen(r#","kvm_shared_dequeue_timers":true"#, "", 1),
dbt_json.replacen(
r#""kvm_shared_dequeue_timers":false"#,
r#""kvm_shared_dequeue_timers":true"#,
1,
),
to_legacy_backend_json(&Config {
sequentialize_threads: false,
..kvm.clone()
})
.unwrap()
.replacen(
r#""kvm_shared_dequeue_timers":false"#,
r#""kvm_shared_dequeue_timers":true"#,
1,
),
] {
assert_ne!(edited, kvm_json);
assert_ne!(edited, dbt_json);
let error = from_legacy_backend_json(&edited).unwrap_err();
assert!(
error.to_string().contains("kvm_shared_dequeue_timers"),
"{error}"
);
}
}
#[test]
fn legacy_backend_keys_decode_as_the_fields_they_were() {
let ptrace_json = to_legacy_backend_json(&Config::default()).unwrap();
let ptrace: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(&ptrace_json).unwrap();
let keys = legacy_backend_keys(&Config::default());
let mut absent = ptrace.clone();
for (key, _) in keys {
assert!(absent.remove(key).is_some(), "{key}");
}
let decoded = from_legacy_backend_json(&serde_json::to_string(&absent).unwrap()).unwrap();
let legacy_ptrace = legacy_expressible(BackendCapabilities::PTRACE);
assert_eq!(decoded.backend, legacy_ptrace);
let unflipped =
serde_json::to_string(&from_legacy_backend_json(&ptrace_json).unwrap()).unwrap();
assert_eq!(serde_json::to_string(&decoded).unwrap(), unflipped);
for (key, ptrace_value) in keys {
let mut expected = legacy_ptrace;
match key {
"cpuid_virtualized_by_backend" => {
let mut flipped = ptrace.clone();
flipped.insert(key.to_owned(), serde_json::Value::Bool(!ptrace_value));
let error = from_legacy_backend_json(&serde_json::to_string(&flipped).unwrap())
.unwrap_err();
assert!(error.to_string().contains(key), "{error}");
continue;
}
"syscall_clobbers_virtualized_by_backend"
| "backend_supports_madvise"
| "backend_defers_vfork_child_registration" => {
let mut flipped = ptrace.clone();
flipped.insert(key.to_owned(), serde_json::Value::Bool(!ptrace_value));
let decoded =
from_legacy_backend_json(&serde_json::to_string(&flipped).unwrap())
.unwrap();
assert_eq!(serde_json::to_string(&decoded).unwrap(), unflipped, "{key}");
continue;
}
"discover_live_file_metadata" => {
expected.tool_shares_guest_descriptor_table = true;
expected.rediscovers_descriptors_after_exec = true;
expected.loopback_pollers_yield_to_peers = true;
}
"detect_host_clock_futex_timeouts" => {
expected.guest_clock_reads_bypass_backend = true
}
"cancel_killed_thread_rpcs" => {
expected.needs_killed_thread_rpc_cancellation = true;
expected.reports_child_exit_publication = false;
expected.reports_kernel_child_exit_signals = false;
}
"backend_reports_physical_process_exits" => {
expected.reports_physical_process_exits = true
}
"backend_tracks_process_children" => expected.tracks_process_children = false,
"backend_runs_exit_robust_list" => expected.runs_exit_robust_list = false,
"backend_requires_thread_directed_process_signals" => {
expected.requires_thread_directed_process_signals = true;
expected.promotes_open_files_before_native_lifecycle = true;
}
"backend_is_kvm" => {
expected.provides_process_signal_control = true;
expected.emulates_child_waits = true;
}
"kvm_shared_dequeue_timers" => {
let mut flipped = ptrace.clone();
flipped.insert(key.to_owned(), serde_json::Value::Bool(!ptrace_value));
assert!(
from_legacy_backend_json(&serde_json::to_string(&flipped).unwrap())
.is_err(),
"{key}"
);
continue;
}
"backend_supports_parked_write_signal_interruption" => {
expected.supports_parked_write_signal_interruption = false
}
"backend_virtualizes_capability_prctls" => {
let mut flipped = ptrace.clone();
flipped.insert(key.to_owned(), serde_json::Value::Bool(!ptrace_value));
let error = from_legacy_backend_json(&serde_json::to_string(&flipped).unwrap())
.unwrap_err();
assert!(error.to_string().contains(key), "{error}");
continue;
}
other => panic!("no expectation for legacy key {other}"),
}
let mut flipped = ptrace.clone();
flipped.insert(key.to_owned(), serde_json::Value::Bool(!ptrace_value));
let decoded =
from_legacy_backend_json(&serde_json::to_string(&flipped).unwrap()).unwrap();
assert_eq!(decoded.backend, expected, "{key}");
assert_ne!(serde_json::to_string(&decoded).unwrap(), unflipped, "{key}");
}
}
fn assert_controlled_key(
json: &str,
backend: &BackendCapabilities,
sequentialize_threads: bool,
name: &str,
) {
let object: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(json).unwrap();
assert_eq!(
object["kvm_shared_dequeue_timers"],
serde_json::Value::Bool(
backend.provides_process_signal_control && sequentialize_threads
),
"{name} sequentialize_threads={sequentialize_threads}"
);
}
#[test]
fn a_legacy_backend_key_of_the_wrong_type_fails_the_parse() {
let json = to_legacy_backend_json(&Config::default()).unwrap();
assert!(from_legacy_backend_json(&json).is_ok());
for (key, value) in legacy_backend_keys(&Config::default()) {
let field = format!("\"{key}\":{value}");
assert_eq!(json.matches(&field).count(), 1, "{field}");
let mistyped = json.replacen(&field, &format!("\"{key}\":0"), 1);
assert!(from_legacy_backend_json(&mistyped).is_err(), "{mistyped}");
let repeated = json.replacen(&field, &format!("{field},{field}"), 1);
assert!(from_legacy_backend_json(&repeated).is_err(), "{repeated}");
}
}
fn ordered_entries(json: &str) -> Vec<(String, serde_json::Value)> {
struct Entries(Vec<(String, serde_json::Value)>);
impl<'de> Deserialize<'de> for Entries {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct EntriesVisitor;
impl<'de> serde::de::Visitor<'de> for EntriesVisitor {
type Value = Entries;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a JSON object")
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Entries, A::Error> {
let mut entries = Vec::new();
while let Some(entry) = map.next_entry()? {
entries.push(entry);
}
Ok(Entries(entries))
}
}
deserializer.deserialize_map(EntriesVisitor)
}
}
serde_json::from_str::<Entries>(json).unwrap().0
}
fn positional(json: &str) -> String {
let values: Vec<serde_json::Value> = ordered_entries(json)
.into_iter()
.map(|(_, value)| value)
.collect();
serde_json::to_string(&values).unwrap()
}
#[test]
fn legacy_positions_are_the_encoded_key_order() {
let names = legacy_backend_keys(&Config::default()).map(|(name, _)| name);
assert_eq!(names, LEGACY_BACKEND_KEY_NAMES);
let fields = serde_json::from_str::<legacy_backend_json::KeyOrder>(
&serde_json::to_string(&Config::default()).unwrap(),
)
.unwrap()
.0;
let mut expected = Vec::new();
for field in &fields {
match field.as_str() {
"backend" => expected.extend(names.map(str::to_owned)),
"strict_schedule_boundaries"
| "record_host_inputs"
| "guest_may_inherit_a_terminal"
| "in_guest_detlog_forward_policy"
| "in_guest_site_patching_off"
| "in_guest_reserved_signals"
| "in_guest_refuses_host_timed_producers"
| "launch_image"
| "target_timeslice_syscalls_only"
| "futex_wake_yields"
| "pipe_wake_latency"
| "expired_wait_charge"
| "sleep_registration"
| "replaying"
| "scheduler_turn_cost"
| "cap_preemption_charge"
| "virtual_timeout"
| "inherited_seccomp"
| "cpu_profile"
| "cpu_profile_host"
| "cpu_profile_source"
| "signal_state_copy"
| "container_mount_table"
| "mountinfo_mount_namespace"
| "directory_placeholder"
| "container_procfs"
| "signal_delivery_check_fatal"
| "strict_binder"
| "work_span_report"
| "signal_at"
| "post_crash_timeslice"
| "in_guest_signal_delivery"
| "annotated_priority_replay"
| "virtual_cpus"
| "notice_host_network_abstract_binds"
| "replay_edited_preemptions"
| "lenient_replay"
| "eager_lone_preemptions"
| "chaos_timeslice_range"
| "chaos_timeslice_draw"
| "chaos_timeslice"
| "guest_ids"
| "detlog_anon"
| "standard_stream_aliases"
| "rewrite_exclusives_unmarked" => {}
"access_trace"
| "access_trace_from"
| "access_trace_max_records"
| "access_trace_max_bytes"
| "rewrite_exclusives_in_memory"
| "rewrite_exclusives_overlay"
| "rewrite_exclusives_overlay_requested"
| "count_store_exclusives"
| "stacktrace_at_schedule_positions"
| "property_snapshot"
| "watch"
| "watch_from"
| "chaos_instruction_offset"
| "untrap_passthrough_syscalls" => {}
"replay_continue_fairly" => {}
other => expected.push(other.to_owned()),
}
}
let encoded = to_legacy_backend_json(&Config::default()).unwrap();
let keys: Vec<String> = ordered_entries(&encoded)
.into_iter()
.map(|(key, _)| key)
.collect();
assert_eq!(keys, expected);
assert!(!fields.iter().any(|field| field == "shared_dequeue_timers"));
assert_eq!(fields.len(), keys.len() + 46);
}
#[test]
fn record_host_inputs_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
record_host_inputs: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("record_host_inputs"), "{json}");
assert!(!from_legacy_backend_json(&json).unwrap().record_host_inputs);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(!from_legacy_backend_json(&array).unwrap().record_host_inputs);
}
#[test]
fn the_unmarked_rewrite_files_never_enter_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
rewrite_exclusives_unmarked: vec!["/lib64/libstdc++.so.6".into()],
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("rewrite_exclusives"), "{json}");
let back = from_legacy_backend_json(&json).unwrap();
assert!(back.rewrite_exclusives_unmarked.is_empty());
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
let back = from_legacy_backend_json(&array).unwrap();
assert!(back.rewrite_exclusives_unmarked.is_empty());
}
#[test]
fn process_exits_complete_asynchronously_never_enters_the_legacy_form() {
let on = Config {
backend: BackendCapabilities::LITEINST_IN_GUEST,
..Config::default()
};
assert!(on.backend.process_exits_complete_asynchronously);
assert!(on.backend.virtualizes_guest_sigalrm);
let off = Config {
backend: legacy_expressible(on.backend),
..on.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(
!json.contains("process_exits_complete_asynchronously"),
"{json}"
);
assert!(!json.contains("virtualizes_guest_sigalrm"), "{json}");
let decoded = from_legacy_backend_json(&json).unwrap();
assert!(!decoded.backend.process_exits_complete_asynchronously);
assert!(!decoded.backend.virtualizes_guest_sigalrm);
let array = positional(&json);
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.backend
.process_exits_complete_asynchronously
);
}
#[test]
fn post_freeze_capabilities_never_enter_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let mut on = off.clone();
set_kernel_signal_facts(&mut on.backend, true);
on.backend.delivers_preemption_timer_events = true;
on.backend.runs_guest_code_between_injections = true;
on.backend.reports_sigreturns = true;
on.backend.kernel_never_walks_robust_lists = true;
on.backend.places_orphans = true;
on.backend.publishable_parent_death_signals =
BackendCapabilities::KVM.publishable_parent_death_signals;
on.backend.rcb_clock_contract = BackendCapabilities::PTRACE.rcb_clock_contract;
assert!(on.backend.rcb_clock_contract.is_some());
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
for key in [
"supports_blocked_wait_signal_interruption",
"kernel_signal_state_is_guests",
"kernel_signal_targets_are_predictable",
"host_task_reads_reach_guest_threads",
"host_timed_signals_are_physical",
"delivers_preemption_timer_events",
"runs_guest_code_between_injections",
"reports_sigreturns",
"kernel_never_walks_robust_lists",
"places_orphans",
"publishable_parent_death_signals",
"rcb_clock_contract",
] {
assert!(!json.contains(key), "{json}");
}
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
for decoded in [&json, &array] {
let backend = from_legacy_backend_json(decoded).unwrap().backend;
assert!(!backend.supports_blocked_wait_signal_interruption);
assert!(!backend.kernel_signal_state_is_guests);
assert!(!backend.kernel_signal_targets_are_predictable);
assert!(!backend.host_task_reads_reach_guest_threads);
assert!(!backend.host_timed_signals_are_physical);
assert!(!backend.delivers_preemption_timer_events);
assert!(!backend.runs_guest_code_between_injections);
assert!(!backend.reports_sigreturns);
assert!(!backend.kernel_never_walks_robust_lists);
assert!(!backend.places_orphans);
assert_eq!(backend.publishable_parent_death_signals, 0);
assert_eq!(backend.rcb_clock_contract, None);
assert_eq!(backend, legacy_expressible(BackendCapabilities::DBT));
}
}
#[test]
fn in_guest_detlog_forward_policy_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
in_guest_detlog_forward_policy: Some("1".to_owned()),
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("in_guest_detlog_forward_policy"), "{json}");
assert!(
from_legacy_backend_json(&json)
.unwrap()
.in_guest_detlog_forward_policy
.is_none()
);
}
#[test]
fn launch_namespace_mounts_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
launch_namespace_mounts: crate::host_input::LaunchNamespaceMounts(vec![
(29, "ext4".to_owned()),
(31, "devtmpfs".to_owned()),
]),
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("launch_namespace_mounts"), "{json}");
assert!(
from_legacy_backend_json(&json)
.unwrap()
.launch_namespace_mounts
.0
.is_empty()
);
let full = serde_json::to_string(&on).unwrap();
assert!(!full.contains("launch_namespace_mounts"), "{full}");
assert!(
serde_json::from_str::<Config>(&full)
.unwrap()
.launch_namespace_mounts
.0
.is_empty()
);
assert_eq!(
format!("{:?}", on.launch_namespace_mounts),
"LaunchNamespaceMounts { mounts: 2 }"
);
}
#[test]
fn launch_image_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
launch_image: Some(LaunchImage {
exe: Some(PathBuf::from("/usr/bin/true")),
launcher: Some(PathBuf::from("/usr/bin/env")),
}),
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("launch_image"), "{json}");
assert!(
from_legacy_backend_json(&json)
.unwrap()
.launch_image
.is_none()
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
from_legacy_backend_json(&array)
.unwrap()
.launch_image
.is_none()
);
}
#[test]
fn in_guest_site_patching_off_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
in_guest_site_patching_off: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("in_guest_site_patching_off"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.in_guest_site_patching_off
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.in_guest_site_patching_off
);
}
#[test]
fn guest_may_inherit_a_terminal_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
guest_may_inherit_a_terminal: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("guest_may_inherit_a_terminal"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.guest_may_inherit_a_terminal
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.guest_may_inherit_a_terminal
);
}
#[test]
fn the_guest_numbering_never_enters_the_legacy_form() {
let namespace = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let chosen = Config {
guest_ids: crate::pid::GuestIds::Chosen {
base: 5000,
refuse_host_ids: true,
},
..namespace.clone()
};
let json = to_legacy_backend_json(&chosen).unwrap();
assert_eq!(json, to_legacy_backend_json(&namespace).unwrap());
assert!(!json.contains("guest_ids"), "{json}");
assert_eq!(
from_legacy_backend_json(&json).unwrap().guest_ids,
crate::pid::GuestIds::Namespace
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert_eq!(
from_legacy_backend_json(&array).unwrap().guest_ids,
crate::pid::GuestIds::Namespace
);
}
#[test]
fn chaos_instruction_offset_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
chaos: true,
chaos_instruction_offset: 16,
..off.clone()
};
let chaos = Config {
chaos: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&chaos).unwrap());
assert!(!json.contains("chaos_instruction_offset"), "{json}");
assert_eq!(
from_legacy_backend_json(&json)
.unwrap()
.chaos_instruction_offset,
0
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert_eq!(
from_legacy_backend_json(&array)
.unwrap()
.chaos_instruction_offset,
0
);
assert!(
!to_legacy_backend_json(&off)
.unwrap()
.contains("chaos_instruction_offset")
);
}
#[test]
fn the_cpu_profile_never_enters_the_legacy_form() {
let v2 = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let v3 = Config {
cpu_profile: crate::cpu_profile::CpuProfile::X86_64V3,
cpu_profile_source: Some(17),
..v2.clone()
};
let json = to_legacy_backend_json(&v3).unwrap();
assert_eq!(json, to_legacy_backend_json(&v2).unwrap());
assert!(!json.contains("cpu_profile"), "{json}");
assert_eq!(
from_legacy_backend_json(&json).unwrap().cpu_profile,
crate::cpu_profile::CpuProfile::X86_64V2
);
assert_eq!(
from_legacy_backend_json(&json).unwrap().cpu_profile_source,
None
);
let wire = bincode::serde::encode_to_vec(&v3, bincode::config::legacy()).unwrap();
let (decoded, _): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(
decoded.cpu_profile,
crate::cpu_profile::CpuProfile::X86_64V3
);
assert_eq!(decoded.cpu_profile_source, Some(17));
}
#[test]
fn inherited_seccomp_never_enters_the_legacy_form() {
use crate::config::InheritedSeccomp;
let unknown = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
assert_eq!(unknown.inherited_seccomp, InheritedSeccomp::Unknown);
let measured = Config {
inherited_seccomp: InheritedSeccomp::Filter(Some(2)),
..unknown.clone()
};
let json = to_legacy_backend_json(&measured).unwrap();
assert_eq!(json, to_legacy_backend_json(&unknown).unwrap());
assert!(!json.contains("inherited_seccomp"), "{json}");
assert_eq!(
from_legacy_backend_json(&json).unwrap().inherited_seccomp,
InheritedSeccomp::Unknown
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert_eq!(
from_legacy_backend_json(&array).unwrap().inherited_seccomp,
InheritedSeccomp::Unknown
);
}
#[test]
fn inherited_seccomp_round_trips_through_reverie_bincode() {
use crate::config::InheritedSeccomp;
for inherited_seccomp in [
InheritedSeccomp::Unknown,
InheritedSeccomp::Disabled,
InheritedSeccomp::Strict,
InheritedSeccomp::Filter(None),
InheritedSeccomp::Filter(Some(3)),
] {
let config = Config {
inherited_seccomp,
..Config::default()
};
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.inherited_seccomp, inherited_seccomp);
assert_eq!(
bincode::serde::encode_to_vec(&decoded, bincode::config::legacy()).unwrap(),
wire
);
}
}
#[test]
fn inherited_seccomp_is_read_from_a_status_file() {
use crate::config::InheritedSeccomp;
let status = |lines: &str| {
InheritedSeccomp::parse(&format!(
"Name:\tguest\nNoNewPrivs:\t1\n{lines}Speculation_Store_Bypass:\tthread vulnerable\n"
))
};
assert_eq!(
status("Seccomp:\t0\nSeccomp_filters:\t0\n"),
InheritedSeccomp::Disabled
);
assert_eq!(
status("Seccomp:\t1\nSeccomp_filters:\t0\n"),
InheritedSeccomp::Strict
);
assert_eq!(
status("Seccomp:\t2\nSeccomp_filters:\t3\n"),
InheritedSeccomp::Filter(Some(3))
);
assert_eq!(status("Seccomp:\t2\n"), InheritedSeccomp::Filter(None));
assert_eq!(status(""), InheritedSeccomp::Unknown);
assert_eq!(status("Seccomp:\t7\n"), InheritedSeccomp::Unknown);
assert_ne!(InheritedSeccomp::measure(), InheritedSeccomp::Unknown);
}
#[test]
fn target_timeslice_syscalls_only_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
target_timeslice: NonZeroU64::new(1_000_000),
..Config::default()
};
let on = Config {
target_timeslice_syscalls_only: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("target_timeslice_syscalls_only"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.target_timeslice_syscalls_only
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.target_timeslice_syscalls_only
);
}
#[test]
fn a_futex_wake_yields_only_when_it_woke_a_waiter() {
let config = Config {
futex_wake_yields: true,
..Config::default()
};
assert!(config.yields_after_futex_wake(1));
assert!(config.yields_after_futex_wake(3));
assert!(!config.yields_after_futex_wake(0));
assert!(!Config::default().futex_wake_yields);
assert!(!Config::default().yields_after_futex_wake(1));
}
#[test]
fn a_futex_wake_yields_under_replay_too() {
let config = Config {
futex_wake_yields: true,
..Config::default()
};
let preemption_replay = Config {
replay_preemptions_from: Some(PathBuf::from("/nonexistent/preemptions.json")),
..config.clone()
};
assert!(preemption_replay.yields_after_futex_wake(1));
assert!(!preemption_replay.yields_after_futex_wake(0));
let schedule_replay = Config {
replay_schedule_from: Some(PathBuf::from("/nonexistent/schedule.json")),
..config
};
assert!(schedule_replay.yields_after_futex_wake(1));
}
#[test]
fn scheduler_turn_charge_refuses_a_scaled_charge_below_one_nanosecond() {
let default = Config::default();
assert_eq!(default.scheduler_turn_charge(), Ok(500_000));
let scaled = Config {
clock_multiplier: Some(0.1),
..Config::default()
};
assert_eq!(scaled.scheduler_turn_charge(), Ok(50_000));
let cost = |cost: u64, multiplier: f64| Config {
scheduler_turn_cost: NonZeroU64::new(cost),
clock_multiplier: Some(multiplier),
..Config::default()
};
assert_eq!(cost(10_000, 0.1).scheduler_turn_charge(), Ok(1_000));
assert_eq!(cost(10, 0.1).scheduler_turn_charge(), Ok(1));
assert!(cost(9, 0.1).scheduler_turn_charge().is_err());
assert!(cost(1, 0.1).scheduler_turn_charge().is_err());
assert_eq!(
cost(MAX_SCHEDULER_TURN_COST, 1.0).scheduler_turn_charge(),
Ok(MAX_SCHEDULER_TURN_COST)
);
assert!(
cost(MAX_SCHEDULER_TURN_COST + 1, 1.0)
.scheduler_turn_charge()
.is_err()
);
assert!(cost(u64::MAX, 1.0).scheduler_turn_charge().is_err());
assert!(
cost(MAX_SCHEDULER_TURN_COST, 1e12)
.scheduler_turn_charge()
.is_err()
);
assert!(
cost(MAX_SCHEDULER_TURN_COST, 9e9)
.scheduler_turn_charge()
.is_err()
);
assert!(cost(1_000_000, 1_001.0).scheduler_turn_charge().is_err());
assert_eq!(
cost(1_000_000, 1_000.0).scheduler_turn_charge(),
Ok(MAX_SCHEDULER_TURN_COST)
);
let message = cost(MAX_SCHEDULER_TURN_COST, 9e9)
.scheduler_turn_charge()
.unwrap_err();
assert!(message.contains("at least 1"), "{message}");
assert!(message.contains("at most 1000000000"), "{message}");
}
#[test]
fn rewrite_exclusives_in_memory_admission_refuses_what_the_cli_refuses() {
let on = Config {
rewrite_exclusives_in_memory: true,
sequentialize_threads: true,
..Config::default()
};
assert_eq!(
on.rewrite_exclusives_in_memory_refusal(false),
Some(RewriteExclusivesRefusal::HostLacksLseAtomics)
);
let concurrent = Config {
sequentialize_threads: false,
..on.clone()
};
assert_eq!(
concurrent.rewrite_exclusives_in_memory_refusal(true),
Some(RewriteExclusivesRefusal::ThreadsNotSequentialized)
);
assert_eq!(on.rewrite_exclusives_in_memory_refusal(true), None);
assert_eq!(
Config::default().rewrite_exclusives_in_memory_refusal(false),
None
);
}
#[test]
fn rewrite_exclusives_in_memory_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
rewrite_exclusives_in_memory: true,
rewrite_exclusives_overlay: vec!["/bin/guest".into()],
rewrite_exclusives_overlay_requested: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("rewrite_exclusives"), "{json}");
let back = from_legacy_backend_json(&json).unwrap();
assert!(!back.rewrite_exclusives_in_memory);
assert!(back.rewrite_exclusives_overlay.is_empty());
assert!(!back.rewrite_exclusives_overlay_requested);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
let back = from_legacy_backend_json(&array).unwrap();
assert!(!back.rewrite_exclusives_in_memory);
assert!(back.rewrite_exclusives_overlay.is_empty());
assert!(!back.rewrite_exclusives_overlay_requested);
}
#[test]
fn rewrite_exclusives_overlay_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
rewrite_exclusives_overlay: vec!["/bin/guest".into(), "/lib/libatomic.so.1".into()],
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("rewrite_exclusives_overlay"), "{json}");
assert!(
from_legacy_backend_json(&json)
.unwrap()
.rewrite_exclusives_overlay
.is_empty()
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
from_legacy_backend_json(&array)
.unwrap()
.rewrite_exclusives_overlay
.is_empty()
);
}
#[test]
fn count_store_exclusives_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
count_store_exclusives: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("count_store_exclusives"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.count_store_exclusives
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.count_store_exclusives
);
}
#[test]
fn untrap_passthrough_syscalls_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
untrap_passthrough_syscalls: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("untrap_passthrough_syscalls"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.untrap_passthrough_syscalls
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.untrap_passthrough_syscalls
);
}
#[test]
fn futex_wake_yields_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
futex_wake_yields: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("futex_wake_yields"), "{json}");
assert!(!from_legacy_backend_json(&json).unwrap().futex_wake_yields);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(!from_legacy_backend_json(&array).unwrap().futex_wake_yields);
}
#[test]
fn scheduler_turn_cost_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
scheduler_turn_cost: NonZeroU64::new(10_000),
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("scheduler_turn_cost"), "{json}");
assert_eq!(
from_legacy_backend_json(&json).unwrap().scheduler_turn_cost,
None
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert_eq!(
from_legacy_backend_json(&array)
.unwrap()
.scheduler_turn_cost,
None
);
}
#[test]
fn virtual_timeout_round_trips_but_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
virtual_timeout: NonZeroU64::new(3_500_000_000),
..off.clone()
};
assert!(
on.to_string().contains(" --virtual-timeout=3500000000"),
"{on}"
);
assert!(!off.to_string().contains("--virtual-timeout"), "{off}");
for config in [&off, &on] {
let wire = bincode::serde::encode_to_vec(config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.virtual_timeout, config.virtual_timeout);
}
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("virtual_timeout"), "{json}");
assert_eq!(
from_legacy_backend_json(&json).unwrap().virtual_timeout,
None
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert_eq!(
from_legacy_backend_json(&array).unwrap().virtual_timeout,
None
);
}
#[test]
fn cap_preemption_charge_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
cap_preemption_charge: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("cap_preemption_charge"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.cap_preemption_charge
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.cap_preemption_charge
);
}
#[test]
fn cap_preemption_charge_is_opt_in_and_round_trips() {
let default = Config::default();
assert!(!default.cap_preemption_charge);
assert!(!default.to_string().contains("--cap-preemption-charge"));
let config = Config::parse_from(["detcore", "--cap-preemption-charge"]);
assert!(config.cap_preemption_charge);
let rendered = config.to_string();
assert!(rendered.contains(" --cap-preemption-charge"), "{rendered}");
let reparsed =
Config::parse_from(std::iter::once("detcore").chain(rendered.split_whitespace()));
assert!(reparsed.cap_preemption_charge);
let json = serde_json::to_string(&config).unwrap();
let back: Config = serde_json::from_str(&json).unwrap();
assert!(back.cap_preemption_charge);
let mut legacy: serde_json::Value = serde_json::to_value(&default).unwrap();
legacy
.as_object_mut()
.unwrap()
.remove("cap_preemption_charge");
let old: Config = serde_json::from_value(legacy).unwrap();
assert!(
!old.cap_preemption_charge,
"a configuration from before the option reads as off"
);
}
#[test]
fn replaying_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
replaying: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("replaying"), "{json}");
assert!(!from_legacy_backend_json(&json).unwrap().replaying);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(!from_legacy_backend_json(&array).unwrap().replaying);
}
#[test]
fn replaying_round_trips_through_reverie_bincode() {
for replaying in [false, true] {
let config = Config {
replaying,
..Config::default()
};
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.replaying, replaying);
assert_eq!(
bincode::serde::encode_to_vec(&decoded, bincode::config::legacy()).unwrap(),
wire
);
}
}
#[test]
fn signal_at_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
signal_at: Some(SignalAt {
turn: 500,
signal: libc::SIGUSR1,
}),
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("signal_at"), "{json}");
assert_eq!(from_legacy_backend_json(&json).unwrap().signal_at, None);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert_eq!(from_legacy_backend_json(&array).unwrap().signal_at, None);
}
#[test]
fn virtual_cpus_never_enter_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
virtual_cpus: NonZeroU32::new(4),
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("virtual_cpus"), "{json}");
assert_eq!(from_legacy_backend_json(&json).unwrap().virtual_cpus, None);
}
#[test]
fn virtual_cpus_parse_from_1_to_128() {
let parse = |count: &str| {
Config::try_parse_from(["detcore".to_owned(), format!("--virtual-cpus={count}")])
};
assert_eq!(parse("1").unwrap().virtual_cpus, NonZeroU32::new(1));
assert_eq!(parse("128").unwrap().virtual_cpus, NonZeroU32::new(128));
for refused in ["0", "129", "-1", "four"] {
let error = parse(refused).unwrap_err().to_string();
assert!(error.contains("from 1 to 128"), "{refused}: {error}");
}
let config = parse("8").unwrap();
assert_eq!(config.virtual_cpu_count(), 8);
assert!(config.to_string().contains(" --virtual-cpus=8"));
assert_eq!(Config::default().virtual_cpus, None);
assert_eq!(Config::default().virtual_cpu_count(), 1);
assert!(!Config::default().to_string().contains("virtual-cpus"));
}
#[test]
fn eager_lone_preemptions_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
eager_lone_preemptions: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("eager_lone_preemptions"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.eager_lone_preemptions
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.eager_lone_preemptions
);
}
#[test]
fn stacktrace_at_schedule_positions_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
stacktrace_at_schedule_positions: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("stacktrace_at_schedule_positions"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.stacktrace_at_schedule_positions
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.stacktrace_at_schedule_positions
);
}
#[test]
fn stacktrace_at_schedule_positions_needs_a_replayed_schedule_and_round_trips() {
assert!(Config::try_parse_from(["detcore", "--stacktrace-at-schedule-positions"]).is_err());
assert!(
Config::try_parse_from([
"detcore",
"--replay-schedule-from=schedule.json",
"--strict-schedule-boundaries",
"--stacktrace-at-schedule-positions",
])
.is_err()
);
let config = Config::try_parse_from([
"detcore",
"--replay-schedule-from=schedule.json",
"--stacktrace-event=7",
"--stacktrace-at-schedule-positions",
])
.unwrap();
assert!(config.stacktrace_at_schedule_positions);
let rendered = config.to_string();
assert!(
rendered.contains(" --stacktrace-at-schedule-positions"),
"{rendered}"
);
let words: Vec<String> = shell_words::split(&rendered)
.unwrap()
.into_iter()
.filter(|word| word.starts_with("--replay-") || word.starts_with("--stacktrace-"))
.collect();
let reparsed =
Config::try_parse_from(std::iter::once("detcore".to_owned()).chain(words)).unwrap();
assert!(reparsed.stacktrace_at_schedule_positions, "{rendered}");
assert_eq!(
reparsed.stacktrace_event, config.stacktrace_event,
"{rendered}"
);
}
#[test]
fn signal_at_round_trips_through_reverie_bincode() {
for signal_at in [
None,
Some(SignalAt {
turn: 3000,
signal: libc::SIGUSR1,
}),
] {
let config = Config {
signal_at,
..Config::default()
};
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.signal_at, signal_at);
}
}
#[test]
fn notice_host_network_abstract_binds_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
notice_host_network_abstract_binds: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(
!json.contains("notice_host_network_abstract_binds"),
"{json}"
);
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.notice_host_network_abstract_binds
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.notice_host_network_abstract_binds
);
}
#[test]
fn notice_host_network_abstract_binds_round_trips_through_reverie_bincode() {
for notice_host_network_abstract_binds in [false, true] {
let config = Config {
notice_host_network_abstract_binds,
..Config::default()
};
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(
decoded.notice_host_network_abstract_binds,
notice_host_network_abstract_binds
);
}
}
#[test]
fn access_trace_never_enters_the_legacy_form_and_round_trips() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
access_trace: Some(PathBuf::from("/var/run 1.access")),
access_trace_from: 7586,
access_trace_max_records: Some(40),
access_trace_max_bytes: Some(4096),
watch: vec!["0x404010:4:rw".parse().unwrap()],
watch_from: 12,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("access_trace"), "{json}");
let decoded = from_legacy_backend_json(&json).unwrap();
assert_eq!((decoded.access_trace, decoded.access_trace_from), (None, 0));
assert_eq!(decoded.access_trace_max_records, None);
assert_eq!(decoded.access_trace_max_bytes, None);
assert_eq!((decoded.watch, decoded.watch_from), (vec![], 0));
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
let decoded = from_legacy_backend_json(&array).unwrap();
assert_eq!((decoded.access_trace, decoded.access_trace_from), (None, 0));
assert_eq!(
(
decoded.access_trace_max_records,
decoded.access_trace_max_bytes
),
(None, None)
);
for config in [Config::default(), on.clone()] {
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.access_trace, config.access_trace);
assert_eq!(decoded.access_trace_from, config.access_trace_from);
assert_eq!(
decoded.access_trace_max_records,
config.access_trace_max_records
);
assert_eq!(
decoded.access_trace_max_bytes,
config.access_trace_max_bytes
);
assert_eq!(
(decoded.watch, decoded.watch_from),
(config.watch.clone(), config.watch_from)
);
}
let spelled = on.to_string();
assert!(
spelled.contains(
" --record-access-trace-to='/var/run 1.access' --access-trace-from=7586 \
--access-trace-max-records=40 --access-trace-max-bytes=4096 \
--watch=0x404010:4:rw --watch-from=12"
),
"{spelled}"
);
assert!(!Config::default().to_string().contains("access-trace"));
let reparsed = Config::parse_from([
"hermit",
"--record-access-trace-to=/var/run 1.access",
"--access-trace-from=7586",
"--access-trace-max-records=40",
"--access-trace-max-bytes=4096",
"--watch=0x404010:4:rw",
"--watch-from=12",
]);
assert_eq!(reparsed.access_trace, on.access_trace);
assert_eq!(reparsed.access_trace_from, 7586);
assert_eq!(reparsed.access_trace_max_records, Some(40));
assert_eq!(reparsed.access_trace_max_bytes, Some(4096));
assert_eq!((reparsed.watch, reparsed.watch_from), (on.watch, 12));
}
#[test]
fn anonymous_mapping_logs_never_enter_the_legacy_form() {
let off = Config {
detlog_stack: true,
detlog_regs: true,
detlog_io_buffers: false,
detlog_regs_cadence: 7,
..Config::default()
};
let legacy = to_legacy_backend_json(&off).unwrap();
assert!(!legacy.contains("detlog_anon"), "{legacy}");
for mode in [None, Some(DetlogAnon::Mappings), Some(DetlogAnon::Pages)] {
let config = Config {
detlog_anon: mode,
..off.clone()
};
let object = to_legacy_backend_json(&config).unwrap();
assert_eq!(object, legacy);
let values: Vec<serde_json::Value> = ordered_entries(&object)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
for encoded in [object, array] {
let decoded = from_legacy_backend_json(&encoded).unwrap();
assert_eq!(decoded.detlog_anon, None);
assert_eq!(to_legacy_backend_json(&decoded).unwrap(), legacy);
}
let current = serde_json::to_value(&config).unwrap();
assert_eq!(current["detlog_anon"], serde_json::to_value(mode).unwrap());
let decoded: Config = serde_json::from_value(current).unwrap();
assert_eq!(decoded.detlog_anon, mode);
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.detlog_anon, mode);
}
}
fn in_guest_reserved_set() -> u64 {
[libc::SIGSYS, libc::SIGSEGV, libc::SIGTRAP]
.into_iter()
.fold(0, |set, signal| set | (1_u64 << (signal - 1)))
}
#[test]
fn in_guest_reserved_signals_never_enters_the_legacy_form() {
let empty = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let reserved = Config {
in_guest_reserved_signals: in_guest_reserved_set(),
..empty.clone()
};
let json = to_legacy_backend_json(&reserved).unwrap();
assert_eq!(json, to_legacy_backend_json(&empty).unwrap());
assert!(!json.contains("in_guest_reserved_signals"), "{json}");
assert_eq!(
from_legacy_backend_json(&json)
.unwrap()
.in_guest_reserved_signals,
0
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert_eq!(
from_legacy_backend_json(&array)
.unwrap()
.in_guest_reserved_signals,
0
);
}
#[test]
fn in_guest_reserved_signals_round_trips_and_defaults_to_empty() {
for set in [0, in_guest_reserved_set()] {
let config = Config {
in_guest_reserved_signals: set,
..Config::default()
};
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.in_guest_reserved_signals, set);
let json: Config =
serde_json::from_str(&serde_json::to_string(&config).unwrap()).unwrap();
assert_eq!(json.in_guest_reserved_signals, set);
}
let mut encoded = serde_json::to_value(Config::default()).unwrap();
encoded
.as_object_mut()
.unwrap()
.remove("in_guest_reserved_signals")
.expect("the field is serialized");
let decoded: Config = serde_json::from_value(encoded).unwrap();
assert_eq!(decoded.in_guest_reserved_signals, 0);
}
#[test]
fn reserves_in_guest_signal_reads_only_the_set() {
let empty = Config::default();
let reserved = Config {
in_guest_reserved_signals: in_guest_reserved_set(),
..Config::default()
};
for signal in -1..=66 {
assert!(!empty.reserves_in_guest_signal(signal), "{signal}");
let expected = [libc::SIGSYS, libc::SIGSEGV, libc::SIGTRAP]
.into_iter()
.any(|reserved| i64::from(reserved) == signal);
assert_eq!(
reserved.reserves_in_guest_signal(signal),
expected,
"{signal}"
);
}
let top = Config {
in_guest_reserved_signals: 1 << 63,
..Config::default()
};
assert!(top.reserves_in_guest_signal(64));
assert!(!top.reserves_in_guest_signal(65));
assert!(!top.reserves_in_guest_signal(0));
}
#[test]
fn in_guest_refuses_host_timed_producers_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
in_guest_refuses_host_timed_producers: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(
!json.contains("in_guest_refuses_host_timed_producers"),
"{json}"
);
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.in_guest_refuses_host_timed_producers
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.in_guest_refuses_host_timed_producers
);
}
#[test]
fn in_guest_refuses_host_timed_producers_round_trips_and_defaults_to_off() {
for refuses in [false, true] {
let config = Config {
in_guest_refuses_host_timed_producers: refuses,
..Config::default()
};
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.in_guest_refuses_host_timed_producers, refuses);
let json: Config =
serde_json::from_str(&serde_json::to_string(&config).unwrap()).unwrap();
assert_eq!(json.in_guest_refuses_host_timed_producers, refuses);
}
let mut encoded = serde_json::to_value(Config::default()).unwrap();
encoded
.as_object_mut()
.unwrap()
.remove("in_guest_refuses_host_timed_producers")
.expect("the field is serialized");
let decoded: Config = serde_json::from_value(encoded).unwrap();
assert!(!decoded.in_guest_refuses_host_timed_producers);
}
#[test]
fn in_guest_signal_delivery_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
in_guest_signal_delivery: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("in_guest_signal_delivery"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.in_guest_signal_delivery
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.in_guest_signal_delivery
);
}
#[test]
fn replay_edited_preemptions_never_enters_the_legacy_form() {
let off = Config {
backend: BackendCapabilities::DBT,
replay_preemptions_from: Some("record.preempts".into()),
..Config::default()
};
let on = Config {
replay_edited_preemptions: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("replay_edited_preemptions"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.replay_edited_preemptions
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.replay_edited_preemptions
);
}
#[test]
fn replay_edited_preemptions_needs_a_replayed_record_and_round_trips() {
assert!(Config::try_parse_from(["detcore", "--replay-edited-preemptions"]).is_err());
let config = Config::try_parse_from([
"detcore",
"--replay-preemptions-from=record.preempts",
"--replay-edited-preemptions",
])
.unwrap();
assert!(config.replay_edited_preemptions);
let rendered = config.to_string();
let words: Vec<String> = shell_words::split(&rendered)
.unwrap()
.into_iter()
.filter(|word| word.starts_with("--replay-"))
.collect();
let reparsed =
Config::try_parse_from(std::iter::once("detcore".to_owned()).chain(words)).unwrap();
assert!(reparsed.replay_edited_preemptions, "{rendered}");
assert_eq!(
reparsed.replay_preemptions_from, config.replay_preemptions_from,
"{rendered}"
);
let strict =
Config::try_parse_from(["detcore", "--replay-preemptions-from=record.preempts"])
.unwrap();
assert!(!strict.to_string().contains("--replay-edited-preemptions"));
for config in [&config, &strict] {
let wire = bincode::serde::encode_to_vec(config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(
decoded.replay_edited_preemptions,
config.replay_edited_preemptions
);
}
let mut encoded = serde_json::to_value(&config).unwrap();
encoded
.as_object_mut()
.unwrap()
.remove("replay_edited_preemptions")
.expect("the field is serialized");
let decoded: Config = serde_json::from_value(encoded).unwrap();
assert!(!decoded.replay_edited_preemptions);
}
#[test]
fn in_guest_signal_delivery_round_trips_and_defaults_to_off() {
for on in [false, true] {
let config = Config {
in_guest_signal_delivery: on,
..Config::default()
};
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.in_guest_signal_delivery, on);
let json: Config =
serde_json::from_str(&serde_json::to_string(&config).unwrap()).unwrap();
assert_eq!(json.in_guest_signal_delivery, on);
}
let mut encoded = serde_json::to_value(Config::default()).unwrap();
encoded
.as_object_mut()
.unwrap()
.remove("in_guest_signal_delivery")
.expect("the field is serialized");
let decoded: Config = serde_json::from_value(encoded).unwrap();
assert!(!decoded.in_guest_signal_delivery);
}
#[test]
fn annotated_priority_replay_never_enters_the_legacy_form_and_round_trips() {
let off = Config {
backend: BackendCapabilities::DBT,
..Config::default()
};
let on = Config {
annotated_priority_replay: true,
..off.clone()
};
let json = to_legacy_backend_json(&on).unwrap();
assert_eq!(json, to_legacy_backend_json(&off).unwrap());
assert!(!json.contains("annotated_priority_replay"), "{json}");
assert!(
!from_legacy_backend_json(&json)
.unwrap()
.annotated_priority_replay
);
let values: Vec<serde_json::Value> = ordered_entries(&json)
.into_iter()
.map(|(_, value)| value)
.collect();
let array = serde_json::to_string(&values).unwrap();
assert!(
!from_legacy_backend_json(&array)
.unwrap()
.annotated_priority_replay
);
for annotated in [false, true] {
let config = Config {
annotated_priority_replay: annotated,
..Config::default()
};
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let (decoded, read): (Config, usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(read, wire.len());
assert_eq!(decoded.annotated_priority_replay, annotated);
let json: Config =
serde_json::from_str(&serde_json::to_string(&config).unwrap()).unwrap();
assert_eq!(json.annotated_priority_replay, annotated);
}
let mut encoded = serde_json::to_value(Config::default()).unwrap();
encoded
.as_object_mut()
.unwrap()
.remove("annotated_priority_replay")
.expect("the field is serialized");
let decoded: Config = serde_json::from_value(encoded).unwrap();
assert!(!decoded.annotated_priority_replay);
}
#[test]
fn annotated_priority_replay_observes_schedule_events() {
let plain = Config::default();
assert!(!plain.should_trace_schedevent() && !plain.observes_schedevents());
let recording = Config {
record_preemptions: true,
..Config::default()
};
assert!(recording.should_trace_schedevent() && recording.observes_schedevents());
let replay = Config {
replay_preemptions_from: Some("history.json".into()),
..Config::default()
};
assert!(!replay.observes_schedevents(), "an unannotated history");
let annotated = Config {
annotated_priority_replay: true,
..replay
};
assert!(!annotated.should_trace_schedevent());
assert!(annotated.observes_schedevents());
}
#[test]
fn annotated_priority_replay_requires_a_qualified_effective_configuration() {
let unprepared = Config {
annotated_priority_replay: true,
replay_preemptions_from: Some("history.json".into()),
..Config::default()
};
assert_eq!(
unprepared.annotated_priority_replay_unqualified(),
Some("cannot deliver Detcore preemption timer events")
);
let qualified = Config {
backend: BackendCapabilities::PTRACE,
sequentialize_threads: true,
max_timeslice: NonZeroU64::new(1_000_000),
imprecise_timers: false,
no_rcb_time: false,
..unprepared.clone()
};
assert_eq!(qualified.annotated_priority_replay_unqualified(), None);
let before = serde_json::to_value(&qualified).unwrap();
for (config, setting) in [
(
Config {
sequentialize_threads: false,
..qualified.clone()
},
"does not sequentialize threads (--no-sequentialize-threads)",
),
(
Config {
max_timeslice: None,
..qualified.clone()
},
"has its preemption timer disabled (--max-timeslice=disabled)",
),
(
Config {
imprecise_timers: true,
..qualified.clone()
},
"requests imprecise timers (--imprecise-timers)",
),
(
Config {
no_rcb_time: true,
..qualified.clone()
},
"requests logical time without RCBs (--no-rcb-time)",
),
] {
assert_eq!(
config.annotated_priority_replay_unqualified(),
Some(setting)
);
}
assert_eq!(serde_json::to_value(&qualified).unwrap(), before);
}
#[test]
fn signal_at_parses_a_turn_and_a_catchable_signal() {
let usr1 = SignalAt {
turn: 500,
signal: libc::SIGUSR1,
};
assert_eq!(parse_signal_at("turn=500:SIGUSR1"), Ok(usr1));
assert_eq!(parse_signal_at("turn=500:10"), Ok(usr1));
for refused in [
"turn=500:SIGKILL",
"turn=500:9",
"turn=500:SIGSTOP",
"turn=500:19",
] {
let error = parse_signal_at(refused).unwrap_err();
assert!(
error.contains("cannot be caught or blocked"),
"{refused}: {error}"
);
}
for malformed in [
"turn=500",
"500:SIGUSR1",
"turn=-1:SIGUSR1",
"turn=5:SIGNOPE",
] {
assert!(parse_signal_at(malformed).is_err(), "{malformed}");
}
}
#[test]
fn a_legacy_positional_array_reads_as_the_object_it_lists() {
for (name, backend) in [
("PTRACE", BackendCapabilities::PTRACE),
("E9PATCH", BackendCapabilities::E9PATCH),
(
"ptrace without exit transitions",
ptrace_without_exit_transitions(),
),
("LITEINST_IN_GUEST", BackendCapabilities::LITEINST_IN_GUEST),
("SABRE", BackendCapabilities::SABRE),
("DBT", BackendCapabilities::DBT),
("KVM", BackendCapabilities::KVM),
] {
for sequentialize_threads in [false, true] {
let sent = Config {
backend,
sequentialize_threads,
seed: 7,
chaos: true,
..Config::default()
};
let json = to_legacy_backend_json(&sent).unwrap();
assert_controlled_key(&json, &backend, sequentialize_threads, name);
let array = positional(&json);
assert!(array.starts_with('['), "{array}");
let received = from_legacy_backend_json(&array).unwrap();
assert_eq!(received.backend, legacy_expressible(backend), "{name}");
assert_eq!(
received.sequentialize_threads, sequentialize_threads,
"{name}"
);
assert_eq!(received.seed, 7, "{name}");
assert!(received.chaos, "{name}");
assert_eq!(to_legacy_backend_json(&received).unwrap(), json, "{name}");
}
}
}
#[test]
fn a_malformed_legacy_positional_array_fails_the_parse() {
let json = to_legacy_backend_json(&Config {
backend: BackendCapabilities::DBT,
..Config::default()
})
.unwrap();
let entries = ordered_entries(&json);
let values: Vec<serde_json::Value> =
entries.iter().map(|(_, value)| value.clone()).collect();
let parse = |values: &[serde_json::Value]| {
from_legacy_backend_json(&serde_json::to_string(values).unwrap())
};
assert!(parse(&values).is_ok());
let mut longer = values.clone();
longer.push(serde_json::Value::Bool(false));
assert!(parse(&longer).is_err());
assert_eq!(entries.last().unwrap().0, "interrupt_at");
for len in 0..values.len() {
assert!(parse(&values[..len]).is_err(), "{len} elements");
}
for (position, (key, _)) in entries.iter().enumerate() {
if LEGACY_BACKEND_KEY_NAMES.contains(&key.as_str()) || key == "seed" {
let mut mistyped = values.clone();
mistyped[position] = serde_json::json!("0");
assert!(parse(&mistyped).is_err(), "{key}");
}
}
}
const LEGACY_INPUT_IN_CHILD: &str = "DETCORE_MODEL_TEST_LEGACY_INPUT";
const LEGACY_EXPECTED_IN_CHILD: &str = "DETCORE_MODEL_TEST_LEGACY_EXPECTED";
const LEGACY_DECODED_IN_CHILD: &str = "legacy configuration decoded under the ambient settings";
#[test]
fn a_legacy_configuration_decodes_whatever_the_ambient_hermit_settings() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
if let Some(input) = std::env::var_os(LEGACY_INPUT_IN_CHILD) {
let expected = std::env::var(LEGACY_EXPECTED_IN_CHILD).unwrap();
let received = from_legacy_backend_json(input.to_str().unwrap()).unwrap();
assert_eq!(
received.backend,
legacy_expressible(BackendCapabilities::DBT)
);
assert_eq!(received.seed, 7);
assert_eq!(received.sched_seed, Some(11));
assert_eq!(to_legacy_backend_json(&received).unwrap(), expected);
println!("{LEGACY_DECODED_IN_CHILD}");
return;
}
const VARIABLES: [&str; 4] = [
"HERMIT_EPOCH",
"HERMIT_PRNG",
"HERMIT_SCHED_SEED",
"HERMIT_CPU_PROFILE",
];
let text = OsStr::new("not-a-value");
let bytes = OsStr::from_bytes(b"\xff");
let mut settings: Vec<Vec<(&str, &OsStr)>> = vec![Vec::new()];
for variable in VARIABLES {
settings.push(vec![(variable, text)]);
settings.push(vec![(variable, bytes)]);
}
settings.push(VARIABLES.map(|variable| (variable, text)).to_vec());
settings.push(VARIABLES.map(|variable| (variable, bytes)).to_vec());
let object = to_legacy_backend_json(&Config {
backend: BackendCapabilities::DBT,
seed: 7,
sched_seed: Some(11),
..Config::default()
})
.unwrap();
let array = positional(&object);
assert!(array.starts_with('['), "{array}");
let test = format!(
"{}::a_legacy_configuration_decodes_whatever_the_ambient_hermit_settings",
module_path!().split_once("::").unwrap().1
);
for input in [&object, &array] {
for setting in &settings {
let mut child = std::process::Command::new(std::env::current_exe().unwrap());
child
.args(["--exact", &test, "--nocapture"])
.env(LEGACY_INPUT_IN_CHILD, input)
.env(LEGACY_EXPECTED_IN_CHILD, &object);
for variable in VARIABLES {
child.env_remove(variable);
}
for (variable, value) in setting {
child.env(variable, value);
}
let output = child.output().unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success()
&& stdout.contains(LEGACY_DECODED_IN_CHILD)
&& stdout.contains("test result: ok. 1 passed; 0 failed;"),
"decoding {} under {setting:?} did not succeed exactly once: {}\n{stdout}\n{stderr}",
if input.starts_with('[') {
"the array"
} else {
"the object"
},
output.status,
);
}
}
}
const CPU_PROFILE_ARGS_IN_CHILD: &str = "DETCORE_MODEL_TEST_CPU_PROFILE_ARGS";
#[test]
fn hermit_cpu_profile_supplies_the_profile_only_when_the_flag_is_absent() {
use clap::Parser;
if let Some(args) = std::env::var_os(CPU_PROFILE_ARGS_IN_CHILD) {
let args = args.into_string().unwrap();
let argv = std::iter::once("config").chain(args.lines());
match Config::try_parse_from(argv) {
Ok(config) => println!(
"cpu-profile={} wire={} default={}",
config.cpu_profile.name(),
config_wire_default().cpu_profile.name(),
match Config::try_parse_from(["config"]) {
Ok(_) => Config::default().cpu_profile.name(),
Err(_) => "refused",
}
),
Err(error) => println!("refused: {:?}", error.kind()),
}
return;
}
let test = format!(
"{}::hermit_cpu_profile_supplies_the_profile_only_when_the_flag_is_absent",
module_path!().split_once("::").unwrap().1
);
let parse = |variable: Option<&str>, args: &[&str]| -> String {
let mut child = std::process::Command::new(std::env::current_exe().unwrap());
child
.args(["--exact", &test, "--nocapture"])
.env(CPU_PROFILE_ARGS_IN_CHILD, args.join("\n"));
for name in [
"HERMIT_EPOCH",
"HERMIT_PRNG",
"HERMIT_SCHED_SEED",
"HERMIT_CPU_PROFILE",
] {
child.env_remove(name);
}
if let Some(value) = variable {
child.env("HERMIT_CPU_PROFILE", value);
}
let output = child.output().unwrap();
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"the child for {variable:?} {args:?} did not run exactly once: {}\n{stdout}",
output.status,
);
stdout
.lines()
.find(|line| line.starts_with("cpu-profile=") || line.starts_with("refused: "))
.unwrap_or_else(|| panic!("the child printed no verdict:\n{stdout}"))
.to_owned()
};
assert_eq!(
parse(None, &[]),
"cpu-profile=auto wire=x86-64-v2 default=auto"
);
assert_eq!(
parse(Some("auto"), &[]),
"cpu-profile=auto wire=x86-64-v2 default=auto"
);
assert_eq!(
parse(Some("auto"), &["--cpu-profile=x86-64-v2"]),
"cpu-profile=x86-64-v2 wire=x86-64-v2 default=auto"
);
assert_eq!(
parse(Some("x86-64-v3"), &[]),
"cpu-profile=x86-64-v3 wire=x86-64-v2 default=x86-64-v3"
);
assert_eq!(
parse(Some("host-no-rdrand"), &[]),
"cpu-profile=host-no-rdrand wire=x86-64-v2 default=host-no-rdrand"
);
assert_eq!(
parse(None, &["--cpu-profile=x86-64-v3"]),
"cpu-profile=x86-64-v3 wire=x86-64-v2 default=auto"
);
assert_eq!(
parse(Some("x86-64-v3"), &["--cpu-profile=x86-64-v2"]),
"cpu-profile=x86-64-v2 wire=x86-64-v2 default=x86-64-v3"
);
assert_eq!(parse(Some("x86-64-v4"), &[]), "refused: InvalidValue");
assert_eq!(
parse(Some("x86-64-v4"), &["--cpu-profile=x86-64-v2"]),
"cpu-profile=x86-64-v2 wire=x86-64-v2 default=refused"
);
}
#[test]
fn keys_the_legacy_form_did_not_name_are_ignored() {
let sent = Config {
backend: legacy_expressible(BackendCapabilities::DBT),
seed: 7,
cpu_profile: crate::cpu_profile::CpuProfile::X86_64V2,
..Config::default()
};
let json = to_legacy_backend_json(&sent).unwrap();
let kvm = serde_json::to_string(&BackendCapabilities::KVM).unwrap();
for extra in [
r#""backend":null"#.to_owned(),
r#""shared_dequeue_timers":null"#.to_owned(),
r#""backend":null,"shared_dequeue_timers":null"#.to_owned(),
format!(r#""backend":{kvm},"shared_dequeue_timers":true"#),
r#""backend":7,"backend":{"tracks_process_children":false}"#.to_owned(),
r#""shared_dequeue_timers":"yes","shared_dequeue_timers":true"#.to_owned(),
r#""no_such_field":[1,{"x":null}]"#.to_owned(),
] {
for edited in [
json.replacen('{', &format!("{{{extra},"), 1),
format!("{},{extra}}}", &json[..json.len() - 1]),
] {
let received = from_legacy_backend_json(&edited).unwrap();
assert_eq!(received.backend, sent.backend, "{edited}");
assert_eq!(
serde_json::to_string(&received).unwrap(),
serde_json::to_string(&sent).unwrap(),
"{edited}"
);
assert_eq!(to_legacy_backend_json(&received).unwrap(), json, "{edited}");
}
}
let repeated = format!("{},\"seed\":7}}", &json[..json.len() - 1]);
assert!(from_legacy_backend_json(&repeated).is_err());
}
#[test]
fn network_perturbation_seed_never_falls_back_to_scheduler_seeds() {
let mut config = Config {
seed: 41,
sched_seed: Some(42),
..Config::default()
};
assert_eq!(config.network_trace.network_perturb_seed, None);
config.network_trace = NetworkTraceConfig {
mode: crate::network_trace::NetworkTraceMode::Replay,
path: Some("network.trace".into()),
network_perturb_seed: Some(43),
};
assert_eq!(config.seed, 41);
assert_eq!(config.sched_seed(), 42);
assert_eq!(config.network_trace.network_perturb_seed, Some(43));
}
#[test]
fn missing_mountinfo_provenance_deserializes_as_empty() {
let mut value = serde_json::to_value(Config::default()).unwrap();
value
.as_object_mut()
.unwrap()
.remove("mountinfo_root_rewrites");
value
.as_object_mut()
.unwrap()
.remove("mountinfo_device_rewrites");
value.as_object_mut().unwrap().remove("mountinfo_mount_ids");
value
.as_object_mut()
.unwrap()
.remove("mountinfo_mount_ids_captured");
value
.as_object_mut()
.unwrap()
.remove("mount_id_assignment_order");
value
.as_object_mut()
.unwrap()
.remove("container_mount_table");
value
.as_object_mut()
.unwrap()
.remove("mountinfo_mount_namespace");
value
.as_object_mut()
.unwrap()
.remove("directory_placeholder");
value.as_object_mut().unwrap().remove("container_procfs");
let restored: Config = serde_json::from_value(value).unwrap();
assert!(restored.mountinfo_root_rewrites.is_empty());
assert!(restored.mountinfo_device_rewrites.is_empty());
assert!(restored.mountinfo_mount_ids.is_empty());
assert!(!restored.mountinfo_mount_ids_captured);
assert!(restored.mount_id_assignment_order.is_empty());
assert!(restored.container_mount_table.is_none());
assert!(restored.mountinfo_mount_namespace.is_none());
assert!(restored.directory_placeholder.is_none());
assert!(!restored.container_procfs);
}
#[test]
fn lone_preemptions_are_replayed_only_where_a_slice_end_reads_nothing_else() {
let base = Config {
sequentialize_threads: true,
backend: reverie::BackendCapabilities::PTRACE,
..Config::parse_from(["detcore"])
};
assert!(base.replays_lone_preemptions());
let off: Vec<(&str, Config)> = vec![
(
"--eager-lone-preemptions",
Config {
eager_lone_preemptions: true,
..base.clone()
},
),
(
"no sequentialization",
Config {
sequentialize_threads: false,
..base.clone()
},
),
(
"--max-timeslice=disabled",
Config {
max_timeslice: None,
..base.clone()
},
),
(
"--no-rcb-time",
Config {
no_rcb_time: true,
..base.clone()
},
),
(
"--imprecise-timers",
Config {
imprecise_timers: true,
..base.clone()
},
),
(
"--chaos-per-thread-slowdown",
Config {
chaos_per_thread_slowdown: true,
..base.clone()
},
),
(
"--strict-schedule-boundaries",
Config {
strict_schedule_boundaries: true,
..base.clone()
},
),
(
"--target-timeslice",
Config {
target_timeslice: NonZeroU64::new(1_000),
..base.clone()
},
),
(
"--preemption-stacktrace",
Config {
preemption_stacktrace: true,
..base.clone()
},
),
(
"--stacktrace-event",
Config {
stacktrace_event: vec![(1, None)],
..base.clone()
},
),
(
"--stop-after-turn",
Config {
stop_after_turn: Some(1),
..base.clone()
},
),
(
"--stop-after-iter",
Config {
stop_after_iter: Some(1),
..base.clone()
},
),
(
"--interrupt-at",
Config {
interrupt_at: vec![(DetTid::from_raw(3), 1)],
..base.clone()
},
),
(
"--signal-at",
Config {
signal_at: Some(parse_signal_at("turn=1:SIGUSR1").unwrap()),
..base.clone()
},
),
(
"--happens-before",
Config {
happens_before: Some(crate::happens_before::HappensBeforeProgram {
version: 1,
anchors: Default::default(),
edges: Vec::new(),
max_hold_ns: None,
}),
..base.clone()
},
),
(
"--chaos --chaos-instruction-offset=8",
Config {
chaos: true,
chaos_instruction_offset: 8,
..base.clone()
},
),
(
"--gdbserver",
Config {
gdbserver: true,
..base.clone()
},
),
];
for (option, config) in off {
assert!(!config.replays_lone_preemptions(), "{option}");
}
let on: Vec<(&str, Config)> = vec![
(
"--record-preemptions",
Config {
record_preemptions: true,
..base.clone()
},
),
(
"--replay-preemptions-from",
Config {
replay_preemptions_from: Some("p".into()),
..base.clone()
},
),
(
"--replay-schedule-from",
Config {
replay_schedule_from: Some("s".into()),
record_preemptions: true,
..base.clone()
},
),
];
for (option, config) in on {
assert!(config.replays_lone_preemptions(), "{option}");
}
assert!(
Config {
chaos: true,
..base.clone()
}
.replays_lone_preemptions()
);
}
#[test]
fn runs_post_fork_parses_all_modes_and_defaults_to_child() {
assert_eq!(Config::default().runs_post_fork, RunsPostFork::Child);
assert_eq!(
Config::parse_from(["detcore", "--runs-post-fork=parent"]).runs_post_fork,
RunsPostFork::Parent
);
assert_eq!(
Config::parse_from(["detcore", "--runs-post-fork=random"]).runs_post_fork,
RunsPostFork::Random
);
assert!(Config::try_parse_from(["detcore", "--runs-post-fork=invalid"]).is_err());
}
#[test]
fn proc_level_parses_both_levels_defaults_to_minimal_and_round_trips() {
assert_eq!(Config::default().proc_level, ProcLevel::Minimal);
assert!(!Config::default().to_string().contains("--proc"));
let standard = Config::parse_from(["detcore", "--proc=standard"]);
assert_eq!(standard.proc_level, ProcLevel::Standard);
assert!(standard.to_string().contains(" --proc=standard"));
assert_eq!(
Config::parse_from(["detcore", "--proc=minimal"]).proc_level,
ProcLevel::Minimal
);
assert!(Config::try_parse_from(["detcore", "--proc=host"]).is_err());
assert!(ProcLevel::Minimal < ProcLevel::Standard);
}
#[test]
fn untrap_passthrough_syscalls_is_opt_in_and_round_trips() {
assert!(!Config::default().untrap_passthrough_syscalls);
let config = Config::parse_from(["detcore", "--untrap-passthrough-syscalls"]);
assert!(config.untrap_passthrough_syscalls);
assert!(
config
.to_string()
.contains(" --untrap-passthrough-syscalls")
);
assert!(!Config::default().to_string().contains("untrap"));
}
#[test]
fn panic_on_rcb_overshoot_is_opt_in_and_round_trips() {
assert!(!Config::default().panic_on_rcb_overshoot);
let config = Config::parse_from(["detcore", "--panic-on-rbc-overshoot"]);
assert!(config.panic_on_rcb_overshoot);
assert!(config.to_string().contains(" --panic-on-rbc-overshoot"));
let alias = Config::parse_from(["detcore", "--panic-on-rcb-overshoot"]);
assert!(alias.panic_on_rcb_overshoot);
}
#[test]
fn config_display_preserves_nondefault_post_fork_modes() {
let mut config = Config {
runs_post_fork: RunsPostFork::Parent,
..Config::default()
};
assert!(config.to_string().contains(" --runs-post-fork=parent"));
config.runs_post_fork = RunsPostFork::Random;
assert!(config.to_string().contains(" --runs-post-fork=random"));
}
#[test]
fn the_expired_wait_charge_is_printed_when_set_and_never_enters_the_legacy_form() {
assert_eq!(Config::default().expired_wait_charge, None);
assert!(
!Config::default()
.to_string()
.contains("--expired-wait-charge")
);
for (value, charge) in [
("each", ExpiredWaitCharge::Each),
("once", ExpiredWaitCharge::Once),
] {
let set =
Config::try_parse_from(["detcore", &format!("--expired-wait-charge={value}")])
.unwrap();
assert_eq!(set.expired_wait_charge, Some(charge));
assert!(
set.to_string()
.contains(&format!(" --expired-wait-charge={value}")),
"{set}"
);
let reparsed: Config =
serde_json::from_str(&serde_json::to_string(&set).unwrap()).unwrap();
assert_eq!(reparsed.expired_wait_charge, Some(charge));
let legacy = to_legacy_backend_json(&set).unwrap();
assert!(!legacy.contains("expired_wait_charge"), "{legacy}");
assert_eq!(
from_legacy_backend_json(&legacy)
.unwrap()
.expired_wait_charge,
None
);
}
}
#[test]
fn the_sleep_registration_is_printed_when_set_and_never_enters_the_legacy_form() {
assert_eq!(Config::default().sleep_registration, None);
assert!(
!Config::default()
.to_string()
.contains("--sleep-registration")
);
for (value, registration) in [
("first-pass", SleepRegistration::FirstPass),
("when-chosen", SleepRegistration::WhenChosen),
] {
let set = Config::try_parse_from(["detcore", &format!("--sleep-registration={value}")])
.unwrap();
assert_eq!(set.sleep_registration, Some(registration));
assert!(
set.to_string()
.contains(&format!(" --sleep-registration={value}")),
"{set}"
);
let reparsed: Config =
serde_json::from_str(&serde_json::to_string(&set).unwrap()).unwrap();
assert_eq!(reparsed.sleep_registration, Some(registration));
let legacy = to_legacy_backend_json(&set).unwrap();
assert!(!legacy.contains("sleep_registration"), "{legacy}");
assert_eq!(
from_legacy_backend_json(&legacy)
.unwrap()
.sleep_registration,
None
);
}
}
#[test]
fn first_pass_sleep_registration_is_the_default_only_where_signal_state_is_read() {
let config = |backend: BackendCapabilities,
gate: bool,
sleep_registration: Option<SleepRegistration>| Config {
backend,
in_guest_signal_delivery: gate,
sleep_registration,
sequentialize_threads: true,
..Config::default()
};
for (name, backend) in [
("PTRACE", BackendCapabilities::PTRACE),
("E9PATCH", BackendCapabilities::E9PATCH),
] {
let default = config(backend, false, None);
assert!(default.reads_sleeper_signal_state(), "{name}");
assert!(default.queued_sleeps_registered_at_first_pass(), "{name}");
}
for (name, backend) in [
("DBT", BackendCapabilities::DBT),
("SABRE", BackendCapabilities::SABRE),
("LITEINST_IN_GUEST", BackendCapabilities::LITEINST_IN_GUEST),
("KVM", BackendCapabilities::KVM),
] {
let default = config(backend, false, None);
assert!(!default.reads_sleeper_signal_state(), "{name}");
assert!(!default.queued_sleeps_registered_at_first_pass(), "{name}");
let gated = config(backend, true, None);
assert!(gated.reads_sleeper_signal_state(), "{name} under the gate");
assert!(
gated.queued_sleeps_registered_at_first_pass(),
"{name} under the gate"
);
assert!(
config(backend, false, Some(SleepRegistration::FirstPass))
.queued_sleeps_registered_at_first_pass(),
"{name}, asked for"
);
}
let unserialized = Config {
sequentialize_threads: false,
..config(BackendCapabilities::PTRACE, false, None)
};
assert!(!unserialized.reads_sleeper_signal_state());
assert!(!unserialized.queued_sleeps_registered_at_first_pass());
let chaos = Config {
chaos: true,
..config(BackendCapabilities::PTRACE, false, None)
};
assert!(!chaos.queued_sleeps_registered_at_first_pass());
let recorded = Config {
recordreplay_modes: true,
..config(
BackendCapabilities::PTRACE,
false,
Some(SleepRegistration::FirstPass),
)
};
assert!(!recorded.queued_sleeps_registered_at_first_pass());
}
#[test]
fn the_work_span_report_is_off_by_default_and_never_enters_the_legacy_form() {
assert_eq!(Config::default().work_span_report, None);
let on = Config::try_parse_from(["detcore", "--work-span-report=/tmp/ws.json"]).unwrap();
assert_eq!(
on.work_span_report.as_deref(),
Some(std::path::Path::new("/tmp/ws.json"))
);
assert!(on.to_string().contains(" --work-span-report=/tmp/ws.json"));
let reparsed: Config = serde_json::from_str(&serde_json::to_string(&on).unwrap()).unwrap();
assert_eq!(reparsed.work_span_report, on.work_span_report);
let mut old = serde_json::to_value(Config::default()).unwrap();
old.as_object_mut().unwrap().remove("work_span_report");
let old: Config = serde_json::from_value(old).unwrap();
assert_eq!(old.work_span_report, None);
let legacy = to_legacy_backend_json(&on).unwrap();
assert!(!legacy.contains("work_span_report"), "{legacy}");
assert_eq!(
from_legacy_backend_json(&legacy).unwrap().work_span_report,
None
);
}
#[test]
fn a_fatal_delivery_check_is_off_by_default_and_never_enters_the_legacy_form() {
assert!(!Config::default().signal_delivery_check_fatal);
let fatal = Config {
signal_delivery_check_fatal: true,
..Config::default()
};
let json = serde_json::to_string(&fatal).unwrap();
let reparsed: Config = serde_json::from_str(&json).unwrap();
assert!(reparsed.signal_delivery_check_fatal);
let mut old = serde_json::to_value(Config::default()).unwrap();
old.as_object_mut()
.unwrap()
.remove("signal_delivery_check_fatal");
let old: Config = serde_json::from_value(old).unwrap();
assert!(!old.signal_delivery_check_fatal);
let legacy = to_legacy_backend_json(&fatal).unwrap();
assert!(!legacy.contains("signal_delivery_check_fatal"), "{legacy}");
assert!(
!from_legacy_backend_json(&legacy)
.unwrap()
.signal_delivery_check_fatal
);
}
#[test]
fn the_signal_state_copy_is_on_by_default_and_its_off_switch_round_trips() {
let dflt = Config::default();
assert!(dflt.signal_state_copy);
assert!(!dflt.to_string().contains("signal-state-copy"));
let mut json = serde_json::to_value(&dflt).unwrap();
json.as_object_mut().unwrap().remove("signal_state_copy");
let old: Config = serde_json::from_value(json).unwrap();
assert!(old.signal_state_copy);
let off = Config::parse_from(["detcore", "--no-signal-state-copy"]);
assert!(!off.signal_state_copy);
let rendered = off.to_string();
assert!(rendered.contains(" --no-signal-state-copy"), "{rendered}");
let reparsed = Config::parse_from(
std::iter::once("detcore".to_string())
.chain(rendered.split_whitespace().map(String::from)),
);
assert!(!reparsed.signal_state_copy);
}
#[test]
fn chaos_per_thread_slowdown_is_opt_in_and_round_trips() {
let dflt = Config::default();
assert!(!dflt.chaos_per_thread_slowdown);
assert_eq!(dflt.chaos_slowdown_max_factor, 10.0);
assert!(!dflt.to_string().contains("--chaos-per-thread-slowdown"));
let config = Config::parse_from([
"detcore",
"--chaos",
"--chaos-per-thread-slowdown",
"--chaos-slowdown-max-factor=4.5",
]);
assert!(config.chaos_per_thread_slowdown);
assert_eq!(config.chaos_slowdown_max_factor, 4.5);
let rendered = config.to_string();
assert!(rendered.contains(" --chaos-per-thread-slowdown"));
assert!(rendered.contains(" --chaos-slowdown-max-factor=4.5"));
let reparsed = Config::parse_from(
std::iter::once("detcore".to_string())
.chain(rendered.split_whitespace().map(String::from)),
);
assert!(reparsed.chaos_per_thread_slowdown);
assert_eq!(reparsed.chaos_slowdown_max_factor, 4.5);
}
#[test]
fn chaos_epoch_length_is_opt_in_and_round_trips() {
let dflt = Config::default();
assert_eq!(dflt.chaos_epoch_length_ns, 0);
assert!(!dflt.to_string().contains("--chaos-epoch-length-ns"));
let config = Config::parse_from([
"detcore",
"--chaos",
"--chaos-per-thread-slowdown",
"--chaos-epoch-length-ns=100000",
]);
assert_eq!(config.chaos_epoch_length_ns, 100000);
let rendered = config.to_string();
assert!(rendered.contains(" --chaos-epoch-length-ns=100000"));
let reparsed = Config::parse_from(
std::iter::once("detcore".to_string())
.chain(rendered.split_whitespace().map(String::from)),
);
assert_eq!(reparsed.chaos_epoch_length_ns, 100000);
let no_slowdown = Config::parse_from(["detcore", "--chaos", "--chaos-epoch-length-ns=100"]);
assert_eq!(no_slowdown.chaos_epoch_length_ns, 100);
assert!(!no_slowdown.to_string().contains("--chaos-epoch-length-ns"));
}
#[test]
#[should_panic(expected = "chaos_slowdown_max_factor must be finite and in")]
fn validate_rejects_chaos_slowdown_max_factor_below_one() {
let mut config = Config {
chaos_slowdown_max_factor: 0.5,
..Default::default()
};
config.validate();
}
#[test]
#[should_panic(expected = "max_timeslice must be at least one RCB")]
fn validate_rejects_max_timeslice_below_one_rcb() {
let mut config = Config {
max_timeslice: NonZeroU64::new(NANOS_PER_RCB as u64 - 1),
..Default::default()
};
config.validate();
}
#[test]
fn validate_accepts_one_rcb_max_timeslice() {
let mut config = Config {
max_timeslice: NonZeroU64::new(NANOS_PER_RCB as u64),
..Default::default()
};
config.validate();
}
#[test]
#[should_panic(expected = "clock_multiplier must be finite and positive")]
fn validate_rejects_invalid_clock_multiplier() {
let mut config = Config {
clock_multiplier: Some(0.0),
..Default::default()
};
config.validate();
}
#[test]
#[should_panic(expected = "max_timeslice must be at least one RCB")]
fn validate_scales_one_rcb_minimum_with_clock_multiplier() {
let mut config = Config {
max_timeslice: NonZeroU64::new(10),
clock_multiplier: Some(2.0),
..Default::default()
};
config.validate();
}
#[test]
fn config_fingerprint_sees_the_width_of_every_backend_capability() {
let config = config_wire_default();
let fields = serde_json::to_value(config.backend).unwrap();
let fields = fields.as_object().unwrap();
for (name, value) in fields {
match name.as_str() {
"hardware_watchpoints" => {
let width = value.as_u64().expect("a u8 count encodes as a number");
assert!(width <= u64::from(u8::MAX), "{name}={width} exceeds a u8");
}
"publishable_parent_death_signals" => {
value
.as_u64()
.expect("a u64 signal set encodes as a number");
}
"rcb_clock_contract" => {
value
.as_str()
.expect("the default's contract is present, a unit variant's name");
}
_ => assert!(value.is_boolean(), "{name}={value} is not a bool"),
}
}
let encode = |config: &Config| {
bincode::serde::encode_to_vec(config, bincode::config::legacy()).unwrap()
};
assert_eq!(
bincode::serde::encode_to_vec(config.backend, bincode::config::legacy())
.unwrap()
.len(),
fields.len() + 7 + 4
);
let flipped = config.clone().with_backend(|backend| {
backend.tracks_process_children = !backend.tracks_process_children
});
assert_eq!(encode(&flipped).len(), encode(&config).len());
assert_ne!(encode(&flipped), encode(&config));
let widened = config.clone().with_backend(|backend| {
backend.hardware_watchpoints = backend.hardware_watchpoints.wrapping_add(1)
});
assert_eq!(encode(&widened).len(), encode(&config).len());
assert_ne!(encode(&widened), encode(&config));
let resigned = config
.clone()
.with_backend(|backend| backend.publishable_parent_death_signals ^= 1 << 63);
assert_eq!(encode(&resigned).len(), encode(&config).len());
assert_ne!(encode(&resigned), encode(&config));
let uncontracted = config
.clone()
.with_backend(|backend| backend.rcb_clock_contract = None);
assert_eq!(encode(&uncontracted).len() + 4, encode(&config).len());
}
#[test]
fn config_fingerprint_includes_clock_rpc_definitions() {
let config = config_wire_default();
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let named_shape = serde_json::to_string(&config).unwrap();
let current = config_wire_fingerprint();
let clock_source = include_bytes!("time.rs").as_slice();
let without_clock: Vec<_> = CONFIG_DEFINITION_SOURCES
.iter()
.copied()
.filter(|source| *source != clock_source)
.collect();
assert_ne!(
fingerprint_of_config_material(&wire, &named_shape, &without_clock),
current,
"the published fingerprint must reject source inputs that omit the RPC clock"
);
let changed_clock =
include_str!("time.rs").replacen(" inherited_nanos: LogicalDuration,", "", 1);
assert_ne!(changed_clock.as_bytes(), clock_source);
let changed_sources: Vec<_> = CONFIG_DEFINITION_SOURCES
.iter()
.map(|source| {
if *source == clock_source {
changed_clock.as_bytes()
} else {
*source
}
})
.collect();
assert_ne!(
fingerprint_of_config_material(&wire, &named_shape, &changed_sources),
current,
"a clock-only serialized field change must invalidate the fingerprint"
);
}
#[test]
fn config_fingerprint_includes_the_inode_rpc_identity() {
let config = config_wire_default();
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let named_shape = serde_json::to_string(&config).unwrap();
let current = config_wire_fingerprint();
let inode_source = include_bytes!("fd.rs").as_slice();
assert!(CONFIG_DEFINITION_SOURCES.contains(&inode_source));
let without_device = include_str!("fd.rs").replacen(" pub dev: u64,\n", "", 1);
assert_ne!(without_device.as_bytes(), inode_source);
let changed_sources: Vec<_> = CONFIG_DEFINITION_SOURCES
.iter()
.map(|source| {
if *source == inode_source {
without_device.as_bytes()
} else {
*source
}
})
.collect();
assert_ne!(
fingerprint_of_config_material(&wire, &named_shape, &changed_sources),
current,
"an inode-identity layout change must invalidate the fingerprint"
);
}
#[test]
fn config_fingerprint_includes_the_watch_element_layout() {
let config = config_wire_default();
assert!(config.watch.is_empty(), "the default hides the element");
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
let named_shape = serde_json::to_string(&config).unwrap();
let current = config_wire_fingerprint();
let watch_source = include_bytes!("watch.rs").as_slice();
assert!(CONFIG_DEFINITION_SOURCES.contains(&watch_source));
let without_len = include_str!("watch.rs").replacen(" pub len: u8,\n", "", 1);
assert_ne!(without_len.as_bytes(), watch_source);
let changed_sources: Vec<_> = CONFIG_DEFINITION_SOURCES
.iter()
.map(|source| {
if *source == watch_source {
without_len.as_bytes()
} else {
*source
}
})
.collect();
assert_ne!(
fingerprint_of_config_material(&wire, &named_shape, &changed_sources),
current,
"a watch element layout change must invalidate the fingerprint"
);
}
#[test]
fn a_config_fingerprint_mismatch_names_both_fingerprints() {
let ours = config_wire_fingerprint();
assert_eq!(
config_fingerprint_mismatch(std::ffi::OsStr::new(&ours)),
None
);
let other = config_fingerprint_mismatch(std::ffi::OsStr::new("0123456789abcdef"))
.expect("another fingerprint is a mismatch");
assert!(other.contains(&ours), "{other}");
assert!(other.contains("0123456789abcdef"), "{other}");
use std::os::unix::ffi::OsStrExt;
assert!(config_fingerprint_mismatch(std::ffi::OsStr::from_bytes(b"\xff")).is_some());
}
#[test]
fn config_fingerprint_is_stable_and_shape_sensitive() {
assert_eq!(config_wire_fingerprint(), config_wire_fingerprint());
assert_eq!(config_wire_fingerprint().len(), 16);
let config = config_wire_default();
let base = serde_json::to_string(&config).unwrap();
let wire = bincode::serde::encode_to_vec(&config, bincode::config::legacy()).unwrap();
assert_eq!(
fingerprint_of_config_material(&wire, &base, CONFIG_DEFINITION_SOURCES),
config_wire_fingerprint()
);
let with_extra_field = format!("{},\"a_new_flag\":false}}", &base[..base.len() - 1]);
assert_ne!(
fingerprint_of_config_material(&wire, &with_extra_field, CONFIG_DEFINITION_SOURCES),
config_wire_fingerprint()
);
let removed = base.replacen("\"virtualize_time\":true,", "", 1);
assert_ne!(
fingerprint_of_config_material(&wire, &removed, CONFIG_DEFINITION_SOURCES),
config_wire_fingerprint()
);
let renamed = base.replacen("\"virtualize_time\"", "\"virtualise_time\"", 1);
assert_ne!(
fingerprint_of_config_material(&wire, &renamed, CONFIG_DEFINITION_SOURCES),
config_wire_fingerprint()
);
#[derive(Serialize)]
struct U32Field {
field: u32,
}
#[derive(Serialize)]
struct U64Field {
field: u64,
}
let u32_value = U32Field { field: 0 };
let u64_value = U64Field { field: 0 };
let u32_json = serde_json::to_string(&u32_value).unwrap();
let u64_json = serde_json::to_string(&u64_value).unwrap();
assert_eq!(
u32_json, u64_json,
"the planted JSON collision must be real"
);
let u32_wire =
bincode::serde::encode_to_vec(&u32_value, bincode::config::legacy()).unwrap();
let u64_wire =
bincode::serde::encode_to_vec(&u64_value, bincode::config::legacy()).unwrap();
assert_ne!(u32_wire, u64_wire, "the planted wire retype must be real");
assert_ne!(
fingerprint_of_config_material(&u32_wire, &u32_json, &[b"struct S { field: u32 }"]),
fingerprint_of_config_material(&u64_wire, &u64_json, &[b"struct S { field: u64 }"]),
"a wire-incompatible integer retype must change the fingerprint"
);
#[derive(Serialize)]
struct OptionalU32 {
field: Option<u32>,
}
#[derive(Serialize)]
struct OptionalU64 {
field: Option<u64>,
}
let optional_u32 = OptionalU32 { field: None };
let optional_u64 = OptionalU64 { field: None };
let optional_u32_json = serde_json::to_string(&optional_u32).unwrap();
let optional_u64_json = serde_json::to_string(&optional_u64).unwrap();
assert_eq!(optional_u32_json, optional_u64_json);
let optional_u32_wire =
bincode::serde::encode_to_vec(&optional_u32, bincode::config::legacy()).unwrap();
let optional_u64_wire =
bincode::serde::encode_to_vec(&optional_u64, bincode::config::legacy()).unwrap();
assert_eq!(
optional_u32_wire, optional_u64_wire,
"the planted default must be invisible in both value encodings"
);
assert_ne!(
fingerprint_of_config_material(
&optional_u32_wire,
&optional_u32_json,
&[b"struct S { field: Option<u32> }"]
),
fingerprint_of_config_material(
&optional_u64_wire,
&optional_u64_json,
&[b"struct S { field: Option<u64> }"]
),
"a hidden wire-incompatible inner-type change must alter the fingerprint"
);
}
#[test]
fn config_fingerprint_uses_environment_free_wire_defaults() {
let environment_derived = Config {
epoch: "2042-03-04T05:06:07.890123456Z".parse().unwrap(),
seed: 41,
sched_seed: Some(42),
cpu_profile: crate::cpu_profile::CpuProfile::X86_64V3,
..Config::default()
};
let canonical = config_wire_default();
assert_ne!(
serde_json::to_string(&environment_derived).unwrap(),
serde_json::to_string(&canonical).unwrap()
);
assert_eq!(
canonical.epoch,
DEFAULT_EPOCH_STR.parse::<DateTime<Utc>>().unwrap()
);
assert_eq!(canonical.seed, 0);
assert_eq!(canonical.sched_seed, None);
assert_eq!(
canonical.cpu_profile,
crate::cpu_profile::CpuProfile::X86_64V2
);
}
#[test]
#[should_panic(expected = "max_timeslice must be at least one RCB")]
fn validate_scales_one_rcb_minimum_with_chaos_slowdown() {
let mut config = Config {
chaos: true,
chaos_per_thread_slowdown: true,
chaos_slowdown_max_factor: 4.0,
max_timeslice: NonZeroU64::new(39),
..Default::default()
};
config.validate();
}
#[test]
fn one_rcb_minimum_multiplies_like_detcores_pmu_epsilon() {
let slowed = |clock_multiplier: f64, factor: f64, max_timeslice: u64| Config {
chaos: true,
chaos_per_thread_slowdown: true,
chaos_slowdown_max_factor: factor,
clock_multiplier: Some(clock_multiplier),
max_timeslice: NonZeroU64::new(max_timeslice),
..Default::default()
};
let mut config = slowed(2.5, 4.4, 110);
assert_eq!(config.minimum_max_timeslice_nanos(), 110);
config.validate();
for (clock_multiplier, factor, minimum) in [
(2.5, 4.4, 110),
(2.5, 2.2, 55),
(7.0, 1.1, 78),
(0.7, 3.0, 21),
(1.1, 5.5, 61),
] {
let detcore = NANOS_PER_RCB * (clock_multiplier * factor);
assert_ne!(
(NANOS_PER_RCB * clock_multiplier * factor).to_bits(),
detcore.to_bits(),
"{clock_multiplier} x {factor} does not tell the orders apart"
);
let config = slowed(clock_multiplier, factor, 1_000_000);
assert_eq!(
config.largest_nanos_per_rcb().to_bits(),
detcore.to_bits(),
"{clock_multiplier} x {factor}"
);
assert_eq!(
config.minimum_max_timeslice_nanos(),
minimum,
"{clock_multiplier} x {factor}"
);
}
}
#[test]
#[should_panic(expected = "chaos_slowdown_max_factor must be finite and in")]
fn validate_rejects_unrepresentable_chaos_slowdown_factor() {
let mut config = Config {
chaos_slowdown_max_factor: RcbTimeMultiplier::MAX * 2.0,
..Default::default()
};
config.validate();
}
}
#[cfg(test)]
mod strict_boundary_mode_tests {
use super::Config;
#[test]
fn strict_boundary_policy_is_explicit_and_round_trips_the_actual_wire() {
let ordinary = Config::default();
assert!(!ordinary.strict_schedule_boundaries);
let mut old_shape = serde_json::to_value(&ordinary).unwrap();
assert_eq!(
old_shape
.as_object_mut()
.unwrap()
.remove("strict_schedule_boundaries"),
Some(false.into())
);
assert!(
!serde_json::from_value::<Config>(old_shape)
.unwrap()
.strict_schedule_boundaries
);
let explicit = Config {
strict_schedule_boundaries: true,
..ordinary
};
let encoded = serde_json::to_value(&explicit).unwrap();
assert_eq!(encoded["strict_schedule_boundaries"], true);
assert!(
serde_json::from_value::<Config>(encoded)
.unwrap()
.strict_schedule_boundaries
);
assert!(
explicit
.to_string()
.contains("--strict-schedule-boundaries")
);
for config in [&Config::default(), &explicit] {
let bytes = bincode::serde::encode_to_vec(config, bincode::config::legacy()).unwrap();
let (decoded, consumed): (Config, usize) =
bincode::serde::decode_from_slice(&bytes, bincode::config::legacy()).unwrap();
assert_eq!(consumed, bytes.len());
assert_eq!(
decoded.strict_schedule_boundaries,
config.strict_schedule_boundaries
);
assert_eq!(
bincode::serde::encode_to_vec(&decoded, bincode::config::legacy()).unwrap(),
bytes
);
}
let legacy = super::to_legacy_backend_json(&Config::default()).unwrap();
assert!(!legacy.contains("strict_schedule_boundaries"));
assert!(
!super::from_legacy_backend_json(&legacy)
.unwrap()
.strict_schedule_boundaries
);
assert!(super::to_legacy_backend_json(&explicit).is_err());
}
}