use std::io::Write;
use std::path::PathBuf;
use std::process::ExitCode;
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
mod health;
const MAX_TIMEOUT_MS: u64 = 86_400_000;
const DEFAULT_STORE_MAX: u64 = 4 << 30;
#[derive(Debug, PartialEq)]
struct Options {
project: PathBuf,
cargo_home: PathBuf,
harnesses: Vec<String>,
unwind: Option<u32>,
jobs: Option<u32>,
arguments: Vec<sail_kani::arguments::Argument>,
solver_policy: sail_kani::SolverPolicy,
timeout_ms: u64,
memory_max: Option<u64>,
harness_memory_max: Option<u64>,
store_max: Option<u64>,
json: bool,
receipts: bool,
}
impl Options {
#[cfg(any(
test,
any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
)
))]
fn single(&self) -> bool {
self.harnesses.len() == 1 && self.jobs.is_none()
}
}
fn pass_through<'a>(
flag: &str,
tokens: &mut impl Iterator<Item = &'a String>,
arguments: &mut Vec<sail_kani::arguments::Argument>,
) -> Result<bool, String> {
use sail_kani::arguments::Argument;
let takes_value = Argument::takes_value(flag);
if !takes_value
&& !matches!(
flag,
"--all-features" | "--no-default-features" | "--workspace" | "--randomize-layout"
)
{
return Ok(false);
}
let value = if takes_value {
Some(
tokens
.next()
.ok_or_else(|| format!("missing value for `{flag}`"))?
.as_str(),
)
} else {
None
};
let argument = Argument::parse(flag, value).map_err(|error| error.to_string())?;
let repeatable = matches!(
argument,
Argument::Unstable(_) | Argument::Package(_) | Argument::Features(_)
);
if !repeatable
&& arguments
.iter()
.any(|seen| std::mem::discriminant(seen) == std::mem::discriminant(&argument))
{
return Err(format!("duplicate Kani option `{flag}`"));
}
arguments.push(argument);
Ok(true)
}
fn push_harness(harnesses: &mut Vec<String>, value: &str) -> Result<(), String> {
if value.is_empty()
|| value.starts_with('-')
|| value.chars().any(char::is_control)
|| value.len() > 4096
{
return Err("use the exact hand-written harness name reported by Kani".into());
}
if harnesses.iter().any(|seen| seen == value) {
return Err(format!("duplicate harness `{value}`"));
}
harnesses.push(value.to_owned());
Ok(())
}
fn parse(args: &[String]) -> Result<Options, String> {
use sail_kani::arguments::Argument;
let mut values = std::collections::BTreeMap::new();
let mut harnesses = Vec::new();
let mut arguments: Vec<Argument> = Vec::new();
let mut tokens = args.iter();
let mut no_store = false;
let mut receipts = std::env::var("SAIL_KANI_RECEIPTS").map_or(true, |value| value != "off");
while let Some(flag) = tokens.next() {
if pass_through(flag, &mut tokens, &mut arguments)? {
continue;
}
if reuse_control(flag, &mut no_store, &mut receipts)? {
continue;
}
if !matches!(
flag.as_str(),
"--backend"
| "--project"
| "--cargo-home"
| "--harness"
| "--unwind"
| "--jobs"
| "--timeout-ms"
| "--memory-max"
| "--harness-memory-max"
| "--store-max"
| "--solver-policy"
| "--output"
) {
return Err(format!("unsupported Kani option `{flag}`"));
}
let value = tokens
.next()
.filter(|value| !value.starts_with("--"))
.ok_or_else(|| format!("missing value for `{flag}`"))?;
if flag == "--harness" {
push_harness(&mut harnesses, value)?;
continue;
}
if values.insert(flag.as_str(), value.as_str()).is_some() {
return Err(format!("duplicate Kani option `{flag}`"));
}
}
if values.get("--backend") != Some(&"kani") {
return Err("expected --backend kani".into());
}
let positive = |name: &str| -> Result<Option<u32>, String> {
values
.get(name)
.map(|value| {
value
.parse::<u32>()
.ok()
.filter(|value| *value > 0)
.ok_or_else(|| format!("{} must be a positive integer", &name[2..]))
})
.transpose()
};
let unwind = positive("--unwind")?;
let jobs = positive("--jobs")?;
let timeout_ms = values
.get("--timeout-ms")
.unwrap_or(&"600000")
.parse::<u64>()
.map_err(|_| "timeout-ms must be an integer")?;
if !(1..=MAX_TIMEOUT_MS).contains(&timeout_ms) {
return Err(format!("timeout-ms must be 1..={MAX_TIMEOUT_MS}"));
}
let [memory_max, harness_memory_max] =
["--memory-max", "--harness-memory-max"].map(|name| size(&values, name));
let (memory_max, harness_memory_max) = (memory_max?, harness_memory_max?);
let store_max = store_max(no_store, values.get("--store-max").copied())?;
let solver_policy = solver_policy(values.get("--solver-policy").copied())?;
let json = match values.get("--output") {
None => false,
Some(&"json") => true,
_ => return Err("expected --output json".into()),
};
let cargo_home = values
.get("--cargo-home")
.map(PathBuf::from)
.or_else(|| std::env::var_os("CARGO_HOME").map(PathBuf::from))
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")))
.ok_or("specify a prepared --cargo-home directory")?;
Ok(Options {
project: PathBuf::from(values.get("--project").unwrap_or(&".")),
cargo_home,
harnesses,
unwind,
jobs,
arguments,
solver_policy,
timeout_ms,
memory_max,
harness_memory_max,
store_max,
json,
receipts,
})
}
fn solver_policy(value: Option<&str>) -> Result<sail_kani::SolverPolicy, String> {
match value {
None => Ok(sail_kani::SolverPolicy::Original),
Some("remembered-best") => Ok(sail_kani::SolverPolicy::RememberedBest),
_ => Err("SAIL6380: expected --solver-policy remembered-best".into()),
}
}
fn reuse_control(flag: &str, no_store: &mut bool, receipts: &mut bool) -> Result<bool, String> {
match flag {
"--no-store" => {
if std::mem::replace(no_store, true) {
return Err(format!("duplicate Kani option `{flag}`"));
}
}
"--no-receipts" => *receipts = false,
_ => return Ok(false),
}
Ok(true)
}
fn size(
values: &std::collections::BTreeMap<&str, &str>,
name: &str,
) -> Result<Option<u64>, String> {
values
.get(name)
.map(|value| {
sail_kani_size(value).map_err(|error| format!("SAIL6343: {}: {error}", &name[2..]))
})
.transpose()
}
fn store_max(no_store: bool, value: Option<&str>) -> Result<Option<u64>, String> {
match (no_store, value) {
(true, Some(_)) => Err("SAIL6350: --store-max and --no-store cannot be combined".into()),
(true, None) => Ok(None),
(false, None) => Ok(Some(DEFAULT_STORE_MAX)),
(false, Some(value)) => sail_kani_size(value)
.map(Some)
.map_err(|error| format!("SAIL6350: store-max: {error}")),
}
}
#[cfg(unix)]
fn sail_kani_size(text: &str) -> Result<u64, String> {
sail_kani::supervise::parse_size(text)
}
#[cfg(not(unix))]
fn sail_kani_size(_text: &str) -> Result<u64, String> {
Err("memory limits need a Unix host".into())
}
pub(crate) fn requested(args: &[String]) -> bool {
args.iter()
.take_while(|arg| arg.as_str() != "--")
.any(|arg| arg == "--backend" || arg.starts_with("--backend="))
}
pub(crate) fn verify(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> ExitCode {
let result = parse(args).and_then(|options| execute(&options, out));
match result {
Ok(code) => ExitCode::from(code),
Err(error) if error.starts_with("error[") => {
let _ = writeln!(err, "{error}");
ExitCode::from(2)
}
Err(error) => {
let _ = writeln!(err, "error[SAIL6306]: experimental Kani check: {error}");
ExitCode::from(2)
}
}
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn evidence_tier(
evidence: &sail_api::bounded::Evidence,
) -> Option<sail_api::output::EvidenceTierName> {
evidence.tier.map(Into::into)
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn outcome_name(outcome: sail_kani::Outcome) -> &'static str {
match outcome {
sail_kani::Outcome::BoundedSuccess => "bounded_success",
sail_kani::Outcome::Counterexample => "counterexample",
sail_kani::Outcome::BoundInsufficient => "bound_insufficient",
sail_kani::Outcome::ExpectedPanicMissing => "expected_panic_missing",
sail_kani::Outcome::Unsupported => "unsupported",
}
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn stage(root: &std::path::Path) -> Result<(sail_kani::tools::Stage, PathBuf), String> {
use sail_kani::tools::{Stage, Tools};
let release = sail_kani::tools::RUNTIME_RELEASE;
let suffix = sail_kani::host::SUFFIX;
let runtime = root.join(format!("{release}-{suffix}"));
let (bundle, rust) = (runtime.join("bundle"), runtime.join("rust"));
let stage_path = root.join(format!("stage-{release}-{suffix}"));
let manifest = root.join(format!("stage-{release}-{suffix}.manifest.json"));
if let Ok(stage) = Stage::open(&stage_path, &bundle, &rust, &manifest) {
return Ok((stage, manifest));
}
let tools = Tools::authenticate(&bundle, &rust)
.map_err(|error| format!("{error}; run `sail engine install --backend kani`"))?;
let stage = if std::fs::symlink_metadata(&stage_path).is_ok() {
tools.inspect_stage(&stage_path)
} else {
tools.stage(&stage_path)
}
.map_err(|error| error.to_string())?;
stage.seal(&manifest).map_err(|error| error.to_string())?;
Ok((stage, manifest))
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn cancellation() -> Result<std::sync::Arc<std::sync::atomic::AtomicBool>, String> {
use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering};
let cancel = Arc::new(AtomicBool::new(false));
let signal = Arc::clone(&cancel);
ctrlc::set_handler(move || signal.store(true, Ordering::SeqCst))
.map_err(|error| format!("cannot install cancellation handler: {error}"))?;
if std::env::var_os(sail_mcp::KANI_STOP_ON_STDIN_EOF).is_some_and(|value| value == "1") {
cancel_at_end_of(std::io::stdin(), Arc::clone(&cancel));
}
Ok(cancel)
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn cancel_at_end_of(
mut input: impl std::io::Read + Send + 'static,
cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
let _ = std::io::copy(&mut input, &mut std::io::sink());
cancel.store(true, std::sync::atomic::Ordering::SeqCst);
})
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn execute(options: &Options, out: &mut dyn Write) -> Result<u8, String> {
use sail_kani::execution::{Check, Jobs, Request, Target};
use std::time::Duration;
let project = options
.project
.canonicalize()
.map_err(|error| format!("project: {error}"))?;
let cargo_home = options
.cargo_home
.canonicalize()
.map_err(|error| format!("Cargo home: {error}"))?;
let root = crate::kani_setup::root()?;
let cancel = cancellation()?;
let supervisor = std::env::current_exe()
.map_err(|error| format!("cannot locate sail: {error}"))?
.with_file_name(sail_kani::supervise::BINARY);
if options.receipts && options.solver_policy == sail_kani::SolverPolicy::Original {
sail_kani::receipts::prefetch_file_sha256(&supervisor);
}
let targets = root.join("targets");
{
use std::os::unix::fs::DirBuilderExt as _;
match std::fs::DirBuilder::new().mode(0o700).create(&targets) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(format!("kept targets: {error}")),
}
}
let limit = Duration::from_millis(options.timeout_ms);
let target = Target::acquire(
&targets,
&project,
&sail_kani::tools::identity(),
limit,
&cancel,
)
.map_err(|error| error.to_string())?;
sail_kani::execution::prefetch_delegation(&target, &supervisor);
let (stage, manifest) = stage(&root)?;
let attempt = crate::kani_setup::private_attempt(&root)?;
let (store, unavailable) = receipts(options, &root);
let jobs = (!options.single()).then(|| {
options
.jobs
.and_then(std::num::NonZeroU32::new)
.map_or(Jobs::Default, Jobs::Count)
});
let store_root = root.join("cbmc-store");
let request = Request {
project: &project,
cargo_home: &cargo_home,
harnesses: &options.harnesses,
unwind: options.unwind,
jobs,
arguments: &options.arguments,
solver_policy: options.solver_policy,
process_limit: limit,
supervisor: sail_kani::execution::Supervisor {
binary: &supervisor,
budget: options.memory_max,
harness_memory_max: options.harness_memory_max,
store: options
.store_max
.map(|max_bytes| sail_kani::execution::StoreRequest {
root: &store_root,
max_bytes,
}),
},
receipts: store.as_ref(),
};
let check = Check::Opened(&manifest);
if options.single() {
let capture = sail_kani::execution::run(
&stage,
check,
&target,
&request,
&attempt.join("capture"),
&cancel,
)
.map_err(|error| error.to_string())?;
let mut capture = capture;
if let Some(status) = unavailable {
capture.receipt = status;
}
return single(options, &capture, out);
}
let batch = sail_kani::execution::run_batch(
&stage,
check,
&target,
&request,
&attempt.join("capture"),
&cancel,
)
.map_err(|error| error.to_string())?;
let mut batch = batch;
if let Some(status) = unavailable {
batch.receipt = status;
}
report(options, &batch, target.directory(), out)
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn receipts(
options: &Options,
root: &std::path::Path,
) -> (
Option<sail_kani::receipts::Store>,
Option<sail_kani::receipts::Status>,
) {
if !options.receipts || options.solver_policy != sail_kani::SolverPolicy::Original {
return (None, None);
}
match sail_kani::receipts::Store::open(root) {
Ok(store) => (Some(store.with_ci_environment()), None),
Err(error) => (
None,
Some(sail_kani::receipts::Status::NotStored {
code: "SAIL6360".into(),
reason: error.to_string(),
replay_refused: None,
}),
),
}
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn memory_note(cgroup: Option<&sail_kani::supervise::Cgroup>) -> String {
match cgroup {
Some(
sail_kani::supervise::Cgroup::Delegated { .. }
| sail_kani::supervise::Cgroup::Sampled { .. },
) => String::new(),
Some(sail_kani::supervise::Cgroup::Unavailable { reason }) => format!(
"warning[SAIL6342]: memory supervision unavailable ({reason}); exit, signal, output and deadline were supervised\n"
),
None => "warning[SAIL6342]: memory supervision state not recorded\n".into(),
}
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn batch_document(
options: &Options,
batch: &sail_kani::execution::Batch,
target: &std::path::Path,
counts: &std::collections::BTreeMap<&str, usize>,
harnesses: &[serde_json::Value],
) -> serde_json::Value {
let selection = if options.harnesses.is_empty() {
serde_json::json!("all")
} else {
serde_json::json!(options.harnesses)
};
serde_json::json!({
"kind": "sail-kani-bounded-batch", "version": 1, "backend": "kani",
"experimental": true, "selection": selection, "unwind": options.unwind,
"arguments": options.arguments,
"jobs": options.jobs.map_or_else(|| serde_json::json!("default"), |jobs| serde_json::json!(jobs)),
"counts": counts, "harnesses": harnesses,
"capture": batch.directory, "target": target,
"memory_supervision": batch.cgroup, "scope_leftovers": batch.scope_leftovers,
"discovered_from": batch.discovered.files,
"result_store": batch.store,
"input_closure_authenticated": batch.receipt.hit(), "proof_authority": false,
"currentness_authority": false,
"cache_reused": batch.receipt.hit() || batch.store.replayed > 0,
"receipt": batch.receipt,
})
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn store_note(store: &sail_kani::execution::StoreSummary, receipt_hit: bool) -> String {
if store.used {
let label = if receipt_hit {
"Original result store"
} else {
"Result store"
};
format!(
"{label}: {} cbmc runs replayed, {} stored.\n",
store.replayed, store.stored
)
} else {
String::new()
}
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn harness_document(
options: &Options,
checked: &sail_kani::execution::Checked,
receipt_hit: bool,
) -> Result<(&'static str, serde_json::Value), String> {
let harness = &checked.decoded;
let evidence = checked
.bounded_evidence()
.map_err(|error| error.to_string())?;
let outcome = checked
.admitted()
.map(|observation| outcome_name(observation.outcome()));
let health = health::harness(
&evidence,
&checked.supervision,
checked.admitted(),
harness.duration_ms,
harness.native_exit_status.as_deref(),
receipt_hit,
&options.arguments,
);
let document = serde_json::json!({
"harness": harness.name,
"crate": harness.crate_name,
"backend": "kani",
"evidence_tier": evidence_tier(&evidence),
"outcome": outcome,
"native_status": harness.native_status,
"native_exit_status": harness.native_exit_status,
"duration_ms": harness.duration_ms,
"attributes": checked.attributes,
"solver": checked.admitted().and_then(|observation| {
checked
.attributes
.as_ref()
.map(|attributes| solver(&options.arguments, attributes, observation.mode(), checked.supervision.solver_choice()))
}),
"observation": checked.admitted(),
"refusal": checked.refusal(),
"supervision": checked.supervision,
"health": health,
"evidence": evidence,
});
Ok((outcome.unwrap_or("refused"), document))
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn report(
options: &Options,
batch: &sail_kani::execution::Batch,
target: &std::path::Path,
out: &mut dyn Write,
) -> Result<u8, String> {
let mut counts = std::collections::BTreeMap::from([
("bounded_success", 0_usize),
("counterexample", 0),
("bound_insufficient", 0),
("expected_panic_missing", 0),
("unsupported", 0),
("refused", 0),
]);
let mut harnesses = Vec::new();
for checked in &batch.harnesses {
let (outcome, document) = harness_document(options, checked, batch.receipt.hit())?;
*counts.entry(outcome).or_insert(0) += 1;
harnesses.push(document);
}
let code = if counts["refused"] > 0 {
2
} else {
u8::from(counts["bounded_success"] != batch.harnesses.len())
};
if options.json {
let mut result = batch_document(options, batch, target, &counts, &harnesses);
label_solver_policy(&mut result, options.solver_policy);
serde_json::to_writer(&mut *out, &result).map_err(|error| error.to_string())?;
writeln!(out).map_err(|error| error.to_string())?;
} else {
let mut named = std::collections::BTreeMap::new();
for checked in &batch.harnesses {
*named
.entry(checked.decoded.name.as_str())
.or_insert(0_usize) += 1;
}
for checked in &batch.harnesses {
let harness = &checked.decoded;
let label = if named[harness.name.as_str()] > 1 {
harness.id().to_string()
} else {
harness.name.clone()
};
match (checked.admitted(), checked.refusal()) {
(Some(observation), _) => writeln!(
out,
"experimental kani: {} for {label}",
outcome_name(observation.outcome()),
),
(None, refusal) => writeln!(
out,
"experimental kani: no admitted result for {label} (native {}): {}",
harness.native_status,
refusal.unwrap_or_default()
),
}
.map_err(|error| error.to_string())?;
if let Some(choice) = checked.supervision.solver_choice() {
writeln!(out, " SAT solver {} (remembered-best)", choice.name)
.map_err(|error| error.to_string())?;
}
}
write!(
out,
"{}{}",
memory_note(batch.cgroup.as_ref()),
store_note(&batch.store, batch.receipt.hit())
)
.map_err(|error| error.to_string())?;
writeln!(
out,
"{} harnesses: {} bounded_success, {} counterexample, {} bound_insufficient, {} expected_panic_missing, {} unsupported, {} without an admitted result\nOriginal captures: {}\n{}",
batch.harnesses.len(),
counts["bounded_success"],
counts["counterexample"],
counts["bound_insufficient"],
counts["expected_panic_missing"],
counts["unsupported"],
counts["refused"],
batch.directory.display(),
authority(&batch.receipt)
)
.map_err(|error| error.to_string())?;
}
Ok(code)
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn single(
options: &Options,
capture: &sail_kani::execution::Captured,
out: &mut dyn Write,
) -> Result<u8, String> {
let success = capture.observation.outcome() == sail_kani::Outcome::BoundedSuccess;
let evidence = capture
.bounded_evidence()
.map_err(|error| error.to_string())?;
if options.json {
let health = health::harness(
&evidence,
&capture.supervision,
Some(&capture.observation),
None,
None,
capture.receipt.hit(),
&options.arguments,
);
let mut result = serde_json::json!({
"kind": "sail-kani-bounded-result", "version": 1, "backend": "kani",
"experimental": true, "harness": options.harnesses[0],
"crate": capture.observation.crate_name(), "unwind": options.unwind,
"arguments": options.arguments,
"observation": capture.observation, "attributes": capture.attributes,
"solver": solver(&options.arguments, &capture.attributes, capture.observation.mode(), capture.supervision.solver_choice()),
"evidence_tier": evidence_tier(&evidence),
"evidence": evidence, "capture": capture.directory, "health": health,
"supervision": capture.supervision, "memory_supervision": capture.cgroup,
"result_store": capture.store,
"input_closure_authenticated": capture.receipt.hit(), "proof_authority": false,
"currentness_authority": false,
"cache_reused": capture.receipt.hit() || capture.store.replayed > 0,
"receipt": capture.receipt,
});
label_solver_policy(&mut result, options.solver_policy);
serde_json::to_writer(&mut *out, &result).map_err(|error| error.to_string())?;
writeln!(out).map_err(|error| error.to_string())?;
} else {
let unwind = options.unwind.map_or_else(
|| "bounds as declared".to_owned(),
|unwind| format!("unwind {unwind}"),
);
if let Some(choice) = capture.supervision.solver_choice() {
writeln!(out, "SAT solver {} (remembered-best)", choice.name)
.map_err(|error| error.to_string())?;
}
writeln!(
out,
"experimental kani: {} for {} ({unwind})\n{}{}Original captures: {}\n{}",
outcome_name(capture.observation.outcome()),
options.harnesses[0],
memory_note(capture.cgroup.as_ref()),
store_note(&capture.store, capture.receipt.hit()),
capture.directory.display(),
authority(&capture.receipt)
)
.map_err(|error| error.to_string())?;
}
Ok(u8::from(!success))
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn label_solver_policy(result: &mut serde_json::Value, policy: sail_kani::SolverPolicy) {
if policy == sail_kani::SolverPolicy::RememberedBest {
result["solver_policy"] = serde_json::json!("remembered-best");
}
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn authority(receipt: &sail_kani::receipts::Status) -> std::borrow::Cow<'static, str> {
if let Some(signer) = receipt.signer() {
format!("Replayed from a signed CI receipt for the exact request and source closure (signer {signer}).").into()
} else if receipt.hit() {
"Replayed from a local kani-v1 receipt: nothing in the input closure changed since the run that produced these results.".into()
} else {
"No reusable proof or source-currentness authority.".into()
}
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
fn solver(
arguments: &[sail_kani::arguments::Argument],
attributes: &sail_kani::Attributes,
mode: &sail_kani::Mode,
choice: Option<&sail_kani::supervise::SolverChoice>,
) -> serde_json::Value {
let argued = arguments
.iter()
.any(|argument| matches!(argument, sail_kani::arguments::Argument::Solver(_)));
let source = if choice.is_some() {
"remembered_best"
} else if argued {
"argument"
} else if attributes.solver.is_some() {
"annotation"
} else {
"tool_default"
};
let binary = (mode.solver == "kissat").then_some("bin/kissat");
let mut solver = serde_json::json!({
"name": mode.solver, "version": mode.solver_version, "source": source,
"binary": binary,
"binary_sha256": binary.and_then(sail_kani::tools::bundle_file_sha256),
});
if let Some(choice) = choice {
solver["selection"] = serde_json::json!(choice);
}
solver
}
#[cfg(not(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
)))]
fn execute(_options: &Options, _out: &mut dyn Write) -> Result<u8, String> {
Err("the pinned experimental Kani backend supports native Linux x86-64 and macOS arm64".into())
}
#[cfg(test)]
mod tests {
use super::{parse, requested};
fn args(text: &str) -> Vec<String> {
text.split_whitespace().map(str::to_owned).collect()
}
#[cfg(any(
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64")
))]
#[test]
fn end_of_stdin_cancels_the_run() -> std::io::Result<()> {
use std::io::Write as _;
use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering};
let (reader, mut writer) = std::io::pipe()?;
let cancel = Arc::new(AtomicBool::new(false));
let watcher = super::cancel_at_end_of(reader, Arc::clone(&cancel));
writer.write_all(b"ignored")?;
std::thread::sleep(std::time::Duration::from_millis(100));
assert!(
!cancel.load(Ordering::SeqCst),
"cancelled while stdin was open"
);
drop(writer);
assert!(watcher.join().is_ok());
assert!(
cancel.load(Ordering::SeqCst),
"not cancelled at end of stdin"
);
Ok(())
}
#[test]
fn bounds_identity_and_mode_boundaries_are_explicit() {
let valid = "--backend kani --harness pilot::proof --unwind 6 --cargo-home prepared";
let result = parse(&args(valid));
assert!(result.is_ok(), "{result:?}");
assert!(result.is_ok_and(|options| options.single()));
for suffix in [
" --unwind 8",
" --harness pilot::proof",
" --output xml",
" --background",
" -- --engine interactive",
" --timeout-ms 0",
" --timeout-ms 86400001",
" --jobs 0",
" --jobs x",
" --memory-max 0",
" --memory-max 3X",
" --harness-memory-max -1",
] {
assert!(
parse(&args(&format!("{valid}{suffix}"))).is_err(),
"{suffix}"
);
}
for text in [
"--backend other --harness pilot::proof --unwind 6",
"--backend kani --harness pilot::proof --unwind 0",
"--backend kani --harness -x",
] {
assert!(parse(&args(text)).is_err(), "{text}");
}
assert!(
parse(&args(
"--backend kani --harness proof --unwind 6 --cargo-home prepared"
))
.is_ok()
);
assert!(requested(&args(valid)));
assert!(!requested(&args("-- --backend kani")));
assert!(requested(&args("--backend=kani")));
}
#[test]
fn batch_selection_jobs_and_optional_unwind() -> Result<(), String> {
let all = parse(&args("--backend kani --cargo-home prepared"))?;
assert!(all.harnesses.is_empty() && !all.single());
assert_eq!(
(all.unwind, all.jobs, all.timeout_ms),
(None, None, 600_000)
);
let several = parse(&args(
"--backend kani --harness a::p --harness b::q --jobs 8 --cargo-home prepared",
))?;
assert_eq!(several.harnesses, ["a::p", "b::q"]);
assert_eq!(several.jobs, Some(8));
assert!(!several.single());
let one_parallel = parse(&args(
"--backend kani --harness a::p --jobs 2 --cargo-home prepared",
))?;
assert!(!one_parallel.single());
let unbounded = parse(&args("--backend kani --harness a::p --cargo-home prepared"))?;
assert!(unbounded.single() && unbounded.unwind.is_none());
assert!(parse(&args("--backend kani --timeout-ms 86400000 --cargo-home p")).is_ok());
let capped = parse(&args(
"--backend kani --memory-max 32G --harness-memory-max 1536M --cargo-home p",
))?;
assert_eq!(
(capped.memory_max, capped.harness_memory_max),
(Some(32 << 30), Some(1536 << 20))
);
Ok(())
}
#[test]
fn the_result_store_is_on_by_default_and_can_be_bounded_or_turned_off() -> Result<(), String> {
let default = parse(&args("--backend kani --cargo-home p"))?;
assert_eq!(default.store_max, Some(super::DEFAULT_STORE_MAX));
let bounded = parse(&args("--backend kani --cargo-home p --store-max 512M"))?;
assert_eq!(bounded.store_max, Some(512 << 20));
let off = parse(&args("--backend kani --no-store --cargo-home p"))?;
assert_eq!(off.store_max, None);
for text in [
"--backend kani --cargo-home p --no-store --store-max 1G",
"--backend kani --cargo-home p --no-store --no-store",
"--backend kani --cargo-home p --store-max 0",
"--backend kani --cargo-home p --store-max x",
] {
assert!(parse(&args(text)).is_err(), "{text}");
}
Ok(())
}
#[test]
fn the_two_reuse_controls_compose_independently() -> Result<(), String> {
let store_only = parse(&args(
"--backend kani --cargo-home p --no-receipts --store-max 64M",
))?;
assert!(!store_only.receipts);
assert_eq!(store_only.store_max, Some(64 << 20));
let both_off = parse(&args(
"--backend kani --cargo-home p --no-store --no-receipts",
))?;
assert!(!both_off.receipts);
assert_eq!(both_off.store_max, None);
Ok(())
}
#[test]
fn remembered_best_is_explicit_and_can_record_an_explicit_solver() -> Result<(), String> {
let original = parse(&args("--backend kani --cargo-home p"))?;
assert_eq!(original.solver_policy, sail_kani::SolverPolicy::Original);
let training = parse(&args(
"--backend kani --cargo-home p --solver-policy remembered-best --solver minisat",
))?;
assert_eq!(
training.solver_policy,
sail_kani::SolverPolicy::RememberedBest
);
assert_eq!(
training.arguments,
[sail_kani::arguments::Argument::Solver("minisat".into())]
);
assert!(parse(&args("--backend kani --cargo-home p --solver-policy race")).is_err());
Ok(())
}
#[test]
fn cargo_selection_and_kani_options_pass_through_in_order() -> Result<(), String> {
let options = parse(&args(
"--backend kani --cargo-home p -Z stubbing --all-features -p vmm --features a,b \
--workspace --solver kissat --harness-timeout 40m -Z function-contracts \
--no-default-features --package utils",
))?;
let rendered: Vec<String> = options
.arguments
.iter()
.flat_map(sail_kani::arguments::Argument::render)
.collect();
assert_eq!(
rendered,
[
"-Z",
"stubbing",
"--all-features",
"--package",
"vmm",
"--features",
"a,b",
"--workspace",
"--solver",
"kissat",
"--harness-timeout",
"40m",
"-Z",
"function-contracts",
"--no-default-features",
"--package",
"utils"
]
);
for text in [
"-Z autoharness",
"-Z",
"--solver z3",
"--solver kissat --solver cadical",
"--workspace --workspace",
"--all-features --all-features",
"--harness-timeout 1s --harness-timeout 2s",
"--cbmc-args --unwind",
"--output-format old",
] {
let parsed = parse(&args(&format!("--backend kani --cargo-home p {text}")));
assert!(parsed.is_err(), "{text}");
}
let refused = parse(&args("--backend kani --cargo-home p -Z autoharness"));
assert!(refused.is_err_and(|error| error.starts_with("error[SAIL6330]")));
Ok(())
}
}