blob: 011f14b6d7f1c5768505a37124830df04689c424 [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
use std::{collections::BTreeMap, process::ExitCode};
use anneal_ffi_check::{emit_c_asserts, emit_lean_parity, verify_ffi_inputs};
const USAGE: &str = "\
usage: anneal-ffi-check --cpp-bundle BUNDLE.json \\
[--rust-ffi RUST_FFI.json] [--rust-type-sizes SIZES.txt] \\
[--map RUST=CPP]... [--format human|json] \\
[--emit-lean OUT.lean|-] [--lean-namespace NS] \\
[--emit-c-asserts OUT.h|-]
Checks C/C++ <-> Rust FFI layout, padding, scalar/enum, ABI passing,
calling-convention, and unwind-safety parity.
Exit status: 0 on pass, 1 on usage/IO/parse error, 2 on FFI violation.";
#[derive(Clone, Copy, PartialEq, Eq)]
enum OutputFormat {
Human,
Json,
}
fn main() -> ExitCode {
run_cli(std::env::args().skip(1))
}
fn run_cli<I>(mut args: I) -> ExitCode
where
I: Iterator<Item = String>,
{
let mut cpp_bundle_path: Option<String> = None;
let mut rust_ffi_path: Option<String> = None;
let mut rust_type_sizes_path: Option<String> = None;
let mut explicit_maps: BTreeMap<String, String> = BTreeMap::new();
let mut format = OutputFormat::Human;
let mut emit_lean_path: Option<String> = None;
let mut lean_namespace = "Anneal.FfiParity".to_owned();
let mut emit_c_asserts_path: Option<String> = None;
while let Some(arg) = args.next() {
let mut next_val = |flag: &str| match args.next() {
Some(v) => Ok(v),
None => Err(format!("missing value for {flag}")),
};
let res: Result<(), String> = match arg.as_str() {
"--cpp-bundle" => next_val("--cpp-bundle").map(|v| cpp_bundle_path = Some(v)),
"--rust-ffi" => next_val("--rust-ffi").map(|v| rust_ffi_path = Some(v)),
"--rust-type-sizes" => {
next_val("--rust-type-sizes").map(|v| rust_type_sizes_path = Some(v))
}
"--map" => next_val("--map").and_then(|v| {
let Some((k, val)) = v.split_once('=') else {
return Err(format!("invalid --map `{v}` (expected RUST_NAME=CPP_RECORD)"));
};
if k.is_empty() || val.is_empty() {
return Err(format!("invalid --map `{v}` (empty name in mapping)"));
}
if explicit_maps.insert(k.to_owned(), val.to_owned()).is_some() {
return Err(format!("duplicate --map entry for `{k}`"));
}
Ok(())
}),
"--format" => next_val("--format").and_then(|v| match v.as_str() {
"human" => {
format = OutputFormat::Human;
Ok(())
}
"json" => {
format = OutputFormat::Json;
Ok(())
}
other => Err(format!("unknown --format `{other}` (expected `human` or `json`)")),
}),
"--emit-lean" => next_val("--emit-lean").map(|v| emit_lean_path = Some(v)),
"--lean-namespace" => next_val("--lean-namespace").map(|v| lean_namespace = v),
"--emit-c-asserts" => {
next_val("--emit-c-asserts").map(|v| emit_c_asserts_path = Some(v))
}
"-h" | "--help" => {
println!("{USAGE}");
return ExitCode::SUCCESS;
}
other => Err(format!("unexpected argument `{other}`")),
};
if let Err(msg) = res {
eprintln!("anneal-ffi-check: {msg}\n{USAGE}");
return ExitCode::from(1);
}
}
let Some(cpp_path) = cpp_bundle_path else {
eprintln!("anneal-ffi-check: missing --cpp-bundle\n{USAGE}");
return ExitCode::from(1);
};
if rust_ffi_path.is_none() && rust_type_sizes_path.is_none() {
eprintln!(
"anneal-ffi-check: provide --rust-ffi and/or --rust-type-sizes\n\
{USAGE}"
);
return ExitCode::from(1);
}
if emit_lean_path.as_deref() == Some("-") && emit_c_asserts_path.as_deref() == Some("-") {
eprintln!(
"anneal-ffi-check: cannot write both --emit-lean and --emit-c-asserts to stdout\n\
{USAGE}"
);
return ExitCode::from(1);
}
let cpp_text = match std::fs::read_to_string(&cpp_path) {
Ok(t) => t,
Err(e) => {
eprintln!("anneal-ffi-check: cannot read {cpp_path}: {e}");
return ExitCode::from(1);
}
};
let rust_ffi_text = match &rust_ffi_path {
None => None,
Some(p) => match std::fs::read_to_string(p) {
Ok(t) => Some(t),
Err(e) => {
eprintln!("anneal-ffi-check: cannot read {p}: {e}");
return ExitCode::from(1);
}
},
};
let ts_text = match &rust_type_sizes_path {
None => None,
Some(p) => match std::fs::read_to_string(p) {
Ok(t) => Some(t),
Err(e) => {
eprintln!("anneal-ffi-check: cannot read {p}: {e}");
return ExitCode::from(1);
}
},
};
let outcome = match verify_ffi_inputs(
&cpp_text,
rust_ffi_text.as_deref(),
ts_text.as_deref(),
&explicit_maps,
) {
Ok(o) => o,
Err(e) => {
eprintln!("anneal-ffi-check: {e}");
return ExitCode::from(1);
}
};
let artifact_to_stdout =
emit_lean_path.as_deref() == Some("-") || emit_c_asserts_path.as_deref() == Some("-");
match format {
OutputFormat::Human => {
if artifact_to_stdout {
eprint!("{}", outcome.report.format_human());
} else {
print!("{}", outcome.report.format_human());
}
}
OutputFormat::Json => match outcome.report.to_json_pretty() {
Ok(json) => {
if artifact_to_stdout {
eprintln!("{json}");
} else {
println!("{json}");
}
}
Err(e) => {
eprintln!("anneal-ffi-check: JSON serialization failed: {e}");
return ExitCode::from(1);
}
},
}
if !outcome.report.ok {
return ExitCode::from(2);
}
if let Some(lean_out) = emit_lean_path {
let lean = match emit_lean_parity(
&lean_namespace,
&outcome.report.target_triple,
&outcome.matched_records,
) {
Ok(l) => l,
Err(e) => {
eprintln!("anneal-ffi-check: cannot emit Lean: {e}");
return ExitCode::from(1);
}
};
if lean_out == "-" {
print!("{lean}");
} else if let Err(e) = std::fs::write(&lean_out, &lean) {
eprintln!("anneal-ffi-check: cannot write {lean_out}: {e}");
return ExitCode::from(1);
}
}
if let Some(c_out) = emit_c_asserts_path {
let hdr = match emit_c_asserts(&outcome) {
Ok(h) => h,
Err(e) => {
eprintln!("anneal-ffi-check: cannot emit C asserts: {e}");
return ExitCode::from(1);
}
};
if c_out == "-" {
print!("{hdr}");
} else if let Err(e) = std::fs::write(&c_out, &hdr) {
eprintln!("anneal-ffi-check: cannot write {c_out}: {e}");
return ExitCode::from(1);
}
}
ExitCode::SUCCESS
}
#[cfg(test)]
mod cli_tests {
use super::*;
struct TempFile(std::path::PathBuf);
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn write_temp(tag: &str, body: &str) -> TempFile {
let mut p = std::env::temp_dir();
p.push(format!(
"anneal_ffi_check_{}_{}_{tag}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos()),
));
std::fs::write(&p, body).expect("write temp file");
TempFile(p)
}
#[test]
fn cli_exit_codes_and_lean_emit() {
// Usage error -> exit 1.
assert_eq!(run_cli(std::iter::empty()), ExitCode::from(1));
let cpp = write_temp(
"cpp.json",
r#"{
"schema_version": 1,
"tu_main_file": "cli.c",
"target_triple": "x86_64-unknown-linux-gnu",
"lang_policy": {
"char_is_signed": true,
"exceptions_enabled": false,
"fast_math": false,
"is_cplusplus": false,
"lang_standard": "c11",
"pointer_width_bits": 64,
"signed_overflow": "iso_ub",
"strict_aliasing": true
},
"records": [
{
"id": "struct.Point",
"name": "Point",
"is_union": false,
"size_bytes": 8,
"align_bytes": 4,
"fields": [
{ "name": "x", "offset_bits": 0, "bit_width": null, "is_const": false, "ty": { "kind": "int", "bits": 32, "signed": true, "is_char_like": false } },
{ "name": "y", "offset_bits": 32, "bit_width": null, "is_const": false, "ty": { "kind": "int", "bits": 32, "signed": true, "is_char_like": false } }
]
}
],
"functions": []
}"#,
);
let rust_ok = write_temp(
"ok.json",
r#"{
"schema_version": 1,
"target_triple": "x86_64-unknown-linux-gnu",
"pointer_width_bits": 64,
"c_char_is_signed": true,
"records": [
{
"rust_name": "Point",
"cpp_record": "struct.Point",
"repr": "C",
"size_bytes": 8,
"align_bytes": 4,
"fields": [
{ "name": "x", "offset_bytes": 0, "size_bytes": 4, "ty": { "kind": "int", "bits": 32, "signed": true } },
{ "name": "y", "offset_bytes": 4, "size_bytes": 4, "ty": { "kind": "int", "bits": 32, "signed": true } }
]
}
]
}"#,
);
let rust_bad = write_temp(
"bad.json",
r#"{
"schema_version": 1,
"target_triple": "x86_64-unknown-linux-gnu",
"pointer_width_bits": 64,
"c_char_is_signed": true,
"records": [
{
"rust_name": "Point",
"cpp_record": "struct.Point",
"repr": "Rust",
"size_bytes": 8,
"align_bytes": 4,
"fields": [
{ "name": "x", "offset_bytes": 0, "size_bytes": 4, "ty": { "kind": "int", "bits": 32, "signed": true } },
{ "name": "y", "offset_bytes": 4, "size_bytes": 4, "ty": { "kind": "int", "bits": 32, "signed": true } }
]
}
]
}"#,
);
let lean_out = write_temp("parity.lean", "");
let c_asserts_out = write_temp("asserts.h", "");
let ok_code = run_cli(
[
"--cpp-bundle",
cpp.0.to_str().unwrap(),
"--rust-ffi",
rust_ok.0.to_str().unwrap(),
"--format",
"json",
"--emit-lean",
lean_out.0.to_str().unwrap(),
"--emit-c-asserts",
c_asserts_out.0.to_str().unwrap(),
]
.into_iter()
.map(str::to_owned),
);
assert_eq!(ok_code, ExitCode::SUCCESS);
let lean_text = std::fs::read_to_string(&lean_out.0).unwrap();
assert!(lean_text.contains("theorem Point_layout_parity"));
let c_asserts_text = std::fs::read_to_string(&c_asserts_out.0).unwrap();
assert!(c_asserts_text.contains("sizeof(struct Point) == 8"));
assert!(c_asserts_text.contains("ANNEAL_ALIGNOF(struct Point) == 4"));
// Reject writing both --emit-lean and --emit-c-asserts to stdout.
let both_stdout = run_cli(
[
"--cpp-bundle",
cpp.0.to_str().unwrap(),
"--rust-ffi",
rust_ok.0.to_str().unwrap(),
"--emit-lean",
"-",
"--emit-c-asserts",
"-",
]
.into_iter()
.map(str::to_owned),
);
assert_eq!(both_stdout, ExitCode::from(1));
let bad_code = run_cli(
["--cpp-bundle", cpp.0.to_str().unwrap(), "--rust-ffi", rust_bad.0.to_str().unwrap()]
.into_iter()
.map(str::to_owned),
);
assert_eq!(bad_code, ExitCode::from(2));
}
}