| // 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. | |
| //! Target-matched Rust FFI layout and ABI descriptor schema (`schema_version` | |
| //! 1). | |
| //! | |
| //! Designed to be emitted directly by a compile-time Rust probe using | |
| //! `const { size_of::<T>(), align_of::<T>(), offset_of!(T, f) }`, or paired | |
| //! with `rustc -Z print-type-sizes` output via [`crate::print_type_sizes`]. | |
| use serde_json::Value; | |
| use crate::{ | |
| cpp_bundle::{ | |
| as_obj, opt_bool, opt_field, opt_str, opt_u64, parse_abi_passing, req_arr, req_bool, | |
| req_field, req_str, req_u64, AbiPassing, | |
| }, | |
| report::ParseError, | |
| }; | |
| /// Half-open byte range `[start_byte, end_byte)`. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| pub struct ByteRange { | |
| pub start_byte: u64, | |
| pub end_byte: u64, | |
| } | |
| /// Direction of an FFI function boundary. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | |
| pub enum FfiDirection { | |
| /// Rust imports and calls a C/C++ definition (`extern "C" { fn f(...); }`). | |
| #[default] | |
| Import, | |
| /// Rust exports a definition called by C/C++ | |
| /// (`#[no_mangle] pub extern "C" fn f(...)`). | |
| Export, | |
| } | |
| /// Rust FFI ABI string from `extern "..."` blocks or exported functions. | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub enum RustAbi { | |
| /// `extern "C"` (undefined behavior if a C++ exception unwinds across it). | |
| C, | |
| /// `extern "C-unwind"` (admits foreign unwind across the FFI boundary). | |
| CUnwind, | |
| /// Any other ABI string (rejected fail-closed against C/C++ `extern "C"`). | |
| Other(String), | |
| } | |
| impl RustAbi { | |
| pub fn as_str(&self) -> &str { | |
| match self { | |
| RustAbi::C => "C", | |
| RustAbi::CUnwind => "C-unwind", | |
| RustAbi::Other(s) => s.as_str(), | |
| } | |
| } | |
| } | |
| /// Rust FFI type descriptor. | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub enum RustType { | |
| /// `()` / `c_void` return. | |
| Void, | |
| /// Rust `bool` (`{0, 1}` validity; 1-bit zero-extended `extend_int`). | |
| Bool, | |
| /// `core::ffi::c_char` (platform-dependent signedness). | |
| CChar, | |
| /// `core::ffi::c_long` (LP64 = 64-bit, LLP64/ILP32 = 32-bit). | |
| CLong, | |
| /// `core::ffi::c_ulong` (LP64 = 64-bit, LLP64/ILP32 = 32-bit). | |
| CULong, | |
| /// Fixed-width integer (`u8`..`u128`, `i8`..`i128`). | |
| Int { bits: u64, signed: bool }, | |
| /// `#[repr(uN/iN)]` C-like Rust enum with restricted discriminants. | |
| Enum { name: String, bits: u64, signed: bool }, | |
| /// Transparent integer wrapper (`#[repr(transparent)]`) bound to a named | |
| /// C/C++ enum without restricted Rust discriminant UB. | |
| CEnum { name: String, bits: u64, signed: bool }, | |
| /// Raw pointer (`*const T` / `*mut T`) or non-null pointer (`NonNull<T>` / | |
| /// `&T` / `&mut T`). | |
| Ptr { pointee: Box<RustType>, is_const: bool, non_null: bool }, | |
| /// Fixed-length array `[T; N]`. | |
| Array { elem: Box<RustType>, len: u64 }, | |
| /// `#[repr(C)]` struct or union bound by name (either `rust_name` or | |
| /// `cpp_record`). | |
| Record { name: String }, | |
| /// Explicit `[MaybeUninit<u8>; len]` or `MaybeUninit<u8>` padding slot. | |
| MaybeUninitBytes { len: u64 }, | |
| /// Opaque FFI handle pointee (only valid behind a pointer, never by value). | |
| Opaque { name: String }, | |
| } | |
| /// One field inside a Rust `#[repr(C)]` struct or union. | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub struct RustField { | |
| pub name: String, | |
| pub offset_bits: u64, | |
| pub size_bytes: Option<u64>, | |
| pub ty: Option<RustType>, | |
| /// True only when this field explicitly covers C/C++ padding bytes via | |
| /// `MaybeUninit<u8>` or `[MaybeUninit<u8>; N]`. | |
| pub is_padding: bool, | |
| } | |
| /// Rust `#[repr(C)]` struct or union layout descriptor. | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub struct RustRecord { | |
| pub rust_name: String, | |
| pub cpp_record: String, | |
| /// Representation attribute (`"C"`, `"transparent"`, `"Rust"`, or | |
| /// `"unattested(print-type-sizes)"`). | |
| pub repr: String, | |
| /// `None` when unattested (e.g. standalone `print-type-sizes`). | |
| pub is_packed: Option<bool>, | |
| /// `None` when unattested (e.g. ambiguous 1-field `variant` in | |
| /// `print-type-sizes`). | |
| pub is_union: Option<bool>, | |
| pub size_bytes: u64, | |
| pub align_bytes: u64, | |
| pub fields: Vec<RustField>, | |
| /// Padding byte spans explicitly audited and marked unread across FFI. | |
| pub unread_padding_ranges: Vec<ByteRange>, | |
| } | |
| /// Standalone Rust `#[repr(int)]` enum (or `#[repr(transparent)]` `c_enum` | |
| /// wrapper when `is_transparent_wrapper: true`) parity check resolved against | |
| /// an attested `RawCppBundle.enums` entry (fails closed if absent from the | |
| /// C/C++ bundle). | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub struct RustEnum { | |
| pub rust_name: String, | |
| pub cpp_name: String, | |
| pub repr_bits: u64, | |
| pub repr_signed: bool, | |
| pub cpp_bits: Option<u64>, | |
| pub cpp_signed: Option<bool>, | |
| /// True when this entry describes a `#[repr(transparent)]` `c_enum` struct | |
| /// wrapper rather than a closed Rust `#[repr(int)] enum`. | |
| pub is_transparent_wrapper: bool, | |
| /// Optional list of declared Rust discriminant values (base-10 strings) | |
| /// checked for exact set parity against `RawCppBundle.enums[].enumerators`. | |
| pub discriminants: Option<Vec<String>>, | |
| } | |
| /// Optional explicit Rust-side ABI passing witness (for cross-checking against | |
| /// Clang's `abi_witness`). | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub struct RustAbiWitness { | |
| pub return_passing: AbiPassing, | |
| pub param_passing: Vec<AbiPassing>, | |
| } | |
| /// One parameter of a Rust `extern` function binding or export. | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub struct RustParam { | |
| pub name: String, | |
| pub ty: RustType, | |
| /// True when the Rust export's `safety_pre` assumes caller memory behind | |
| /// this pointer/reference parameter is writable (rejected if the C/C++ | |
| /// prototype declares the parameter `const`). | |
| pub safety_pre_requires_write: bool, | |
| } | |
| /// Rust `extern` function declaration (import) or definition (export) bound to | |
| /// a C/C++ symbol. | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub struct RustFunction { | |
| pub rust_name: String, | |
| pub cpp_symbol: String, | |
| pub direction: FfiDirection, | |
| pub abi: RustAbi, | |
| pub is_variadic: bool, | |
| pub return_ty: RustType, | |
| pub params: Vec<RustParam>, | |
| pub abi_witness: Option<RustAbiWitness>, | |
| } | |
| /// Complete target-matched Rust FFI descriptor. | |
| /// | |
| /// Target policy fields are `Option` so standalone `print-type-sizes` input | |
| /// never fabricates unattested target facts; JSON parsing requires all three. | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub struct RustFfiDescriptor { | |
| pub target_triple: Option<String>, | |
| pub pointer_width_bits: Option<u64>, | |
| pub c_char_is_signed: Option<bool>, | |
| /// Bit width of `core::ffi::c_long` on the Rust target (`64` on LP64, `32` | |
| /// on LLP64/ILP32). If omitted, inferred from `target_triple` when known. | |
| pub c_long_bits: Option<u64>, | |
| pub records: Vec<RustRecord>, | |
| pub enums: Vec<RustEnum>, | |
| pub functions: Vec<RustFunction>, | |
| } | |
| /// Parses a `RustFfiDescriptor` JSON document (`schema_version == 1`). | |
| pub fn parse_rust_descriptor_json(text: &str) -> Result<RustFfiDescriptor, ParseError> { | |
| let value: Value = serde_json::from_str(text).map_err(|e| ParseError::Json(e.to_string()))?; | |
| let root = as_obj(&value, "rust_ffi")?; | |
| let version = req_u64(root, "schema_version", "rust_ffi")?; | |
| if version != 1 { | |
| return Err(ParseError::Schema(format!( | |
| "unsupported rust_ffi schema_version {version} (expected 1)" | |
| ))); | |
| } | |
| let target_triple = req_str(root, "target_triple", "rust_ffi")?; | |
| let pointer_width_bits = req_u64(root, "pointer_width_bits", "rust_ffi")?; | |
| let c_char_is_signed = req_bool(root, "c_char_is_signed", "rust_ffi")?; | |
| let c_long_bits = opt_u64(root, "c_long_bits", "rust_ffi")?; | |
| let mut records = Vec::new(); | |
| if let Some(arr_v) = opt_field(root, "records") { | |
| let arr = arr_v | |
| .as_array() | |
| .ok_or_else(|| ParseError::Schema("rust_ffi: `records` must be an array".to_owned()))?; | |
| for r in arr { | |
| records.push(parse_rust_record(r)?); | |
| } | |
| } | |
| let mut enums = Vec::new(); | |
| if let Some(arr_v) = opt_field(root, "enums") { | |
| let arr = arr_v | |
| .as_array() | |
| .ok_or_else(|| ParseError::Schema("rust_ffi: `enums` must be an array".to_owned()))?; | |
| for e in arr { | |
| enums.push(parse_rust_enum(e)?); | |
| } | |
| } | |
| let mut functions = Vec::new(); | |
| if let Some(arr_v) = opt_field(root, "functions") { | |
| let arr = arr_v.as_array().ok_or_else(|| { | |
| ParseError::Schema("rust_ffi: `functions` must be an array".to_owned()) | |
| })?; | |
| for f in arr { | |
| functions.push(parse_rust_function(f)?); | |
| } | |
| } | |
| Ok(RustFfiDescriptor { | |
| target_triple: Some(target_triple), | |
| pointer_width_bits: Some(pointer_width_bits), | |
| c_char_is_signed: Some(c_char_is_signed), | |
| c_long_bits, | |
| records, | |
| enums, | |
| functions, | |
| }) | |
| } | |
| fn parse_rust_record(v: &Value) -> Result<RustRecord, ParseError> { | |
| let o = as_obj(v, "rust record")?; | |
| let rust_name = req_str(o, "rust_name", "rust record")?; | |
| let ctx = format!("rust record `{rust_name}`"); | |
| let cpp_record = req_str(o, "cpp_record", &ctx)?; | |
| let repr = req_str(o, "repr", &ctx)?; | |
| let is_packed = opt_bool(o, "is_packed", &ctx)?.unwrap_or(false); | |
| let is_union = opt_bool(o, "is_union", &ctx)?.unwrap_or(false); | |
| let size_bytes = req_u64(o, "size_bytes", &ctx)?; | |
| let align_bytes = req_u64(o, "align_bytes", &ctx)?; | |
| let mut fields = Vec::new(); | |
| for f in req_arr(o, "fields", &ctx)? { | |
| let fo = as_obj(f, &ctx)?; | |
| let fname = req_str(fo, "name", &ctx)?; | |
| let fctx = format!("{ctx}.field `{fname}`"); | |
| let off_bytes = opt_u64(fo, "offset_bytes", &fctx)?; | |
| let off_bits = opt_u64(fo, "offset_bits", &fctx)?; | |
| let offset_bits = match (off_bytes, off_bits) { | |
| (Some(b), None) => b | |
| .checked_mul(8) | |
| .ok_or_else(|| ParseError::Schema(format!("{fctx}: offset_bytes overflow")))?, | |
| (None, Some(bits)) => bits, | |
| (Some(b), Some(bits)) => { | |
| let expected = b | |
| .checked_mul(8) | |
| .ok_or_else(|| ParseError::Schema(format!("{fctx}: offset_bytes overflow")))?; | |
| if expected != bits { | |
| return Err(ParseError::Schema(format!( | |
| "{fctx}: conflicting offset_bytes ({b}) and \ | |
| offset_bits ({bits})" | |
| ))); | |
| } | |
| bits | |
| } | |
| (None, None) => { | |
| return Err(ParseError::Schema(format!( | |
| "{fctx}: missing required `offset_bytes` or `offset_bits`" | |
| ))); | |
| } | |
| }; | |
| let size_bytes = opt_u64(fo, "size_bytes", &fctx)?; | |
| let ty = match opt_field(fo, "ty") { | |
| Some(tv) => Some(parse_rust_type(tv, &fctx)?), | |
| None => None, | |
| }; | |
| let explicit_pad = opt_bool(fo, "is_padding", &fctx)?.unwrap_or(false); | |
| let is_maybe_uninit = matches!(ty, Some(RustType::MaybeUninitBytes { .. })); | |
| if explicit_pad && !is_maybe_uninit { | |
| return Err(ParseError::Schema(format!( | |
| "{fctx}: `is_padding: true` requires `ty` to be \ | |
| `maybe_uninit_bytes` (initialized types like `[u8; N]` \ | |
| cannot cover uninitialized C/C++ padding)" | |
| ))); | |
| } | |
| let is_padding = explicit_pad || is_maybe_uninit; | |
| if let Some(RustType::MaybeUninitBytes { len }) = &ty { | |
| if !offset_bits.is_multiple_of(8) { | |
| return Err(ParseError::Schema(format!( | |
| "{fctx}: `maybe_uninit_bytes` padding field must be \ | |
| byte-aligned (offset_bits={offset_bits})" | |
| ))); | |
| } | |
| if let Some(sz) = size_bytes { | |
| if sz != *len { | |
| return Err(ParseError::Schema(format!( | |
| "{fctx}: `maybe_uninit_bytes` len ({len}) disagrees \ | |
| with size_bytes ({sz})" | |
| ))); | |
| } | |
| } | |
| } | |
| fields.push(RustField { name: fname, offset_bits, size_bytes, ty, is_padding }); | |
| } | |
| let mut unread_padding_ranges = Vec::new(); | |
| if let Some(rv) = opt_field(o, "unread_padding_ranges") { | |
| let arr = rv.as_array().ok_or_else(|| { | |
| ParseError::Schema(format!("{ctx}: `unread_padding_ranges` must be an array")) | |
| })?; | |
| for r in arr { | |
| let ro = as_obj(r, &ctx)?; | |
| let start_byte = req_u64(ro, "start_byte", &ctx)?; | |
| let end_byte = req_u64(ro, "end_byte", &ctx)?; | |
| if end_byte <= start_byte { | |
| return Err(ParseError::Schema(format!( | |
| "{ctx}: invalid unread_padding_ranges \ | |
| [{start_byte}..{end_byte})" | |
| ))); | |
| } | |
| unread_padding_ranges.push(ByteRange { start_byte, end_byte }); | |
| } | |
| } | |
| Ok(RustRecord { | |
| rust_name, | |
| cpp_record, | |
| repr, | |
| is_packed: Some(is_packed), | |
| is_union: Some(is_union), | |
| size_bytes, | |
| align_bytes, | |
| fields, | |
| unread_padding_ranges, | |
| }) | |
| } | |
| fn parse_rust_enum(v: &Value) -> Result<RustEnum, ParseError> { | |
| let o = as_obj(v, "rust enum")?; | |
| let rust_name = req_str(o, "rust_name", "rust enum")?; | |
| let ctx = format!("rust enum `{rust_name}`"); | |
| let discriminants = match opt_field(o, "discriminants") { | |
| None => None, | |
| Some(dv) => { | |
| let arr = dv.as_array().ok_or_else(|| { | |
| ParseError::Schema(format!("{ctx}: `discriminants` must be an array")) | |
| })?; | |
| let mut vals = Vec::with_capacity(arr.len()); | |
| for item in arr { | |
| if let Some(s) = item.as_str() { | |
| vals.push(s.to_owned()); | |
| } else if let Some(n) = item.as_i64() { | |
| vals.push(n.to_string()); | |
| } else if let Some(n) = item.as_u64() { | |
| vals.push(n.to_string()); | |
| } else { | |
| return Err(ParseError::Schema(format!( | |
| "{ctx}: each entry in `discriminants` must be an integer or base-10 string" | |
| ))); | |
| } | |
| } | |
| Some(vals) | |
| } | |
| }; | |
| Ok(RustEnum { | |
| rust_name, | |
| cpp_name: req_str(o, "cpp_name", &ctx)?, | |
| repr_bits: req_u64(o, "repr_bits", &ctx)?, | |
| repr_signed: req_bool(o, "repr_signed", &ctx)?, | |
| cpp_bits: opt_u64(o, "cpp_bits", &ctx)?, | |
| cpp_signed: opt_bool(o, "cpp_signed", &ctx)?, | |
| is_transparent_wrapper: opt_bool(o, "is_transparent_wrapper", &ctx)?.unwrap_or(false), | |
| discriminants, | |
| }) | |
| } | |
| fn parse_rust_function(v: &Value) -> Result<RustFunction, ParseError> { | |
| let o = as_obj(v, "rust function")?; | |
| let rust_name = req_str(o, "rust_name", "rust function")?; | |
| let ctx = format!("rust function `{rust_name}`"); | |
| let cpp_symbol = opt_str(o, "cpp_symbol", &ctx)?.unwrap_or_else(|| rust_name.clone()); | |
| let direction = match opt_str(o, "direction", &ctx)?.as_deref() { | |
| None | Some("import") => FfiDirection::Import, | |
| Some("export") => FfiDirection::Export, | |
| Some(other) => { | |
| return Err(ParseError::Schema(format!( | |
| "{ctx}: unknown direction `{other}` (expected `import` or `export`)" | |
| ))); | |
| } | |
| }; | |
| let abi_str = req_str(o, "abi", &ctx)?; | |
| let abi = match abi_str.as_str() { | |
| "C" => RustAbi::C, | |
| "C-unwind" => RustAbi::CUnwind, | |
| other => RustAbi::Other(other.to_owned()), | |
| }; | |
| let is_variadic = opt_bool(o, "is_variadic", &ctx)?.unwrap_or(false); | |
| let return_ty = parse_rust_type(req_field(o, "return_ty", &ctx)?, &format!("{ctx}.return_ty"))?; | |
| let mut params = Vec::new(); | |
| for p in req_arr(o, "params", &ctx)? { | |
| let po = as_obj(p, &ctx)?; | |
| let pname = req_str(po, "name", &ctx)?; | |
| let pctx = format!("{ctx}.param `{pname}`"); | |
| let safety_pre_requires_write = | |
| opt_bool(po, "safety_pre_requires_write", &pctx)?.unwrap_or(false); | |
| params.push(RustParam { | |
| ty: parse_rust_type(req_field(po, "ty", &ctx)?, &pctx)?, | |
| name: pname, | |
| safety_pre_requires_write, | |
| }); | |
| } | |
| let abi_witness = match opt_field(o, "abi_witness") { | |
| None => None, | |
| Some(av) => { | |
| let ao = as_obj(av, &format!("{ctx}.abi_witness"))?; | |
| let return_passing = parse_abi_passing( | |
| req_field(ao, "return_passing", &format!("{ctx}.abi_witness"))?, | |
| &format!("{ctx}.abi_witness.return_passing"), | |
| )?; | |
| let mut param_passing = Vec::new(); | |
| for (i, pp) in | |
| req_arr(ao, "param_passing", &format!("{ctx}.abi_witness"))?.iter().enumerate() | |
| { | |
| param_passing | |
| .push(parse_abi_passing(pp, &format!("{ctx}.abi_witness.param_passing[{i}]"))?); | |
| } | |
| Some(RustAbiWitness { return_passing, param_passing }) | |
| } | |
| }; | |
| Ok(RustFunction { | |
| rust_name, | |
| cpp_symbol, | |
| direction, | |
| abi, | |
| is_variadic, | |
| return_ty, | |
| params, | |
| abi_witness, | |
| }) | |
| } | |
| fn parse_rust_type(v: &Value, ctx: &str) -> Result<RustType, ParseError> { | |
| let o = as_obj(v, ctx)?; | |
| let kind = req_str(o, "kind", ctx)?; | |
| match kind.as_str() { | |
| "void" | "unit" => Ok(RustType::Void), | |
| "bool" => Ok(RustType::Bool), | |
| "c_char" => Ok(RustType::CChar), | |
| "c_long" => Ok(RustType::CLong), | |
| "c_ulong" => Ok(RustType::CULong), | |
| "int" => Ok(RustType::Int { | |
| bits: req_u64(o, "bits", ctx)?, | |
| signed: req_bool(o, "signed", ctx)?, | |
| }), | |
| "enum" => Ok(RustType::Enum { | |
| name: req_str(o, "name", ctx)?, | |
| bits: req_u64(o, "bits", ctx)?, | |
| signed: req_bool(o, "signed", ctx)?, | |
| }), | |
| "c_enum" => Ok(RustType::CEnum { | |
| name: req_str(o, "name", ctx)?, | |
| bits: req_u64(o, "bits", ctx)?, | |
| signed: req_bool(o, "signed", ctx)?, | |
| }), | |
| "ptr" => Ok(RustType::Ptr { | |
| pointee: Box::new(parse_rust_type(req_field(o, "pointee", ctx)?, ctx)?), | |
| is_const: opt_bool(o, "is_const", ctx)?.unwrap_or(false), | |
| non_null: opt_bool(o, "non_null", ctx)?.unwrap_or(false), | |
| }), | |
| "array" => Ok(RustType::Array { | |
| elem: Box::new(parse_rust_type(req_field(o, "elem", ctx)?, ctx)?), | |
| len: req_u64(o, "len", ctx)?, | |
| }), | |
| "record" => Ok(RustType::Record { name: req_str(o, "name", ctx)? }), | |
| "maybe_uninit_bytes" => Ok(RustType::MaybeUninitBytes { len: req_u64(o, "len", ctx)? }), | |
| "opaque" => Ok(RustType::Opaque { name: req_str(o, "name", ctx)? }), | |
| other => Err(ParseError::Schema(format!("{ctx}: unknown rust type `{other}`"))), | |
| } | |
| } |