From f295764e89ca5e7afbf39c6ddcaefb14df82cc09 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Thu, 24 Sep 2026 22:35:23 -0700 Subject: [PATCH 01/24] Add an unstable --target option and a riscv64 machine model Kani's cargo target, sysroot, target allowlist and machine model were all keyed to the host triple, so code that only compiles for another target could not be verified. CBMC's machine model is data in the goto program, so no such host is needed. - kani-compiler: riscv64 (LP64D) machine model, riscv64gc target features, riscv64-unknown-linux-gnu in check_target. - kani-driver: --target , gated on -Z unstable-options; rejected with non-host concrete playback and with verify-std. - build-kani: `cargo build-dev --lib-target ` builds that target's verification libraries into targets//lib, a sysroot of its own; the host's lib/ is unchanged. - tests/script-based-pre/target_riscv64, run by kani-regression.sh. Towards #2402. Co-Authored-By: Claude Opus 5.5 --- docs/src/SUMMARY.md | 1 + docs/src/reference/experimental/target.md | 54 ++++++++++++++++ .../compiler_interface.rs | 60 ++++++++++++++++-- kani-driver/src/args/mod.rs | 32 ++++++++++ kani-driver/src/args/std_args.rs | 8 +++ kani-driver/src/call_cargo.rs | 19 +++--- kani-driver/src/call_single_file.rs | 8 ++- kani-driver/src/concrete_playback/playback.rs | 4 +- kani-driver/src/coverage/cov_session.rs | 4 +- kani-driver/src/session.rs | 19 ++++++ scripts/kani-regression.sh | 5 +- .../target_riscv64/config.yml | 4 ++ .../target_riscv64/riscv64.rs | 24 ++++++++ .../target_riscv64/sample_crate/Cargo.toml | 12 ++++ .../target_riscv64/sample_crate/src/lib.rs | 32 ++++++++++ .../target_riscv64/target_riscv64.expected | 17 ++++++ .../target_riscv64/target_riscv64.sh | 25 ++++++++ tools/build-kani/src/main.rs | 6 +- tools/build-kani/src/parser.rs | 4 ++ tools/build-kani/src/sysroot.rs | 61 +++++++++++++++---- 20 files changed, 366 insertions(+), 33 deletions(-) create mode 100644 docs/src/reference/experimental/target.md create mode 100644 tests/script-based-pre/target_riscv64/config.yml create mode 100644 tests/script-based-pre/target_riscv64/riscv64.rs create mode 100644 tests/script-based-pre/target_riscv64/sample_crate/Cargo.toml create mode 100644 tests/script-based-pre/target_riscv64/sample_crate/src/lib.rs create mode 100644 tests/script-based-pre/target_riscv64/target_riscv64.expected create mode 100755 tests/script-based-pre/target_riscv64/target_riscv64.sh diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index eb9544fd0d3..ee83e23d8d6 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -28,6 +28,7 @@ - [Loop Contracts](./reference/experimental/loop-contracts.md) - [Concrete Playback](./reference/experimental/concrete-playback.md) - [Quantifiers](./reference/experimental/quantifiers.md) + - [Verifying for another target](./reference/experimental/target.md) - [Application](./application.md) - [Comparison with other tools](./tool-comparison.md) - [Where to start on real code](./tutorial-real-code.md) diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md new file mode 100644 index 00000000000..5f23cf8bcfd --- /dev/null +++ b/docs/src/reference/experimental/target.md @@ -0,0 +1,54 @@ +# Verifying for another target + +By default Kani verifies a crate as it would be compiled for the host: the same pointer width, +endianness, `cfg(target_arch)` and C type sizes. With `--target`, Kani verifies it for another +target triple instead, from the same host. This is useful for code that only compiles for a +platform you do not develop on, such as a kernel's `riscv64` modules on an x86_64 or Apple +Silicon machine. + +This is an experimental feature, tracked in [#2402](https://github.com/model-checking/kani/issues/2402). + +## Supported targets + +A target needs a CBMC machine model in Kani. These are the targets that have one: + +| Target | Notes | +|--------|-------| +| `x86_64-unknown-linux-gnu` | | +| `aarch64-unknown-linux-gnu` | | +| `riscv64gc-unknown-linux-gnu` | LP64D data model | +| `x86_64-apple-darwin` | | +| `aarch64-apple-darwin` | | + +Any other target is rejected by the compiler with an error that lists these. + +## Building the libraries + +Kani verifies against its own build of the standard library and of the `kani` crate, compiled for +the target. Release bundles contain these for the host only, so today `--target` needs Kani +built from source ([build from source](../../build-from-source.md)), with each extra target named: + +```bash +cargo build-dev --lib-target riscv64gc-unknown-linux-gnu +``` + +The option may be repeated. Each target's libraries go to `targets//lib/` beside the +host's `lib/`, so one Kani installation can verify for several targets. The rustup target itself +does not need to be installed: the standard library is built from the `rust-src` component. + +## Usage + +```bash +kani file.rs --target riscv64gc-unknown-linux-gnu -Z unstable-options +cargo kani --target riscv64gc-unknown-linux-gnu -Z unstable-options +``` + +## Limitations + +* `--concrete-playback` is rejected with a non-host `--target`, because the generated test runs + on the host. +* The `verify-std` subcommand does not support `--target`. +* Inline assembly is unsupported on every target, as it is on the host. Code behind + `core::arch::asm!` has to be [stubbed](stubbing.md) to be verified. +* Only 64-bit little-endian targets are supported. A 32-bit target needs `goto-cc -m32` and a + review of Kani's 64-bit assumptions ([#2086](https://github.com/model-checking/kani/issues/2086)). diff --git a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs index 9c65098f234..6e61e1962e4 100644 --- a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs +++ b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs @@ -309,6 +309,12 @@ impl CodegenBackend for GotocCodegenBackend { // AArch64 mandates Neon support _ => vec![sym::neon], } + } else if sess.target.arch == Arch::RiscV64 && sess.target.os != Os::None { + // The features of `riscv64gc` (`+m,+a,+f,+d,+c,+zicsr,+zifencei`), with the features + // each implies. The LP64D ABI requires `d`, and rustc warns when it is missing. + ["a", "c", "d", "f", "m", "zaamo", "zalrsc", "zca", "zicsr", "zifencei", "zmmul"] + .map(Symbol::intern) + .to_vec() } else { vec![] }; @@ -608,16 +614,19 @@ fn check_target(session: &Session) { let is_x86_64_darwin_target = session.target.llvm_target.starts_with("x86_64-apple-"); // looking for `arm64-apple-*` let is_arm64_darwin_target = session.target.llvm_target.starts_with("arm64-apple-"); + // `riscv64gc-unknown-linux-gnu`, whose LLVM target drops the `gc`. + let is_riscv64_linux_target = session.target.llvm_target == "riscv64-unknown-linux-gnu"; if !is_x86_64_linux_target && !is_arm64_linux_target && !is_x86_64_darwin_target && !is_arm64_darwin_target + && !is_riscv64_linux_target { let err_msg = format!( "Kani requires the target platform to be `x86_64-unknown-linux-gnu`, \ - `aarch64-unknown-linux-gnu`, `x86_64-apple-*` or `arm64-apple-*`, but \ - it is {}", + `aarch64-unknown-linux-gnu`, `riscv64gc-unknown-linux-gnu`, `x86_64-apple-*` \ + or `arm64-apple-*`, but it is {}", session.target.llvm_target ); session.dcx().err(err_msg); @@ -801,8 +810,8 @@ impl GotoCodegenResults { /// Builds a machine model which is required by CBMC fn new_machine_model(sess: &Session) -> MachineModel { - // The model assumes a `x86_64-unknown-linux-gnu`, `x86_64-apple-darwin` - // or `aarch64-apple-darwin` platform. We check the target platform in function + // The model assumes a `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu`, + // `riscv64gc-unknown-linux-gnu`, `x86_64-apple-darwin` or `aarch64-apple-darwin` platform. We check the target platform in function // `check_target` from src/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs // and error if it is not any of the ones we expect. let architecture = &sess.target.arch; @@ -917,6 +926,49 @@ fn new_machine_model(sess: &Session) -> MachineModel { word_size: int_width, } } + Arch::RiscV64 => { + // The RISC-V psABI's LP64D data model, which is also what CBMC's + // `set_arch_spec_riscv64` assumes: `char` is unsigned, `wchar_t` is a signed `int`, + // and `long double` is IEEE binary128. + // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/master/riscv-cc.adoc + let bool_width = 8; + let char_is_unsigned = true; + let char_width = 8; + let double_width = 64; + let float_width = 32; + let int_width = 32; + let long_double_width = 128; + let long_int_width = 64; + let long_long_int_width = 64; + let short_int_width = 16; + let single_width = 32; + let wchar_t_is_unsigned = false; + let wchar_t_width = 32; + + MachineModel { + architecture: "riscv64".to_string(), + alignment, + bool_width, + char_is_unsigned, + char_width, + double_width, + float_width, + int_width, + is_big_endian, + long_double_width, + long_int_width, + long_long_int_width, + memory_operand_size: int_width / 8, + null_is_zero: true, + pointer_width, + rounding_mode: RoundingMode::ToNearest, + short_int_width, + single_width, + wchar_t_is_unsigned, + wchar_t_width, + word_size: int_width, + } + } _ => { panic!("Unsupported architecture: {architecture}"); } diff --git a/kani-driver/src/args/mod.rs b/kani-driver/src/args/mod.rs index 80cafbbcd2a..da25037de9f 100644 --- a/kani-driver/src/args/mod.rs +++ b/kani-driver/src/args/mod.rs @@ -91,6 +91,10 @@ pub fn print_stabilized_feature_warning( // By default we configure CBMC to use 16 bits to represent the object bits in pointers. const DEFAULT_OBJECT_BITS: u32 = 16; +/// The target triple Kani itself was built for, which is the default verification target +/// (see build.rs). +pub const HOST_TARGET: &str = env!("TARGET"); + #[derive(Clone, Copy, Debug, PartialEq, Eq, strum_macros::EnumString)] enum TimeUnit { #[strum(serialize = "s")] @@ -403,6 +407,12 @@ pub struct VerificationArgs { #[arg(long)] pub target_dir: Option, + /// Verify for this target triple instead of the host's, e.g. `riscv64gc-unknown-linux-gnu`. + /// Kani's libraries must have been built for it, see `cargo build-dev --lib-target`. + /// This option is experimental and requires `-Z unstable-options` to be used. + #[arg(long = "target", value_name = "TRIPLE")] + pub target_triple: Option, + /// Enable test function verification. Only use this option when the entry point is a test function #[arg(long)] pub tests: bool, @@ -477,6 +487,11 @@ impl VerificationArgs { self.common_args.unstable_features.contains(UnstableFeature::Lean) } + /// The target triple to verify for: the one given with `--target`, otherwise the host's. + pub fn verification_target(&self) -> &str { + self.target_triple.as_deref().unwrap_or(HOST_TARGET) + } + pub fn restrict_vtable(&self) -> bool { self.common_args.unstable_features.contains(UnstableFeature::RestrictVtable) && !self.no_restrict_vtable @@ -820,6 +835,12 @@ impl ValidateArgs for VerificationArgs { UnstableFeature::UnstableOptions, )?; + self.common_args.check_unstable( + self.target_triple.is_some(), + "target", + UnstableFeature::UnstableOptions, + )?; + Ok(()) }; @@ -857,6 +878,17 @@ impl ValidateArgs for VerificationArgs { --output-format=old.", )); } + if self.concrete_playback.is_some() + && let Some(triple) = &self.target_triple + && triple != HOST_TARGET + { + // Playback compiles and runs the generated test on the host. + return Err(Error::raw( + ErrorKind::ArgumentConflict, + "Conflicting options: --concrete-playback runs on the host, so it isn't \ + compatible with --target for another platform.", + )); + } if self.sarif.is_some() && self.output_format() == OutputFormat::Old { return Err(Error::raw( ErrorKind::ArgumentConflict, diff --git a/kani-driver/src/args/std_args.rs b/kani-driver/src/args/std_args.rs index 2968b1108cc..208e64f95ae 100644 --- a/kani-driver/src/args/std_args.rs +++ b/kani-driver/src/args/std_args.rs @@ -40,6 +40,14 @@ impl ValidateArgs for VerifyStdArgs { )); } + if self.verify_opts.target_triple.is_some() { + // Kani's `no_core` library, which `verify-std` builds against, exists for the host only. + return Err(Error::raw( + ErrorKind::ArgumentConflict, + "The `verify-std` subcommand does not support `--target`", + )); + } + validate_std_path(&self.std_path) } } diff --git a/kani-driver/src/call_cargo.rs b/kani-driver/src/call_cargo.rs index a555e27a3a6..518eaba50a5 100644 --- a/kani-driver/src/call_cargo.rs +++ b/kani-driver/src/call_cargo.rs @@ -1,11 +1,11 @@ // Copyright Kani Contributors // SPDX-License-Identifier: Apache-2.0 OR MIT -use crate::args::VerificationArgs; +use crate::args::{HOST_TARGET, VerificationArgs}; use crate::call_single_file::LibConfig; use crate::project::Artifact; use crate::session::{ - KaniSession, get_cargo_path, lib_folder, lib_no_core_folder, setup_cargo_command, + KaniSession, get_cargo_path, lib_folder_for, lib_no_core_folder, setup_cargo_command, setup_cargo_command_inner, }; use crate::util; @@ -97,7 +97,7 @@ crate-type = ["lib"] ])); let mut cargo_args: Vec = vec!["build".into()]; - cargo_args.append(&mut cargo_config_args()); + cargo_args.append(&mut cargo_config_args(HOST_TARGET)); // Configuration needed to parse cargo compilation status. cargo_args.push("--message-format".into()); @@ -140,7 +140,8 @@ crate-type = ["lib"] /// Calls `cargo_build` to generate `*.symtab.json` files in `target_dir` pub fn cargo_build(&mut self, keep_going: bool) -> Result { - let build_target = env!("TARGET"); // see build.rs + let build_target = self.args.verification_target().to_string(); + let build_target = build_target.as_str(); let metadata = self.cargo_metadata(build_target)?; let target_dir = self .args @@ -157,7 +158,7 @@ crate-type = ["lib"] fs::remove_dir_all(&target_dir)?; } - let lib_path = lib_folder().unwrap(); + let lib_path = lib_folder_for(build_target)?; let mut rustc_args = self.kani_rustc_flags(LibConfig::new(lib_path)); rustc_args.push(encode_as_rustc_arg(&self.kani_compiler_dependency_flags())); @@ -177,7 +178,7 @@ crate-type = ["lib"] // declare the same features. This matches cargo's behavior. let requested_features = self.args.cargo.features(); - cargo_args.append(&mut cargo_config_args()); + cargo_args.append(&mut cargo_config_args(build_target)); cargo_args.push("--target-dir".into()); cargo_args.push(target_dir.into()); @@ -499,10 +500,12 @@ crate-type = ["lib"] } } -pub fn cargo_config_args() -> Vec { +/// The cargo arguments that build for `target`, which is the host's triple unless the user asked +/// for another with `--target`. +pub fn cargo_config_args(target: &str) -> Vec { [ "--target", - env!("TARGET"), + target, // Propagate `--cfg=kani_host` to build scripts. "-Zhost-config", "-Ztarget-applies-to-host", diff --git a/kani-driver/src/call_single_file.rs b/kani-driver/src/call_single_file.rs index 86dda556cca..25cb9326006 100644 --- a/kani-driver/src/call_single_file.rs +++ b/kani-driver/src/call_single_file.rs @@ -6,7 +6,7 @@ use kani_metadata::UnstableFeature; use std::path::{Path, PathBuf}; use std::process::Command; -use crate::session::{KaniSession, lib_folder}; +use crate::session::{KaniSession, lib_folder_for}; use crate::util::args::{CommandWrapper, KaniArg, PassTo, RustcArg, encode_as_rustc_arg}; pub struct LibConfig { @@ -64,8 +64,12 @@ impl KaniSession { let mut kani_args = self.kani_compiler_local_flags(); kani_args.push(format!("--reachability={}", self.reachability_mode()).into()); - let lib_path = lib_folder().unwrap(); + let lib_path = lib_folder_for(self.args.verification_target())?; let mut rustc_args = self.kani_rustc_flags(LibConfig::new(lib_path)); + if let Some(triple) = &self.args.target_triple { + rustc_args.push("--target".into()); + rustc_args.push(triple.into()); + } rustc_args.push(file.into()); rustc_args.push("--out-dir".into()); rustc_args.push(RustcArg::from(outdir.as_os_str())); diff --git a/kani-driver/src/concrete_playback/playback.rs b/kani-driver/src/concrete_playback/playback.rs index 6ee8398e6c9..85af40c0cb2 100644 --- a/kani-driver/src/concrete_playback/playback.rs +++ b/kani-driver/src/concrete_playback/playback.rs @@ -3,6 +3,7 @@ //! Implements the logic related to the playback subcommand //! This can be achieved with playback --test +use crate::args::HOST_TARGET; use crate::args::common::Verbosity; use crate::args::playback_args::{CargoPlaybackArgs, KaniPlaybackArgs, MessageFormat}; use crate::call_cargo::cargo_config_args; @@ -114,7 +115,8 @@ fn cargo_test(args: CargoPlaybackArgs) -> Result<()> { } cargo_args.append(&mut args.cargo.to_cargo_args()); - cargo_args.append(&mut cargo_config_args()); + // Playback runs the test on the host. + cargo_args.append(&mut cargo_config_args(HOST_TARGET)); // These have to be the last arguments to cargo test. if !args.playback.test_args.is_empty() { diff --git a/kani-driver/src/coverage/cov_session.rs b/kani-driver/src/coverage/cov_session.rs index d29759299c9..52603249de3 100644 --- a/kani-driver/src/coverage/cov_session.rs +++ b/kani-driver/src/coverage/cov_session.rs @@ -26,7 +26,7 @@ impl KaniSession { } fn save_coverage_metadata_cargo(&self, project: &Project, stamp: &String) -> Result<()> { - let build_target = env!("TARGET"); + let build_target = self.args.verification_target(); let metadata = self.cargo_metadata(build_target)?; let target_dir = self .args @@ -109,7 +109,7 @@ impl KaniSession { results: &Vec, stamp: &String, ) -> Result<()> { - let build_target = env!("TARGET"); + let build_target = self.args.verification_target(); let metadata = self.cargo_metadata(build_target)?; let target_dir = self .args diff --git a/kani-driver/src/session.rs b/kani-driver/src/session.rs index 2adacf1070b..aa8c3e8012a 100644 --- a/kani-driver/src/session.rs +++ b/kani-driver/src/session.rs @@ -1,6 +1,7 @@ // Copyright Kani Contributors // SPDX-License-Identifier: Apache-2.0 OR MIT +use crate::args::HOST_TARGET; use crate::args::Timeout; use crate::args::VerificationArgs; use crate::args::autoharness_args::AutoharnessBounds; @@ -309,6 +310,24 @@ pub fn lib_folder() -> Result { Ok(base_folder()?.join("lib")) } +/// Return the folder with the pre-compiled rust libraries for verifying `target`. +/// The host's are in `lib/`. Any other target's are in `targets//lib/`, which is a +/// sysroot of its own, built by `cargo build-dev --lib-target `. +pub fn lib_folder_for(target: &str) -> Result { + if target == HOST_TARGET { + return lib_folder(); + } + let path = base_folder()?.join("targets").join(target).join("lib"); + if !path.is_dir() { + bail!( + "Kani's libraries have not been built for target `{target}` (expected them in `{}`). \ + From a Kani source checkout, build them with `cargo build-dev --lib-target {target}`.", + path.display() + ); + } + Ok(path) +} + /// Return the path for the folder where the pre-compiled rust libraries are located. pub fn lib_playback_folder() -> Result { Ok(base_folder()?.join("playback/lib")) diff --git a/scripts/kani-regression.sh b/scripts/kani-regression.sh index ddebd65f5e5..59d58cdad3e 100755 --- a/scripts/kani-regression.sh +++ b/scripts/kani-regression.sh @@ -30,8 +30,9 @@ check_kissat_version.sh # Formatting check ${SCRIPT_DIR}/kani-fmt.sh --check -# Build kani -cargo build-dev +# Build kani, with the libraries for one non-host target so that `--target` is tested +# (tests/script-based-pre/target_riscv64). +cargo build-dev --lib-target riscv64gc-unknown-linux-gnu # Unit tests cargo test -p cprover_bindings diff --git a/tests/script-based-pre/target_riscv64/config.yml b/tests/script-based-pre/target_riscv64/config.yml new file mode 100644 index 00000000000..ea039a9e43d --- /dev/null +++ b/tests/script-based-pre/target_riscv64/config.yml @@ -0,0 +1,4 @@ +# Copyright Kani Contributors +# SPDX-License-Identifier: Apache-2.0 OR MIT +script: target_riscv64.sh +expected: target_riscv64.expected diff --git a/tests/script-based-pre/target_riscv64/riscv64.rs b/tests/script-based-pre/target_riscv64/riscv64.rs new file mode 100644 index 00000000000..b33370e4de9 --- /dev/null +++ b/tests/script-based-pre/target_riscv64/riscv64.rs @@ -0,0 +1,24 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT +// +//! These harnesses exist only when Kani compiles for a riscv64 target, so they are verified only +//! with `--target riscv64gc-unknown-linux-gnu`. + +#[cfg(target_arch = "riscv64")] +mod riscv64 { + /// Facts that hold for `riscv64gc-unknown-linux-gnu` and not for every host Kani runs on: + /// `c_char` is unsigned there but signed on x86_64, and the LP64D ABI needs the `d` feature. + #[kani::proof] + fn target_is_riscv64gc() { + assert!(core::ffi::c_char::MIN == 0); + assert!(cfg!(target_feature = "d")); + assert!(core::mem::size_of::() == 8); + } + + /// A failing check, so the test also shows that CBMC checked the riscv64 program. + #[kani::proof] + fn overflow_is_found() { + let x: u32 = kani::any(); + let _ = x + 1; + } +} diff --git a/tests/script-based-pre/target_riscv64/sample_crate/Cargo.toml b/tests/script-based-pre/target_riscv64/sample_crate/Cargo.toml new file mode 100644 index 00000000000..fa6b61fadd9 --- /dev/null +++ b/tests/script-based-pre/target_riscv64/sample_crate/Cargo.toml @@ -0,0 +1,12 @@ +# Copyright Kani Contributors +# SPDX-License-Identifier: Apache-2.0 OR MIT + +[package] +name = "sample_crate" +version = "0.1.0" +edition = "2024" + +[dependencies] + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(kani)'] } diff --git a/tests/script-based-pre/target_riscv64/sample_crate/src/lib.rs b/tests/script-based-pre/target_riscv64/sample_crate/src/lib.rs new file mode 100644 index 00000000000..18bfc6b373e --- /dev/null +++ b/tests/script-based-pre/target_riscv64/sample_crate/src/lib.rs @@ -0,0 +1,32 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A crate whose only harness exists when it is compiled for a riscv64 target. + +/// Reads the RISC-V `cycle` counter. Kani does not model the instruction, so the harness below +/// stubs it; the point is that this code only compiles for riscv64. +#[cfg(target_arch = "riscv64")] +pub fn cycles() -> u64 { + let value: u64; + unsafe { core::arch::asm!("rdcycle {}", out(reg) value) }; + value +} + +#[cfg(target_arch = "riscv64")] +pub fn elapsed(start: u64) -> u64 { + cycles().wrapping_sub(start) +} + +#[cfg(all(kani, target_arch = "riscv64"))] +mod verify { + fn stub_cycles() -> u64 { + kani::any() + } + + #[kani::proof] + #[kani::stub(super::cycles, stub_cycles)] + fn elapsed_never_panics() { + let start: u64 = kani::any(); + let _ = super::elapsed(start); + } +} diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected new file mode 100644 index 00000000000..c5baffa4bdc --- /dev/null +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -0,0 +1,17 @@ +[TEST] --target needs -Z unstable-options +error: The `--target` option is unstable and requires `-Z unstable-options` to be used. + +[TEST] single file on the host: the riscv64 harnesses are compiled out +No proof harnesses (functions with #[kani::proof]) were found to verify. + +[TEST] single file for riscv64 +Checking harness riscv64::target_is_riscv64gc... +VERIFICATION:- SUCCESSFUL +Checking harness riscv64::overflow_is_found... +attempt to add with overflow +VERIFICATION:- FAILED +Complete - 1 successfully verified harnesses, 1 failures, 2 total. + +[TEST] cargo kani for riscv64 +Checking harness verify::elapsed_never_panics... +Complete - 1 successfully verified harnesses, 0 failures, 1 total. diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh new file mode 100755 index 00000000000..e202c3ffaf5 --- /dev/null +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Copyright Kani Contributors +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# Verify for `riscv64gc-unknown-linux-gnu` from whatever host this runs on, through both `kani` +# and `cargo kani`. Needs Kani's libraries for that target, which `scripts/kani-regression.sh` +# builds with `cargo build-dev --lib-target riscv64gc-unknown-linux-gnu`. + +set +e +TARGET=riscv64gc-unknown-linux-gnu + +echo "[TEST] --target needs -Z unstable-options" +kani riscv64.rs --target $TARGET + +echo "[TEST] single file on the host: the riscv64 harnesses are compiled out" +kani riscv64.rs + +echo "[TEST] single file for riscv64" +kani riscv64.rs --target $TARGET -Z unstable-options + +echo "[TEST] cargo kani for riscv64" +pushd sample_crate > /dev/null +cargo kani --target $TARGET -Z unstable-options -Z stubbing +cargo clean +popd > /dev/null diff --git a/tools/build-kani/src/main.rs b/tools/build-kani/src/main.rs index 1e37cba165a..58b18c71ed9 100644 --- a/tools/build-kani/src/main.rs +++ b/tools/build-kani/src/main.rs @@ -11,7 +11,8 @@ mod parser; mod sysroot; use crate::sysroot::{ - build_bin, build_lib, build_tools, kani_no_core_lib, kani_playback_lib, kani_sysroot_lib, + build_bin, build_lib, build_target_lib, build_tools, kani_no_core_lib, kani_playback_lib, + kani_sysroot_lib, }; use anyhow::{Result, bail}; use clap::Parser; @@ -25,6 +26,9 @@ fn main() -> Result<()> { let bin_folder = &build_bin(&build_parser.args)?; if !build_parser.skip_libs { build_lib(bin_folder)?; + for target in &build_parser.lib_targets { + build_target_lib(bin_folder, target)?; + } } Ok(()) } diff --git a/tools/build-kani/src/parser.rs b/tools/build-kani/src/parser.rs index 718cbb00bcb..3e10a5ad262 100644 --- a/tools/build-kani/src/parser.rs +++ b/tools/build-kani/src/parser.rs @@ -21,6 +21,10 @@ pub struct BuildDevParser { /// libraries or the underlying Rust compiler. #[clap(long)] pub skip_libs: bool, + /// Also build Kani's verification libraries for this target triple, so that + /// `kani --target -Z unstable-options` can verify for it. May be repeated. + #[clap(long = "lib-target", value_name = "TRIPLE")] + pub lib_targets: Vec, } #[derive(Args, Debug, Eq, PartialEq)] diff --git a/tools/build-kani/src/sysroot.rs b/tools/build-kani/src/sysroot.rs index d577a013fa9..e04f6fe25fb 100644 --- a/tools/build-kani/src/sysroot.rs +++ b/tools/build-kani/src/sysroot.rs @@ -6,10 +6,13 @@ //! - `bin/`: Where all Kani binaries will be located. //! - `lib/`: Kani libraries as well as rust standard libraries. //! +//! - `targets//lib/`: the `lib/` folder for another target, when one is +//! requested with `--lib-target`. Each is a sysroot of its own. +//! //! Rustc expects the sysroot to have a specific folder layout: //! `{SYSROOT}/rustlib//lib/` //! -//! Note: We don't cross-compile. Target is the same as the host. +//! Kani's binaries always run on the host. Only the libraries are built for another target. use crate::{AutoRun, cp}; use anyhow::{Result, bail, format_err}; @@ -60,13 +63,19 @@ pub fn kani_no_core_lib() -> PathBuf { path_buf!(kani_sysroot(), "no_core/lib") } +/// Returns the path to where Kani and std pre-compiled libraries for `target` are stored, when +/// `target` is not the host. +pub fn kani_target_lib(target: &str) -> PathBuf { + path_buf!(kani_sysroot(), "targets", target, "lib") +} + /// Returns the path to where Kani's pre-compiled binaries are stored. fn kani_sysroot_bin() -> PathBuf { path_buf!(kani_sysroot(), "bin") } -/// Returns the build target -fn build_target() -> &'static str { +/// Returns the host target, which Kani's own libraries are built for unless asked otherwise. +fn host_target() -> &'static str { env!("TARGET") } @@ -83,12 +92,32 @@ pub fn build_lib(bin_folder: &Path) -> Result<()> { /// Build the `lib/` folder for the new sysroot used during verification. /// This will include Kani's libraries as well as the standard libraries compiled with --emit-mir. fn build_verification_lib(compiler_path: &Path) -> Result<()> { + build_verification_lib_for(compiler_path, host_target(), &kani_sysroot_lib()) +} + +/// Build the verification `lib/` folder for a target other than the host, in +/// `targets//lib/`. Only verification needs it: concrete playback runs on the host, and +/// `verify-std` uses the host's `no_core` library. +pub fn build_target_lib(bin_folder: &Path, target: &str) -> Result<()> { + if target == host_target() { + // The host's libraries are already in `lib/`. + return Ok(()); + } + let compiler_path = bin_folder.join("kani-compiler"); + build_verification_lib_for(&compiler_path, target, &kani_target_lib(target)) +} + +fn build_verification_lib_for( + compiler_path: &Path, + target: &str, + sysroot_lib: &Path, +) -> Result<()> { let extra_args = ["-Z", "build-std=panic_abort,std,test", "--config", "profile.dev.panic=\"abort\""]; let compiler_args = ["--kani-compiler", "-Cllvm-args=--ignore-global-asm --build-std"]; let packages = ["std", "kani", "kani_macros"]; - let artifacts = build_kani_lib(compiler_path, &packages, &extra_args, &compiler_args)?; - copy_artifacts(&artifacts, &kani_sysroot_lib(), true) + let artifacts = build_kani_lib(compiler_path, target, &packages, &extra_args, &compiler_args)?; + copy_artifacts(&artifacts, sysroot_lib, Some(target)) } /// Build the `lib-playback/` folder that will be used during counter example playback. @@ -97,26 +126,26 @@ fn build_playback_lib(compiler_path: &Path) -> Result<()> { let extra_args = ["--features=std/concrete_playback,kani/concrete_playback", "-Z", "build-std=std,test"]; let packages = ["std", "kani", "kani_macros"]; - let artifacts = build_kani_lib(compiler_path, &packages, &extra_args, &[])?; - copy_artifacts(&artifacts, &kani_playback_lib(), true) + let artifacts = build_kani_lib(compiler_path, host_target(), &packages, &extra_args, &[])?; + copy_artifacts(&artifacts, &kani_playback_lib(), Some(host_target())) } /// Build the no core library folder that will be used during std verification. fn build_no_core_lib(compiler_path: &Path) -> Result<()> { let extra_args = ["--features=kani_macros/no_core", "--features=kani_core/no_core"]; let packages = ["kani_core", "kani_macros"]; - let artifacts = build_kani_lib(compiler_path, &packages, &extra_args, &[])?; - copy_artifacts(&artifacts, &kani_no_core_lib(), false) + let artifacts = build_kani_lib(compiler_path, host_target(), &packages, &extra_args, &[])?; + copy_artifacts(&artifacts, &kani_no_core_lib(), None) } fn build_kani_lib( compiler_path: &Path, + target: &str, packages: &[&str], extra_cargo_args: &[&str], extra_rustc_args: &[&str], ) -> Result> { // Run cargo build with -Z build-std - let target = build_target(); let target_dir = env!("KANI_BUILD_LIBS"); let args = [ "build", @@ -180,7 +209,13 @@ fn build_kani_lib( } /// Copy all the artifacts to their correct place to generate a valid sysroot. -fn copy_artifacts(artifacts: &[Artifact], sysroot_lib: &Path, copy_std: bool) -> Result<()> { +/// With `std_target`, the standard libraries are also copied, into the folder rustc expects for +/// that target. +fn copy_artifacts( + artifacts: &[Artifact], + sysroot_lib: &Path, + std_target: Option<&str>, +) -> Result<()> { // Create sysroot folder. sysroot_lib.exists().then(|| fs::remove_dir_all(sysroot_lib)); fs::create_dir_all(sysroot_lib)?; @@ -189,8 +224,8 @@ fn copy_artifacts(artifacts: &[Artifact], sysroot_lib: &Path, copy_std: bool) -> copy_libs(artifacts, sysroot_lib, &is_kani_lib); // Copy standard libraries into rustlib//lib/ folder. - if copy_std { - let std_path = path_buf!(&sysroot_lib, "rustlib", build_target(), "lib"); + if let Some(target) = std_target { + let std_path = path_buf!(&sysroot_lib, "rustlib", target, "lib"); fs::create_dir_all(&std_path).unwrap_or_else(|_| panic!("Failed to create {std_path:?}")); copy_libs(artifacts, &std_path, &is_std_lib); } From 5ce11c835042224c8ed87ab6c17577a1e9d3f396 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Tue, 29 Sep 2026 20:20:51 -0700 Subject: [PATCH 02/24] test the two --target rejections; document the goto-cc arch overwrite The script test now exercises the --concrete-playback and verify-std rejections alongside the -Z gate, so every new argument conflict has coverage. The missing-library bail has no transcript-stable test: every target check_target accepts is a host triple on some CI runner, so its libraries exist somewhere in the matrix. The docs page's Limitations now carries the __CPROVER_architecture_* overwrite the README discloses. --- docs/src/reference/experimental/target.md | 6 ++++++ shim/kani | 2 ++ .../target_riscv64/target_riscv64.expected | 16 ++++++++++++++++ .../target_riscv64/target_riscv64.sh | 9 +++++++++ 4 files changed, 33 insertions(+) create mode 100755 shim/kani diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index 5f23cf8bcfd..22dcdd906ca 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -48,6 +48,12 @@ cargo kani --target riscv64gc-unknown-linux-gnu -Z unstable-options * `--concrete-playback` is rejected with a non-host `--target`, because the generated test runs on the host. * The `verify-std` subcommand does not support `--target`. +* After linking, `goto-cc` configures itself for the host, so the `__CPROVER_architecture_*` + symbols in the final `.out` are the host's rather than the ones Kani wrote; on macOS a + cross-target run reports the host's `arm64` and `char_is_unsigned = 0` there. The Rust side of + the goto program spells out its own widths and signedness, which is what the proof checks. This + is [#2086](https://github.com/model-checking/kani/issues/2086)'s problem in general form, and + `goto-cc`'s `-march` table has no entry for most Kani targets. * Inline assembly is unsupported on every target, as it is on the host. Code behind `core::arch::asm!` has to be [stubbed](stubbing.md) to be verified. * Only 64-bit little-endian targets are supported. A 32-bit target needs `goto-cc -m32` and a diff --git a/shim/kani b/shim/kani new file mode 100755 index 00000000000..a2948724e03 --- /dev/null +++ b/shim/kani @@ -0,0 +1,2 @@ +#!/bin/sh +exec /var/folders/k8/vfxgc_cs5l52g36064xt6n8r0000gn/T/opencode/kani-upstream-build/kani/target/kani/bin/kani-driver "$@" diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected index c5baffa4bdc..ae17eb85aa5 100644 --- a/tests/script-based-pre/target_riscv64/target_riscv64.expected +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -15,3 +15,19 @@ Complete - 1 successfully verified harnesses, 1 failures, 2 total. [TEST] cargo kani for riscv64 Checking harness verify::elapsed_never_panics... Complete - 1 successfully verified harnesses, 0 failures, 1 total. + +[TEST] --concrete-playback is refused for another target +error: Conflicting options: --concrete-playback runs on the host, so it isn't compatible with --target for another platform. + +Usage: kani [OPTIONS] [INPUT] + kani + +For more information, try '--help'. + +[TEST] verify-std is refused with --target +error: The `verify-std` subcommand does not support `--target` + +Usage: kani [OPTIONS] [INPUT] + kani + +For more information, try '--help'. diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh index e202c3ffaf5..40c4638c259 100755 --- a/tests/script-based-pre/target_riscv64/target_riscv64.sh +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -23,3 +23,12 @@ pushd sample_crate > /dev/null cargo kani --target $TARGET -Z unstable-options -Z stubbing cargo clean popd > /dev/null + +echo "[TEST] --concrete-playback is refused for another target" +kani riscv64.rs --target $TARGET -Z unstable-options -Z concrete-playback --concrete-playback print + +echo "[TEST] verify-std is refused with --target" +kani verify-std . --target $TARGET -Z unstable-options + +# The rejections above exit non-zero on purpose; the suite passes when the transcript matches. +exit 0 From 9023df2053d50cf121110a5dd071be0a1e275903 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Wed, 30 Sep 2026 08:39:45 -0700 Subject: [PATCH 03/24] drop the local verification shim committed by mistake A PATH wrapper pointing at this machine's build directory, created to run the committed test against the dev-built driver; it never belonged in the branch and the copyright check said so. --- shim/kani | 2 -- 1 file changed, 2 deletions(-) delete mode 100755 shim/kani diff --git a/shim/kani b/shim/kani deleted file mode 100755 index a2948724e03..00000000000 --- a/shim/kani +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -exec /var/folders/k8/vfxgc_cs5l52g36064xt6n8r0000gn/T/opencode/kani-upstream-build/kani/target/kani/bin/kani-driver "$@" From a5fac6aeb3f457a9e095596e81130a0b09f718fc Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Fri, 2 Oct 2026 23:07:31 -0700 Subject: [PATCH 04/24] Accept only the targets the machine models were written for check_target matched on the LLVM target alone. riscv64a23-unknown-linux-gnu and riscv64-wrs-vxworks share riscv64gc's LLVM target, but target_config reports riscv64gc's features for all of them, so a23 was accepted and verified with the wrong cfg(target_feature) set. The Apple prefix checks also let iOS, tvOS, visionOS and watchOS through now that --target makes them reachable. Match the OS for both, and the feature string for riscv64. The error now names the target triple as well as its LLVM target, since the LLVM target alone made a rejected a23 read like riscv64gc. Also rewrap an over-long comment in new_machine_model. Co-Authored-By: Claude Opus 5.5 --- .../compiler_interface.rs | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs index 6e61e1962e4..831157c859f 100644 --- a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs +++ b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs @@ -610,12 +610,19 @@ fn check_target(session: &Session) { let is_x86_64_linux_target = session.target.llvm_target == "x86_64-unknown-linux-gnu"; let is_arm64_linux_target = session.target.llvm_target == "aarch64-unknown-linux-gnu"; // Comparison with `x86_64-apple-darwin` does not work well because the LLVM - // target may become `x86_64-apple-macosx10.7.0` (or similar) and fail - let is_x86_64_darwin_target = session.target.llvm_target.starts_with("x86_64-apple-"); + // target may become `x86_64-apple-macosx10.7.0` (or similar) and + // fail. Other Apple targets (iOS, tvOS and so on) share these prefixes, so also match the OS. + let is_x86_64_darwin_target = + session.target.llvm_target.starts_with("x86_64-apple-") && session.target.os == Os::MacOs; // looking for `arm64-apple-*` - let is_arm64_darwin_target = session.target.llvm_target.starts_with("arm64-apple-"); + let is_arm64_darwin_target = + session.target.llvm_target.starts_with("arm64-apple-") && session.target.os == Os::MacOs; // `riscv64gc-unknown-linux-gnu`, whose LLVM target drops the `gc`. - let is_riscv64_linux_target = session.target.llvm_target == "riscv64-unknown-linux-gnu"; + // `riscv64a23-unknown-linux-gnu` and `riscv64-wrs-vxworks` share that LLVM target, so also + // match the OS and the features that `target_config` hardcodes. + let is_riscv64_linux_target = session.target.llvm_target == "riscv64-unknown-linux-gnu" + && session.target.os == Os::Linux + && session.target.features == "+m,+a,+f,+d,+c,+zicsr,+zifencei"; if !is_x86_64_linux_target && !is_arm64_linux_target @@ -625,8 +632,9 @@ fn check_target(session: &Session) { { let err_msg = format!( "Kani requires the target platform to be `x86_64-unknown-linux-gnu`, \ - `aarch64-unknown-linux-gnu`, `riscv64gc-unknown-linux-gnu`, `x86_64-apple-*` \ - or `arm64-apple-*`, but it is {}", + `aarch64-unknown-linux-gnu`, `riscv64gc-unknown-linux-gnu`, `x86_64-apple-darwin` \ + or `aarch64-apple-darwin`, but it is `{}` (LLVM target `{}`)", + session.opts.target_triple.tuple(), session.target.llvm_target ); session.dcx().err(err_msg); @@ -811,7 +819,8 @@ impl GotoCodegenResults { /// Builds a machine model which is required by CBMC fn new_machine_model(sess: &Session) -> MachineModel { // The model assumes a `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu`, - // `riscv64gc-unknown-linux-gnu`, `x86_64-apple-darwin` or `aarch64-apple-darwin` platform. We check the target platform in function + // `riscv64gc-unknown-linux-gnu`, `x86_64-apple-darwin` or `aarch64-apple-darwin` platform. + // We check the target platform in function // `check_target` from src/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs // and error if it is not any of the ones we expect. let architecture = &sess.target.arch; From 2d0a62316e007d67ce807f9447ecd1ef7f6ae830 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Fri, 2 Oct 2026 23:07:31 -0700 Subject: [PATCH 05/24] Correct the cause of the architecture overwrite in the target docs The overwrite does not come from linking. When goto-cc links goto binaries the first input's __CPROVER_architecture_* symbols win, and kani_lib.c reaches the link as C source, which goto-cc compiles with the host's configuration. Say so, and say what would keep the model Kani wrote. Co-Authored-By: Claude Opus 5.5 --- docs/src/reference/experimental/target.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index 22dcdd906ca..c22076ad0d6 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -48,12 +48,14 @@ cargo kani --target riscv64gc-unknown-linux-gnu -Z unstable-options * `--concrete-playback` is rejected with a non-host `--target`, because the generated test runs on the host. * The `verify-std` subcommand does not support `--target`. -* After linking, `goto-cc` configures itself for the host, so the `__CPROVER_architecture_*` - symbols in the final `.out` are the host's rather than the ones Kani wrote; on macOS a - cross-target run reports the host's `arm64` and `char_is_unsigned = 0` there. The Rust side of - the goto program spells out its own widths and signedness, which is what the proof checks. This - is [#2086](https://github.com/model-checking/kani/issues/2086)'s problem in general form, and - `goto-cc`'s `-march` table has no entry for most Kani targets. +* The `__CPROVER_architecture_*` symbols in the final `.out` are the host's rather than the ones + Kani wrote. When `goto-cc` links goto binaries, the first input's architecture symbols win, and + Kani currently passes `kani_lib.c` to the link as a C source, which `goto-cc` compiles with the + host's configuration. On macOS a cross-target run therefore reports the host's `arm64` and + `char_is_unsigned = 0` there. The Rust side of the goto program spells out its own widths and + signedness, which is what the proof checks, and every target Kani accepts has the same C type + widths as every supported host. Compiling `kani_lib.c` to a goto object ahead of time and + linking it after the Rust inputs would keep the model Kani wrote. * Inline assembly is unsupported on every target, as it is on the host. Code behind `core::arch::asm!` has to be [stubbed](stubbing.md) to be verified. * Only 64-bit little-endian targets are supported. A 32-bit target needs `goto-cc -m32` and a From 450cbc2fee24791e0f8fa3ffc5b59e1fedb9c8b0 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Sat, 3 Oct 2026 12:29:57 -0700 Subject: [PATCH 06/24] Tighten the --target test, docs and build-dev flags after self-review - build-dev: --lib-target conflicts with --skip-libs instead of being ignored. - target_riscv64: drop the usize-width assertion, which holds on every host Kani runs on and so does not show the target changed. - docs: name long double as a C width that differs (64-bit on macOS arm64, 128-bit on riscv64), and say where the overwritten model matters. Co-Authored-By: Claude Opus 5.5 --- docs/src/reference/experimental/target.md | 7 ++++--- tests/script-based-pre/target_riscv64/riscv64.rs | 1 - tools/build-kani/src/parser.rs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index c22076ad0d6..28cb6b2b25c 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -52,9 +52,10 @@ cargo kani --target riscv64gc-unknown-linux-gnu -Z unstable-options Kani wrote. When `goto-cc` links goto binaries, the first input's architecture symbols win, and Kani currently passes `kani_lib.c` to the link as a C source, which `goto-cc` compiles with the host's configuration. On macOS a cross-target run therefore reports the host's `arm64` and - `char_is_unsigned = 0` there. The Rust side of the goto program spells out its own widths and - signedness, which is what the proof checks, and every target Kani accepts has the same C type - widths as every supported host. Compiling `kani_lib.c` to a goto object ahead of time and + `char_is_unsigned = 0` there, and a 64-bit `long double` where riscv64's is 128-bit. The Rust + side of the goto program spells out its own widths and signedness, which is what the proof + checks, so this matters only where CBMC interprets C: `kani_lib.c`, its C library models, and + any C code a harness reaches. Compiling `kani_lib.c` to a goto object ahead of time and linking it after the Rust inputs would keep the model Kani wrote. * Inline assembly is unsupported on every target, as it is on the host. Code behind `core::arch::asm!` has to be [stubbed](stubbing.md) to be verified. diff --git a/tests/script-based-pre/target_riscv64/riscv64.rs b/tests/script-based-pre/target_riscv64/riscv64.rs index b33370e4de9..baf41a917ce 100644 --- a/tests/script-based-pre/target_riscv64/riscv64.rs +++ b/tests/script-based-pre/target_riscv64/riscv64.rs @@ -12,7 +12,6 @@ mod riscv64 { fn target_is_riscv64gc() { assert!(core::ffi::c_char::MIN == 0); assert!(cfg!(target_feature = "d")); - assert!(core::mem::size_of::() == 8); } /// A failing check, so the test also shows that CBMC checked the riscv64 program. diff --git a/tools/build-kani/src/parser.rs b/tools/build-kani/src/parser.rs index 3e10a5ad262..fc233304954 100644 --- a/tools/build-kani/src/parser.rs +++ b/tools/build-kani/src/parser.rs @@ -23,7 +23,7 @@ pub struct BuildDevParser { pub skip_libs: bool, /// Also build Kani's verification libraries for this target triple, so that /// `kani --target -Z unstable-options` can verify for it. May be repeated. - #[clap(long = "lib-target", value_name = "TRIPLE")] + #[clap(long = "lib-target", value_name = "TRIPLE", conflicts_with = "skip_libs")] pub lib_targets: Vec, } From 1eaa2d9a3e714a95b6ec5a441273468f97b84b19 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 09:56:09 -0700 Subject: [PATCH 07/24] Keep the target's machine model in the linked goto binary link_goto_binary passed kani_lib.c to goto-cc as C source. goto-cc compiles it with the host's C configuration, and that configuration replaced the __CPROVER_architecture_* symbols kani-compiler wrote, so a riscv64 run was checked with the host's char signedness and long double width (CBMC printed "Adding CPROVER library (arm64)" on a macOS host). When goto-cc links goto binaries the first input's symbols win. For a cross target, compile kani_lib.c to an object next to the link output and pass it after the Rust inputs. Host runs keep the old command line. --c-lib now conflicts with a cross --target: those sources would also be compiled for the host and replace the model. goto-cc does accept clang's --target=, but it only sets the architecture (not the OS), and needs a native compiler that understands the flag, which gcc does not. Co-Authored-By: Claude Opus 5.5 --- kani-driver/src/args/mod.rs | 52 ++++++++++++++++++++++++++++++--- kani-driver/src/call_goto_cc.rs | 26 +++++++++++++++-- 2 files changed, 71 insertions(+), 7 deletions(-) diff --git a/kani-driver/src/args/mod.rs b/kani-driver/src/args/mod.rs index da25037de9f..c2b400a338d 100644 --- a/kani-driver/src/args/mod.rs +++ b/kani-driver/src/args/mod.rs @@ -492,6 +492,11 @@ impl VerificationArgs { self.target_triple.as_deref().unwrap_or(HOST_TARGET) } + /// Whether `--target` names a platform other than the host's. + pub fn is_cross_target(&self) -> bool { + self.verification_target() != HOST_TARGET + } + pub fn restrict_vtable(&self) -> bool { self.common_args.unstable_features.contains(UnstableFeature::RestrictVtable) && !self.no_restrict_vtable @@ -878,10 +883,7 @@ impl ValidateArgs for VerificationArgs { --output-format=old.", )); } - if self.concrete_playback.is_some() - && let Some(triple) = &self.target_triple - && triple != HOST_TARGET - { + if self.concrete_playback.is_some() && self.is_cross_target() { // Playback compiles and runs the generated test on the host. return Err(Error::raw( ErrorKind::ArgumentConflict, @@ -889,6 +891,16 @@ impl ValidateArgs for VerificationArgs { compatible with --target for another platform.", )); } + if !self.c_lib.is_empty() && self.is_cross_target() { + // goto-cc compiles C sources with the host's C configuration, and when it + // compiles them as part of a link, that configuration replaces the target's + // machine model in the linked binary. + return Err(Error::raw( + ErrorKind::ArgumentConflict, + "Conflicting options: --c-lib is compiled for the host, so it isn't \ + compatible with --target for another platform.", + )); + } if self.sarif.is_some() && self.output_format() == OutputFormat::Old { return Err(Error::raw( ErrorKind::ArgumentConflict, @@ -1556,4 +1568,36 @@ mod tests { assert_eq!(err.kind(), ErrorKind::ArgumentConflict, "for `{args}`"); } } + + /// A target triple that is not the host's, whatever the host is. + fn other_target() -> &'static str { + if HOST_TARGET == "riscv64gc-unknown-linux-gnu" { + "x86_64-unknown-linux-gnu" + } else { + "riscv64gc-unknown-linux-gnu" + } + } + + #[test] + fn check_c_lib_conflicts_with_cross_target() { + let args = format!( + "kani input.rs -Z unstable-options -Z c-ffi --c-lib lib.c --target {}", + other_target() + ); + let err = StandaloneArgs::try_parse_from(args.split_whitespace()) + .unwrap() + .verify_opts + .validate() + .unwrap_err(); + assert_eq!(err.kind(), ErrorKind::ArgumentConflict); + + let args = format!( + "kani input.rs -Z unstable-options -Z c-ffi --c-lib lib.c --target {HOST_TARGET}" + ); + StandaloneArgs::try_parse_from(args.split_whitespace()) + .unwrap() + .verify_opts + .validate() + .unwrap(); + } } diff --git a/kani-driver/src/call_goto_cc.rs b/kani-driver/src/call_goto_cc.rs index b906c256904..50bc1fa59da 100644 --- a/kani-driver/src/call_goto_cc.rs +++ b/kani-driver/src/call_goto_cc.rs @@ -16,9 +16,29 @@ impl KaniSession { args.extend(inputs.iter().map(|x| x.clone().into_os_string())); args.extend(self.args.c_lib.iter().map(|x| x.clone().into_os_string())); - // TODO think about this: kani_lib_c is just an empty c file. Maybe we could just - // create such an empty file ourselves instead of having to look up this path. - args.push(self.kani_lib_c.clone().into_os_string()); + if self.args.is_cross_target() { + // goto-cc compiles any C source it is given with the host's C configuration, and + // that configuration then replaces the `__CPROVER_architecture_*` symbols that + // kani-compiler wrote for the target. When it links goto binaries instead, the first + // input's symbols win. So compile `kani_lib.c` on its own and link the object after + // the Rust inputs, which keeps the target's machine model. + // + // The object is still compiled for the host. That is safe because, outside its + // headers, `kani_lib.c` uses only `size_t`, `uint8_t` and pointers, never `int`, + // `long double`, `wchar_t` or `char` (apart from its ASCII assertion messages), and + // those three types are the same width on every target `check_target` accepts. + // `--c-lib` is rejected with a cross target, because arbitrary C has no such limit. + let kani_lib_o = output.with_extension("kani_lib.o"); + self.record_temporary_file(&kani_lib_o); + let mut cmd = Command::new("goto-cc"); + cmd.arg("-c").arg(&self.kani_lib_c).arg("-o").arg(&kani_lib_o); + self.run_suppress(cmd)?; + args.push(kani_lib_o.into_os_string()); + } else { + // `kani_lib.c` defines the allocator entry points (`__rust_alloc` and friends) that + // rustc expects a backend to provide. + args.push(self.kani_lib_c.clone().into_os_string()); + } args.push("-o".into()); args.push(output.to_owned().into_os_string()); From 08bbefe039701f49aa578e7e1b3869c0b7803454 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 09:56:09 -0700 Subject: [PATCH 08/24] Check the machine model in the linked riscv64 goto binary The target_riscv64 assertions are rustc facts (c_char, cfg), which hold whatever machine model CBMC ends up using. Inspect the binary Kani links for a harness and check that __CPROVER_architecture_arch is riscv64 and char_is_unsigned is 1. Without the previous commit it reads "arm64" and 0 on a macOS arm64 host. Co-Authored-By: Claude Opus 5.5 --- .../target_riscv64/target_riscv64.expected | 4 ++++ .../target_riscv64/target_riscv64.sh | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected index ae17eb85aa5..1e593efb9a0 100644 --- a/tests/script-based-pre/target_riscv64/target_riscv64.expected +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -12,6 +12,10 @@ attempt to add with overflow VERIFICATION:- FAILED Complete - 1 successfully verified harnesses, 1 failures, 2 total. +[TEST] the linked goto binary keeps the riscv64 machine model +__CPROVER_architecture_arch = "riscv64" +__CPROVER_architecture_char_is_unsigned = 1 + [TEST] cargo kani for riscv64 Checking harness verify::elapsed_never_panics... Complete - 1 successfully verified harnesses, 0 failures, 1 total. diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh index 40c4638c259..4fbc3332a07 100755 --- a/tests/script-based-pre/target_riscv64/target_riscv64.sh +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -18,6 +18,21 @@ kani riscv64.rs echo "[TEST] single file for riscv64" kani riscv64.rs --target $TARGET -Z unstable-options +echo "[TEST] the linked goto binary keeps the riscv64 machine model" +# CBMC takes its C semantics (char signedness, long double width, the C library it adds) from the +# __CPROVER_architecture_* symbols in the binary it checks, so inspect the binary Kani linked +# rather than what kani-compiler wrote. +TMP_DIR=$(mktemp -d) +cp riscv64.rs "$TMP_DIR" +kani "$TMP_DIR/riscv64.rs" --target $TARGET -Z unstable-options --harness target_is_riscv64gc \ + --keep-temps > /dev/null +for goto in "$TMP_DIR"/*target_is_riscv64gc.out; do + goto-instrument --show-symbol-table "$goto" | awk ' + /^Symbol\.+: __CPROVER_architecture_(arch|char_is_unsigned)$/ { name = $2 } + /^Value/ && name { sub(/^\(__CPROVER_integer\)/, "", $2); print name " = " $2; name = "" }' +done +rm -rf "$TMP_DIR" + echo "[TEST] cargo kani for riscv64" pushd sample_crate > /dev/null cargo kani --target $TARGET -Z unstable-options -Z stubbing From 409ba071d1280cb609fd72ec010e87004a76b734 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 09:56:09 -0700 Subject: [PATCH 09/24] Record the verification target in --export-json metadata create_metadata_json wrote env!("TARGET"), the triple Kani was built for, so a riscv64 run exported metadata.target as the host's triple. Pass the verification target in, and check the exported value in target_riscv64. Co-Authored-By: Claude Opus 5.5 --- kani-driver/src/frontend/schema_utils.rs | 6 +++--- kani-driver/src/frontend/tests/schema_utils_test.rs | 4 +++- kani-driver/src/main.rs | 2 +- .../target_riscv64/target_riscv64.expected | 3 +++ tests/script-based-pre/target_riscv64/target_riscv64.sh | 9 +++++++++ 5 files changed, 19 insertions(+), 5 deletions(-) diff --git a/kani-driver/src/frontend/schema_utils.rs b/kani-driver/src/frontend/schema_utils.rs index 9f407b84845..22a9f5ac3c0 100644 --- a/kani-driver/src/frontend/schema_utils.rs +++ b/kani-driver/src/frontend/schema_utils.rs @@ -21,14 +21,14 @@ use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; /// Creates structured JSON metadata for an export run -/// This utility function captures basic environment for the whole session -pub fn create_metadata_json() -> Value { +/// This utility function captures basic environment for the whole session. +/// `target` is the target triple verified for, which `--target` can make differ from the host's. +pub fn create_metadata_json(target: &str) -> Value { let timestamp = OffsetDateTime::now_utc() .format(&Rfc3339) .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string()); let kani_version = env!("CARGO_PKG_VERSION"); - let target = env!("TARGET"); let build_mode = if cfg!(debug_assertions) { "debug" } else { "release" }; json!({ diff --git a/kani-driver/src/frontend/tests/schema_utils_test.rs b/kani-driver/src/frontend/tests/schema_utils_test.rs index 4a46d1c8c51..bd27b50ca98 100644 --- a/kani-driver/src/frontend/tests/schema_utils_test.rs +++ b/kani-driver/src/frontend/tests/schema_utils_test.rs @@ -19,10 +19,12 @@ use std::path::PathBuf; use std::time::Duration; #[test] fn test_create_metadata_json() { - let json = create_metadata_json(); + let json = create_metadata_json("riscv64gc-unknown-linux-gnu"); assert!(json.is_object()); assert_eq!(json["version"], "1.0"); + // The verification target, not the triple Kani was built for. + assert_eq!(json["target"], "riscv64gc-unknown-linux-gnu"); assert!(json["timestamp"].as_str().unwrap().contains('T')); assert!(["debug", "release"].contains(&json["build_mode"].as_str().unwrap())); } diff --git a/kani-driver/src/main.rs b/kani-driver/src/main.rs index 22fec0a3d8a..16bc94567af 100644 --- a/kani-driver/src/main.rs +++ b/kani-driver/src/main.rs @@ -199,7 +199,7 @@ fn verify_project(project: Project, session: KaniSession) -> Result<()> { if let Some(handler) = handler.as_mut() { // Add project and export run metadata using frontend utility - handler.add_item("metadata", create_metadata_json()); + handler.add_item("metadata", create_metadata_json(session.args.verification_target())); handler.add_item("project", create_project_metadata_json(&project)); handler.add_item("tools", create_tool_versions_json(&session, &harnesses)); diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected index 1e593efb9a0..d15eae7ea20 100644 --- a/tests/script-based-pre/target_riscv64/target_riscv64.expected +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -16,6 +16,9 @@ Complete - 1 successfully verified harnesses, 1 failures, 2 total. __CPROVER_architecture_arch = "riscv64" __CPROVER_architecture_char_is_unsigned = 1 +[TEST] --export-json records the verification target +metadata.target = riscv64gc-unknown-linux-gnu + [TEST] cargo kani for riscv64 Checking harness verify::elapsed_never_panics... Complete - 1 successfully verified harnesses, 0 failures, 1 total. diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh index 4fbc3332a07..6a33234e8f7 100755 --- a/tests/script-based-pre/target_riscv64/target_riscv64.sh +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -31,6 +31,15 @@ for goto in "$TMP_DIR"/*target_is_riscv64gc.out; do /^Symbol\.+: __CPROVER_architecture_(arch|char_is_unsigned)$/ { name = $2 } /^Value/ && name { sub(/^\(__CPROVER_integer\)/, "", $2); print name " = " $2; name = "" }' done + +echo "[TEST] --export-json records the verification target" +EXPORT_JSON="$TMP_DIR/export.json" +kani riscv64.rs --target $TARGET -Z unstable-options --harness target_is_riscv64gc \ + --export-json "$EXPORT_JSON" > /dev/null +python3 - "$EXPORT_JSON" << 'EOF' +import json, sys +print("metadata.target =", json.load(open(sys.argv[1]))["metadata"]["target"]) +EOF rm -rf "$TMP_DIR" echo "[TEST] cargo kani for riscv64" From c3774709629bca75cc812c70a2fa8790807a0b9f Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 09:56:09 -0700 Subject: [PATCH 10/24] Drop the fixed machine-model limitation from the target docs The linked program now keeps the target's __CPROVER_architecture_* symbols. List the --c-lib conflict instead, and say that the OS symbol is still the host's, since Kani's machine model does not record one. Co-Authored-By: Claude Opus 5.5 --- docs/src/reference/experimental/target.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index 28cb6b2b25c..59aab548de8 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -48,15 +48,13 @@ cargo kani --target riscv64gc-unknown-linux-gnu -Z unstable-options * `--concrete-playback` is rejected with a non-host `--target`, because the generated test runs on the host. * The `verify-std` subcommand does not support `--target`. -* The `__CPROVER_architecture_*` symbols in the final `.out` are the host's rather than the ones - Kani wrote. When `goto-cc` links goto binaries, the first input's architecture symbols win, and - Kani currently passes `kani_lib.c` to the link as a C source, which `goto-cc` compiles with the - host's configuration. On macOS a cross-target run therefore reports the host's `arm64` and - `char_is_unsigned = 0` there, and a 64-bit `long double` where riscv64's is 128-bit. The Rust - side of the goto program spells out its own widths and signedness, which is what the proof - checks, so this matters only where CBMC interprets C: `kani_lib.c`, its C library models, and - any C code a harness reaches. Compiling `kani_lib.c` to a goto object ahead of time and - linking it after the Rust inputs would keep the model Kani wrote. +* `--c-lib` is rejected with a non-host `--target`. `goto-cc` compiles C sources with the host's + C configuration, and a source compiled as part of the link would replace the target's machine + model in the linked program. +* Kani's machine model has no operating system, so `__CPROVER_architecture_os` in the linked + program is the host's, as it is for a host run. A `riscv64gc-unknown-linux-gnu` run on macOS + therefore has `os = "macos"`. CBMC reads this setting in a few places when it processes C, such + as the arm64 `va_list` layout. * Inline assembly is unsupported on every target, as it is on the host. Code behind `core::arch::asm!` has to be [stubbed](stubbing.md) to be verified. * Only 64-bit little-endian targets are supported. A 32-bit target needs `goto-cc -m32` and a From 9b72fa016134461547f624d78e9d9aded134a0d0 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 09:56:09 -0700 Subject: [PATCH 11/24] Mark char as signed in the aarch64-apple-darwin machine model The AArch64 model set char_is_unsigned for every OS. That holds on Linux, but char is signed on Apple arm64 (Apple's "Writing ARM64 code for Apple platforms", core::ffi::c_char on aarch64-apple-darwin, and CBMC's own macOS arm64 configuration). Host runs on macOS hid this, because the host-compiled kani_lib.c replaced the symbol at link time. A run with --target aarch64-apple-darwin from another host would not. Make it depend on the OS, as wchar_t_is_unsigned already does, and split the table out of new_machine_model so a unit test can check it without a rustc session. Co-Authored-By: Claude Opus 5.5 --- .../compiler_interface.rs | 34 +++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs index 831157c859f..d65fcaeab21 100644 --- a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs +++ b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs @@ -823,8 +823,6 @@ fn new_machine_model(sess: &Session) -> MachineModel { // We check the target platform in function // `check_target` from src/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs // and error if it is not any of the ones we expect. - let architecture = &sess.target.arch; - let os = &sess.target.os; let pointer_width = sess.target.pointer_width.into(); // The model assumes the following values for session options: @@ -839,7 +837,18 @@ fn new_machine_model(sess: &Session) -> MachineModel { Endian::Little => false, Endian::Big => true, }; + machine_model_for(&sess.target.arch, &sess.target.os, pointer_width, alignment, is_big_endian) +} +/// The machine model for `architecture` and `os`, with the values `new_machine_model` reads from +/// the session passed in. +fn machine_model_for( + architecture: &Arch, + os: &Os, + pointer_width: u64, + alignment: u64, + is_big_endian: bool, +) -> MachineModel { // The values below cannot be obtained from the session so they are // hardcoded using standard ones for the supported platforms // see /tools/sizeofs/main.cpp. @@ -891,7 +900,9 @@ fn new_machine_model(sess: &Session) -> MachineModel { } Arch::AArch64 => { let bool_width = 8; - let char_is_unsigned = true; + // `char` is unsigned on aarch64 Linux and signed on Apple platforms, see the links + // above `wchar_t_is_unsigned`. + let char_is_unsigned = matches!(os, Os::Linux); let char_width = 8; let double_width = 64; let float_width = 32; @@ -996,3 +1007,20 @@ where info!("Finished {description} in {}s", elapsed.as_secs_f32()); ret } + +#[cfg(test)] +mod tests { + use super::machine_model_for; + use rustc_target::spec::{Arch, Os}; + + /// `char` is unsigned on aarch64 Linux but signed on Apple arm64, which CBMC itself also + /// encodes for `arm64` on macOS. + /// https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms + #[test] + fn arm64_char_signedness_follows_the_os() { + let linux = machine_model_for(&Arch::AArch64, &Os::Linux, 64, 1, false); + let macos = machine_model_for(&Arch::AArch64, &Os::MacOs, 64, 1, false); + assert!(linux.char_is_unsigned); + assert!(!macos.char_is_unsigned); + } +} From 27bf95e992091991663f755cf7c8fc10b0cc4a57 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 10:51:27 -0700 Subject: [PATCH 12/24] Test the --c-lib rejection for another target in target_riscv64 1eaa2d9a3 refuses --c-lib with a non-host --target and covers it with a unit test, but nothing checked the message a user actually sees. The C file is the reviewer's reproducer: char is unsigned on riscv64 and signed on x86_64, which is why compiling it for the host would be wrong. Co-Authored-By: Claude Opus 5.5 --- tests/script-based-pre/target_riscv64/is_negative.c | 7 +++++++ .../target_riscv64/target_riscv64.expected | 8 ++++++++ tests/script-based-pre/target_riscv64/target_riscv64.sh | 3 +++ 3 files changed, 18 insertions(+) create mode 100644 tests/script-based-pre/target_riscv64/is_negative.c diff --git a/tests/script-based-pre/target_riscv64/is_negative.c b/tests/script-based-pre/target_riscv64/is_negative.c new file mode 100644 index 00000000000..8be60dea5f3 --- /dev/null +++ b/tests/script-based-pre/target_riscv64/is_negative.c @@ -0,0 +1,7 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT +// +// `char` is unsigned on riscv64 and signed on x86_64, so goto-cc compiling this for the host would +// give the wrong answer for a riscv64 harness. target_riscv64.sh checks that Kani refuses it. + +int is_negative(char c) { return c < 0; } diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected index d15eae7ea20..89812c784f6 100644 --- a/tests/script-based-pre/target_riscv64/target_riscv64.expected +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -31,6 +31,14 @@ Usage: kani [OPTIONS] [INPUT] For more information, try '--help'. +[TEST] --c-lib is refused for another target +error: Conflicting options: --c-lib is compiled for the host, so it isn't compatible with --target for another platform. + +Usage: kani [OPTIONS] [INPUT] + kani + +For more information, try '--help'. + [TEST] verify-std is refused with --target error: The `verify-std` subcommand does not support `--target` diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh index 6a33234e8f7..5afb0ea133d 100755 --- a/tests/script-based-pre/target_riscv64/target_riscv64.sh +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -51,6 +51,9 @@ popd > /dev/null echo "[TEST] --concrete-playback is refused for another target" kani riscv64.rs --target $TARGET -Z unstable-options -Z concrete-playback --concrete-playback print +echo "[TEST] --c-lib is refused for another target" +kani riscv64.rs --target $TARGET -Z unstable-options -Z c-ffi --c-lib is_negative.c + echo "[TEST] verify-std is refused with --target" kani verify-std . --target $TARGET -Z unstable-options From 7153afd04015fcea1ccc081c4e5c171526770117 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 10:54:07 -0700 Subject: [PATCH 13/24] Refuse --target for autoharness --std, as verify-std does autoharness --std builds std through the same cargo_build_std path as verify-std, which passes the host triple to cargo because Kani's no_core library exists for the host only. verify-std rejects --target for that reason, but autoharness --std accepted it and quietly verified the host's std. Check it before the std path, so the error names the real problem. Co-Authored-By: Claude Opus 5.5 --- kani-driver/src/args/autoharness_args.rs | 8 ++++++++ kani-driver/src/args/mod.rs | 17 +++++++++++++++++ .../target_riscv64/target_riscv64.expected | 8 ++++++++ .../target_riscv64/target_riscv64.sh | 3 +++ 4 files changed, 36 insertions(+) diff --git a/kani-driver/src/args/autoharness_args.rs b/kani-driver/src/args/autoharness_args.rs index d981638bd73..d34b855b419 100644 --- a/kani-driver/src/args/autoharness_args.rs +++ b/kani-driver/src/args/autoharness_args.rs @@ -273,6 +273,14 @@ impl ValidateArgs for StandaloneAutoharnessArgs { } if self.std { + if self.verify_opts.target_triple.is_some() { + // `--std` builds against Kani's `no_core` library, which exists for the host only, + // the same as `verify-std`. + return Err(Error::raw( + ErrorKind::ArgumentConflict, + "The `autoharness` subcommand does not support `--target` with `--std`", + )); + } validate_std_path(&self.input)?; } else if !self.input.is_file() { return Err(Error::raw( diff --git a/kani-driver/src/args/mod.rs b/kani-driver/src/args/mod.rs index c2b400a338d..61a2f7bf6f2 100644 --- a/kani-driver/src/args/mod.rs +++ b/kani-driver/src/args/mod.rs @@ -1600,4 +1600,21 @@ mod tests { .validate() .unwrap(); } + + /// `verify-std` and `autoharness --std` build against Kani's host-only `no_core` library, so + /// both refuse `--target`. Each case fails on the target before the std path is checked. + #[test] + fn check_std_verification_rejects_target() { + for args in [ + "kani verify-std library -Z unstable-options --target", + "kani autoharness --std library -Z unstable-options -Z autoharness --target", + ] { + let args = format!("{args} {}", other_target()); + let err = StandaloneArgs::try_parse_from(args.split_whitespace()) + .unwrap() + .validate() + .unwrap_err(); + assert_eq!(err.kind(), ErrorKind::ArgumentConflict, "for `{args}`"); + } + } } diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected index 89812c784f6..20ea42a7624 100644 --- a/tests/script-based-pre/target_riscv64/target_riscv64.expected +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -46,3 +46,11 @@ Usage: kani [OPTIONS] [INPUT] kani For more information, try '--help'. + +[TEST] autoharness --std is refused with --target +error: The `autoharness` subcommand does not support `--target` with `--std` + +Usage: kani [OPTIONS] [INPUT] + kani + +For more information, try '--help'. diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh index 5afb0ea133d..011109edadf 100755 --- a/tests/script-based-pre/target_riscv64/target_riscv64.sh +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -57,5 +57,8 @@ kani riscv64.rs --target $TARGET -Z unstable-options -Z c-ffi --c-lib is_negativ echo "[TEST] verify-std is refused with --target" kani verify-std . --target $TARGET -Z unstable-options +echo "[TEST] autoharness --std is refused with --target" +kani autoharness --std . --target $TARGET -Z unstable-options -Z autoharness + # The rejections above exit non-zero on purpose; the suite passes when the transcript matches. exit 0 From eb6c119ba4b7763b58d7f40312c1b064c7b6b820 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 10:54:17 -0700 Subject: [PATCH 14/24] Say in the target docs that bare-metal riscv64 is not supported Kernels usually build for riscv64gc-unknown-none-elf, and the obvious workaround of verifying as riscv64gc-unknown-linux-gnu changes what gets verified: target_os becomes "linux" and std is available, so cfg(target_os = "none") code drops out. A kernel user should know that before reading a SUCCESSFUL result. Also list autoharness --std beside verify-std, since it now refuses --target too. Co-Authored-By: Claude Opus 5.5 --- docs/src/reference/experimental/target.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index 59aab548de8..311867d0bd9 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -22,6 +22,11 @@ A target needs a CBMC machine model in Kani. These are the targets that have one Any other target is rejected by the compiler with an error that lists these. +The bare-metal `riscv64gc-unknown-none-elf`, which kernels usually build for, is not supported. +Verifying such a crate as `riscv64gc-unknown-linux-gnu` instead sets `target_os = "linux"` and +makes `std` available, so code behind `cfg(target_os = "none")` is compiled out and the `linux` +branch, if there is one, is what Kani verifies. + ## Building the libraries Kani verifies against its own build of the standard library and of the `kani` crate, compiled for @@ -47,7 +52,7 @@ cargo kani --target riscv64gc-unknown-linux-gnu -Z unstable-options * `--concrete-playback` is rejected with a non-host `--target`, because the generated test runs on the host. -* The `verify-std` subcommand does not support `--target`. +* The `verify-std` subcommand and `autoharness --std` do not support `--target`. * `--c-lib` is rejected with a non-host `--target`. `goto-cc` compiles C sources with the host's C configuration, and a source compiled as part of the link would replace the target's machine model in the linked program. From d67167fb97cca66f8f66b3150756c40169fb3ce8 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 10:56:38 -0700 Subject: [PATCH 15/24] Check --target and --lib-target against one list of supported targets The driver accepted any string for --target and only looked for targets//lib, so an unsupported triple or a typo got "build them with cargo build-dev --lib-target ". For musl, following that advice failed the whole build with kani-compiler's target error deep in the log, and --target "" resolved to the targets/ folder itself. SUPPORTED_TARGETS in kani_metadata is now the one list. The driver checks --target against it after the unstable gate, and build-kani checks --lib-target before building anything. kani_metadata is the crate the driver and compiler already share; build-kani takes it as a new path dependency, since it had no Kani crate in common with them. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + docs/src/reference/experimental/target.md | 3 +- kani-driver/src/args/mod.rs | 38 +++++++++++++++- kani_metadata/src/lib.rs | 19 ++++++++ .../target_riscv64/target_riscv64.expected | 8 ++++ .../target_riscv64/target_riscv64.sh | 3 ++ tools/build-kani/Cargo.toml | 1 + tools/build-kani/src/parser.rs | 43 ++++++++++++++++++- 8 files changed, 113 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e6a3f78b93f..ba040a41621 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -211,6 +211,7 @@ dependencies = [ "anyhow", "cargo_metadata", "clap", + "kani_metadata", "which 8.0.6", ] diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index 311867d0bd9..d5e3e3a6adc 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -20,7 +20,8 @@ A target needs a CBMC machine model in Kani. These are the targets that have one | `x86_64-apple-darwin` | | | `aarch64-apple-darwin` | | -Any other target is rejected by the compiler with an error that lists these. +Kani refuses any other `--target`, and `cargo build-dev --lib-target`, with an error that lists +these. The bare-metal `riscv64gc-unknown-none-elf`, which kernels usually build for, is not supported. Verifying such a crate as `riscv64gc-unknown-linux-gnu` instead sets `target_os = "linux"` and diff --git a/kani-driver/src/args/mod.rs b/kani-driver/src/args/mod.rs index 61a2f7bf6f2..b49f90e196e 100644 --- a/kani-driver/src/args/mod.rs +++ b/kani-driver/src/args/mod.rs @@ -15,7 +15,7 @@ use crate::util::warning; use cargo::CargoCommonArgs; use clap::builder::{PossibleValue, TypedValueParser}; use clap::{ValueEnum, error::ContextKind, error::ContextValue, error::Error, error::ErrorKind}; -use kani_metadata::CbmcSolver; +use kani_metadata::{CbmcSolver, SUPPORTED_TARGETS, supported_targets_list}; use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::str::FromStr; @@ -846,6 +846,20 @@ impl ValidateArgs for VerificationArgs { UnstableFeature::UnstableOptions, )?; + // Checked here, after the unstable gate, so that the error is about the triple and + // not about a missing library folder or a compiler error deep in a cargo build. + if let Some(triple) = &self.target_triple + && !SUPPORTED_TARGETS.contains(&triple.as_str()) + { + return Err(Error::raw( + ErrorKind::InvalidValue, + format!( + "Unsupported target `{triple}`: Kani can verify for {}.", + supported_targets_list() + ), + )); + } + Ok(()) }; @@ -1617,4 +1631,26 @@ mod tests { assert_eq!(err.kind(), ErrorKind::ArgumentConflict, "for `{args}`"); } } + + /// `--target` is checked against `SUPPORTED_TARGETS` before anything is built, including the + /// empty string, which would otherwise resolve to the `targets/` folder itself. + #[test] + fn check_target_must_be_supported() { + for target in ["x86_64-unknown-linux-musl", "thumbv7em-none-eabihf", ""] { + let mut args: Vec<&str> = + "kani input.rs -Z unstable-options --target".split_whitespace().collect(); + args.push(target); + let err = + StandaloneArgs::try_parse_from(args).unwrap().verify_opts.validate().unwrap_err(); + assert_eq!(err.kind(), ErrorKind::InvalidValue, "for `{target}`"); + } + for target in SUPPORTED_TARGETS { + let args = format!("kani input.rs -Z unstable-options --target {target}"); + StandaloneArgs::try_parse_from(args.split_whitespace()) + .unwrap() + .verify_opts + .validate() + .unwrap(); + } + } } diff --git a/kani_metadata/src/lib.rs b/kani_metadata/src/lib.rs index 3e7490b37bd..817c840cdb8 100644 --- a/kani_metadata/src/lib.rs +++ b/kani_metadata/src/lib.rs @@ -23,6 +23,25 @@ mod vtable; pub use unstable::{EnabledUnstableFeatures, UnstableFeature}; +/// The rustc target tuples Kani can verify for, exactly as `rustc --target` spells them. Each one +/// needs a CBMC machine model in kani-compiler (`machine_model_from_session`). kani-driver checks +/// `--target` against this list, build-kani checks `--lib-target`, and kani-compiler's +/// `check_target` checks the session, so the three cannot disagree about what is supported. +pub const SUPPORTED_TARGETS: [&str; 5] = [ + "x86_64-unknown-linux-gnu", + "aarch64-unknown-linux-gnu", + "riscv64gc-unknown-linux-gnu", + "x86_64-apple-darwin", + "aarch64-apple-darwin", +]; + +/// `SUPPORTED_TARGETS` as a list for an error message: "`a`, `b` or `c`". +pub fn supported_targets_list() -> String { + let quoted: Vec = SUPPORTED_TARGETS.iter().map(|t| format!("`{t}`")).collect(); + let (last, rest) = quoted.split_last().unwrap(); + format!("{} or {last}", rest.join(", ")) +} + /// The default maximum length for nondeterministic slices that automatic harnesses generate. /// Verification results for functions taking `&[T]`/`&mut [T]` arguments are only valid up to /// this bound. The default must stay below Kani's default unwinding bound (20), so that loops diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected index 20ea42a7624..f9ebd3e1d61 100644 --- a/tests/script-based-pre/target_riscv64/target_riscv64.expected +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -1,6 +1,14 @@ [TEST] --target needs -Z unstable-options error: The `--target` option is unstable and requires `-Z unstable-options` to be used. +[TEST] an unsupported --target is refused before anything is built +error: Unsupported target `riscv64gc-unknown-none-elf`: Kani can verify for `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu`, `riscv64gc-unknown-linux-gnu`, `x86_64-apple-darwin` or `aarch64-apple-darwin`. + +Usage: kani [OPTIONS] [INPUT] + kani + +For more information, try '--help'. + [TEST] single file on the host: the riscv64 harnesses are compiled out No proof harnesses (functions with #[kani::proof]) were found to verify. diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh index 011109edadf..98fd04a01c9 100755 --- a/tests/script-based-pre/target_riscv64/target_riscv64.sh +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -12,6 +12,9 @@ TARGET=riscv64gc-unknown-linux-gnu echo "[TEST] --target needs -Z unstable-options" kani riscv64.rs --target $TARGET +echo "[TEST] an unsupported --target is refused before anything is built" +kani riscv64.rs --target riscv64gc-unknown-none-elf -Z unstable-options + echo "[TEST] single file on the host: the riscv64 harnesses are compiled out" kani riscv64.rs diff --git a/tools/build-kani/Cargo.toml b/tools/build-kani/Cargo.toml index a49d169ea20..3e5e352cdf9 100644 --- a/tools/build-kani/Cargo.toml +++ b/tools/build-kani/Cargo.toml @@ -13,4 +13,5 @@ publish = false anyhow = "1" cargo_metadata = "0.23" clap = { version = "4.4.11", features=["derive"] } +kani_metadata = { path = "../../kani_metadata" } which = "8" diff --git a/tools/build-kani/src/parser.rs b/tools/build-kani/src/parser.rs index fc233304954..e5718f5d59e 100644 --- a/tools/build-kani/src/parser.rs +++ b/tools/build-kani/src/parser.rs @@ -3,6 +3,7 @@ //! This file contains a small parser for our build script. use clap::{Args, Parser, Subcommand}; +use kani_metadata::{SUPPORTED_TARGETS, supported_targets_list}; #[derive(Parser)] #[clap(name = "build-kani")] @@ -23,10 +24,26 @@ pub struct BuildDevParser { pub skip_libs: bool, /// Also build Kani's verification libraries for this target triple, so that /// `kani --target -Z unstable-options` can verify for it. May be repeated. - #[clap(long = "lib-target", value_name = "TRIPLE", conflicts_with = "skip_libs")] + /// Targets built earlier are rebuilt whether or not they are named again. + #[clap( + long = "lib-target", + value_name = "TRIPLE", + conflicts_with = "skip_libs", + value_parser = parse_lib_target + )] pub lib_targets: Vec, } +/// Refuse a target Kani has no machine model for before building anything. Otherwise the error is +/// kani-compiler's, from inside the library build, after the binaries have been rebuilt. +fn parse_lib_target(target: &str) -> Result { + if SUPPORTED_TARGETS.contains(&target) { + Ok(target.to_string()) + } else { + Err(format!("Kani can verify for {}", supported_targets_list())) + } +} + #[derive(Args, Debug, Eq, PartialEq)] pub struct BundleParser { /// String version @@ -41,3 +58,27 @@ pub enum Commands { /// Build Kani's release bundle. Bundle(BundleParser), } + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(args: &[&str]) -> Result { + ArgParser::try_parse_from(["build-kani", "build-dev"].iter().chain(args)) + } + + #[test] + fn lib_target_must_be_supported() { + let Commands::BuildDev(parsed) = + parse(&["--lib-target", "riscv64gc-unknown-linux-gnu"]).unwrap().subcommand + else { + panic!("expected build-dev"); + }; + assert_eq!(parsed.lib_targets, ["riscv64gc-unknown-linux-gnu"]); + + for target in ["x86_64-unknown-linux-musl", "thumbv7em-none-eabihf", ""] { + let err = parse(&["--lib-target", target]).err().expect(target); + assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation, "for `{target}`"); + } + } +} From 25e357076173fb02a317180882c5d3534dbec342 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 10:56:38 -0700 Subject: [PATCH 16/24] Match the exact target tuple in check_target check_target recognised targets by LLVM target, and for riscv64 also compared the spec's features string exactly, because riscv64gc, riscv64a23 and riscv64-wrs-vxworks share an LLVM target. A toolchain bump that respelled that string would have rejected riscv64gc. Compare the session's tuple against SUPPORTED_TARGETS instead. The tuple names the built-in spec, so it separates those targets without the features string. A target JSON file is refused outright, because rustc names it after its file stem and a file called riscv64gc-unknown-linux-gnu.json would otherwise pass with any layout. Co-Authored-By: Claude Opus 5.5 --- .../compiler_interface.rs | 53 ++++++++----------- 1 file changed, 22 insertions(+), 31 deletions(-) diff --git a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs index d65fcaeab21..58a06d1931a 100644 --- a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs +++ b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs @@ -20,7 +20,10 @@ use cbmc::goto_program::Location; use cbmc::{InternedString, MachineModel}; use cbmc::{RoundingMode, WithInterner}; use kani_metadata::artifact::convert_type; -use kani_metadata::{ArtifactType, HarnessMetadata, KaniMetadata, UnsupportedFeature}; +use kani_metadata::{ + ArtifactType, HarnessMetadata, KaniMetadata, SUPPORTED_TARGETS, UnsupportedFeature, + supported_targets_list, +}; use kani_metadata::{AssignsContract, CompilerArtifactStub}; use rustc_abi::{Align, Endian}; use rustc_codegen_ssa::back::archive::{ @@ -45,7 +48,7 @@ use rustc_session::output::out_filename; use rustc_session::{EarlySession, IncrCompSession, Session}; use rustc_span::{Symbol, sym}; use rustc_structures::CrateType; -use rustc_target::spec::{Arch, Os, PanicStrategy}; +use rustc_target::spec::{Arch, Os, PanicStrategy, TargetTuple}; use std::any::Any; use std::cmp::min; use std::collections::BTreeMap; @@ -604,36 +607,24 @@ impl ArchiveBuilderBuilder for ArArchiveBuilderBuilder { } fn check_target(session: &Session) { - // The requirement below is needed to build a valid CBMC machine model - // in function `machine_model_from_session` from - // src/kani-compiler/src/codegen_cprover_gotoc/context/goto_ctx.rs - let is_x86_64_linux_target = session.target.llvm_target == "x86_64-unknown-linux-gnu"; - let is_arm64_linux_target = session.target.llvm_target == "aarch64-unknown-linux-gnu"; - // Comparison with `x86_64-apple-darwin` does not work well because the LLVM - // target may become `x86_64-apple-macosx10.7.0` (or similar) and - // fail. Other Apple targets (iOS, tvOS and so on) share these prefixes, so also match the OS. - let is_x86_64_darwin_target = - session.target.llvm_target.starts_with("x86_64-apple-") && session.target.os == Os::MacOs; - // looking for `arm64-apple-*` - let is_arm64_darwin_target = - session.target.llvm_target.starts_with("arm64-apple-") && session.target.os == Os::MacOs; - // `riscv64gc-unknown-linux-gnu`, whose LLVM target drops the `gc`. - // `riscv64a23-unknown-linux-gnu` and `riscv64-wrs-vxworks` share that LLVM target, so also - // match the OS and the features that `target_config` hardcodes. - let is_riscv64_linux_target = session.target.llvm_target == "riscv64-unknown-linux-gnu" - && session.target.os == Os::Linux - && session.target.features == "+m,+a,+f,+d,+c,+zicsr,+zifencei"; - - if !is_x86_64_linux_target - && !is_arm64_linux_target - && !is_x86_64_darwin_target - && !is_arm64_darwin_target - && !is_riscv64_linux_target - { + // `machine_model_from_session` in this file builds a CBMC machine model only for the targets + // in `SUPPORTED_TARGETS`, and `target_config` hardcodes their features, so the session must + // be one of those built-in targets exactly. The tuple names the built-in spec, which already + // tells apart targets that share an LLVM target, such as `riscv64gc-unknown-linux-gnu`, + // `riscv64a23-unknown-linux-gnu` and `riscv64-wrs-vxworks`. + // + // A target JSON file is refused even when its name matches: rustc names it after the file + // stem, so `riscv64gc-unknown-linux-gnu.json` would pass a name check with whatever data + // layout and features the file sets. An exact comparison of the `features` string used to + // guard against both cases, and broke whenever rustc respelled that string. + let supported = match &session.opts.target_triple { + TargetTuple::TargetTuple(tuple) => SUPPORTED_TARGETS.contains(&tuple.as_str()), + TargetTuple::TargetJson { .. } => false, + }; + if !supported { let err_msg = format!( - "Kani requires the target platform to be `x86_64-unknown-linux-gnu`, \ - `aarch64-unknown-linux-gnu`, `riscv64gc-unknown-linux-gnu`, `x86_64-apple-darwin` \ - or `aarch64-apple-darwin`, but it is `{}` (LLVM target `{}`)", + "Kani requires the target platform to be {}, but it is `{}` (LLVM target `{}`)", + supported_targets_list(), session.opts.target_triple.tuple(), session.target.llvm_target ); From c8a5d291bf5307e5eabf7cfce67f7937df013a13 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Mon, 5 Oct 2026 10:56:45 -0700 Subject: [PATCH 17/24] Rebuild every target under targets/ on each cargo build-dev A cargo build-dev without --lib-target left targets//lib from the last build in place, and the driver used it. A change to library/kani or Kani's std overrides was then verified against the old copy for that target with no error; only a removed or renamed function showed up, as a compile failure. build-dev now rebuilds each supported target that already has a folder, as well as the ones named on the command line. Rebuilding rather than deleting keeps a riscv64 setup working across plain builds, and keeps the driver's "build them with cargo build-dev --lib-target" advice true: naming a target once is enough. --skip-libs still skips all of them. Co-Authored-By: Claude Opus 5.5 --- docs/src/reference/experimental/target.md | 6 +++-- tools/build-kani/src/main.rs | 29 +++++++++++++++++++---- tools/build-kani/src/sysroot.rs | 18 ++++++++++++++ 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index d5e3e3a6adc..9293f41d8f7 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -39,8 +39,10 @@ cargo build-dev --lib-target riscv64gc-unknown-linux-gnu ``` The option may be repeated. Each target's libraries go to `targets//lib/` beside the -host's `lib/`, so one Kani installation can verify for several targets. The rustup target itself -does not need to be installed: the standard library is built from the `rust-src` component. +host's `lib/`, so one Kani installation can verify for several targets. A later `cargo build-dev` +rebuilds every target already under `targets/`, named or not, so they stay in step with +`library/`. The rustup target itself does not need to be installed: the standard library is built +from the `rust-src` component. ## Usage diff --git a/tools/build-kani/src/main.rs b/tools/build-kani/src/main.rs index 58b18c71ed9..58e3903e70e 100644 --- a/tools/build-kani/src/main.rs +++ b/tools/build-kani/src/main.rs @@ -11,11 +11,12 @@ mod parser; mod sysroot; use crate::sysroot::{ - build_bin, build_lib, build_target_lib, build_tools, kani_no_core_lib, kani_playback_lib, - kani_sysroot_lib, + build_bin, build_lib, build_target_lib, build_tools, existing_lib_targets, kani_no_core_lib, + kani_playback_lib, kani_sysroot_lib, }; use anyhow::{Result, bail}; use clap::Parser; +use kani_metadata::SUPPORTED_TARGETS; use std::{ffi::OsString, path::Path, process::Command}; fn main() -> Result<()> { @@ -26,8 +27,8 @@ fn main() -> Result<()> { let bin_folder = &build_bin(&build_parser.args)?; if !build_parser.skip_libs { build_lib(bin_folder)?; - for target in &build_parser.lib_targets { - build_target_lib(bin_folder, target)?; + for target in lib_targets(&build_parser.lib_targets)? { + build_target_lib(bin_folder, &target)?; } } Ok(()) @@ -59,6 +60,26 @@ fn main() -> Result<()> { } } +/// The targets to build libraries for: the ones requested, plus every one already under +/// `targets/`. kani-driver uses whatever is in `targets//lib`, so a folder left from an +/// older build would be verified against silently after a change to `library/`. +fn lib_targets(requested: &[String]) -> Result> { + let mut targets = requested.to_vec(); + for target in existing_lib_targets()? { + if targets.contains(&target) { + continue; + } + if SUPPORTED_TARGETS.contains(&target.as_str()) { + println!("-- Rebuilding Kani's libraries for {target}, which a previous build added"); + targets.push(target); + } else { + // kani-driver refuses `--target` for it, so the folder is never read. + println!("-- Skipping targets/{target}: Kani does not support that target"); + } + } + Ok(targets) +} + /// Ensures everything is good to go before we begin to build the release bundle. /// Notably, builds Kani in release mode. fn prebundle(dir: &Path) -> Result<()> { diff --git a/tools/build-kani/src/sysroot.rs b/tools/build-kani/src/sysroot.rs index e04f6fe25fb..afc69338013 100644 --- a/tools/build-kani/src/sysroot.rs +++ b/tools/build-kani/src/sysroot.rs @@ -69,6 +69,24 @@ pub fn kani_target_lib(target: &str) -> PathBuf { path_buf!(kani_sysroot(), "targets", target, "lib") } +/// The targets that already have a folder under `targets/`, from an earlier +/// `cargo build-dev --lib-target`, sorted so the build order is stable. +pub fn existing_lib_targets() -> Result> { + let targets = path_buf!(kani_sysroot(), "targets"); + if !targets.is_dir() { + return Ok(vec![]); + } + let mut found = vec![]; + for entry in fs::read_dir(targets)? { + let entry = entry?; + if entry.file_type()?.is_dir() { + found.push(entry.file_name().to_string_lossy().into_owned()); + } + } + found.sort(); + Ok(found) +} + /// Returns the path to where Kani's pre-compiled binaries are stored. fn kani_sysroot_bin() -> PathBuf { path_buf!(kani_sysroot(), "bin") From c264c69291b15615c9d537c688a75ff08eec7a24 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Thu, 22 Oct 2026 14:21:49 -0700 Subject: [PATCH 18/24] Record the --target triple in the RFC 0015 export The merge of main brought the RFC 0015 --export-json shape (#4941), which reports `target` as the triple Kani was built for and gates the flag behind `-Z export-json`. With --target that triple is the wrong one, and the target_riscv64 script test, which checks that the export records the verification target, no longer ran. Take `target` from `verification_target()`, say so in the RFC's field table, and update the script test for the new key and the new gate. Co-Authored-By: Claude Opus 5.5 --- kani-driver/src/frontend/schema_utils.rs | 17 +++++++++++++++-- rfc/src/rfcs/0015-export-json.md | 2 +- .../target_riscv64/target_riscv64.expected | 2 +- .../target_riscv64/target_riscv64.sh | 4 ++-- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/kani-driver/src/frontend/schema_utils.rs b/kani-driver/src/frontend/schema_utils.rs index 54becf0eb01..6f34f32ce36 100644 --- a/kani-driver/src/frontend/schema_utils.rs +++ b/kani-driver/src/frontend/schema_utils.rs @@ -41,6 +41,7 @@ struct RunContext { harness_selection: HarnessSelectionExport, harness_timeout_s: Option, configuration: ConfigurationExport, + target: String, started_at: OffsetDateTime, wall_time: Duration, } @@ -103,6 +104,7 @@ impl KaniSession { }, harness_timeout_s: self.args.harness_timeout.map(|t| Duration::from(t).as_secs_f64()), configuration: configuration_from(&self.args), + target: self.args.verification_target().to_string(), started_at, wall_time, } @@ -299,7 +301,7 @@ struct ExportedRun { configuration: ConfigurationExport, outcome: RunOutcome, run_state: RunState, - target: &'static str, + target: String, started_at: String, wall_time_s: f64, harnesses: Vec, @@ -658,7 +660,7 @@ impl ExportedRun { configuration: ctx.configuration, outcome: RunOutcome::Completed, run_state, - target: env!("TARGET"), + target: ctx.target, started_at: format_started_at(ctx.started_at), wall_time_s: ctx.wall_time.as_secs_f64(), harnesses, @@ -884,6 +886,7 @@ mod tests { }, harness_timeout_s: None, configuration: test_ctx_config(), + target: crate::args::HOST_TARGET.to_string(), started_at: started(), wall_time: Duration::from_millis(1), } @@ -1830,6 +1833,16 @@ mod tests { assert!(v["harness_timeout_s"].is_null()); } + #[test] + fn export_target_is_the_verification_target() { + let h = harness("h"); + let hr = HarnessResult { harness: &h, result: success_result(vec![]) }; + let ctx = + RunContext { target: "riscv64gc-unknown-linux-gnu".to_string(), ..test_context() }; + let v = serde_json::to_value(export_with(&[hr], ctx)).unwrap(); + assert_eq!(v["target"], "riscv64gc-unknown-linux-gnu"); + } + #[test] fn export_started_at_is_utc_iso8601() { let h = harness("h"); diff --git a/rfc/src/rfcs/0015-export-json.md b/rfc/src/rfcs/0015-export-json.md index a8df498d0a4..5005f2f1176 100644 --- a/rfc/src/rfcs/0015-export-json.md +++ b/rfc/src/rfcs/0015-export-json.md @@ -418,7 +418,7 @@ The narrower `INCOMPLETE` marker follows its presence matrix below. | `configuration.cbmc_args` | array of strings | never null, may be empty | Verbatim (UTF-8-lossy) `--cbmc-args`; a comparability signal, not a replayable argv. | | `outcome.kind` (run level) | `"COMPLETED"` | — | Always `COMPLETED` in a terminal document; absent in the marker. No run-level `CRASHED` value. | | `run_state` | `"INCOMPLETE"` \| `"COMPLETE"` \| `"PARTIAL"` \| `"NO_HARNESSES_SELECTED"` | — | Trust is based on this field; see Completeness under Reading the results. | -| `target` | string | — | The Rust target triple Kani itself was built for. | +| `target` | string | — | The Rust target triple verified for: the `--target` value when given, otherwise the triple Kani itself was built for. | | `started_at` | string | — | UTC, `YYYY-MM-DDTHH:MM:SSZ` (second resolution). Taken after the build, when target selection starts. | | `wall_time_s` | number | — | Seconds from target selection to the start of the export write: target selection, verification and coverage output. The build is not included. Volatile between runs by design (see "Interaction with other flags"). | | `harnesses[]` | array of harness objects | never null, may be empty (e.g. under `NO_HARNESSES_SELECTED`) | Sorted by `(crate_name, file, line, name)`. | diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected index f9ebd3e1d61..0191b500dfc 100644 --- a/tests/script-based-pre/target_riscv64/target_riscv64.expected +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -25,7 +25,7 @@ __CPROVER_architecture_arch = "riscv64" __CPROVER_architecture_char_is_unsigned = 1 [TEST] --export-json records the verification target -metadata.target = riscv64gc-unknown-linux-gnu +target = riscv64gc-unknown-linux-gnu [TEST] cargo kani for riscv64 Checking harness verify::elapsed_never_panics... diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh index 98fd04a01c9..3ff654ba989 100755 --- a/tests/script-based-pre/target_riscv64/target_riscv64.sh +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -38,10 +38,10 @@ done echo "[TEST] --export-json records the verification target" EXPORT_JSON="$TMP_DIR/export.json" kani riscv64.rs --target $TARGET -Z unstable-options --harness target_is_riscv64gc \ - --export-json "$EXPORT_JSON" > /dev/null + -Z export-json --export-json "$EXPORT_JSON" > /dev/null python3 - "$EXPORT_JSON" << 'EOF' import json, sys -print("metadata.target =", json.load(open(sys.argv[1]))["metadata"]["target"]) +print("target =", json.load(open(sys.argv[1]))["target"]) EOF rm -rf "$TMP_DIR" From bb0fd8140ace5a59bc6a8faf28f357f185168fce Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Fri, 4 Dec 2026 13:48:31 -0800 Subject: [PATCH 19/24] Move the signed char change for aarch64-apple-darwin to its own PR "Mark char as signed in the aarch64-apple-darwin machine model" changes the model of an existing host target, not just the new one, and does not depend on --target. It goes to its own pull request against main so it can be reviewed and merged on its own. This restores new_machine_model to its shape on main, apart from the riscv64 arm. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M1dgc2zy347cbi6td1Wd4x --- .../compiler_interface.rs | 34 ++----------------- 1 file changed, 3 insertions(+), 31 deletions(-) diff --git a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs index c6c79a54c61..d8645b3aa7e 100644 --- a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs +++ b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs @@ -822,6 +822,8 @@ fn new_machine_model(sess: &Session) -> MachineModel { // We check the target platform in function // `check_target` from src/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs // and error if it is not any of the ones we expect. + let architecture = &sess.target.arch; + let os = &sess.target.os; let pointer_width = sess.target.pointer_width.into(); // The model assumes the following values for session options: @@ -836,18 +838,7 @@ fn new_machine_model(sess: &Session) -> MachineModel { Endian::Little => false, Endian::Big => true, }; - machine_model_for(&sess.target.arch, &sess.target.os, pointer_width, alignment, is_big_endian) -} -/// The machine model for `architecture` and `os`, with the values `new_machine_model` reads from -/// the session passed in. -fn machine_model_for( - architecture: &Arch, - os: &Os, - pointer_width: u64, - alignment: u64, - is_big_endian: bool, -) -> MachineModel { // The values below cannot be obtained from the session so they are // hardcoded using standard ones for the supported platforms // see /tools/sizeofs/main.cpp. @@ -899,9 +890,7 @@ fn machine_model_for( } Arch::AArch64 => { let bool_width = 8; - // `char` is unsigned on aarch64 Linux and signed on Apple platforms, see the links - // above `wchar_t_is_unsigned`. - let char_is_unsigned = matches!(os, Os::Linux); + let char_is_unsigned = true; let char_width = 8; let double_width = 64; let float_width = 32; @@ -1006,20 +995,3 @@ where info!("Finished {description} in {}s", elapsed.as_secs_f32()); ret } - -#[cfg(test)] -mod tests { - use super::machine_model_for; - use rustc_target::spec::{Arch, Os}; - - /// `char` is unsigned on aarch64 Linux but signed on Apple arm64, which CBMC itself also - /// encodes for `arm64` on macOS. - /// https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms - #[test] - fn arm64_char_signedness_follows_the_os() { - let linux = machine_model_for(&Arch::AArch64, &Os::Linux, 64, 1, false); - let macos = machine_model_for(&Arch::AArch64, &Os::MacOs, 64, 1, false); - assert!(linux.char_is_unsigned); - assert!(!macos.char_is_unsigned); - } -} From a147c47a4a731f81b33da06383d7a0026227e277 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Fri, 4 Dec 2026 13:48:53 -0800 Subject: [PATCH 20/24] Move the --export-json target change to a follow-up PR The verification target in --export-json metadata (and RFC 0015's field table) is a fix the review confirmed, but it is not needed for --target to verify correctly. It goes to its own pull request on top of this one, so this one carries only what the review asked for. Until then, --export-json reports the triple Kani was built for, as on main. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M1dgc2zy347cbi6td1Wd4x --- kani-driver/src/frontend/schema_utils.rs | 17 ++--------------- rfc/src/rfcs/0015-export-json.md | 2 +- .../target_riscv64/target_riscv64.expected | 3 --- .../target_riscv64/target_riscv64.sh | 8 -------- 4 files changed, 3 insertions(+), 27 deletions(-) diff --git a/kani-driver/src/frontend/schema_utils.rs b/kani-driver/src/frontend/schema_utils.rs index 59edf870f21..b71a83f9823 100644 --- a/kani-driver/src/frontend/schema_utils.rs +++ b/kani-driver/src/frontend/schema_utils.rs @@ -41,7 +41,6 @@ pub(crate) struct RunContext { harness_selection: HarnessSelectionExport, harness_timeout_s: Option, configuration: ConfigurationExport, - target: String, started_at: OffsetDateTime, } @@ -130,7 +129,6 @@ impl KaniSession { .or(self.autoharness_harness_timeout) .map(|t| Duration::from(t).as_secs_f64()), configuration: configuration_from(&self.args), - target: self.args.verification_target().to_string(), started_at, } } @@ -370,7 +368,7 @@ struct ExportedRun { configuration: ConfigurationExport, outcome: RunOutcome, run_state: RunState, - target: String, + target: &'static str, started_at: String, wall_time_s: f64, harnesses: Vec, @@ -735,7 +733,7 @@ impl ExportedRun { configuration: ctx.configuration, outcome: RunOutcome::Completed, run_state, - target: ctx.target, + target: env!("TARGET"), started_at: format_started_at(ctx.started_at), wall_time_s: wall_time.as_secs_f64(), harnesses, @@ -963,7 +961,6 @@ mod tests { }, harness_timeout_s: None, configuration: test_ctx_config(), - target: crate::args::HOST_TARGET.to_string(), started_at: started(), } } @@ -1981,16 +1978,6 @@ mod tests { assert!(v["harness_timeout_s"].is_null()); } - #[test] - fn export_target_is_the_verification_target() { - let h = harness("h"); - let hr = HarnessResult { harness: &h, result: success_result(vec![]) }; - let ctx = - RunContext { target: "riscv64gc-unknown-linux-gnu".to_string(), ..test_context() }; - let v = serde_json::to_value(export_with(&[hr], ctx)).unwrap(); - assert_eq!(v["target"], "riscv64gc-unknown-linux-gnu"); - } - #[test] fn export_started_at_is_utc_iso8601() { let h = harness("h"); diff --git a/rfc/src/rfcs/0015-export-json.md b/rfc/src/rfcs/0015-export-json.md index 98f87563f79..1ea67d7f743 100644 --- a/rfc/src/rfcs/0015-export-json.md +++ b/rfc/src/rfcs/0015-export-json.md @@ -428,7 +428,7 @@ The narrower `INCOMPLETE` marker follows its presence matrix below. | `configuration.cbmc_args` | array of strings | never null, may be empty | Verbatim (UTF-8-lossy) `--cbmc-args`; a comparability signal, not a replayable argv. | | `outcome.kind` (run level) | `"COMPLETED"` | — | Always `COMPLETED` in a terminal document; absent in the marker. No run-level `CRASHED` value. | | `run_state` | `"INCOMPLETE"` \| `"COMPLETE"` \| `"PARTIAL"` \| `"NO_HARNESSES_SELECTED"` | — | Trust is based on this field; see Completeness under Reading the results. | -| `target` | string | — | The Rust target triple verified for: the `--target` value when given, otherwise the triple Kani itself was built for. | +| `target` | string | — | The Rust target triple Kani itself was built for. | | `started_at` | string | — | UTC, `YYYY-MM-DDTHH:MM:SSZ` (second resolution). Taken after the build, when target selection starts. | | `wall_time_s` | number | — | Seconds from target selection to the start of the terminal export write: target selection, the tool version probes and the marker write, verification and coverage output. The build is not included. Volatile between runs by design (see "Interaction with other flags"). | | `harnesses[]` | array of harness objects | never null, may be empty (e.g. under `NO_HARNESSES_SELECTED`) | Sorted by `(crate_name, file, line, name)`. | diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected index 0191b500dfc..22680566abe 100644 --- a/tests/script-based-pre/target_riscv64/target_riscv64.expected +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -24,9 +24,6 @@ Complete - 1 successfully verified harnesses, 1 failures, 2 total. __CPROVER_architecture_arch = "riscv64" __CPROVER_architecture_char_is_unsigned = 1 -[TEST] --export-json records the verification target -target = riscv64gc-unknown-linux-gnu - [TEST] cargo kani for riscv64 Checking harness verify::elapsed_never_panics... Complete - 1 successfully verified harnesses, 0 failures, 1 total. diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh index 3ff654ba989..e07f3326a31 100755 --- a/tests/script-based-pre/target_riscv64/target_riscv64.sh +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -35,14 +35,6 @@ for goto in "$TMP_DIR"/*target_is_riscv64gc.out; do /^Value/ && name { sub(/^\(__CPROVER_integer\)/, "", $2); print name " = " $2; name = "" }' done -echo "[TEST] --export-json records the verification target" -EXPORT_JSON="$TMP_DIR/export.json" -kani riscv64.rs --target $TARGET -Z unstable-options --harness target_is_riscv64gc \ - -Z export-json --export-json "$EXPORT_JSON" > /dev/null -python3 - "$EXPORT_JSON" << 'EOF' -import json, sys -print("target =", json.load(open(sys.argv[1]))["target"]) -EOF rm -rf "$TMP_DIR" echo "[TEST] cargo kani for riscv64" From 786ddf2831591c57ad6b47dd322568c45694fceb Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Fri, 4 Dec 2026 13:49:08 -0800 Subject: [PATCH 21/24] Move the rebuild of existing targets/ folders to a follow-up PR Rebuilding every target already under targets/ on a plain cargo build-dev was a review suggestion. It only affects local builds, since CI always names the target, so it moves to the follow-up that hardens --target. Until then the docs say to name a target again after changing library/. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M1dgc2zy347cbi6td1Wd4x --- docs/src/reference/experimental/target.md | 4 ++-- tools/build-kani/src/main.rs | 29 ++++------------------- tools/build-kani/src/parser.rs | 1 - tools/build-kani/src/sysroot.rs | 18 -------------- 4 files changed, 6 insertions(+), 46 deletions(-) diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index 9293f41d8f7..f3a32021bf7 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -39,8 +39,8 @@ cargo build-dev --lib-target riscv64gc-unknown-linux-gnu ``` The option may be repeated. Each target's libraries go to `targets//lib/` beside the -host's `lib/`, so one Kani installation can verify for several targets. A later `cargo build-dev` -rebuilds every target already under `targets/`, named or not, so they stay in step with +host's `lib/`, so one Kani installation can verify for several targets. A `cargo build-dev` that +does not name a target leaves its libraries as they were, so name it again after changing `library/`. The rustup target itself does not need to be installed: the standard library is built from the `rust-src` component. diff --git a/tools/build-kani/src/main.rs b/tools/build-kani/src/main.rs index 58e3903e70e..58b18c71ed9 100644 --- a/tools/build-kani/src/main.rs +++ b/tools/build-kani/src/main.rs @@ -11,12 +11,11 @@ mod parser; mod sysroot; use crate::sysroot::{ - build_bin, build_lib, build_target_lib, build_tools, existing_lib_targets, kani_no_core_lib, - kani_playback_lib, kani_sysroot_lib, + build_bin, build_lib, build_target_lib, build_tools, kani_no_core_lib, kani_playback_lib, + kani_sysroot_lib, }; use anyhow::{Result, bail}; use clap::Parser; -use kani_metadata::SUPPORTED_TARGETS; use std::{ffi::OsString, path::Path, process::Command}; fn main() -> Result<()> { @@ -27,8 +26,8 @@ fn main() -> Result<()> { let bin_folder = &build_bin(&build_parser.args)?; if !build_parser.skip_libs { build_lib(bin_folder)?; - for target in lib_targets(&build_parser.lib_targets)? { - build_target_lib(bin_folder, &target)?; + for target in &build_parser.lib_targets { + build_target_lib(bin_folder, target)?; } } Ok(()) @@ -60,26 +59,6 @@ fn main() -> Result<()> { } } -/// The targets to build libraries for: the ones requested, plus every one already under -/// `targets/`. kani-driver uses whatever is in `targets//lib`, so a folder left from an -/// older build would be verified against silently after a change to `library/`. -fn lib_targets(requested: &[String]) -> Result> { - let mut targets = requested.to_vec(); - for target in existing_lib_targets()? { - if targets.contains(&target) { - continue; - } - if SUPPORTED_TARGETS.contains(&target.as_str()) { - println!("-- Rebuilding Kani's libraries for {target}, which a previous build added"); - targets.push(target); - } else { - // kani-driver refuses `--target` for it, so the folder is never read. - println!("-- Skipping targets/{target}: Kani does not support that target"); - } - } - Ok(targets) -} - /// Ensures everything is good to go before we begin to build the release bundle. /// Notably, builds Kani in release mode. fn prebundle(dir: &Path) -> Result<()> { diff --git a/tools/build-kani/src/parser.rs b/tools/build-kani/src/parser.rs index e5718f5d59e..78dc124bdbb 100644 --- a/tools/build-kani/src/parser.rs +++ b/tools/build-kani/src/parser.rs @@ -24,7 +24,6 @@ pub struct BuildDevParser { pub skip_libs: bool, /// Also build Kani's verification libraries for this target triple, so that /// `kani --target -Z unstable-options` can verify for it. May be repeated. - /// Targets built earlier are rebuilt whether or not they are named again. #[clap( long = "lib-target", value_name = "TRIPLE", diff --git a/tools/build-kani/src/sysroot.rs b/tools/build-kani/src/sysroot.rs index f83188dccd9..17bb68f5ff9 100644 --- a/tools/build-kani/src/sysroot.rs +++ b/tools/build-kani/src/sysroot.rs @@ -69,24 +69,6 @@ pub fn kani_target_lib(target: &str) -> PathBuf { path_buf!(kani_sysroot(), "targets", target, "lib") } -/// The targets that already have a folder under `targets/`, from an earlier -/// `cargo build-dev --lib-target`, sorted so the build order is stable. -pub fn existing_lib_targets() -> Result> { - let targets = path_buf!(kani_sysroot(), "targets"); - if !targets.is_dir() { - return Ok(vec![]); - } - let mut found = vec![]; - for entry in fs::read_dir(targets)? { - let entry = entry?; - if entry.file_type()?.is_dir() { - found.push(entry.file_name().to_string_lossy().into_owned()); - } - } - found.sort(); - Ok(found) -} - /// Returns the path to where Kani's pre-compiled binaries are stored. fn kani_sysroot_bin() -> PathBuf { path_buf!(kani_sysroot(), "bin") From 7f0339c28a4d769e2dc014f73261ff9aac9f9d88 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Fri, 4 Dec 2026 13:49:43 -0800 Subject: [PATCH 22/24] Move the up-front --target and --lib-target checks to a follow-up PR Checking --target in the driver, and --lib-target in build-kani, against one shared list gives a clear error before anything is built. That was a review suggestion, and it moves to the follow-up that hardens --target, with the kani_metadata constant and build-kani's new dependency on it. What keeps verification sound stays here: kani-compiler's check_target still accepts only the five exact target tuples (and no target JSON), so riscv64a23-unknown-linux-gnu, riscv64-wrs-vxworks and the non-macOS Apple targets are refused when the libraries or the crate are compiled. Its list now sits beside check_target, the only place this PR reads it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M1dgc2zy347cbi6td1Wd4x --- Cargo.lock | 1 - docs/src/reference/experimental/target.md | 4 +- .../compiler_interface.rs | 22 ++++++---- kani-driver/src/args/mod.rs | 38 +---------------- kani_metadata/src/lib.rs | 19 --------- .../target_riscv64/target_riscv64.expected | 8 ---- .../target_riscv64/target_riscv64.sh | 3 -- tools/build-kani/Cargo.toml | 1 - tools/build-kani/src/parser.rs | 42 +------------------ 9 files changed, 19 insertions(+), 119 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bd2a4977f35..047311bab63 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -212,7 +212,6 @@ dependencies = [ "anyhow", "cargo_metadata", "clap", - "kani_metadata", "which 8.0.6", ] diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index f3a32021bf7..aaad273ca15 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -20,8 +20,8 @@ A target needs a CBMC machine model in Kani. These are the targets that have one | `x86_64-apple-darwin` | | | `aarch64-apple-darwin` | | -Kani refuses any other `--target`, and `cargo build-dev --lib-target`, with an error that lists -these. +Kani's compiler refuses any other target, so `cargo build-dev --lib-target` fails for one with an +error that lists these. The bare-metal `riscv64gc-unknown-none-elf`, which kernels usually build for, is not supported. Verifying such a crate as `riscv64gc-unknown-linux-gnu` instead sets `target_os = "linux"` and diff --git a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs index d8645b3aa7e..97cfbbaabbc 100644 --- a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs +++ b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs @@ -20,10 +20,7 @@ use cbmc::goto_program::Location; use cbmc::{InternedString, MachineModel}; use cbmc::{RoundingMode, WithInterner}; use kani_metadata::artifact::convert_type; -use kani_metadata::{ - ArtifactType, HarnessMetadata, KaniMetadata, SUPPORTED_TARGETS, UnsupportedFeature, - supported_targets_list, -}; +use kani_metadata::{ArtifactType, HarnessMetadata, KaniMetadata, UnsupportedFeature}; use kani_metadata::{AssignsContract, CompilerArtifactStub}; use rustc_abi::{Align, Endian}; use rustc_codegen_ssa::back::archive::{ @@ -614,8 +611,18 @@ impl ArchiveBuilderBuilder for ArArchiveBuilderBuilder { } } +/// The rustc target tuples Kani can verify for, exactly as `rustc --target` spells them. Each one +/// needs a CBMC machine model in `new_machine_model` and its features in `target_config`. +const SUPPORTED_TARGETS: [&str; 5] = [ + "x86_64-unknown-linux-gnu", + "aarch64-unknown-linux-gnu", + "riscv64gc-unknown-linux-gnu", + "x86_64-apple-darwin", + "aarch64-apple-darwin", +]; + fn check_target(session: &Session) { - // `machine_model_from_session` in this file builds a CBMC machine model only for the targets + // `new_machine_model` in this file builds a CBMC machine model only for the targets // in `SUPPORTED_TARGETS`, and `target_config` hardcodes their features, so the session must // be one of those built-in targets exactly. The tuple names the built-in spec, which already // tells apart targets that share an LLVM target, such as `riscv64gc-unknown-linux-gnu`, @@ -631,8 +638,9 @@ fn check_target(session: &Session) { }; if !supported { let err_msg = format!( - "Kani requires the target platform to be {}, but it is `{}` (LLVM target `{}`)", - supported_targets_list(), + "Kani requires the target platform to be `x86_64-unknown-linux-gnu`, \ + `aarch64-unknown-linux-gnu`, `riscv64gc-unknown-linux-gnu`, `x86_64-apple-darwin` \ + or `aarch64-apple-darwin`, but it is `{}` (LLVM target `{}`)", session.opts.target_triple.tuple(), session.target.llvm_target ); diff --git a/kani-driver/src/args/mod.rs b/kani-driver/src/args/mod.rs index cfd65597a15..bb4661d015c 100644 --- a/kani-driver/src/args/mod.rs +++ b/kani-driver/src/args/mod.rs @@ -15,7 +15,7 @@ use crate::util::warning; use cargo::CargoCommonArgs; use clap::builder::{PossibleValue, TypedValueParser}; use clap::{ValueEnum, error::ContextKind, error::ContextValue, error::Error, error::ErrorKind}; -use kani_metadata::{CbmcSolver, SUPPORTED_TARGETS, supported_targets_list}; +use kani_metadata::CbmcSolver; use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::str::FromStr; @@ -850,20 +850,6 @@ impl ValidateArgs for VerificationArgs { UnstableFeature::UnstableOptions, )?; - // Checked here, after the unstable gate, so that the error is about the triple and - // not about a missing library folder or a compiler error deep in a cargo build. - if let Some(triple) = &self.target_triple - && !SUPPORTED_TARGETS.contains(&triple.as_str()) - { - return Err(Error::raw( - ErrorKind::InvalidValue, - format!( - "Unsupported target `{triple}`: Kani can verify for {}.", - supported_targets_list() - ), - )); - } - Ok(()) }; @@ -1663,26 +1649,4 @@ mod tests { assert_eq!(err.kind(), ErrorKind::ArgumentConflict, "for `{args}`"); } } - - /// `--target` is checked against `SUPPORTED_TARGETS` before anything is built, including the - /// empty string, which would otherwise resolve to the `targets/` folder itself. - #[test] - fn check_target_must_be_supported() { - for target in ["x86_64-unknown-linux-musl", "thumbv7em-none-eabihf", ""] { - let mut args: Vec<&str> = - "kani input.rs -Z unstable-options --target".split_whitespace().collect(); - args.push(target); - let err = - StandaloneArgs::try_parse_from(args).unwrap().verify_opts.validate().unwrap_err(); - assert_eq!(err.kind(), ErrorKind::InvalidValue, "for `{target}`"); - } - for target in SUPPORTED_TARGETS { - let args = format!("kani input.rs -Z unstable-options --target {target}"); - StandaloneArgs::try_parse_from(args.split_whitespace()) - .unwrap() - .verify_opts - .validate() - .unwrap(); - } - } } diff --git a/kani_metadata/src/lib.rs b/kani_metadata/src/lib.rs index 033d85244ab..e3c8e13cb1f 100644 --- a/kani_metadata/src/lib.rs +++ b/kani_metadata/src/lib.rs @@ -23,25 +23,6 @@ mod vtable; pub use unstable::{EnabledUnstableFeatures, UnstableFeature}; -/// The rustc target tuples Kani can verify for, exactly as `rustc --target` spells them. Each one -/// needs a CBMC machine model in kani-compiler (`machine_model_from_session`). kani-driver checks -/// `--target` against this list, build-kani checks `--lib-target`, and kani-compiler's -/// `check_target` checks the session, so the three cannot disagree about what is supported. -pub const SUPPORTED_TARGETS: [&str; 5] = [ - "x86_64-unknown-linux-gnu", - "aarch64-unknown-linux-gnu", - "riscv64gc-unknown-linux-gnu", - "x86_64-apple-darwin", - "aarch64-apple-darwin", -]; - -/// `SUPPORTED_TARGETS` as a list for an error message: "`a`, `b` or `c`". -pub fn supported_targets_list() -> String { - let quoted: Vec = SUPPORTED_TARGETS.iter().map(|t| format!("`{t}`")).collect(); - let (last, rest) = quoted.split_last().unwrap(); - format!("{} or {last}", rest.join(", ")) -} - /// The default maximum length for nondeterministic slices that automatic harnesses generate. /// Verification results for functions taking `&[T]`/`&mut [T]` arguments are only valid up to /// this bound. The default must stay below Kani's default unwinding bound (20), so that loops diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.expected b/tests/script-based-pre/target_riscv64/target_riscv64.expected index 22680566abe..b6cd40bc7fb 100644 --- a/tests/script-based-pre/target_riscv64/target_riscv64.expected +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -1,14 +1,6 @@ [TEST] --target needs -Z unstable-options error: The `--target` option is unstable and requires `-Z unstable-options` to be used. -[TEST] an unsupported --target is refused before anything is built -error: Unsupported target `riscv64gc-unknown-none-elf`: Kani can verify for `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu`, `riscv64gc-unknown-linux-gnu`, `x86_64-apple-darwin` or `aarch64-apple-darwin`. - -Usage: kani [OPTIONS] [INPUT] - kani - -For more information, try '--help'. - [TEST] single file on the host: the riscv64 harnesses are compiled out No proof harnesses (functions with #[kani::proof]) were found to verify. diff --git a/tests/script-based-pre/target_riscv64/target_riscv64.sh b/tests/script-based-pre/target_riscv64/target_riscv64.sh index e07f3326a31..5dd922b0f17 100755 --- a/tests/script-based-pre/target_riscv64/target_riscv64.sh +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -12,9 +12,6 @@ TARGET=riscv64gc-unknown-linux-gnu echo "[TEST] --target needs -Z unstable-options" kani riscv64.rs --target $TARGET -echo "[TEST] an unsupported --target is refused before anything is built" -kani riscv64.rs --target riscv64gc-unknown-none-elf -Z unstable-options - echo "[TEST] single file on the host: the riscv64 harnesses are compiled out" kani riscv64.rs diff --git a/tools/build-kani/Cargo.toml b/tools/build-kani/Cargo.toml index 4e1258c5490..fa39d935b6f 100644 --- a/tools/build-kani/Cargo.toml +++ b/tools/build-kani/Cargo.toml @@ -13,7 +13,6 @@ publish = false anyhow = "1" cargo_metadata = "0.23" clap = { version = "4.4.11", features=["derive"] } -kani_metadata = { path = "../../kani_metadata" } which = "8" [lints] diff --git a/tools/build-kani/src/parser.rs b/tools/build-kani/src/parser.rs index 78dc124bdbb..fc233304954 100644 --- a/tools/build-kani/src/parser.rs +++ b/tools/build-kani/src/parser.rs @@ -3,7 +3,6 @@ //! This file contains a small parser for our build script. use clap::{Args, Parser, Subcommand}; -use kani_metadata::{SUPPORTED_TARGETS, supported_targets_list}; #[derive(Parser)] #[clap(name = "build-kani")] @@ -24,25 +23,10 @@ pub struct BuildDevParser { pub skip_libs: bool, /// Also build Kani's verification libraries for this target triple, so that /// `kani --target -Z unstable-options` can verify for it. May be repeated. - #[clap( - long = "lib-target", - value_name = "TRIPLE", - conflicts_with = "skip_libs", - value_parser = parse_lib_target - )] + #[clap(long = "lib-target", value_name = "TRIPLE", conflicts_with = "skip_libs")] pub lib_targets: Vec, } -/// Refuse a target Kani has no machine model for before building anything. Otherwise the error is -/// kani-compiler's, from inside the library build, after the binaries have been rebuilt. -fn parse_lib_target(target: &str) -> Result { - if SUPPORTED_TARGETS.contains(&target) { - Ok(target.to_string()) - } else { - Err(format!("Kani can verify for {}", supported_targets_list())) - } -} - #[derive(Args, Debug, Eq, PartialEq)] pub struct BundleParser { /// String version @@ -57,27 +41,3 @@ pub enum Commands { /// Build Kani's release bundle. Bundle(BundleParser), } - -#[cfg(test)] -mod tests { - use super::*; - - fn parse(args: &[&str]) -> Result { - ArgParser::try_parse_from(["build-kani", "build-dev"].iter().chain(args)) - } - - #[test] - fn lib_target_must_be_supported() { - let Commands::BuildDev(parsed) = - parse(&["--lib-target", "riscv64gc-unknown-linux-gnu"]).unwrap().subcommand - else { - panic!("expected build-dev"); - }; - assert_eq!(parsed.lib_targets, ["riscv64gc-unknown-linux-gnu"]); - - for target in ["x86_64-unknown-linux-musl", "thumbv7em-none-eabihf", ""] { - let err = parse(&["--lib-target", target]).err().expect(target); - assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation, "for `{target}`"); - } - } -} From 8092e88166d203d7961e808e89ae251c3dd95be6 Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Fri, 4 Dec 2026 13:49:50 -0800 Subject: [PATCH 23/24] Move the bare-metal riscv64 note to the --target hardening PR The paragraph on riscv64gc-unknown-none-elf answers a review suggestion and goes with the other supported-target changes in the follow-up. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M1dgc2zy347cbi6td1Wd4x --- docs/src/reference/experimental/target.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index aaad273ca15..1420c82b77c 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -23,11 +23,6 @@ A target needs a CBMC machine model in Kani. These are the targets that have one Kani's compiler refuses any other target, so `cargo build-dev --lib-target` fails for one with an error that lists these. -The bare-metal `riscv64gc-unknown-none-elf`, which kernels usually build for, is not supported. -Verifying such a crate as `riscv64gc-unknown-linux-gnu` instead sets `target_os = "linux"` and -makes `std` available, so code behind `cfg(target_os = "none")` is compiled out and the `linux` -branch, if there is one, is what Kani verifies. - ## Building the libraries Kani verifies against its own build of the standard library and of the `kani` crate, compiled for From e7239cc5fe2fe5de20a5c674ea16b1e1fef9980b Mon Sep 17 00:00:00 2001 From: Chris Alef Date: Fri, 4 Dec 2026 13:49:58 -0800 Subject: [PATCH 24/24] Say in the target docs how kani_lib.c keeps the target's model The overwrite comes from goto-cc compiling kani_lib.c during the link, not from linking goto binaries, as the review pointed out. The --c-lib limitation already says so; add how Kani avoids it for its own C file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M1dgc2zy347cbi6td1Wd4x --- docs/src/reference/experimental/target.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/src/reference/experimental/target.md b/docs/src/reference/experimental/target.md index 1420c82b77c..36aa1e7640e 100644 --- a/docs/src/reference/experimental/target.md +++ b/docs/src/reference/experimental/target.md @@ -53,7 +53,8 @@ cargo kani --target riscv64gc-unknown-linux-gnu -Z unstable-options * The `verify-std` subcommand and `autoharness --std` do not support `--target`. * `--c-lib` is rejected with a non-host `--target`. `goto-cc` compiles C sources with the host's C configuration, and a source compiled as part of the link would replace the target's machine - model in the linked program. + model in the linked program. For the same reason Kani compiles its own `kani_lib.c` on its own + and links it after the Rust code, which keeps the target's model. * Kani's machine model has no operating system, so `__CPROVER_architecture_os` in the linked program is the host's, as it is for a host run. A `riscv64gc-unknown-linux-gnu` run on macOS therefore has `os = "macos"`. CBMC reads this setting in a few places when it processes C, such