Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
f295764
Add an unstable --target option and a riscv64 machine model
calef Sep 25, 2026
5ce11c8
test the two --target rejections; document the goto-cc arch overwrite
calef Sep 30, 2026
9023df2
drop the local verification shim committed by mistake
calef Sep 30, 2026
a5fac6a
Accept only the targets the machine models were written for
calef Oct 3, 2026
2d0a623
Correct the cause of the architecture overwrite in the target docs
calef Oct 3, 2026
450cbc2
Tighten the --target test, docs and build-dev flags after self-review
calef Oct 3, 2026
1eaa2d9
Keep the target's machine model in the linked goto binary
calef Oct 5, 2026
08bbefe
Check the machine model in the linked riscv64 goto binary
calef Oct 5, 2026
409ba07
Record the verification target in --export-json metadata
calef Oct 5, 2026
c377470
Drop the fixed machine-model limitation from the target docs
calef Oct 5, 2026
9b72fa0
Mark char as signed in the aarch64-apple-darwin machine model
calef Oct 5, 2026
27bf95e
Test the --c-lib rejection for another target in target_riscv64
calef Oct 5, 2026
7153afd
Refuse --target for autoharness --std, as verify-std does
calef Oct 5, 2026
eb6c119
Say in the target docs that bare-metal riscv64 is not supported
calef Oct 5, 2026
d67167f
Check --target and --lib-target against one list of supported targets
calef Oct 5, 2026
25e3570
Match the exact target tuple in check_target
calef Oct 5, 2026
c8a5d29
Rebuild every target under targets/ on each cargo build-dev
calef Oct 5, 2026
0467068
Merge branch 'main' into riscv64-target
calef Oct 9, 2026
3b69842
Merge branch 'main' into riscv64-target
calef Oct 22, 2026
c264c69
Record the --target triple in the RFC 0015 export
calef Oct 22, 2026
629bdb3
Merge branch 'main' into riscv64-target
calef Oct 26, 2026
e2e4a07
Merge remote-tracking branch 'upstream/main' into riscv64-target
calef Nov 23, 2026
f9c72e8
Merge branch 'main' into riscv64-target
calef Nov 26, 2026
9d8eb59
Merge branch 'main' into riscv64-target
calef Dec 1, 2026
bb0fd81
Move the signed char change for aarch64-apple-darwin to its own PR
calef Dec 4, 2026
a147c47
Move the --export-json target change to a follow-up PR
calef Dec 4, 2026
786ddf2
Move the rebuild of existing targets/ folders to a follow-up PR
calef Dec 4, 2026
7f0339c
Move the up-front --target and --lib-target checks to a follow-up PR
calef Dec 4, 2026
8092e88
Move the bare-metal riscv64 note to the --target hardening PR
calef Dec 4, 2026
e7239cc
Say in the target docs how kani_lib.c keeps the target's model
calef Dec 4, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
65 changes: 65 additions & 0 deletions docs/src/reference/experimental/target.md
Original file line number Diff line number Diff line change
@@ -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 |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: kernels usually build for riscv64gc-unknown-none-elf, which check_target rejects. Verifying such a crate as riscv64gc-unknown-linux-gnu sets target_os = "linux" and makes std available, so code behind cfg(target_os = "none") is compiled out and the linux branch is verified in its place. A sentence here saying the bare-metal target isn't supported, and what changes when the Linux one stands in for it, would tell kernel users what they are and aren't verifying.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in eb6c119. The page now says riscv64gc-unknown-none-elf isn't supported, and that verifying such a crate as riscv64gc-unknown-linux-gnu sets target_os = "linux" and makes std available, so cfg(target_os = "none") code is compiled out and the linux branch is what gets verified.

| `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/<TRIPLE>/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)).
102 changes: 81 additions & 21 deletions kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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![]
};
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -925,6 +942,49 @@ fn new_machine_model(sess: &Session) -> MachineModel {
word_size: int_width,
}
}
Arch::RiscV64 => {
Comment thread
calef marked this conversation as resolved.
Resolved
// 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
Comment thread
calef marked this conversation as resolved.
Resolved
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}");
}
Expand Down
8 changes: 8 additions & 0 deletions kani-driver/src/args/autoharness_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
93 changes: 93 additions & 0 deletions kani-driver/src/args/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -407,6 +411,12 @@ pub struct VerificationArgs {
#[arg(long)]
pub target_dir: Option<PathBuf>,

/// 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<String>,
Comment thread
calef marked this conversation as resolved.
Resolved
Comment thread
calef marked this conversation as resolved.
Resolved

/// Enable test function verification. Only use this option when the entry point is a test function
#[arg(long)]
pub tests: bool,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -824,6 +844,12 @@ impl ValidateArgs for VerificationArgs {
UnstableFeature::ExportJson,
)?;

self.common_args.check_unstable(
self.target_triple.is_some(),
"target",
UnstableFeature::UnstableOptions,
)?;

Ok(())
};

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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}`");
}
}
}
8 changes: 8 additions & 0 deletions kani-driver/src/args/std_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ impl ValidateArgs for VerifyStdArgs {
));
}

if self.verify_opts.target_triple.is_some() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: kani autoharness --std goes through the same cargo_build_std path, which now passes HOST_TARGET, but nothing rejects --target there. With kani autoharness --std <library> --target riscv64gc-unknown-linux-gnu -Z unstable-options -Z autoharness --verbose, the cargo command has --target x86_64-unknown-linux-gnu, so a successful run would be a result for the host's std while the user asked for riscv64. The same check in AutoharnessArgs::validate when self.std is set would cover it, plus a line in the test next to the verify-std one.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in 7153afd. AutoharnessArgs::validate now refuses --target when --std is set, before the std path check, the same way verify-std does. There is a unit test covering both subcommands and a line in target_riscv64.

// 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)
}
}
Loading