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..36aa1e7640e --- /dev/null +++ b/docs/src/reference/experimental/target.md @@ -0,0 +1,65 @@ +# 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` | | + +Kani's compiler refuses any other target, so `cargo build-dev --lib-target` fails for one 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. 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. + +## 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 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. 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 + 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 + 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 73d21df8af9..97cfbbaabbc 100644 --- a/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs +++ b/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs @@ -45,7 +45,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; @@ -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![] }; @@ -605,27 +611,37 @@ 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) { - // 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 - 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-"); - - if !is_x86_64_linux_target - && !is_arm64_linux_target - && !is_x86_64_darwin_target - && !is_arm64_darwin_target - { + // `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`, + // `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`, `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); @@ -809,8 +825,9 @@ 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; @@ -925,6 +942,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/autoharness_args.rs b/kani-driver/src/args/autoharness_args.rs index 4d1442b8dbe..47975d43547 100644 --- a/kani-driver/src/args/autoharness_args.rs +++ b/kani-driver/src/args/autoharness_args.rs @@ -285,6 +285,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 4207be5aa21..bb4661d015c 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")] @@ -407,6 +411,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, @@ -481,6 +491,16 @@ 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) + } + + /// 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 @@ -824,6 +844,12 @@ impl ValidateArgs for VerificationArgs { UnstableFeature::ExportJson, )?; + self.common_args.check_unstable( + self.target_triple.is_some(), + "target", + UnstableFeature::UnstableOptions, + )?; + Ok(()) }; @@ -861,6 +887,24 @@ impl ValidateArgs for VerificationArgs { --output-format=old.", )); } + 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, + "Conflicting options: --concrete-playback runs on the host, so it isn't \ + 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 +1600,53 @@ 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(); + } + + /// `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/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 394c81faae1..ac697423829 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; @@ -98,7 +98,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()); @@ -141,7 +141,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 @@ -158,7 +159,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())); @@ -178,7 +179,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()); @@ -501,10 +502,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_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()); diff --git a/kani-driver/src/call_single_file.rs b/kani-driver/src/call_single_file.rs index 7ba952917f5..03a80f4efaf 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.extend(self.kani_rustc_local_flags()); rustc_args.push(file.into()); rustc_args.push("--out-dir".into()); diff --git a/kani-driver/src/concrete_playback/playback.rs b/kani-driver/src/concrete_playback/playback.rs index ad514d29f28..4f22500d797 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 1fcbb8a4d92..dc09f6b5244 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; @@ -321,6 +322,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 9927fae1d0b..fcafb38ff1d 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/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/riscv64.rs b/tests/script-based-pre/target_riscv64/riscv64.rs new file mode 100644 index 00000000000..baf41a917ce --- /dev/null +++ b/tests/script-based-pre/target_riscv64/riscv64.rs @@ -0,0 +1,23 @@ +// 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")); + } + + /// 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..b6cd40bc7fb --- /dev/null +++ b/tests/script-based-pre/target_riscv64/target_riscv64.expected @@ -0,0 +1,53 @@ +[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] 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. + +[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] --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` + +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 new file mode 100755 index 00000000000..5dd922b0f17 --- /dev/null +++ b/tests/script-based-pre/target_riscv64/target_riscv64.sh @@ -0,0 +1,56 @@ +#!/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] 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 +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] --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 + +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 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..fc233304954 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", conflicts_with = "skip_libs")] + 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 d62360dce4c..17bb68f5ff9 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)?; @@ -194,8 +229,8 @@ fn copy_artifacts(artifacts: &[Artifact], sysroot_lib: &Path, copy_std: bool) -> copy_unhashed_kani_rlibs(artifacts, sysroot_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); }