blob: 611b22e36f662650176ab5a0af3a3a6dfd8fb1f2 [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.
//! Core C/C++ <-> Rust FFI layout, scalar/enum, ABI passing, and unwind-safety
//! verification engine.
use std::collections::{BTreeMap, BTreeSet};
use crate::{
cpp_bundle::{AbiPassing, CppBundle, CppEnum, CppFunction, CppMethodKind, CppRecord, CppType},
report::{
CheckReport, Diagnostic, DiagnosticCategory, DiagnosticCode, PaddingKind,
PaddingRegionReport, PaddingResolution, Warning, WarningCode,
},
rust_desc::{
FfiDirection, RustAbi, RustEnum, RustFfiDescriptor, RustField, RustFunction, RustRecord,
RustType,
},
};
const BASELINE_VALIDITY_CAVEAT: &str = "Non-flagged parameters (integers, raw pointers, and \
#[repr(C)] aggregates composed solely of them, unlike MaybeUninit<T>) are NOT \
validity-free: C callers must still ensure all non-padding bytes are initialized.";
/// Result of verifying a `CppBundle` against a `RustFfiDescriptor`, together
/// with clean verified record, enum, and export pairs for optional Lean parity
/// and C assertion-header emission.
#[derive(Debug, Clone)]
pub struct CheckOutcome {
pub report: CheckReport,
/// Only records that passed every layout, type, and padding check with
/// zero diagnostics are included here.
pub matched_records: Vec<MatchedRecord>,
/// Verified C/C++ enums (from top-level `enums[]` checks or referenced in
/// verified export signatures), deduplicated in deterministic order.
pub matched_enums: Vec<MatchedEnum>,
/// Verified `direction == Export` function pairs.
pub matched_exports: Vec<MatchedExport>,
/// Verified target policy summary for C assertion-header emission.
pub target_policy: VerifiedTargetPolicy,
/// Record id -> C/C++ tag spelling metadata (including opaque pointees).
pub(crate) record_tags: BTreeMap<String, CppTagMeta>,
/// Enum id or name -> C/C++ enum tag spelling metadata.
pub(crate) enum_tags: BTreeMap<String, CppTagMeta>,
}
/// Verified target policy facts for C assertion-header emission.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedTargetPolicy {
pub target_triple: String,
pub is_cplusplus: bool,
pub pointer_width_bits: u64,
pub char_is_signed: bool,
pub c_long_bits: Option<u64>,
}
/// C/C++ type spelling metadata retained for `--emit-c-asserts`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CppTagMeta {
pub name: String,
pub qualified_name: Option<String>,
pub is_union: bool,
pub is_anonymous_typedef: bool,
pub is_scoped: bool,
}
/// Verified C/C++ and Rust record pair.
#[derive(Debug, Clone)]
pub struct MatchedRecord {
pub rust: RustRecord,
pub cpp: CppRecord,
}
/// Verified C/C++ enum entry for C assertion-header emission.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MatchedEnum {
pub cpp: CppEnum,
}
/// Verified C/C++ declaration and Rust export pair.
#[derive(Debug, Clone)]
pub struct MatchedExport {
pub rust: RustFunction,
pub cpp: CppFunction,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TypeRole {
Field,
ImportParam,
ImportReturn,
ExportParam,
ExportReturn,
}
/// Runs all FFI layout, padding, scalar/enum, calling-convention, ABI passing,
/// unwind-ABI, and C++ object-model checks.
pub fn check_ffi(bundle: &CppBundle, rust: &RustFfiDescriptor) -> CheckOutcome {
let mut ctx = Checker::new(bundle, rust);
ctx.check_target_policy();
ctx.check_records();
ctx.check_enums();
ctx.check_functions();
ctx.finish()
}
/// Fixed integer bit widths supported uniformly across C/C++, Rust, System V
/// ABI classification, and Lean parity emission.
pub(crate) fn is_supported_int_bits(bits: u64) -> bool {
matches!(bits, 8 | 16 | 32 | 64 | 128)
}
/// Valid C/Rust `c_long` / `c_ulong` bit widths (32-bit ILP32/LLP64 or 64-bit
/// LP64).
pub(crate) fn is_supported_c_long_bits(bits: u64) -> bool {
matches!(bits, 32 | 64)
}
/// Supported target pointer widths (16-, 32-, or 64-bit).
pub(crate) fn is_supported_pointer_width_bits(bits: u64) -> bool {
matches!(bits, 16 | 32 | 64)
}
enum MutableStatus {
Clean,
HasMutable(String),
Unattested(String),
}
fn is_lossy_or_empty_passing(p: &AbiPassing) -> bool {
match p {
AbiPassing::Other { .. } => true,
AbiPassing::DirectOther { desc } => desc.trim().is_empty(),
_ => false,
}
}
struct Checker<'a> {
bundle: &'a CppBundle,
rust: &'a RustFfiDescriptor,
/// `Some(r)` when the record `id` is unique in `bundle.records`, or `None`
/// when multiple colliding records share that `id` (fail closed).
cpp_records_by_id: BTreeMap<&'a str, Option<&'a CppRecord>>,
/// `Some(f)` when the linker `symbol` is unique in `bundle.functions`, or
/// `None` when multiple colliding entries share that `symbol`.
cpp_fns_by_sym: BTreeMap<&'a str, Option<&'a CppFunction>>,
enums_checked: usize,
matched_records: Vec<MatchedRecord>,
matched_enums: Vec<MatchedEnum>,
seen_matched_enum_keys: BTreeSet<String>,
matched_exports: Vec<MatchedExport>,
padding_regions: Vec<PaddingRegionReport>,
diagnostics: Vec<Diagnostic>,
warnings: Vec<Warning>,
}
impl<'a> Checker<'a> {
fn new(bundle: &'a CppBundle, rust: &'a RustFfiDescriptor) -> Self {
let mut cpp_records_by_id: BTreeMap<&'a str, Option<&'a CppRecord>> = BTreeMap::new();
for r in &bundle.records {
cpp_records_by_id
.entry(r.id.as_str())
.and_modify(|slot| *slot = None)
.or_insert(Some(r));
}
let mut cpp_fns_by_sym: BTreeMap<&'a str, Option<&'a CppFunction>> = BTreeMap::new();
for f in &bundle.functions {
cpp_fns_by_sym
.entry(f.symbol.as_str())
.and_modify(|slot| *slot = None)
.or_insert(Some(f));
}
Self {
bundle,
rust,
cpp_records_by_id,
cpp_fns_by_sym,
enums_checked: 0,
matched_records: Vec::new(),
matched_enums: Vec::new(),
seen_matched_enum_keys: BTreeSet::new(),
matched_exports: Vec::new(),
padding_regions: Vec::new(),
diagnostics: Vec::new(),
warnings: Vec::new(),
}
}
fn record_matched_enum(&mut self, ce: &CppEnum) {
let key = ce.id.clone().unwrap_or_else(|| ce.name.clone());
if self.seen_matched_enum_keys.insert(key) {
self.matched_enums.push(MatchedEnum { cpp: ce.clone() });
}
}
fn unique_cpp_record_by_id(&self, id: &str) -> Option<&'a CppRecord> {
self.cpp_records_by_id.get(id).copied().flatten()
}
fn finish(self) -> CheckOutcome {
let ok = self.diagnostics.is_empty();
let effective_c_long = self
.bundle
.lang_policy
.c_long_bits
.or(self.rust.c_long_bits)
.or_else(|| inferred_target_c_long_bits(&self.bundle.target_triple));
let target_policy = VerifiedTargetPolicy {
target_triple: self.bundle.target_triple.clone(),
is_cplusplus: self.bundle.lang_policy.is_cplusplus,
pointer_width_bits: self.bundle.lang_policy.pointer_width_bits,
char_is_signed: self.bundle.lang_policy.char_is_signed,
c_long_bits: effective_c_long,
};
let (matched_records, matched_enums, matched_exports) = if ok {
(self.matched_records, self.matched_enums, self.matched_exports)
} else {
(Vec::new(), Vec::new(), Vec::new())
};
let mut record_tags = BTreeMap::new();
let mut enum_tags = BTreeMap::new();
if ok {
for r in &self.bundle.records {
record_tags.insert(
r.id.clone(),
CppTagMeta {
name: r.name.clone(),
qualified_name: r.qualified_name.clone(),
is_union: r.is_union,
is_anonymous_typedef: r.is_anonymous_typedef,
is_scoped: false,
},
);
}
for e in &self.bundle.enums {
let meta = CppTagMeta {
name: e.name.clone(),
qualified_name: e.qualified_name.clone(),
is_union: false,
is_anonymous_typedef: e.is_anonymous_typedef,
is_scoped: e.is_scoped.unwrap_or(false),
};
if let Some(id) = &e.id {
enum_tags.insert(id.clone(), meta.clone());
}
if let Some(qname) = &e.qualified_name {
enum_tags.insert(qname.clone(), meta.clone());
}
enum_tags.entry(format!("enum {}", e.name)).or_insert_with(|| meta.clone());
enum_tags.entry(format!("enum.{}", e.name)).or_insert_with(|| meta.clone());
enum_tags.entry(e.name.clone()).or_insert(meta);
}
}
let report = CheckReport {
schema_version: 1,
ok,
target_triple: self.bundle.target_triple.clone(),
records_checked: self.rust.records.len(),
enums_checked: self.enums_checked,
functions_checked: self.rust.functions.len(),
padding_regions: self.padding_regions,
diagnostics: self.diagnostics,
warnings: self.warnings,
};
CheckOutcome {
report,
matched_records,
matched_enums,
matched_exports,
target_policy,
record_tags,
enum_tags,
}
}
fn push_warning(
&mut self,
code: WarningCode,
subject: impl Into<String>,
message: impl Into<String>,
) {
self.warnings.push(Warning {
code,
subject: subject.into(),
message: message.into(),
baseline_validity_caveat: BASELINE_VALIDITY_CAVEAT.to_owned(),
});
}
fn push(
&mut self,
code: DiagnosticCode,
category: DiagnosticCategory,
subject: impl Into<String>,
message: impl Into<String>,
remediation: impl Into<String>,
) {
self.diagnostics.push(Diagnostic {
code,
category,
subject: subject.into(),
message: message.into(),
remediation: remediation.into(),
});
}
// ---------------------------------------------------------------------
// 1. Target and language-policy checks
// ---------------------------------------------------------------------
fn check_target_policy(&mut self) {
match &self.rust.target_triple {
None => self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::TargetPolicy,
"target",
"Rust target_triple is unattested (rustc -Z print-type-sizes \
does not emit target triples)",
"supply a `--rust-ffi` JSON descriptor with `target_triple`",
),
Some(rt) if *rt != self.bundle.target_triple => self.push(
DiagnosticCode::TargetTripleMismatch,
DiagnosticCategory::TargetPolicy,
"target",
format!(
"C/C++ target_triple `{}` != Rust target_triple `{rt}`",
self.bundle.target_triple
),
"compile both C/C++ and Rust for the exact same target triple",
),
Some(_) => {}
}
let cpp_pw = self.bundle.lang_policy.pointer_width_bits;
if !is_supported_pointer_width_bits(cpp_pw) {
self.push(
DiagnosticCode::PointerWidthMismatch,
DiagnosticCategory::TargetPolicy,
"target.pointer_width",
format!(
"C/C++ pointer_width_bits ({cpp_pw}) is unsupported \
(expected 16, 32, or 64)"
),
"use a standard 16-, 32-, or 64-bit target pointer width",
);
} else if let Some(expected_pw) =
inferred_target_pointer_width_bits(&self.bundle.target_triple)
{
if cpp_pw != expected_pw {
self.push(
DiagnosticCode::PointerWidthMismatch,
DiagnosticCategory::TargetPolicy,
"target.pointer_width",
format!(
"C/C++ pointer_width_bits ({cpp_pw}) disagrees with \
target triple `{}` (expected {expected_pw})",
self.bundle.target_triple
),
"match `pointer_width_bits` to the target architecture ABI",
);
}
}
match self.rust.pointer_width_bits {
None => self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::TargetPolicy,
"target.pointer_width",
"Rust pointer_width_bits is unattested",
"supply a `--rust-ffi` JSON descriptor with \
`pointer_width_bits`",
),
Some(rw) if !is_supported_pointer_width_bits(rw) => self.push(
DiagnosticCode::PointerWidthMismatch,
DiagnosticCategory::TargetPolicy,
"target.pointer_width",
format!(
"Rust pointer_width_bits ({rw}) is unsupported (expected \
16, 32, or 64)"
),
"use a standard 16-, 32-, or 64-bit target pointer width",
),
Some(rw) if rw != cpp_pw => {
self.push(
DiagnosticCode::PointerWidthMismatch,
DiagnosticCategory::TargetPolicy,
"target.pointer_width",
format!(
"C/C++ pointer_width_bits ({cpp_pw}) != Rust \
pointer_width_bits ({rw})"
),
"match pointer widths across both toolchains",
);
}
Some(rw) => {
if let Some(expected_pw) =
self.rust.target_triple.as_deref().and_then(inferred_target_pointer_width_bits)
{
if rw != expected_pw {
self.push(
DiagnosticCode::PointerWidthMismatch,
DiagnosticCategory::TargetPolicy,
"target.pointer_width",
format!(
"Rust pointer_width_bits ({rw}) disagrees with \
target triple (expected {expected_pw})"
),
"match `pointer_width_bits` to the Rust target \
architecture ABI",
);
}
}
}
}
match self.rust.c_char_is_signed {
None => self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
"target.c_char",
"Rust c_char_is_signed is unattested",
"supply a `--rust-ffi` JSON descriptor with `c_char_is_signed`",
),
Some(rs) if rs != self.bundle.lang_policy.char_is_signed => {
self.push(
DiagnosticCode::CCharSignednessMismatch,
DiagnosticCategory::ScalarAndEnum,
"target.c_char",
format!(
"C/C++ char_is_signed ({}) != Rust c_char_is_signed \
({rs})",
self.bundle.lang_policy.char_is_signed
),
"use `core::ffi::c_char` compiled for the same target or \
explicit `i8`/`u8` matching `signed char`/`unsigned char`",
);
}
Some(_) => {}
}
if let Some(cpp_long) = self.bundle.lang_policy.c_long_bits {
if !is_supported_c_long_bits(cpp_long) {
self.push(
DiagnosticCode::CLongWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
"target.c_long",
format!(
"C/C++ lang_policy.c_long_bits ({cpp_long}) is \
unsupported (expected 32 or 64)"
),
"use a standard 32-bit (ILP32/LLP64) or 64-bit (LP64) C \
long width",
);
} else if let Some(expected_long) =
inferred_target_c_long_bits(&self.bundle.target_triple)
{
if cpp_long != expected_long {
self.push(
DiagnosticCode::CLongWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
"target.c_long",
format!(
"C/C++ lang_policy.c_long_bits ({cpp_long}) \
disagrees with target triple `{}` (expected \
{expected_long})",
self.bundle.target_triple
),
"match `lang_policy.c_long_bits` to the target data \
model",
);
}
}
}
if let Some(rust_long) = self.rust.c_long_bits {
if !is_supported_c_long_bits(rust_long) {
self.push(
DiagnosticCode::CLongWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
"target.c_long",
format!(
"Rust c_long_bits ({rust_long}) is unsupported \
(expected 32 or 64)"
),
"set `c_long_bits` to 32 (ILP32/LLP64) or 64 (LP64)",
);
} else if let Some(cpp_long) = self
.bundle
.lang_policy
.c_long_bits
.or_else(|| inferred_target_c_long_bits(&self.bundle.target_triple))
{
if rust_long != cpp_long {
self.push(
DiagnosticCode::CLongWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
"target.c_long",
format!(
"Rust c_long_bits ({rust_long}) != C/C++ target \
data-model c_long width ({cpp_long}) for `{}`",
self.bundle.target_triple
),
"use `core::ffi::c_long` for the exact target \
LP64/LLP64 model or fixed-width `i32`/`i64`",
);
}
}
}
}
fn effective_c_long_bits(&self) -> Option<u64> {
self.rust
.c_long_bits
.or_else(|| self.rust.target_triple.as_deref().and_then(inferred_target_c_long_bits))
}
// ---------------------------------------------------------------------
// 2. Aggregate geometry, padding, and C++ object-model checks
// ---------------------------------------------------------------------
fn check_records(&mut self) {
for rrec in &self.rust.records {
let subject = format!("record:{}<->{}", rrec.rust_name, rrec.cpp_record);
let diag_start = self.diagnostics.len();
let Some(crec) = self.resolve_cpp_record(&rrec.cpp_record, &subject) else {
continue;
};
self.check_single_record(rrec, crec, &subject);
if self.diagnostics.len() == diag_start {
self.matched_records.push(MatchedRecord { rust: rrec.clone(), cpp: crec.clone() });
}
}
}
fn resolve_cpp_record(&mut self, key: &str, subject: &str) -> Option<&'a CppRecord> {
match self.cpp_records_by_id.get(key) {
Some(Some(r)) => return Some(*r),
Some(None) => {
self.push(
DiagnosticCode::AmbiguousCppRecord,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"C/C++ record id `{key}` appears multiple times in \
RawCppBundle (conflicting definitions)"
),
"deduplicate or disambiguate conflicting record ids in \
`RawCppBundle`",
);
return None;
}
None => {}
}
let matches: Vec<&CppRecord> = self
.bundle
.records
.iter()
.filter(|r| {
r.name == key || r.id == format!("struct.{key}") || r.id == format!("union.{key}")
})
.collect();
match matches.as_slice() {
[only] => Some(*only),
[] => {
self.push(
DiagnosticCode::MissingCppRecord,
DiagnosticCategory::AggregateGeometry,
subject,
format!("C/C++ record `{key}` not found in RawCppBundle"),
"verify the record name/id or include a function using it \
in `anneal-clang-dump`",
);
None
}
_ => {
self.push(
DiagnosticCode::AmbiguousCppRecord,
DiagnosticCategory::AggregateGeometry,
subject,
format!("C/C++ record name `{key}` matches multiple records"),
"specify the exact Clang record id (e.g. `struct.Foo`)",
);
None
}
}
}
/// Resolves a Rust record reference by `rust_name` or `cpp_record`.
fn resolve_rust_record(&self, name: &str) -> Option<&'a RustRecord> {
let exact_name: Vec<&RustRecord> =
self.rust.records.iter().filter(|r| r.rust_name == name).collect();
if exact_name.len() == 1 {
return Some(exact_name[0]);
}
if exact_name.len() > 1 {
return None;
}
let target_cpp_id = self.find_cpp_record(name).map(|c| c.id.as_str());
let by_cpp: Vec<&RustRecord> = self
.rust
.records
.iter()
.filter(|r| {
r.cpp_record == name
|| format!("struct.{}", r.cpp_record) == name
|| format!("union.{}", r.cpp_record) == name
|| target_cpp_id.is_some_and(|tid| {
self.find_cpp_record(&r.cpp_record).is_some_and(|c| c.id == tid)
})
})
.collect();
if by_cpp.len() == 1 {
Some(by_cpp[0])
} else {
None
}
}
fn find_cpp_record(&self, key: &str) -> Option<&'a CppRecord> {
match self.cpp_records_by_id.get(key) {
Some(Some(r)) => return Some(*r),
Some(None) => return None,
None => {}
}
let matches: Vec<&CppRecord> = self
.bundle
.records
.iter()
.filter(|r| {
r.name == key || r.id == format!("struct.{key}") || r.id == format!("union.{key}")
})
.collect();
match matches.as_slice() {
[only] => Some(*only),
_ => None,
}
}
fn check_single_record(&mut self, rrec: &RustRecord, crec: &CppRecord, subject: &str) {
let repr_ok = matches!(rrec.repr.as_str(), "C" | "c");
if !repr_ok {
self.push(
DiagnosticCode::ReprNotC,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"Rust record `{}` has repr `{}`; C/C++ aggregate FFI \
requires `#[repr(C)]` (`#[repr(transparent)]` uses its \
inner field's scalar ABI rather than C struct ABI)",
rrec.rust_name, rrec.repr
),
"annotate the Rust struct/union with `#[repr(C)]` and attest \
it via `--rust-ffi` (or bind the scalar type directly)",
);
}
// C++ object-model boundary checks on `#[repr(C)]` layout bindings.
self.check_cpp_record_by_value_safety(crec, subject);
match rrec.is_union {
None => self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::AggregateGeometry,
subject,
"Rust struct/union kind is unattested or ambiguous in \
`print-type-sizes`",
"supply `--rust-ffi` with explicit `is_union`",
),
Some(ru) if ru != crec.is_union => self.push(
DiagnosticCode::UnionMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"union kind mismatch: Rust is_union={ru} vs C/C++ \
is_union={}",
crec.is_union
),
"match `struct` with `struct` and `union` with `union`",
),
Some(_) => {}
}
match rrec.is_packed {
None => self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::AggregateGeometry,
subject,
"Rust `is_packed` attribute is unattested (`print-type-sizes` \
does not report packedness)",
"supply `--rust-ffi` with explicit `is_packed`",
),
Some(rp) if rp != crec.is_packed => self.push(
DiagnosticCode::PackedMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"packed attribute mismatch: Rust is_packed={rp} vs C/C++ \
is_packed={}",
crec.is_packed
),
"match `#[repr(C, packed)]` with `__attribute__((packed))`",
),
Some(_) => {}
}
if rrec.size_bytes != crec.size_bytes {
self.push(
DiagnosticCode::SizeMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"size_bytes mismatch: Rust={} vs C/C++={}",
rrec.size_bytes, crec.size_bytes
),
"align field types, padding, and target data model",
);
}
if rrec.align_bytes != crec.align_bytes {
self.push(
DiagnosticCode::AlignMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"align_bytes mismatch: Rust={} vs C/C++={}",
rrec.align_bytes, crec.align_bytes
),
"match `#[repr(C, align(N))]` / field alignments to C/C++",
);
}
if !crec.align_bytes.is_power_of_two() {
self.push(
DiagnosticCode::AlignMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"C/C++ record `{}` align_bytes ({}) must be a positive \
power of two",
crec.id, crec.align_bytes
),
"verify the record alignment in `RawCppBundle`",
);
} else if !crec.size_bytes.is_multiple_of(crec.align_bytes) {
self.push(
DiagnosticCode::SizeMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"C/C++ record `{}` size_bytes ({}) is not a multiple of \
align_bytes ({})",
crec.id, crec.size_bytes, crec.align_bytes
),
"verify `size_bytes` and `align_bytes` in `RawCppBundle`",
);
}
if !rrec.align_bytes.is_power_of_two() {
self.push(
DiagnosticCode::AlignMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"Rust record `{}` align_bytes ({}) must be a positive \
power of two",
rrec.rust_name, rrec.align_bytes
),
"verify `align_of::<T>()` in `--rust-ffi`",
);
} else if !rrec.size_bytes.is_multiple_of(rrec.align_bytes) {
self.push(
DiagnosticCode::SizeMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"Rust record `{}` size_bytes ({}) is not a multiple of \
align_bytes ({})",
rrec.rust_name, rrec.size_bytes, rrec.align_bytes
),
"verify `size_of::<T>()` and `align_of::<T>()` in `--rust-ffi`",
);
}
// Reject C/C++ bitfields, non-byte-aligned field offsets, and
// unsupported C field types unconditionally, even when Rust field types
// are absent.
let mut has_bitfield = false;
for cf in &crec.fields {
let fsub = format!("{subject}.{}", cf.name);
if let Some(bw) = cf.bit_width {
has_bitfield = true;
self.push(
DiagnosticCode::BitfieldUnsupported,
DiagnosticCategory::AggregateGeometry,
&fsub,
format!(
"C/C++ bitfield `{}` ({bw} bits at bit offset {}) has \
no guaranteed Rust `#[repr(C)]` parity",
cf.name, cf.offset_bits
),
"replace bitfields across FFI with explicit integer masks",
);
} else if !cf.offset_bits.is_multiple_of(8) {
self.push(
DiagnosticCode::FieldOffsetMismatch,
DiagnosticCategory::AggregateGeometry,
&fsub,
format!(
"non-byte-aligned C/C++ field `{}` offset_bits ({}) \
has no guaranteed Rust `#[repr(C)]` parity",
cf.name, cf.offset_bits
),
"replace sub-byte/bitfield layouts across FFI",
);
}
self.check_cpp_field_type_supported(&cf.ty, &fsub);
}
// Separate Rust value fields from padding fields.
let rust_value_fields: Vec<&RustField> =
rrec.fields.iter().filter(|f| !f.is_padding).collect();
let rust_pad_fields: Vec<&RustField> =
rrec.fields.iter().filter(|f| f.is_padding).collect();
for rf in &rust_value_fields {
if !rf.offset_bits.is_multiple_of(8) {
self.push(
DiagnosticCode::FieldOffsetMismatch,
DiagnosticCategory::AggregateGeometry,
format!("{subject}.{}", rf.name),
format!(
"non-byte-aligned Rust field `{}` offset_bits ({}) is \
unsupported across FFI",
rf.name, rf.offset_bits
),
"align every FFI value field to a byte boundary",
);
}
}
if rust_value_fields.len() != crec.fields.len() {
self.push(
DiagnosticCode::FieldCountMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"value field count mismatch: Rust has {} non-padding \
fields vs C/C++ {}",
rust_value_fields.len(),
crec.fields.len()
),
"ensure every C/C++ field maps 1:1 to a Rust value field \
(padding bytes belong in `MaybeUninit<u8>` fields)",
);
}
for (rf, cf) in rust_value_fields.iter().zip(crec.fields.iter()) {
let fsub = format!("{subject}.{}<->{}", rf.name, cf.name);
if rf.offset_bits != cf.offset_bits {
self.push(
DiagnosticCode::FieldOffsetMismatch,
DiagnosticCategory::AggregateGeometry,
&fsub,
format!(
"offset_bits mismatch: Rust={} vs C/C++={}",
rf.offset_bits, cf.offset_bits
),
"check preceding field sizes, alignment, and packed attrs",
);
}
let cpp_sz = self.cpp_type_size_bytes(&cf.ty);
if let (Some(rsz), Some(csz)) = (rf.size_bytes, cpp_sz) {
if rsz != csz {
self.push(
DiagnosticCode::FieldSizeMismatch,
DiagnosticCategory::AggregateGeometry,
&fsub,
format!(
"field size_bytes mismatch: Rust={rsz} vs \
C/C++={csz}"
),
"match field storage widths on both sides of FFI",
);
}
}
match &rf.ty {
Some(rty) => self.check_type_parity(rty, &cf.ty, &fsub, TypeRole::Field),
None => self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
&fsub,
format!(
"Rust field `{}` lacks `ty` metadata; scalar/type \
parity cannot be verified",
rf.name
),
"provide field `ty` entries in `--rust-ffi`",
),
}
}
// Audit interior/tail padding and validate `is_padding` fields plus
// `unread_padding_ranges` for both structs and unions.
if !has_bitfield {
if crec.is_union {
self.check_union_padding(rrec, crec, &rust_pad_fields, subject);
} else {
self.check_record_padding(rrec, crec, &rust_pad_fields, subject);
}
}
}
fn check_cpp_field_type_supported(&mut self, ty: &CppType, subject: &str) {
let mut visited = BTreeSet::new();
self.check_cpp_field_type_supported_rec(ty, subject, &mut visited);
}
fn check_cpp_field_type_supported_rec(
&mut self,
ty: &CppType,
subject: &str,
visited: &mut BTreeSet<String>,
) {
match ty {
CppType::Unsupported { desc } => self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ field type `{desc}` is unsupported (e.g. float, \
double, volatile, or incomplete)"
),
"avoid unsupported types across the checked FFI boundary",
),
CppType::Int { bits, .. } if !is_supported_int_bits(*bits) => self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ integer width {bits} is unsupported (expected 8, \
16, 32, 64, or 128)"
),
"use standard fixed-width integer types across FFI",
),
CppType::Array { elem, .. } => {
self.check_cpp_field_type_supported_rec(elem, subject, visited);
}
CppType::Record { id } => match self.cpp_records_by_id.get(id.as_str()) {
None => self.push(
DiagnosticCode::MissingCppRecord,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"nested C/C++ record `{id}` is missing from \
RawCppBundle"
),
"ensure all nested record definitions are present in the \
bundle",
),
Some(None) => self.push(
DiagnosticCode::AmbiguousCppRecord,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"nested C/C++ record `{id}` appears multiple times in \
RawCppBundle"
),
"deduplicate conflicting record ids in `RawCppBundle`",
),
Some(Some(sub)) => {
let sub = *sub;
if visited.insert(id.clone()) {
for f in &sub.fields {
self.check_cpp_field_type_supported_rec(
&f.ty,
&format!("{subject}.{}", f.name),
visited,
);
}
}
}
},
_ => {}
}
}
fn check_cpp_record_by_value_safety(&mut self, crec: &CppRecord, subject: &str) {
if crec.is_polymorphic {
self.push(
DiagnosticCode::PolymorphicRecordByValue,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"C++ record `{}` is polymorphic (contains hidden vptr) and \
cannot cross `#[repr(C)]` FFI by value",
crec.id
),
"pass polymorphic C++ objects strictly behind opaque handles",
);
}
if crec.has_non_trivial_dtor || crec.dtor_symbol.is_some() {
self.push(
DiagnosticCode::NonTrivialDtorByValue,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"C++ record `{}` has a non-trivial destructor and cannot \
cross `#[repr(C)]` FFI by value",
crec.id
),
"pass RAII C++ types behind opaque pointers with explicit \
create/destroy `extern \"C\"` functions",
);
}
if !crec.is_trivially_copyable {
self.push(
DiagnosticCode::NonTriviallyCopyableByValue,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"C++ record `{}` is not trivially copyable (Itanium ABI \
forbids bitwise value passing across `#[repr(C)]`)",
crec.id
),
"restrict by-value FFI structs to trivially copyable C++ PODs",
);
}
if !crec.bases.is_empty() {
self.push(
DiagnosticCode::CxxBasesUnsupported,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"C++ record `{}` has {} base class(es), which have no \
`#[repr(C)]` layout equivalent",
crec.id,
crec.bases.len()
),
"flatten inherited data into a plain C-compatible struct or \
use an opaque pointer",
);
}
}
fn check_record_padding(
&mut self,
rrec: &RustRecord,
crec: &CppRecord,
rust_pad_fields: &[&RustField],
subject: &str,
) {
// Build sorted disjoint byte intervals for C/C++ value fields; fail
// closed if any field has a non-byte offset, unknown/overflowing size,
// extends past `crec.size_bytes`, or overlaps another struct field.
let mut raw_value_spans: Vec<(u64, u64, &str)> = Vec::new();
let mut last_value_end = 0u64;
let mut layout_incomplete = false;
for cf in &crec.fields {
if !cf.offset_bits.is_multiple_of(8) {
layout_incomplete = true;
continue;
}
let start = cf.offset_bits / 8;
let Some(sz) = self.cpp_type_size_bytes(&cf.ty) else {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::Padding,
format!("{subject}.{}", cf.name),
format!(
"cannot determine byte size of C/C++ field `{}` for \
padding verification",
cf.name
),
"ensure every field type in the record has a known FFI \
size",
);
layout_incomplete = true;
continue;
};
let Some(end) = start.checked_add(sz) else {
self.push(
DiagnosticCode::FieldSizeMismatch,
DiagnosticCategory::Padding,
format!("{subject}.{}", cf.name),
"C/C++ field end offset overflows u64",
"check array length and field offsets",
);
layout_incomplete = true;
continue;
};
if end > crec.size_bytes {
self.push(
DiagnosticCode::FieldSizeMismatch,
DiagnosticCategory::AggregateGeometry,
format!("{subject}.{}", cf.name),
format!(
"C/C++ field `{}` byte range [{start}..{end}) exceeds \
record size_bytes ({})",
cf.name, crec.size_bytes
),
"verify field offsets, field widths, and record size_bytes",
);
layout_incomplete = true;
continue;
}
if sz > 0 {
raw_value_spans.push((start, end, cf.name.as_str()));
}
if end > last_value_end {
last_value_end = end;
}
}
raw_value_spans.sort_unstable_by_key(|&(s, e, _)| (s, e));
for pair in raw_value_spans.windows(2) {
let (s0, e0, n0) = pair[0];
let (s1, e1, n1) = pair[1];
if e0 > s1 {
self.push(
DiagnosticCode::FieldOffsetMismatch,
DiagnosticCategory::AggregateGeometry,
format!("{subject}.{n0}<->{n1}"),
format!(
"non-union C/C++ fields `{n0}` [{s0}..{e0}) and \
`{n1}` [{s1}..{e1}) overlap (e.g. \
`[[no_unique_address]]` tail-padding reuse is \
incompatible with Rust `#[repr(C)]`)"
),
"avoid overlapping non-union subobjects across \
`#[repr(C)]` FFI",
);
layout_incomplete = true;
}
}
if layout_incomplete {
return;
}
let value_spans =
merge_intervals(raw_value_spans.into_iter().map(|(s, e, _)| (s, e)).collect());
// Validate Rust explicit `MaybeUninit<u8>` padding fields (defense in
// depth: require `MaybeUninitBytes`, byte alignment, matching size,
// bounds <= `crec.size_bytes`, and zero overlap with C value fields).
let mut raw_maybe_uninit_spans = Vec::new();
for pf in rust_pad_fields {
let fsub = format!("{subject}.{}", pf.name);
if !pf.offset_bits.is_multiple_of(8) {
self.push(
DiagnosticCode::FieldOffsetMismatch,
DiagnosticCategory::Padding,
&fsub,
format!(
"padding field `{}` offset_bits ({}) is not byte \
aligned",
pf.name, pf.offset_bits
),
"align `MaybeUninit<u8>` padding fields to byte boundaries",
);
continue;
}
let Some(RustType::MaybeUninitBytes { len }) = &pf.ty else {
self.push(
DiagnosticCode::FieldTypeMismatch,
DiagnosticCategory::Padding,
&fsub,
format!(
"padding field `{}` must have type \
`maybe_uninit_bytes` (`MaybeUninit<u8>` / \
`[MaybeUninit<u8>; N]`), not initialized bytes",
pf.name
),
"change the padding field type to `[MaybeUninit<u8>; N]`",
);
continue;
};
if let Some(sz) = pf.size_bytes {
if sz != *len {
self.push(
DiagnosticCode::FieldSizeMismatch,
DiagnosticCategory::Padding,
&fsub,
format!(
"padding field `{}` size_bytes ({sz}) != \
maybe_uninit_bytes len ({len})",
pf.name
),
"match `size_bytes` to `maybe_uninit_bytes.len`",
);
continue;
}
}
let start = pf.offset_bits / 8;
let Some(end) = start.checked_add(*len) else {
self.push(
DiagnosticCode::FieldSizeMismatch,
DiagnosticCategory::Padding,
&fsub,
"padding field end offset overflows u64",
"check padding offset and length",
);
continue;
};
if end > crec.size_bytes {
self.push(
DiagnosticCode::PaddingOverlapsValue,
DiagnosticCategory::Padding,
&fsub,
format!(
"padding field `{}` [{start}..{end}) exceeds C/C++ \
record size ({})",
pf.name, crec.size_bytes
),
"keep padding fields strictly within the record's byte \
extent",
);
continue;
}
if let Some(overlap_byte) = first_overlap((start, end), &value_spans) {
self.push(
DiagnosticCode::PaddingOverlapsValue,
DiagnosticCategory::Padding,
&fsub,
format!(
"Rust MaybeUninit padding field `{}` overlaps C/C++ \
value byte {overlap_byte}",
pf.name
),
"restrict padding fields strictly to C/C++ padding bytes",
);
continue;
}
if *len > 0 {
raw_maybe_uninit_spans.push((start, end));
}
}
let maybe_uninit_spans = merge_intervals(raw_maybe_uninit_spans);
// Validate `unread_padding_ranges` bounds and non-overlap with C value
// bytes (interval-based, zero per-byte allocation).
let mut raw_unread_spans = Vec::new();
for r in &rrec.unread_padding_ranges {
if r.start_byte >= r.end_byte || r.end_byte > crec.size_bytes {
self.push(
DiagnosticCode::PaddingOverlapsValue,
DiagnosticCategory::Padding,
subject,
format!(
"unread_padding_ranges [{}..{}) is out of bounds for \
record size {}",
r.start_byte, r.end_byte, crec.size_bytes
),
"bound every `unread_padding_ranges` span to \
`0..size_bytes`",
);
continue;
}
if let Some(overlap_byte) = first_overlap((r.start_byte, r.end_byte), &value_spans) {
self.push(
DiagnosticCode::PaddingOverlapsValue,
DiagnosticCategory::Padding,
subject,
format!(
"unread_padding_ranges [{}..{}) overlaps C/C++ value \
byte {overlap_byte}",
r.start_byte, r.end_byte
),
"restrict `unread_padding_ranges` strictly to C/C++ \
padding bytes",
);
continue;
}
raw_unread_spans.push((r.start_byte, r.end_byte));
}
let mut combined_cov = maybe_uninit_spans.clone();
combined_cov.extend(raw_unread_spans);
let all_covered_spans = merge_intervals(combined_cov);
// Compute exact C/C++ padding gaps in `[0, crec.size_bytes)` as the
// complement of `value_spans`.
let padding_gaps = complement_intervals(crec.size_bytes, &value_spans);
for (start, end) in padding_gaps {
let kind =
if start < last_value_end { PaddingKind::Interior } else { PaddingKind::Tail };
let resolution = if interval_covered((start, end), &maybe_uninit_spans) {
PaddingResolution::CoveredByMaybeUninit
} else if interval_covered((start, end), &all_covered_spans) {
PaddingResolution::DeclaredUnread
} else {
PaddingResolution::Exposed
};
self.padding_regions.push(PaddingRegionReport {
record: subject.to_owned(),
kind,
start_byte: start,
end_byte: end,
resolution,
});
if resolution == PaddingResolution::Exposed {
let code = match kind {
PaddingKind::Interior => DiagnosticCode::InteriorPaddingExposed,
PaddingKind::Tail => DiagnosticCode::TailPaddingExposed,
};
let label = match kind {
PaddingKind::Interior => "interior",
PaddingKind::Tail => "tail",
};
self.push(
code,
DiagnosticCategory::Padding,
subject,
format!(
"uninitialized C/C++ {label} padding bytes \
[{start}..{end}) ({} bytes) are not mapped to \
`MaybeUninit<u8>` or marked unread across FFI",
end - start
),
format!(
"add a `[MaybeUninit<u8>; {}]` field at byte offset \
{start} or declare [{start}..{end}) in \
`unread_padding_ranges`",
end - start
),
);
}
}
}
fn check_union_padding(
&mut self,
rrec: &RustRecord,
crec: &CppRecord,
rust_pad_fields: &[&RustField],
subject: &str,
) {
// Rust `#[repr(C)]` union variants overlay at offset 0 rather than
// filling disjoint struct padding gaps, so `is_padding: true` fields
// are invalid on unions.
for pf in rust_pad_fields {
self.push(
DiagnosticCode::PaddingOverlapsValue,
DiagnosticCategory::Padding,
format!("{subject}.{}", pf.name),
format!(
"union `{}` cannot declare `is_padding: true` field `{}` \
(union variants overlay at offset 0 rather than filling \
disjoint struct padding gaps)",
rrec.rust_name, pf.name
),
"remove `is_padding` fields from unions and declare any \
union-wide tail padding via `unread_padding_ranges`",
);
}
// Compute merged byte intervals covered by any C/C++ union variant.
let mut raw_value_spans = Vec::new();
let mut layout_incomplete = false;
for cf in &crec.fields {
if !cf.offset_bits.is_multiple_of(8) {
layout_incomplete = true;
continue;
}
let start = cf.offset_bits / 8;
let Some(sz) = self.cpp_type_size_bytes(&cf.ty) else {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::Padding,
format!("{subject}.{}", cf.name),
format!(
"cannot determine byte size of C/C++ union field `{}` \
for padding verification",
cf.name
),
"ensure every union field type has a known FFI size",
);
layout_incomplete = true;
continue;
};
let Some(end) = start.checked_add(sz) else {
self.push(
DiagnosticCode::FieldSizeMismatch,
DiagnosticCategory::Padding,
format!("{subject}.{}", cf.name),
"C/C++ union field end offset overflows u64",
"check array length and field offsets",
);
layout_incomplete = true;
continue;
};
if end > crec.size_bytes {
self.push(
DiagnosticCode::FieldSizeMismatch,
DiagnosticCategory::AggregateGeometry,
format!("{subject}.{}", cf.name),
format!(
"C/C++ union field `{}` byte range [{start}..{end}) \
exceeds union size_bytes ({})",
cf.name, crec.size_bytes
),
"verify union field widths and union size_bytes",
);
layout_incomplete = true;
continue;
}
if sz > 0 {
raw_value_spans.push((start, end));
}
}
if layout_incomplete {
return;
}
let value_spans = merge_intervals(raw_value_spans);
// Validate `unread_padding_ranges` bounds and non-overlap with union
// value bytes.
let mut raw_unread_spans = Vec::new();
for r in &rrec.unread_padding_ranges {
if r.start_byte >= r.end_byte || r.end_byte > crec.size_bytes {
self.push(
DiagnosticCode::PaddingOverlapsValue,
DiagnosticCategory::Padding,
subject,
format!(
"unread_padding_ranges [{}..{}) is out of bounds for \
union size {}",
r.start_byte, r.end_byte, crec.size_bytes
),
"bound every `unread_padding_ranges` span to \
`0..size_bytes`",
);
continue;
}
if let Some(overlap_byte) = first_overlap((r.start_byte, r.end_byte), &value_spans) {
self.push(
DiagnosticCode::PaddingOverlapsValue,
DiagnosticCategory::Padding,
subject,
format!(
"unread_padding_ranges [{}..{}) overlaps C/C++ union \
value byte {overlap_byte}",
r.start_byte, r.end_byte
),
"restrict `unread_padding_ranges` strictly to union-wide \
tail padding bytes outside all variants",
);
continue;
}
raw_unread_spans.push((r.start_byte, r.end_byte));
}
let unread_spans = merge_intervals(raw_unread_spans);
// Audit union-wide tail padding outside every variant.
let padding_gaps = complement_intervals(crec.size_bytes, &value_spans);
for (start, end) in padding_gaps {
let resolution = if interval_covered((start, end), &unread_spans) {
PaddingResolution::DeclaredUnread
} else {
PaddingResolution::Exposed
};
self.padding_regions.push(PaddingRegionReport {
record: subject.to_owned(),
kind: PaddingKind::Tail,
start_byte: start,
end_byte: end,
resolution,
});
if resolution == PaddingResolution::Exposed {
self.push(
DiagnosticCode::TailPaddingExposed,
DiagnosticCategory::Padding,
subject,
format!(
"uninitialized C/C++ union tail padding bytes \
[{start}..{end}) ({} bytes) are not declared unread \
across FFI",
end - start
),
format!("declare [{start}..{end}) in `unread_padding_ranges`"),
);
}
}
}
fn cpp_type_size_bytes(&self, ty: &CppType) -> Option<u64> {
match ty {
CppType::Void => Some(0),
CppType::Bool => Some(1),
CppType::Int { bits, .. } if is_supported_int_bits(*bits) => Some(bits / 8),
CppType::Int { .. } => None,
CppType::Ptr { .. } | CppType::Ref { .. } | CppType::NullPtrT => {
let pw = self.bundle.lang_policy.pointer_width_bits;
is_supported_pointer_width_bits(pw).then_some(pw / 8)
}
CppType::Array { elem, len } => self.cpp_type_size_bytes(elem)?.checked_mul(*len),
CppType::Record { id } => {
self.unique_cpp_record_by_id(id.as_str()).map(|r| r.size_bytes)
}
CppType::Unsupported { .. } => None,
}
}
// ---------------------------------------------------------------------
// 3. Scalar, enum, and recursive type parity
// ---------------------------------------------------------------------
fn check_enums(&mut self) {
let mut seen_rust_names = BTreeSet::new();
for en in &self.rust.enums {
if !seen_rust_names.insert(en.rust_name.as_str()) {
self.push(
DiagnosticCode::EnumTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
format!("enum:{}", en.rust_name),
format!(
"duplicate `rust_ffi.enums` entry for Rust enum `{}` \
(one Rust type cannot map to multiple C/C++ enums)",
en.rust_name
),
"keep a single unique entry per `rust_name` in \
`rust_ffi.enums`",
);
}
self.check_single_enum(en);
}
}
fn cpp_enum_matches_key(ce: &CppEnum, key: &str) -> bool {
ce.id.as_deref() == Some(key)
|| ce.qualified_name.as_deref() == Some(key)
|| ce.name == key
|| format!("enum {}", ce.name) == key
|| format!("enum.{}", ce.name) == key
}
fn resolve_cpp_enum_by_type_tag(
&mut self,
enum_id: Option<&str>,
enum_name: Option<&str>,
subject: &str,
) -> Option<&'a CppEnum> {
if let Some(eid) = enum_id {
let exact: Vec<&CppEnum> =
self.bundle.enums.iter().filter(|ce| ce.id.as_deref() == Some(eid)).collect();
return match exact.as_slice() {
[only] => Some(*only),
[] => {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ enum id `{eid}` referenced by signature is \
missing from `RawCppBundle.enums`"
),
"re-extract a consistent `RawCppBundle` so every \
referenced enum id exists in `RawCppBundle.enums`",
);
None
}
_ => {
self.push(
DiagnosticCode::AmbiguousCppRecord,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ enum id `{eid}` matches multiple entries in \
`RawCppBundle.enums`"
),
"deduplicate conflicting enum ids in `RawCppBundle.enums`",
);
None
}
};
}
let lookup = enum_name?;
let matches: Vec<&CppEnum> =
self.bundle.enums.iter().filter(|ce| Self::cpp_enum_matches_key(ce, lookup)).collect();
match matches.as_slice() {
[only] => Some(*only),
[] => {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ enum `{lookup}` referenced by signature is \
missing from `RawCppBundle.enums`"
),
"re-extract with `anneal-clang-dump` so every referenced \
enum appears in `RawCppBundle.enums`",
);
None
}
_ => {
self.push(
DiagnosticCode::AmbiguousCppRecord,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ enum `{lookup}` matches multiple entries in \
`RawCppBundle.enums`"
),
"disambiguate conflicting enum names in `RawCppBundle.enums`",
);
None
}
}
}
fn rust_enum_matches_cpp(&self, rust_enum_name: &str, ce: &CppEnum) -> bool {
let matching_entries: Vec<&RustEnum> =
self.rust.enums.iter().filter(|e| e.rust_name == rust_enum_name).collect();
match matching_entries.as_slice() {
[only] => Self::cpp_enum_matches_key(ce, &only.cpp_name),
[] => {
// Without an explicit `rust_ffi.enums` mapping, require an
// unambiguous match across `RawCppBundle.enums` so colliding
// short names across C++ namespaces (e.g. `a::Mode` vs
// `b::Mode`) fail closed.
if !Self::cpp_enum_matches_key(ce, rust_enum_name) {
return false;
}
self.bundle
.enums
.iter()
.filter(|e| Self::cpp_enum_matches_key(e, rust_enum_name))
.count()
== 1
}
_ => false,
}
}
fn check_single_enum(&mut self, en: &RustEnum) {
let subject = format!("enum:{}<->{}", en.rust_name, en.cpp_name);
let diag_start = self.diagnostics.len();
if !is_supported_int_bits(en.repr_bits) {
self.push(
DiagnosticCode::EnumWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"Rust enum `{}` repr_bits ({}) is unsupported (expected \
8, 16, 32, 64, or 128)",
en.rust_name, en.repr_bits
),
"specify a standard `#[repr(uN/iN)]` width (8, 16, 32, 64, \
or 128)",
);
}
let matches: Vec<_> = self
.bundle
.enums
.iter()
.filter(|ce| Self::cpp_enum_matches_key(ce, &en.cpp_name))
.collect();
let cpp_enum = match matches.as_slice() {
[only] => *only,
[] => {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"C/C++ enum `{}` is not attested in \
`RawCppBundle.enums` (self-attested `cpp_bits`/ \
`cpp_signed` in the Rust descriptor is not trusted)",
en.cpp_name
),
"include an attested entry for this enum in \
`RawCppBundle.enums`",
);
return;
}
_ => {
self.push(
DiagnosticCode::AmbiguousCppRecord,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"C/C++ enum name `{}` matches multiple entries in \
`RawCppBundle.enums`",
en.cpp_name
),
"disambiguate `cpp_name` in the descriptor",
);
return;
}
};
self.enums_checked += 1;
if cpp_enum.underlying_is_bool {
self.push(
DiagnosticCode::BoolU8Conflation,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"C/C++ enum `{}` has `bool` underlying type (valid values \
restricted to {{0, 1}}); cannot bind as an integer-backed \
FFI enum",
cpp_enum.name
),
"use a fixed-width integer underlying type (`uint8_t`/`int32_t`) \
for C++ enums crossing FFI, or pass `bool` directly",
);
}
if !is_supported_int_bits(cpp_enum.bits) {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"C/C++ enum `{}` underlying width ({}) is unsupported \
(expected 8, 16, 32, 64, or 128)",
cpp_enum.name, cpp_enum.bits
),
"use a standard fixed-width underlying integer type for FFI \
enums",
);
}
if en.repr_bits != cpp_enum.bits {
self.push(
DiagnosticCode::EnumWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"enum width mismatch: Rust #[repr] is {}-bit vs C/C++ \
bundle underlying {}-bit",
en.repr_bits, cpp_enum.bits
),
format!(
"change Rust `#[repr(...)]` to a {}-bit integer type \
matching C/C++",
cpp_enum.bits
),
);
}
if en.repr_signed != cpp_enum.signed {
self.push(
DiagnosticCode::EnumSignednessMismatch,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"enum signedness mismatch: Rust signed={} vs C/C++ \
bundle signed={}",
en.repr_signed, cpp_enum.signed
),
"match Rust `#[repr(iN/uN)]` signedness to the C/C++ enum's \
underlying integer type",
);
}
if let Some(claimed_bits) = en.cpp_bits {
if claimed_bits != cpp_enum.bits {
self.push(
DiagnosticCode::EnumWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"descriptor claimed cpp_bits ({claimed_bits}) != \
RawCppBundle enum width ({})",
cpp_enum.bits
),
"update `cpp_bits` or omit it so the C/C++ bundle is \
authoritative",
);
}
}
if let Some(claimed_signed) = en.cpp_signed {
if claimed_signed != cpp_enum.signed {
self.push(
DiagnosticCode::EnumSignednessMismatch,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"descriptor claimed cpp_signed ({claimed_signed}) != \
RawCppBundle enum signedness ({})",
cpp_enum.signed
),
"update `cpp_signed` or omit it so the C/C++ bundle is \
authoritative",
);
}
}
if let Some(rust_discs) = &en.discriminants {
match &cpp_enum.enumerators {
None => self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"C/C++ enum `{}` in RawCppBundle omits `enumerators`; \
cannot verify Rust discriminant parity",
cpp_enum.name
),
"re-extract with `anneal-clang-dump` so `enums[].enumerators` \
is populated",
),
Some(cpp_enumerators) => {
let normalize = |vals: &[String]| -> BTreeSet<String> {
vals.iter()
.map(|s| {
s.trim()
.parse::<i128>()
.map(|n| n.to_string())
.unwrap_or_else(|_| s.trim().to_owned())
})
.collect()
};
let rust_set = normalize(rust_discs);
let cpp_vals: Vec<String> =
cpp_enumerators.iter().map(|e| e.value_str.clone()).collect();
let cpp_set = normalize(&cpp_vals);
if rust_set != cpp_set {
self.push(
DiagnosticCode::EnumDiscriminantMismatch,
DiagnosticCategory::ScalarAndEnum,
&subject,
format!(
"enum discriminant set mismatch: Rust {:?} vs \
C/C++ {:?}",
rust_set, cpp_set
),
"align the Rust enum discriminants with the C/C++ \
enumerator values",
);
}
}
}
}
if self.diagnostics.len() == diag_start {
self.record_matched_enum(cpp_enum);
}
}
fn check_type_parity(&mut self, rty: &RustType, cty: &CppType, subject: &str, role: TypeRole) {
match (rty, cty) {
(RustType::Void, CppType::Void) => {}
(RustType::Bool, CppType::Bool) => {}
(RustType::Bool, CppType::Int { bits: 8, .. }) => {
self.push(
DiagnosticCode::BoolU8Conflation,
DiagnosticCategory::ScalarAndEnum,
subject,
"Rust `bool` bound to C/C++ 8-bit integer (invalid bit \
patterns outside {0, 1} cause immediate Rust UB)",
"bind C/C++ `uint8_t`/`int8_t` to Rust `u8`/`i8`, or use \
C99 `_Bool` / C++ `bool` on the C/C++ side",
);
}
(RustType::Int { bits: 8, .. }, CppType::Bool) => {
self.push(
DiagnosticCode::BoolU8Conflation,
DiagnosticCategory::ScalarAndEnum,
subject,
"Rust 8-bit integer bound to C/C++ `bool` (ABI passing \
uses `extend_int { bits: 1, sign_ext: false }`)",
"bind C99 `_Bool` / C++ `bool` to Rust `bool`",
);
}
(
RustType::CChar,
CppType::Int { bits, signed, is_char_like, enum_id, enum_name, .. },
) => {
if let Some(elabel) = enum_name.as_deref().or(enum_id.as_deref()) {
self.push(
DiagnosticCode::EnumTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust `c_char` bound to C/C++ enum `{elabel}` \
(enum-vs-integer drift breaks CFI type identity \
and `-fshort-enums` parity)"
),
"bind C/C++ enums with `c_enum`/`enum` or declare the \
C/C++ parameter as `char`",
);
} else if *bits != 8 || !is_char_like {
self.push(
DiagnosticCode::FieldTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust `c_char` bound to non-char C/C++ int \
(bits={bits}, is_char_like={is_char_like})"
),
"match `c_char` only to C/C++ `char`",
);
} else if let Some(rust_signed) = self.rust.c_char_is_signed {
if *signed != rust_signed {
self.push(
DiagnosticCode::CCharSignednessMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust `c_char` signedness ({rust_signed}) != \
C/C++ char signedness ({signed})"
),
"use explicit `i8`/`u8` or align target `c_char` \
signedness",
);
}
}
}
(
RustType::CLong | RustType::CULong,
CppType::Int { bits, signed, enum_id, enum_name, .. },
) => {
if let Some(elabel) = enum_name.as_deref().or(enum_id.as_deref()) {
self.push(
DiagnosticCode::EnumTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust `c_long`/`c_ulong` bound to C/C++ enum \
`{elabel}` (enum-vs-integer drift breaks CFI \
type identity and `-fshort-enums` parity)"
),
"bind C/C++ enums explicitly with `c_enum`/`enum` or \
use `long`/`unsigned long` on the C/C++ side",
);
}
let rust_signed = matches!(rty, RustType::CLong);
if !is_supported_int_bits(*bits) {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ integer width {bits} is unsupported (expected \
8, 16, 32, 64, or 128)"
),
"use standard fixed-width C/C++ integer types across \
FFI",
);
}
let Some(rust_bits) = self.effective_c_long_bits() else {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
subject,
"cannot determine `c_long` width for target triple",
"set `c_long_bits` explicitly in the Rust FFI \
descriptor",
);
return;
};
if !is_supported_c_long_bits(rust_bits) {
self.push(
DiagnosticCode::CLongWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust `c_long`/`c_ulong` width ({rust_bits} bits) \
is unsupported (expected 32 or 64)"
),
"set `c_long_bits` to 32 (ILP32/LLP64) or 64 (LP64)",
);
} else if rust_bits != *bits {
self.push(
DiagnosticCode::CLongWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust `c_long`/`c_ulong` width ({rust_bits} bits) \
!= C/C++ integer width ({bits} bits)"
),
"verify LP64 vs LLP64 data model or use fixed-width \
`int32_t`/`int64_t`",
);
}
if rust_signed != *signed {
self.push(
DiagnosticCode::IntSignednessMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"signedness mismatch: Rust signed={rust_signed} vs \
C/C++ signed={signed}"
),
"match `c_long` to `long` and `c_ulong` to \
`unsigned long`",
);
}
}
(
RustType::Int { bits: rb, signed: rs },
CppType::Int { bits: cb, signed: cs, enum_id, enum_name, c_spelling, .. },
) => {
if matches!(c_spelling.as_deref(), Some("bool" | "_Bool")) {
self.push(
DiagnosticCode::BoolU8Conflation,
DiagnosticCategory::ScalarAndEnum,
subject,
"C/C++ `bool`-backed type cannot bind to Rust integer \
(values outside {0, 1} cause C++ UB)",
"use a fixed-width integer underlying type on the C/C++ \
side or bind `bool` directly",
);
}
if let Some(elabel) = enum_name.as_deref().or(enum_id.as_deref()) {
self.push(
DiagnosticCode::EnumTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust plain integer ({rb}-bit signed={rs}) bound \
to C/C++ enum `{elabel}` (C11 compatibility hides \
enum-vs-integer drift, which breaks CFI type \
identity and `-fshort-enums` ABI parity)"
),
"bind C/C++ enums explicitly via `c_enum` (transparent \
integer wrapper) or `enum`, or change the C/C++ \
declaration to a fixed-width integer",
);
}
if !is_supported_int_bits(*rb) {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust integer width {rb} is unsupported (expected \
8, 16, 32, 64, or 128)"
),
"use standard fixed-width Rust integer types across FFI",
);
}
if !is_supported_int_bits(*cb) {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ integer width {cb} is unsupported (expected \
8, 16, 32, 64, or 128)"
),
"use standard fixed-width C/C++ integer types across \
FFI",
);
}
if rb != cb {
self.push(
DiagnosticCode::IntWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"integer width mismatch: Rust {rb}-bit vs C/C++ \
{cb}-bit"
),
"use matching fixed-width integer types on both sides",
);
}
if rs != cs {
self.push(
DiagnosticCode::IntSignednessMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"integer signedness mismatch: Rust signed={rs} vs \
C/C++ signed={cs}"
),
"match signedness (`iN` <-> `intN_t`, `uN` <-> \
`uintN_t`)",
);
}
}
(
RustType::Enum { name, bits: rb, signed: rs }
| RustType::CEnum { name, bits: rb, signed: rs },
CppType::Int { bits: cb, signed: cs, enum_id, enum_name, c_spelling, .. },
) => {
let is_closed_rust_enum = matches!(rty, RustType::Enum { .. });
if matches!(c_spelling.as_deref(), Some("bool" | "_Bool")) {
self.push(
DiagnosticCode::BoolU8Conflation,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ `bool`-backed enum `{name}` cannot bind as \
an integer-backed Rust enum/`c_enum` (values \
outside {{0, 1}} cause C++ UB)"
),
"use a fixed-width integer underlying type (`uint8_t`) \
for C++ enums crossing FFI, or pass `bool` directly",
);
}
if !is_supported_int_bits(*rb) {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust enum `{name}` width {rb} is unsupported \
(expected 8, 16, 32, 64, or 128)"
),
"use a standard fixed-width `#[repr(uN/iN)]` width",
);
}
if !is_supported_int_bits(*cb) {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ integer width {cb} is unsupported (expected \
8, 16, 32, 64, or 128)"
),
"use a standard fixed-width C/C++ integer type",
);
}
if rb != cb {
self.push(
DiagnosticCode::EnumWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"enum `{name}` width mismatch: Rust #[repr] is \
{rb}-bit vs C/C++ underlying {cb}-bit"
),
format!(
"set `#[repr(...)]` on `{name}` to match C/C++ \
{cb}-bit enum width"
),
);
}
if rs != cs {
self.push(
DiagnosticCode::EnumSignednessMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"enum `{name}` signedness mismatch: Rust \
signed={rs} vs C/C++ signed={cs}"
),
format!("match signedness of `#[repr]` on `{name}` to C/C++"),
);
}
if enum_id.is_none() && enum_name.is_none() {
if is_closed_rust_enum {
// `RawCppBundle` carries no enum tag here: the C side
// declared a plain integer rather than an enum, so
// binding a Rust `enum` risks both enum-vs-integer
// drift and immediate UB on out-of-range values.
self.push(
DiagnosticCode::EnumValidityUnverified,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust enum `{name}` bound directly to \
unrestricted C/C++ integer (not a declared \
C/C++ enum; unlisted values cause immediate \
Rust UB)"
),
format!(
"pass the underlying {cb}-bit integer across \
FFI and convert into `{name}` via `TryFrom` \
in Rust"
),
);
} else {
self.push(
DiagnosticCode::EnumTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust `c_enum` `{name}` bound to plain C/C++ \
integer rather than a declared C/C++ enum"
),
"declare the C/C++ parameter as the matching \
`enum` or use a fixed-width integer on the Rust \
side",
);
}
} else {
let diag_before = self.diagnostics.len();
let resolved_ce = self.resolve_cpp_enum_by_type_tag(
enum_id.as_deref(),
enum_name.as_deref(),
subject,
);
if let Some(ce) = resolved_ce {
let name_matched = self.rust_enum_matches_cpp(name, ce);
if !name_matched {
self.push(
DiagnosticCode::EnumTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust enum `{name}` bound to different \
C/C++ enum `{}` (CFI type-identity drift)",
ce.name
),
"align the Rust enum name or `rust_ffi.enums` \
mapping with the C/C++ enum declaration",
);
}
if ce.underlying_is_bool {
self.push(
DiagnosticCode::BoolU8Conflation,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ enum `{}` has `bool` underlying type \
(valid values restricted to {{0, 1}}); \
cannot bind as an integer-backed FFI enum",
ce.name
),
"use a fixed-width integer underlying type \
(`uint8_t`) for C++ enums crossing FFI, or \
pass `bool` directly",
);
}
if ce.bits != *cb {
self.push(
DiagnosticCode::EnumWidthMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ signature integer width ({cb}) != \
`RawCppBundle.enums` width ({}) for `{}`",
ce.bits, ce.name
),
"re-extract a consistent `RawCppBundle`",
);
}
if ce.signed != *cs {
self.push(
DiagnosticCode::EnumSignednessMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ signature signedness ({cs}) != \
`RawCppBundle.enums` signedness ({}) for \
`{}`",
ce.signed, ce.name
),
"re-extract a consistent `RawCppBundle`",
);
}
if name_matched {
let matching_rust_enums: Vec<&RustEnum> = self
.rust
.enums
.iter()
.filter(|e| {
e.rust_name == *name
&& Self::cpp_enum_matches_key(ce, &e.cpp_name)
})
.collect();
if !is_closed_rust_enum && matching_rust_enums.is_empty() {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"transparent `c_enum` `{name}` bound \
to C/C++ enum `{}` requires a unique \
`rust_ffi.enums` entry with \
`is_transparent_wrapper: true` so \
`--rust-type-sizes` can verify it is \
a `Struct` wrapper rather than a \
closed Rust `enum`",
ce.name
),
format!(
"add `{name}` to `rust_ffi.enums` with \
`cpp_name: \"{}\"` and \
`is_transparent_wrapper: true`",
ce.id.as_deref().unwrap_or(&ce.name)
),
);
}
if let [only] = matching_rust_enums.as_slice() {
if is_closed_rust_enum && only.is_transparent_wrapper {
self.push(
DiagnosticCode::EnumTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"closed Rust enum `{name}` cannot \
bind through an \
`is_transparent_wrapper: true` \
entry in `rust_ffi.enums`"
),
"use `kind: \"c_enum\"` for a \
transparent wrapper or set \
`is_transparent_wrapper: false` for a \
closed Rust `enum`",
);
} else if !is_closed_rust_enum && !only.is_transparent_wrapper {
self.push(
DiagnosticCode::EnumTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"transparent `c_enum` `{name}` \
cannot bind through a closed-enum \
entry in `rust_ffi.enums`"
),
"set `is_transparent_wrapper: true` on \
the `rust_ffi.enums` entry for a \
transparent `c_enum` wrapper",
);
}
}
if is_closed_rust_enum
&& matches!(
role,
TypeRole::ExportParam
| TypeRole::ImportParam
| TypeRole::ExportReturn
)
{
match matching_rust_enums.as_slice() {
[only]
if !only.is_transparent_wrapper
&& only.discriminants.is_some() =>
{
if ce.enumerators.is_none() {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ enum `{}` in \
`RawCppBundle` omits \
`enumerators`; cannot \
verify closed Rust enum \
`{name}` discriminant \
parity",
ce.name
),
"re-extract with \
`anneal-clang-dump` so \
`enums[].enumerators` is \
populated",
);
}
}
[only] if only.is_transparent_wrapper => {
// Already diagnosed with
// `EnumTypeMismatch` above.
}
_ => {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"closed Rust enum `{name}` \
bound to C/C++ enum `{}` \
requires a unique \
`rust_ffi.enums` entry with \
explicit `discriminants` to \
verify discriminant parity",
ce.name
),
format!(
"add `{name}` to \
`rust_ffi.enums` with \
`discriminants` matching `{}` \
or switch to a transparent \
`c_enum` wrapper",
ce.name
),
);
}
}
}
}
}
if is_closed_rust_enum {
match role {
TypeRole::ExportReturn | TypeRole::ImportParam => {
// Rust produces the enum value, so Rust's own
// type system guarantees a valid discriminant.
}
TypeRole::ExportParam => {
// Top-level by-value export parameters follow
// the warn-and-disclose caller-contract policy
// (disclosing the C-caller discriminant duty
// with an explicit baseline-validity caveat),
// whereas struct fields, pointees, and C-side
// import returns remain fail-closed below.
self.push_warning(
WarningCode::ExportValidityObligation,
subject,
format!(
"export parameter has Rust enum type \
`{name}`: C `enum` typing does not \
discharge discriminant validity; C \
callers must pass only a declared \
discriminant or behavior is immediate \
Rust UB"
),
);
}
TypeRole::ImportReturn | TypeRole::Field => {
self.push(
DiagnosticCode::EnumValidityUnverified,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"Rust enum `{name}` bound to C/C++ \
enum in a C-produced position (C \
values outside declared discriminants \
cause immediate Rust UB)"
),
format!(
"use a transparent `c_enum` wrapper \
for `{name}` and convert via \
`TryFrom` in Rust"
),
);
}
}
}
if let Some(ce) = resolved_ce {
if self.diagnostics.len() == diag_before {
self.record_matched_enum(ce);
}
}
}
}
(
RustType::Ptr { pointee: rp, is_const: rc, non_null },
CppType::Ptr { pointee: cp, is_const: cc, .. },
) => {
if *non_null {
self.push(
DiagnosticCode::PointerMutOrNullMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
"Rust non-null pointer (`&T`/`NonNull<T>`, \
`non_null: true`) bound to nullable C/C++ pointer \
(a C `NULL` pointer causes immediate Rust UB)",
"use raw `*const T`/`*mut T` (`non_null: false`) or \
`Option<NonNull<T>>`, or bind a C++ `T&` reference",
);
}
if *cc && !*rc {
self.push(
DiagnosticCode::PointerMutOrNullMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
"Rust `*mut` pointer bound to C/C++ `const` pointer",
"change the Rust pointer to `*const T`",
);
} else if !*cc && *rc {
self.push(
DiagnosticCode::PointerMutOrNullMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
"Rust `*const` pointer bound to mutable C/C++ `T*` \
pointer (C/C++ may mutate through a non-`const` \
pointer, violating immutability or nested pointer \
invariance)",
"change the Rust pointer to `*mut T` or declare the \
C/C++ pointer `const T*`",
);
}
// Allow opaque handle pointers `*const Opaque` / `*mut Opaque`
// strictly to point to `void` or a C/C++ record (never `T**`,
// scalars, arrays, or `volatile`/unsupported pointees).
let psub = format!("{subject}.*pointee");
match rp.as_ref() {
RustType::Opaque { name } => {
self.check_opaque_pointee_parity(name, cp, true, &psub);
}
_ => self.check_type_parity(rp, cp, &psub, TypeRole::Field),
}
}
(
RustType::Ptr { pointee: rp, is_const: rc, non_null },
CppType::Ref { pointee: cp, is_const: cc, .. },
) => {
if !*non_null {
self.push(
DiagnosticCode::PointerMutOrNullMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
"nullable Rust raw pointer bound to C++ reference \
(`T&`/`T&&` must be non-null)",
"mark the Rust pointer `non_null: true` (`NonNull<T>` \
or `&T`/`&mut T`)",
);
}
if *cc && !*rc {
self.push(
DiagnosticCode::PointerMutOrNullMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
"mutable Rust reference/pointer bound to C++ `const&`",
"bind C++ `const T&` as `is_const: true`",
);
} else if !*cc && *rc {
self.push(
DiagnosticCode::PointerMutOrNullMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
"immutable Rust reference/pointer (`&T`) bound to \
mutable C++ `T&` reference (mutating through `&T` is \
immediate Rust UB)",
"bind C++ `T&` as `is_const: false` (`&mut T` or \
`NonNull<T>`), or declare the C++ parameter `const T&`",
);
} else if *cc && *rc && *non_null {
// C++ `const T&` still permits mutating `mutable`
// subobjects, which violates Rust `&T` shared immutability
// outside `UnsafeCell`.
self.check_const_ref_mutable_safety(cp, subject);
}
let psub = format!("{subject}.&pointee");
match rp.as_ref() {
RustType::Opaque { name } => {
self.check_opaque_pointee_parity(name, cp, false, &psub);
}
_ => self.check_type_parity(rp, cp, &psub, TypeRole::Field),
}
}
(RustType::Array { elem: re, len: rl }, CppType::Array { elem: ce, len: cl }) => {
if rl != cl {
self.push(
DiagnosticCode::ArrayLenMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!("array length mismatch: Rust [{rl}] vs C/C++ [{cl}]"),
"match array element counts across FFI",
);
}
self.check_type_parity(re, ce, &format!("{subject}[]"), TypeRole::Field);
}
(RustType::Record { name }, CppType::Record { id }) => {
// Every record referenced by type (by value or behind a
// non-opaque pointer) must have a checked layout entry in
// `rust_ffi.records` mapping to `id`.
let Some(rrec) = self.resolve_rust_record(name) else {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"Rust record `{name}` referenced against C/C++ \
`{id}` has no layout entry in `rust_ffi.records`"
),
"add a layout entry for this record to \
`rust_ffi.records`, or bind behind an opaque pointer",
);
return;
};
let maps_to_id =
self.find_cpp_record(&rrec.cpp_record).is_some_and(|c| c.id == *id);
if !maps_to_id {
self.push(
DiagnosticCode::FieldTypeMismatch,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"Rust record `{name}` maps to `{}` rather than \
C/C++ `{id}`",
rrec.cpp_record
),
"align the record types in both signatures",
);
}
}
(_, CppType::Unsupported { desc }) => {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C/C++ type `{desc}` is unsupported by \
`anneal-clang-dump` (e.g. volatile, float, or \
incomplete)"
),
"avoid unsupported types across the checked FFI boundary",
);
}
(RustType::Opaque { name }, _) => {
self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"opaque Rust type `{name}` cannot be passed by value \
across FFI"
),
"pass opaque types behind pointers",
);
}
_ => {
self.push(
DiagnosticCode::FieldTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"incompatible FFI types: Rust `{rty:?}` vs C/C++ \
`{cty:?}`"
),
"use ABI-compatible Rust and C/C++ types",
);
}
}
}
fn check_const_ref_mutable_safety(&mut self, cp: &CppType, subject: &str) {
let mut visited = BTreeSet::new();
match self.cpp_type_mutable_status(cp, &mut visited) {
MutableStatus::Clean => {}
MutableStatus::HasMutable(rec_id) => self.push(
DiagnosticCode::PointerMutOrNullMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C++ `const` reference to record `{rec_id}` with \
`mutable` subobject(s) cannot bind to immutable Rust \
`&T` (interior mutation behind `&T` outside `UnsafeCell` \
is immediate Rust UB)"
),
"pass via raw pointer (`*const T`/`*mut T`), remove `mutable` \
members, or model interior mutability explicitly",
),
MutableStatus::Unattested(rec_id) => self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"C++ `const` reference to record `{rec_id}` lacks \
`has_mutable` attestation in RawCppBundle; cannot verify \
Rust `&T` shared immutability"
),
"ensure `anneal-clang-dump` emits `has_mutable` for the \
pointee record or bind as a raw pointer",
),
}
}
fn cpp_type_mutable_status(
&self,
ty: &CppType,
visited: &mut BTreeSet<String>,
) -> MutableStatus {
match ty {
CppType::Array { elem, .. } => self.cpp_type_mutable_status(elem, visited),
CppType::Record { id } => {
let Some(crec) = self.unique_cpp_record_by_id(id.as_str()) else {
return if self.bundle.lang_policy.is_cplusplus {
MutableStatus::Unattested(id.clone())
} else {
MutableStatus::Clean
};
};
match crec.has_mutable {
Some(true) => return MutableStatus::HasMutable(crec.id.clone()),
None if crec.is_cxx_record || self.bundle.lang_policy.is_cplusplus => {
return MutableStatus::Unattested(crec.id.clone());
}
_ => {}
}
if !visited.insert(crec.id.clone()) {
return MutableStatus::Clean;
}
let mut status = MutableStatus::Clean;
for b in &crec.bases {
match self.cpp_type_mutable_status(
&CppType::Record { id: b.record_id.clone() },
visited,
) {
MutableStatus::Clean => {}
other => {
status = other;
break;
}
}
}
if matches!(status, MutableStatus::Clean) {
for f in &crec.fields {
match self.cpp_type_mutable_status(&f.ty, visited) {
MutableStatus::Clean => {}
other => {
status = other;
break;
}
}
}
}
visited.remove(crec.id.as_str());
status
}
_ => MutableStatus::Clean,
}
}
fn check_opaque_pointee_parity(
&mut self,
opaque_name: &str,
cp: &CppType,
allow_void: bool,
subject: &str,
) {
match cp {
CppType::Record { .. } => {}
CppType::Void if allow_void => {}
CppType::Unsupported { desc } => self.push(
DiagnosticCode::UnsupportedType,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"opaque Rust handle `{opaque_name}` cannot bind \
unsupported C/C++ pointee `{desc}` (e.g. volatile or \
unmodeled type)"
),
"avoid unsupported/volatile pointees across the checked FFI \
boundary",
),
other => self.push(
DiagnosticCode::FieldTypeMismatch,
DiagnosticCategory::ScalarAndEnum,
subject,
format!(
"opaque Rust handle `{opaque_name}` cannot bind C/C++ \
pointee `{other:?}` (expected a C/C++ record{})",
if allow_void { " or `void`" } else { "" }
),
"match pointer indirection (`*mut *mut Opaque` for `T**`) and \
bind scalar/array pointees to their explicit Rust types",
),
}
}
// ---------------------------------------------------------------------
// 4. Calling convention, ABI passing, unwind-ABI, and by-value C++ checks
// ---------------------------------------------------------------------
fn check_functions(&mut self) {
for rfn in &self.rust.functions {
let subject = format!("fn:{}<->{}", rfn.rust_name, rfn.cpp_symbol);
let diag_start = self.diagnostics.len();
let Some(cfn) = self.resolve_cpp_function(&rfn.cpp_symbol, &subject) else {
continue;
};
self.check_single_function(rfn, cfn, &subject);
if rfn.direction == FfiDirection::Export && self.diagnostics.len() == diag_start {
self.matched_exports.push(MatchedExport { rust: rfn.clone(), cpp: cfn.clone() });
}
}
}
fn resolve_cpp_function(&mut self, symbol: &str, subject: &str) -> Option<&'a CppFunction> {
match self.cpp_fns_by_sym.get(symbol) {
Some(Some(f)) => return Some(*f),
Some(None) => {
self.push(
DiagnosticCode::MissingCppFunction,
DiagnosticCategory::CallingConvention,
subject,
format!(
"C/C++ symbol `{symbol}` appears multiple times in \
RawCppBundle (ambiguous definitions)"
),
"deduplicate conflicting function symbols in \
`RawCppBundle`",
);
return None;
}
None => {}
}
let by_unmangled: Vec<&CppFunction> =
self.bundle.functions.iter().filter(|f| f.unmangled_name == symbol).collect();
if let [only] = by_unmangled.as_slice() {
return Some(*only);
}
self.push(
DiagnosticCode::MissingCppFunction,
DiagnosticCategory::CallingConvention,
subject,
format!("C/C++ symbol `{symbol}` not found in RawCppBundle"),
"ensure `anneal-clang-dump` includes the target function",
);
None
}
fn check_single_function(&mut self, rfn: &RustFunction, cfn: &'a CppFunction, subject: &str) {
// 4a. `is_extern_c == true`, exact linker symbol parity, and
// free-function requirement.
if !cfn.is_extern_c {
self.push(
DiagnosticCode::NotExternC,
DiagnosticCategory::CallingConvention,
subject,
format!(
"C++ function `{}` (symbol `{}`) is not `extern \"C\"`",
cfn.unmangled_name, cfn.symbol
),
"declare the C++ function with `extern \"C\"` so its symbol \
and ABI are unmangled",
);
} else if cfn.symbol != rfn.cpp_symbol {
self.push(
DiagnosticCode::MissingCppFunction,
DiagnosticCategory::CallingConvention,
subject,
format!(
"linker symbol mismatch: Rust binds `{}` but C/C++ \
`extern \"C\"` declaration `{}` exports linker symbol \
`{}` (e.g. via `__asm__` redirect)",
rfn.cpp_symbol, cfn.unmangled_name, cfn.symbol
),
format!(
"bind the actual C/C++ linker symbol `{}` (e.g. via \
`#[link_name = \"{}\"]`)",
cfn.symbol, cfn.symbol
),
);
}
if cfn.method_kind != CppMethodKind::Free
|| cfn.is_virtual
|| cfn.params.iter().any(|p| p.is_this)
{
self.push(
DiagnosticCode::CxxMethodAsExternC,
DiagnosticCategory::CallingConvention,
subject,
format!(
"C++ non-free method `{}` (kind={:?}, virtual={}) cannot \
be bound directly as `extern \"C\"`",
cfn.symbol, cfn.method_kind, cfn.is_virtual
),
"expose a free `extern \"C\"` trampoline taking an explicit \
opaque pointer",
);
}
// 4a-proto. Fail closed on unprototyped C declarations
// (`FunctionNoProtoType`, e.g. `int f();`), which omit parameter type
// lists and allow silent C11 signature drift.
match cfn.has_prototype {
Some(false) => {
self.push(
DiagnosticCode::UnprototypedDeclaration,
DiagnosticCategory::CallingConvention,
subject,
format!(
"C function `{}` has an unprototyped declaration \
(`FunctionNoProtoType`, e.g. `int f()`): parameter \
types are unspecified and cannot verify FFI parity",
cfn.symbol
),
"give the C declaration a strict prototype (use `(void)` \
for zero parameters) and compile with \
`-Werror=strict-prototypes`",
);
}
None if rfn.direction == FfiDirection::Export
&& !self.bundle.lang_policy.is_cplusplus =>
{
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::CallingConvention,
subject,
format!(
"C export declaration `{}` omits `has_prototype` in \
RawCppBundle; cannot rule out unprototyped \
`FunctionNoProtoType`",
cfn.symbol
),
"re-extract the C header with `anneal-clang-dump \
--decl-roots` so `has_prototype` is attested",
);
}
_ => {}
}
// 4b. Direction-aware unwind-ABI and definition/declaration checks.
match rfn.direction {
FfiDirection::Import => match &rfn.abi {
RustAbi::C => {
if self.bundle.lang_policy.exceptions_enabled {
self.push(
DiagnosticCode::UnwindAbiMismatch,
DiagnosticCategory::UnwindAndObjectModel,
subject,
"C/C++ TU has `exceptions_enabled == true`, but \
Rust binding uses `extern \"C\"` (unwinding \
across `extern \"C\"` is UB)",
"compile C++ with `-fno-exceptions` or bind the \
function as `extern \"C-unwind\"` in Rust",
);
} else if !cfn.is_definition {
self.push(
DiagnosticCode::UnwindAbiMismatch,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"C/C++ function `{}` is only a declaration \
(`is_definition == false`); the defining TU \
may be compiled with exceptions enabled and \
unwind across Rust `extern \"C\"` (UB)",
cfn.symbol
),
"dump the defining C/C++ translation unit \
compiled with `-fno-exceptions`, or bind the \
function as `extern \"C-unwind\"` in Rust",
);
} else {
self.check_extern_c_unwind_closure(cfn, subject);
}
}
RustAbi::CUnwind => {}
RustAbi::Other(other) => {
self.push(
DiagnosticCode::CallingConvMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"unsupported Rust FFI ABI `extern \"{other}\"` \
(expected `C` or `C-unwind`)"
),
"use `extern \"C\"` or `extern \"C-unwind\"`",
);
}
},
FfiDirection::Export => {
if cfn.is_definition {
self.push(
DiagnosticCode::ExportDefinedInCpp,
DiagnosticCategory::CallingConvention,
subject,
format!(
"Rust export `{}` matched a C/C++ definition \
(`is_definition == true`) instead of a header \
declaration; defining the symbol on both sides \
causes duplicate-symbol/ODR conflicts",
cfn.symbol
),
"extract the C/C++ header declaration with \
`anneal-clang-dump --decl-roots` (or switch \
`direction` to `import` if C/C++ defines the symbol)",
);
}
// Reversed unwind check for export direction:
// - `extern "C"`: rustc guarantees abort-on-unwind at the ABI
// boundary, so nothing is required of C's `-fexceptions`
// flag or call graph.
// - `extern "C-unwind"`: refused fail-closed (C callers cannot
// catch Rust unwinds and unwinding exports are not admitted).
match &rfn.abi {
RustAbi::C => {}
RustAbi::CUnwind => {
self.push(
DiagnosticCode::UnwindAbiMismatch,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"Rust export `{}` uses `extern \"C-unwind\"`, \
which is refused: C callers cannot catch \
Rust unwinds and unwinding exports are not \
admitted",
rfn.rust_name
),
"export the function as non-unwinding \
`extern \"C\"`",
);
}
RustAbi::Other(other) => {
self.push(
DiagnosticCode::CallingConvMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"unsupported Rust export ABI \
`extern \"{other}\"` (expected `C`)"
),
"use non-unwinding `extern \"C\"` for exported \
functions",
);
}
}
}
}
// 4c. Calling convention and variadic parity.
if cfn.abi_witness.cc != "c" {
self.push(
DiagnosticCode::CallingConvMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!("C/C++ abi_witness.cc is `{}` (expected `\"c\"`)", cfn.abi_witness.cc),
"ensure the C/C++ function uses the default C calling \
convention",
);
}
if rfn.direction == FfiDirection::Export && (rfn.is_variadic || cfn.is_variadic) {
self.push(
DiagnosticCode::VariadicMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"C-variadic Rust export `{}` is not admitted \
(Rust is_variadic={}, C/C++ is_variadic={})",
rfn.rust_name, rfn.is_variadic, cfn.is_variadic
),
"replace C-variadic export signatures with fixed-arity \
parameters",
);
} else if rfn.is_variadic != cfn.is_variadic {
self.push(
DiagnosticCode::VariadicMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"variadic mismatch: Rust is_variadic={} vs C/C++ \
is_variadic={}",
rfn.is_variadic, cfn.is_variadic
),
"match `...` variadic signatures identically on both sides",
);
}
// 4d. Parameter count & signature type parity + by-value C++ checks +
// const-consistency vs `safety_pre` + export validity disclosures.
if rfn.params.len() != cfn.params.len() {
self.push(
DiagnosticCode::ParamCountMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"parameter count mismatch: Rust has {} vs C/C++ {}",
rfn.params.len(),
cfn.params.len()
),
"align parameter counts between Rust `extern` block and C/C++ \
header",
);
}
let (ret_role, param_role) = match rfn.direction {
FfiDirection::Import => (TypeRole::ImportReturn, TypeRole::ImportParam),
FfiDirection::Export => (TypeRole::ExportReturn, TypeRole::ExportParam),
};
self.check_type_parity(
&rfn.return_ty,
&cfn.return_ty,
&format!("{subject}.return"),
ret_role,
);
self.check_by_value_cpp_type(&cfn.return_ty, &format!("{subject}.return"));
for (idx, (rp, cp)) in rfn.params.iter().zip(cfn.params.iter()).enumerate() {
let psub = format!("{subject}.param[{idx}:{}]", rp.name);
self.check_type_parity(&rp.ty, &cp.ty, &psub, param_role);
self.check_by_value_cpp_type(&cp.ty, &psub);
if rp.safety_pre_requires_write {
match (&rp.ty, &cp.ty) {
(_, CppType::Ptr { is_const: true, .. })
| (_, CppType::Ref { is_const: true, .. }) => {
self.push(
DiagnosticCode::ConstConsistencyViolation,
DiagnosticCategory::UnwindAndObjectModel,
&psub,
format!(
"parameter `{}` is declared `const` in the \
C/C++ prototype, but Rust `safety_pre` \
requires writability (C callers may pass \
read-only memory)",
rp.name
),
"remove `const` from the C/C++ pointer/reference \
parameter or strengthen `safety_pre` not to \
require writes through it",
);
}
(RustType::Ptr { is_const: true, .. }, _) => {
self.push(
DiagnosticCode::ConstConsistencyViolation,
DiagnosticCategory::UnwindAndObjectModel,
&psub,
format!(
"parameter `{}` has immutable Rust type \
`*const`/`&T`, but `safety_pre` requires \
writability",
rp.name
),
"declare the Rust parameter as `*mut T` (and \
non-`const` in C/C++) or remove the write \
requirement from `safety_pre`",
);
}
(RustType::Ptr { .. }, CppType::Ptr { .. } | CppType::Ref { .. }) => {}
_ => {
self.push(
DiagnosticCode::ConstConsistencyViolation,
DiagnosticCategory::UnwindAndObjectModel,
&psub,
format!(
"`safety_pre_requires_write` is set on \
non-pointer parameter `{}`",
rp.name
),
"set `safety_pre_requires_write` only on pointer \
or reference parameters",
);
}
}
}
if rfn.direction == FfiDirection::Export {
let mut visited = BTreeSet::new();
self.warn_export_param_validity(&rp.ty, &psub, &rp.name, &mut visited);
}
if cp.dtor_symbol.is_some() {
self.push(
DiagnosticCode::NonTrivialDtorByValue,
DiagnosticCategory::UnwindAndObjectModel,
&psub,
format!(
"by-value parameter `{}` runs non-trivial C++ \
destructor `{}`",
cp.name,
cp.dtor_symbol.as_deref().unwrap_or("")
),
"pass types with non-trivial destructors by pointer",
);
}
}
// 4e. `abi_witness` return & parameter passing parity.
self.check_abi_witness(rfn, cfn, subject);
}
/// Recursively walks a by-value export parameter type (`bool`, non-null
/// pointer/reference, arrays, and `#[repr(C)]` record fields) to emit
/// `ExportValidityObligation` warnings for every extra-validity-bearing
/// subobject. Top-level closed `RustType::Enum` export parameters are
/// warned in `check_type_parity`; closed `RustType::Enum` inside struct
/// fields or pointees fails closed with `EnumValidityUnverified`.
fn warn_export_param_validity(
&mut self,
rty: &RustType,
subject: &str,
label: &str,
visited: &mut BTreeSet<String>,
) {
match rty {
RustType::Bool => {
self.push_warning(
WarningCode::ExportValidityObligation,
subject,
format!(
"export value `{label}` has Rust type `bool`: C \
callers must pass a valid byte in {{0, 1}} (C `_Bool` \
discharges absent type punning)"
),
);
}
RustType::Ptr { pointee, non_null: true, is_const } => {
let kind_desc =
if *is_const { "`&T` / `NonNull<T>`" } else { "`&mut T` / `NonNull<T>`" };
self.push_warning(
WarningCode::ExportValidityObligation,
subject,
format!(
"export value `{label}` has non-null Rust type \
{kind_desc}: C callers must pass a non-null, aligned, \
dereferenceable, initialized pointer to a valid value \
of its pointee type (and exclusively aliased for \
`&mut T`)"
),
);
self.warn_export_param_validity(
pointee,
&format!("*{subject}"),
&format!("*{label}"),
visited,
);
}
RustType::Array { elem, .. } => {
self.warn_export_param_validity(
elem,
&format!("{subject}[]"),
&format!("{label}[]"),
visited,
);
}
RustType::Record { name } => {
if let Some(rrec) = self.resolve_rust_record(name) {
if !visited.insert(rrec.rust_name.clone()) {
return;
}
for field in &rrec.fields {
if field.is_padding {
continue;
}
if let Some(fty) = &field.ty {
self.warn_export_param_validity(
fty,
&format!("{subject}.{}", field.name),
&format!("{label}.{}", field.name),
visited,
);
}
}
visited.remove(rrec.rust_name.as_str());
}
}
_ => {}
}
}
/// Walks all reachable callees from `root` inside `RawCppBundle.functions`
/// and fails closed for `extern "C"` whenever any reachable function omits
/// `body_stmt`, executes an indirect/virtual/unmodeled call, or calls an
/// unresolved or declaration-only (`is_definition == false`) callee that
/// could throw from an exception-enabled external TU.
fn check_extern_c_unwind_closure(&mut self, root: &'a CppFunction, subject: &str) {
let mut visited: BTreeSet<&'a str> = BTreeSet::new();
let mut worklist: Vec<&'a CppFunction> = vec![root];
visited.insert(root.symbol.as_str());
while let Some(cur) = worklist.pop() {
if !cur.has_body_stmt {
self.push(
DiagnosticCode::UnwindAbiMismatch,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"C/C++ function `{}` omits `body_stmt` in \
RawCppBundle; transitive callees cannot be audited \
for foreign unwinding across Rust `extern \"C\"`",
cur.symbol
),
"supply a full `anneal-clang-dump` bundle with \
`body_stmt`, or bind the function as `extern \"C-unwind\"`",
);
return;
}
if cur.has_opaque_call {
self.push(
DiagnosticCode::UnwindAbiMismatch,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"C/C++ function `{}` performs an indirect, virtual, \
or unmodeled call/statement that may invoke a \
throwing out-of-TU callee across Rust `extern \"C\"`",
cur.symbol
),
"bind the function as `extern \"C-unwind\"` in Rust or \
restrict the call graph to direct in-TU `-fno-exceptions` \
callees",
);
return;
}
for callee_sym in &cur.direct_callees {
match self.cpp_fns_by_sym.get(callee_sym.as_str()) {
Some(Some(callee)) => {
let callee = *callee;
if !callee.is_definition {
self.push(
DiagnosticCode::UnwindAbiMismatch,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"C/C++ function `{}` transitively calls \
declaration-only callee `{callee_sym}` \
(`is_definition == false`); an out-of-TU \
definition built with exceptions can \
unwind through a `-fno-exceptions` frame \
into Rust `extern \"C\"` (UB)",
root.symbol
),
"bind the function as `extern \"C-unwind\"` \
in Rust or include an attested \
`-fno-exceptions` definition for every \
reachable callee",
);
return;
}
if visited.insert(callee.symbol.as_str()) {
worklist.push(callee);
}
}
_ => {
self.push(
DiagnosticCode::UnwindAbiMismatch,
DiagnosticCategory::UnwindAndObjectModel,
subject,
format!(
"C/C++ function `{}` transitively calls \
unresolved or ambiguous callee `{callee_sym}` \
that may unwind across Rust `extern \"C\"`",
root.symbol
),
"bind the function as `extern \"C-unwind\"` in \
Rust or include a unique in-TU `-fno-exceptions` \
definition for `{callee_sym}`",
);
return;
}
}
}
}
}
fn check_by_value_cpp_type(&mut self, cty: &CppType, subject: &str) {
let mut visited = BTreeSet::new();
self.check_by_value_cpp_type_rec(cty, subject, &mut visited);
}
fn check_by_value_cpp_type_rec(
&mut self,
cty: &CppType,
subject: &str,
visited: &mut BTreeSet<String>,
) {
match cty {
CppType::Array { elem, .. } => {
self.check_by_value_cpp_type_rec(elem, subject, visited);
}
CppType::Record { id } => {
let crec = match self.cpp_records_by_id.get(id.as_str()) {
Some(Some(crec)) => *crec,
Some(None) => {
self.push(
DiagnosticCode::AmbiguousCppRecord,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"by-value C/C++ record `{id}` appears multiple \
times in RawCppBundle.records"
),
"deduplicate conflicting record ids in \
`RawCppBundle.records`",
);
return;
}
None => {
self.push(
DiagnosticCode::MissingCppRecord,
DiagnosticCategory::AggregateGeometry,
subject,
format!(
"by-value C/C++ record `{id}` is missing from \
RawCppBundle.records"
),
"ensure all by-value record definitions are \
extracted into `RawCppBundle.records`",
);
return;
}
};
if !visited.insert(id.clone()) {
return;
}
self.check_cpp_record_by_value_safety(crec, subject);
for f in &crec.fields {
self.check_by_value_cpp_type_rec(
&f.ty,
&format!("{subject}.{}", f.name),
visited,
);
}
}
_ => {}
}
}
fn check_abi_witness(&mut self, rfn: &RustFunction, cfn: &CppFunction, subject: &str) {
let Some(cpp_ret_pass) = &cfn.abi_witness.return_passing else {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::CallingConvention,
format!("{subject}.abi_witness"),
"C/C++ abi_witness is missing `return_passing` (cc=unknown)",
"re-extract the C/C++ bundle with full Clang CodeGen ABI info",
);
return;
};
if cfn.abi_witness.param_passing.len() != cfn.params.len() {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::CallingConvention,
format!("{subject}.abi_witness"),
format!(
"C/C++ abi_witness.param_passing length ({}) != params \
length ({})",
cfn.abi_witness.param_passing.len(),
cfn.params.len()
),
"re-extract a complete RawCppBundle ABI witness",
);
}
if let Some(rw) = &rfn.abi_witness {
self.compare_passing(
&rw.return_passing,
cpp_ret_pass,
&format!("{subject}.return_passing"),
true,
);
if rw.param_passing.len() != cfn.abi_witness.param_passing.len() {
self.push(
DiagnosticCode::ParamCountMismatch,
DiagnosticCategory::CallingConvention,
format!("{subject}.abi_witness.param_passing"),
format!(
"Rust abi_witness.param_passing count ({}) != C/C++ \
({})",
rw.param_passing.len(),
cfn.abi_witness.param_passing.len()
),
"ensure Rust and C/C++ abi_witness parameter counts match",
);
}
for (i, (rp, cp)) in
rw.param_passing.iter().zip(cfn.abi_witness.param_passing.iter()).enumerate()
{
self.compare_passing(rp, cp, &format!("{subject}.param_passing[{i}]"), false);
}
} else {
self.check_inferred_passing(
&rfn.return_ty,
cpp_ret_pass,
&format!("{subject}.return_passing"),
true,
);
for (i, (rp, cp)) in
rfn.params.iter().zip(cfn.abi_witness.param_passing.iter()).enumerate()
{
self.check_inferred_passing(
&rp.ty,
cp,
&format!("{subject}.param_passing[{i}]"),
false,
);
}
}
}
fn compare_passing(
&mut self,
rust_pass: &AbiPassing,
cpp_pass: &AbiPassing,
subject: &str,
is_return: bool,
) {
if is_lossy_or_empty_passing(rust_pass) || is_lossy_or_empty_passing(cpp_pass) {
let role = if is_return { "return" } else { "param" };
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"{role} ABI passing uses an unmodeled or lossy class \
(Rust `{rust_pass:?}` vs C/C++ `{cpp_pass:?}`): \
catch-all `other` buckets and empty `direct_other` \
descriptors erase coerced LLVM types and cannot verify \
parity"
),
"pass aggregates with unmodeled ABI passing classes behind \
pointers",
);
return;
}
if rust_pass == cpp_pass {
return;
}
// On `sret` returns, Clang's `getNaturalAlignIndirect` sets
// `byval: true` for trivially-copyable records while Rust/LLVM `sret`
// uses `byval: false`; `byval` is meaningless on indirect returns.
if is_return
&& matches!(rust_pass, AbiPassing::Indirect { .. })
&& matches!(cpp_pass, AbiPassing::Indirect { .. })
{
return;
}
match (rust_pass, cpp_pass) {
(
AbiPassing::ExtendInt { bits: rb, sign_ext: rs },
AbiPassing::ExtendInt { bits: cb, sign_ext: cs },
) if rb == cb && rs != cs => {
self.push(
DiagnosticCode::ExtendSignMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"extend_int sign_ext mismatch on {rb}-bit value: \
Rust sign_ext={rs} vs C/C++ sign_ext={cs}"
),
"match signed vs unsigned sub-word integer / bool ABI \
types",
);
}
_ => {
let role = if is_return { "return (sret/direct)" } else { "param" };
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"{role} ABI passing mismatch: Rust `{rust_pass:?}` vs \
C/C++ `{cpp_pass:?}`"
),
"align aggregate size/layout (`>16 B` indirect/byval/sret) \
and scalar passing conventions",
);
}
}
}
fn check_inferred_passing(
&mut self,
rty: &RustType,
cpp_pass: &AbiPassing,
subject: &str,
is_return: bool,
) {
match rty {
RustType::Void => {
if *cpp_pass != AbiPassing::Ignore {
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"Rust `()` expects `ignore`, but C/C++ uses \
`{cpp_pass:?}`"
),
"match `void` return to `()`",
);
}
}
RustType::Bool => {
let ok = matches!(
cpp_pass,
AbiPassing::ExtendInt { bits: 1, sign_ext: false }
| AbiPassing::ExtendInt { bits: 8, sign_ext: false }
);
if !ok {
let code = match cpp_pass {
AbiPassing::ExtendInt { sign_ext: true, .. } => {
DiagnosticCode::ExtendSignMismatch
}
_ => DiagnosticCode::AbiPassingMismatch,
};
self.push(
code,
DiagnosticCategory::CallingConvention,
subject,
format!(
"Rust `bool` requires zero-extended `extend_int`, \
but C/C++ uses `{cpp_pass:?}`"
),
"ensure both sides use C/C++ `bool` (`extend_int` \
1-bit zero-extended)",
);
}
}
RustType::Ptr { .. } => {
if *cpp_pass != AbiPassing::DirectPtr {
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"Rust pointer expects `direct_ptr`, but C/C++ uses \
`{cpp_pass:?}`"
),
"check pointer vs by-value parameter passing",
);
}
}
RustType::Int { bits, signed }
| RustType::Enum { bits, signed, .. }
| RustType::CEnum { bits, signed, .. } => {
self.check_int_passing(*bits, *signed, cpp_pass, subject);
}
RustType::CChar => {
if let Some(signed) = self.rust.c_char_is_signed {
self.check_int_passing(8, signed, cpp_pass, subject);
}
}
RustType::CLong => {
if let Some(bits) = self.effective_c_long_bits() {
self.check_int_passing(bits, true, cpp_pass, subject);
}
}
RustType::CULong => {
if let Some(bits) = self.effective_c_long_bits() {
self.check_int_passing(bits, false, cpp_pass, subject);
}
}
RustType::Record { name } => {
self.check_inferred_record_passing(name, cpp_pass, subject, is_return);
}
RustType::Array { .. }
| RustType::MaybeUninitBytes { .. }
| RustType::Opaque { .. } => {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::CallingConvention,
subject,
format!(
"cannot infer ABI passing for `{rty:?}` without an \
explicit Rust `abi_witness`"
),
"supply an explicit `abi_witness` or pass by pointer",
);
}
}
}
fn check_inferred_record_passing(
&mut self,
name: &str,
cpp_pass: &AbiPassing,
subject: &str,
is_return: bool,
) {
let Some(rrec) = self.resolve_rust_record(name) else {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::CallingConvention,
subject,
format!(
"cannot verify ABI passing for by-value record `{name}`: \
no layout entry in `rust_ffi.records`"
),
"add `{name}` to `rust_ffi.records` or supply an explicit \
`abi_witness`",
);
return;
};
if !is_sysv_x86_64(&self.bundle.target_triple)
|| self.bundle.lang_policy.pointer_width_bits != 64
{
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::CallingConvention,
subject,
format!(
"inferred by-value record passing is only implemented for \
64-bit System V x86-64; target `{}` ({}-bit pointers) \
requires an explicit Rust `abi_witness`",
self.bundle.target_triple, self.bundle.lang_policy.pointer_width_bits
),
"supply an explicit `abi_witness` on this function for \
non-SysV-x86-64 targets",
);
return;
}
if rrec.size_bytes == 0 {
if *cpp_pass != AbiPassing::Ignore {
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"zero-sized record `{name}` expects `ignore`, but \
C/C++ uses `{cpp_pass:?}`"
),
"avoid passing zero-sized structs by value across FFI",
);
}
return;
}
// System V AMD64 ABI §3.2.3p2 classifies aggregates > 16 B OR
// aggregates transitively containing unaligned scalar subobjects as
// MEMORY (`indirect` with `byval: true` for params; for `sret` returns
// Clang's `getNaturalAlignIndirect` sets `byval: true` on trivially
// copyable records while `byval` is meaningless on `sret`, so any
// `AbiPassing::Indirect` matches a return).
let Some(unaligned) = self.record_has_unaligned_field(rrec) else {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::CallingConvention,
subject,
format!(
"cannot determine natural subobject alignment for record \
`{name}` (`{}`); explicit Rust `abi_witness` is required",
rrec.cpp_record
),
"ensure all nested C/C++ records exist in `RawCppBundle` or \
provide an explicit `abi_witness`",
);
return;
};
if rrec.size_bytes > 16 || unaligned {
let passes = if is_return {
matches!(cpp_pass, AbiPassing::Indirect { .. })
} else {
*cpp_pass == AbiPassing::Indirect { byval: true }
};
if !passes {
let expected =
if is_return { "Indirect (sret)" } else { "Indirect { byval: true }" };
let reason = if rrec.size_bytes > 16 {
format!("{} B (> 16 B)", rrec.size_bytes)
} else {
format!("{} B with unaligned subobject", rrec.size_bytes)
};
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"SysV x86-64 classifies `#[repr(C)]` struct `{name}` \
({reason}) as `{expected}`, but C/C++ uses \
`{cpp_pass:?}`"
),
"align struct size/packing or pass by pointer",
);
}
return;
}
// Aligned `1..=16 B` struct on SysV x86-64: register-passed.
let ptr_bytes = self.bundle.lang_policy.pointer_width_bits / 8;
match cpp_pass {
AbiPassing::DirectInt { bits } => {
let expected_bits = rrec.size_bytes.saturating_mul(8);
if *bits != expected_bits {
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"direct_int({bits}) does not match {}-byte \
({expected_bits}-bit) record `{name}`",
rrec.size_bytes
),
"match coerced aggregate integer width exactly or \
supply an explicit `abi_witness`",
);
}
}
AbiPassing::DirectPtr if rrec.size_bytes == ptr_bytes => {}
AbiPassing::DirectOther { desc } => {
self.push(
DiagnosticCode::MissingAbiField,
DiagnosticCategory::CallingConvention,
subject,
format!(
"C/C++ passes `<= 16 B` record `{name}` via \
`direct_other({desc})`; explicit Rust `abi_witness` \
is required to confirm multi-register coercion parity"
),
"supply an explicit `abi_witness` matching `{desc}` or \
pass the struct by pointer",
);
}
other => {
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"aligned `<= 16 B` record `{name}` ({} B) expects \
register passing on SysV x86-64, but C/C++ uses \
`{other:?}`",
rrec.size_bytes
),
"check struct layout, packing, or non-trivial C++ \
copy/dtor causing hidden indirect/sret ABI",
);
}
}
}
/// Recursively checks whether `rrec`'s matched C/C++ record transitively
/// contains any scalar subobject whose byte offset is not a multiple of
/// its natural alignment (System V AMD64 ABI §3.2.3p2).
fn record_has_unaligned_field(&self, rrec: &RustRecord) -> Option<bool> {
let crec = self.find_cpp_record(&rrec.cpp_record)?;
let mut visited = BTreeSet::new();
self.cpp_record_has_unaligned_subobject(0, crec, &mut visited)
}
fn cpp_record_has_unaligned_subobject(
&self,
base_offset_bytes: u64,
crec: &'a CppRecord,
visited: &mut BTreeSet<&'a str>,
) -> Option<bool> {
if !visited.insert(crec.id.as_str()) {
return None;
}
let mut unaligned = false;
for cf in &crec.fields {
if !cf.offset_bits.is_multiple_of(8) {
visited.remove(crec.id.as_str());
return Some(true);
}
let off = base_offset_bytes.checked_add(cf.offset_bits / 8)?;
if self.cpp_type_has_unaligned_subobject(off, &cf.ty, visited)? {
unaligned = true;
break;
}
}
visited.remove(crec.id.as_str());
Some(unaligned)
}
fn cpp_type_has_unaligned_subobject(
&self,
base_offset_bytes: u64,
ty: &'a CppType,
visited: &mut BTreeSet<&'a str>,
) -> Option<bool> {
match ty {
CppType::Void | CppType::Bool => Some(false),
CppType::Int { bits, .. } => {
if !is_supported_int_bits(*bits) {
return None;
}
let nat_align = bits / 8;
Some(!base_offset_bytes.is_multiple_of(nat_align))
}
CppType::Ptr { .. } | CppType::Ref { .. } | CppType::NullPtrT => {
let pw = self.bundle.lang_policy.pointer_width_bits;
if !is_supported_pointer_width_bits(pw) {
return None;
}
let ptr_align = pw / 8;
Some(!base_offset_bytes.is_multiple_of(ptr_align))
}
CppType::Array { elem, len } => {
if *len == 0 {
return Some(false);
}
if self.cpp_type_has_unaligned_subobject(base_offset_bytes, elem, visited)? {
return Some(true);
}
if *len > 1 {
let elem_sz = self.cpp_type_size_bytes(elem)?;
let next_off = base_offset_bytes.checked_add(elem_sz)?;
return self.cpp_type_has_unaligned_subobject(next_off, elem, visited);
}
Some(false)
}
CppType::Record { id } => {
let sub = self.unique_cpp_record_by_id(id.as_str())?;
self.cpp_record_has_unaligned_subobject(base_offset_bytes, sub, visited)
}
CppType::Unsupported { .. } => None,
}
}
fn check_int_passing(&mut self, bits: u64, signed: bool, cpp_pass: &AbiPassing, subject: &str) {
match cpp_pass {
AbiPassing::DirectInt { bits: cb } => {
if *cb != bits {
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"integer ABI width mismatch: Rust {bits}-bit vs \
C/C++ direct_int({cb})"
),
"match integer widths across FFI",
);
}
}
AbiPassing::ExtendInt { bits: cb, sign_ext } => {
if *cb != bits {
let code = if *cb == 1 && bits == 8 {
DiagnosticCode::BoolU8Conflation
} else {
DiagnosticCode::AbiPassingMismatch
};
self.push(
code,
DiagnosticCategory::CallingConvention,
subject,
format!(
"extended integer ABI width mismatch: Rust \
{bits}-bit vs C/C++ extend_int(bits={cb}, \
sign_ext={sign_ext})"
),
"match scalar integer / bool types across FFI",
);
} else if *sign_ext != signed {
self.push(
DiagnosticCode::ExtendSignMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"extend_int sign_ext mismatch: Rust \
signed={signed} vs C/C++ sign_ext={sign_ext} \
({bits}-bit)"
),
"match signedness on sub-word FFI integer types",
);
}
}
other => {
self.push(
DiagnosticCode::AbiPassingMismatch,
DiagnosticCategory::CallingConvention,
subject,
format!(
"Rust {bits}-bit integer cannot match C/C++ passing \
`{other:?}`"
),
"align scalar and ABI passing types across FFI",
);
}
}
}
}
/// Merges overlapping or adjacent half-open intervals `[start, end)`.
fn merge_intervals(mut spans: Vec<(u64, u64)>) -> Vec<(u64, u64)> {
spans.retain(|(s, e)| s < e);
spans.sort_unstable();
let mut out: Vec<(u64, u64)> = Vec::new();
for (s, e) in spans {
if let Some(last) = out.last_mut() {
if s <= last.1 {
last.1 = last.1.max(e);
continue;
}
}
out.push((s, e));
}
out
}
/// Returns the first byte offset where `span` overlaps any sorted interval in
/// `merged`.
fn first_overlap(span: (u64, u64), merged: &[(u64, u64)]) -> Option<u64> {
for &(s, e) in merged {
if e <= span.0 {
continue;
}
if s >= span.1 {
break;
}
return Some(span.0.max(s));
}
None
}
/// Returns the complement of sorted `merged` intervals within `[0, total)`.
fn complement_intervals(total: u64, merged: &[(u64, u64)]) -> Vec<(u64, u64)> {
let mut gaps = Vec::new();
let mut cur = 0u64;
for &(s, e) in merged {
if s >= total {
break;
}
if s > cur {
gaps.push((cur, s));
}
cur = cur.max(e.min(total));
}
if cur < total {
gaps.push((cur, total));
}
gaps
}
/// Returns true iff every byte in `[span.0, span.1)` is covered by sorted
/// merged intervals `cov`.
fn interval_covered(span: (u64, u64), cov: &[(u64, u64)]) -> bool {
let mut cur = span.0;
for &(s, e) in cov {
if e <= cur {
continue;
}
if s > cur {
return false;
}
cur = cur.max(e);
if cur >= span.1 {
return true;
}
}
cur >= span.1
}
/// Infers target pointer bit-width for known 32-bit and 64-bit target triples,
/// returning `None` for unknown architectures.
pub fn inferred_target_pointer_width_bits(triple: &str) -> Option<u64> {
let lower = triple.to_ascii_lowercase();
if lower.contains("gnux32") || lower.contains("ilp32") || lower.ends_with("-x32") {
return Some(32);
}
if lower.starts_with("i686-")
|| lower.starts_with("i586-")
|| lower.starts_with("i386-")
|| lower.starts_with("arm-")
|| lower.starts_with("armv7")
|| lower.starts_with("wasm32-")
|| lower.starts_with("riscv32")
{
return Some(32);
}
if lower.starts_with("x86_64-")
|| lower.starts_with("aarch64-")
|| lower.starts_with("riscv64")
|| lower.starts_with("powerpc64")
|| lower.starts_with("s390x-")
{
return Some(64);
}
None
}
/// Infers C `long` bit-width for known LP64 / LLP64 / ILP32 target triples,
/// returning `None` (fail closed) for ambiguous or non-standard ABIs.
pub fn inferred_target_c_long_bits(triple: &str) -> Option<u64> {
let lower = triple.to_ascii_lowercase();
if lower.contains("cygwin") {
return None;
}
if lower.contains("windows")
|| lower.contains("mingw")
|| lower.contains("uefi")
|| lower.contains("gnux32")
|| lower.contains("ilp32")
|| lower.ends_with("-x32")
{
return Some(32);
}
if lower.starts_with("i686-")
|| lower.starts_with("i586-")
|| lower.starts_with("i386-")
|| lower.starts_with("arm-")
|| lower.starts_with("armv7")
|| lower.starts_with("wasm32-")
|| lower.starts_with("riscv32")
{
return Some(32);
}
let is_64_arch = lower.starts_with("x86_64-")
|| lower.starts_with("aarch64-")
|| lower.starts_with("riscv64")
|| lower.starts_with("powerpc64")
|| lower.starts_with("s390x-");
let is_known_lp64_os = lower.contains("-linux-")
|| lower.contains("-darwin")
|| lower.contains("-macos")
|| lower.contains("-freebsd")
|| lower.contains("-netbsd")
|| lower.contains("-openbsd")
|| lower.contains("-dragonfly")
|| lower.contains("-fuchsia")
|| lower.contains("-android")
|| lower.contains("-solaris")
|| lower.contains("-illumos")
|| lower.contains("-none")
|| lower.ends_with("-elf");
if is_64_arch && is_known_lp64_os {
return Some(64);
}
None
}
fn is_sysv_x86_64(triple: &str) -> bool {
let lower = triple.to_ascii_lowercase();
if !lower.starts_with("x86_64-") {
return false;
}
if lower.contains("windows")
|| lower.contains("mingw")
|| lower.contains("uefi")
|| lower.contains("cygwin")
|| lower.contains("gnux32")
|| lower.contains("ilp32")
|| lower.ends_with("-x32")
{
return false;
}
lower.contains("-linux-")
|| lower.contains("-darwin")
|| lower.contains("-macos")
|| lower.contains("-freebsd")
|| lower.contains("-netbsd")
|| lower.contains("-openbsd")
|| lower.contains("-dragonfly")
|| lower.contains("-fuchsia")
|| lower.contains("-android")
|| lower.contains("-solaris")
|| lower.contains("-illumos")
|| lower.contains("-none")
|| lower.ends_with("-elf")
}