Skip to main content

nativeview_codegen/abi/layout/
mod.rs

1//! ABI type spellings and the C layout of every record on 32-bit and 64-bit targets.
2//!
3//! `#[derive(NvAbi)]` records `rustc`'s field offsets for the build target only. Hosts also run on
4//! 32-bit targets, so this module recomputes every record's C layout for the three data models NV
5//! runs on, from the field types:
6//!
7//! - **LP64 / LLP64** (64-bit pointers);
8//! - **ILP32** with 8-byte-aligned 64-bit fields (`armeabi-v7a`, `arm64_32` watchOS, wasm32, Windows x86);
9//! - **i386 System V** (Android x86, 32-bit Linux), where 64-bit fields are only 4-byte aligned
10//!   inside structs.
11//!
12//! It then checks the model of the running build against `rustc` and every declared `offset` /
13//! `size` contract. A record whose layout drifts is a codegen error, never a wrong `static_assert`.
14
15use std::collections::{BTreeMap, BTreeSet};
16
17use nativeview_abi::schema::{AbiFieldDescriptor, AbiFileDescriptor, AbiRecordDescriptor};
18
19use crate::error::CodegenError;
20
21/// Fixed-width scalar of the ABI.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Scalar {
24    Bool,
25    U8,
26    U16,
27    U32,
28    U64,
29    I32,
30    I64,
31    F32,
32    F64,
33    Usize,
34}
35
36impl Scalar {
37    fn parse(s: &str) -> Option<Self> {
38        Some(match s {
39            "bool" => Self::Bool,
40            "u8" | "PrimarySlot" => Self::U8,
41            "u16" | "ShortLen" => Self::U16,
42            "u32" | "NodeIndex" | "Word" => Self::U32,
43            "u64" => Self::U64,
44            "i32" | "ZIndex" => Self::I32,
45            "i64" => Self::I64,
46            "f32" => Self::F32,
47            "f64" => Self::F64,
48            "usize" => Self::Usize,
49            _ => return None,
50        })
51    }
52
53    /// Size and in-struct alignment under each [`Model`].
54    fn shape(self) -> Shape {
55        match self {
56            Self::Bool | Self::U8 => Shape::same(1),
57            Self::U16 => Shape::same(2),
58            Self::U32 | Self::I32 | Self::F32 => Shape::same(4),
59            Self::U64 | Self::I64 | Self::F64 => Shape {
60                size: Width::same(8),
61                align: Width([8, 8, 4]),
62            },
63            Self::Usize => Shape::POINTER,
64        }
65    }
66}
67
68/// The C data models NV hosts run on, in [`Width`] order.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Model {
71    /// 64-bit pointers.
72    P64 = 0,
73    /// 32-bit pointers, 8-byte-aligned 64-bit fields.
74    P32 = 1,
75    /// 32-bit pointers, 4-byte-aligned 64-bit fields (i386 System V).
76    I386 = 2,
77}
78
79impl Model {
80    /// The model of the running build.
81    pub const fn host() -> Self {
82        #[repr(C)]
83        struct Probe {
84            pad: u8,
85            value: u64,
86        }
87        if size_of::<usize>() == 8 {
88            Self::P64
89        } else if std::mem::offset_of!(Probe, value) == 8 {
90            Self::P32
91        } else {
92            Self::I386
93        }
94    }
95}
96
97/// One parsed ABI type spelling (`u32`, `*const NvValue`, `[u32; 5]`, `Option<NvHostInvokeFn>`,
98/// `NvStrSlice`, `()`).
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum Ty<'a> {
101    Unit,
102    Void,
103    Scalar(Scalar),
104    Ptr { mutable: bool, pointee: &'a str },
105    Array { elem: &'a str, len: usize },
106    /// Nullable callback typedef (`Option<CallbackFn>`). Only valid when the inner name is a
107    /// declared `AbiCallbackDescriptor`.
108    Nullable(&'a str),
109    Named(&'a str),
110}
111
112impl<'a> Ty<'a> {
113    pub fn parse(spelling: &'a str) -> Result<Self, CodegenError> {
114        let s = spelling.trim();
115        if s == "()" {
116            return Ok(Self::Unit);
117        }
118        if s == "c_void" {
119            return Ok(Self::Void);
120        }
121        if let Some(scalar) = Scalar::parse(s) {
122            return Ok(Self::Scalar(scalar));
123        }
124        if let Some(pointee) = s.strip_prefix("*const ") {
125            return Ok(Self::Ptr {
126                mutable: false,
127                pointee: pointee.trim(),
128            });
129        }
130        if let Some(pointee) = s.strip_prefix("*mut ") {
131            return Ok(Self::Ptr {
132                mutable: true,
133                pointee: pointee.trim(),
134            });
135        }
136        if let Some(inner) = s.strip_prefix("Option<").and_then(|b| b.strip_suffix('>')) {
137            let inner = inner.trim();
138            if inner.is_empty() || inner.contains(['(', ')', '<', '>']) {
139                return Err(bad_type(spelling, "unsupported `Option<...>` ABI type"));
140            }
141            return Ok(Self::Nullable(inner));
142        }
143        if let Some(body) = s.strip_prefix('[').and_then(|b| b.strip_suffix(']')) {
144            let (elem, len) = body
145                .split_once(';')
146                .ok_or_else(|| bad_type(spelling, "array needs `[T; N]`"))?;
147            let len = len
148                .trim()
149                .parse()
150                .map_err(|_| bad_type(spelling, "array length"))?;
151            return Ok(Self::Array {
152                elem: elem.trim(),
153                len,
154            });
155        }
156        if !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
157            return Ok(Self::Named(s));
158        }
159        Err(bad_type(spelling, "unsupported ABI type spelling"))
160    }
161}
162
163fn bad_type(spelling: &str, why: &str) -> CodegenError {
164    CodegenError::validation(format!("ABI type `{spelling}`: {why}"))
165}
166
167/// A size or offset under each [`Model`] (`[P64, P32, I386]`).
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct Width(pub [usize; 3]);
170
171impl Width {
172    const fn same(n: usize) -> Self {
173        Self([n; 3])
174    }
175
176    pub const fn at(self, model: Model) -> usize {
177        self.0[model as usize]
178    }
179
180    /// 64-bit value.
181    pub const fn p64(self) -> usize {
182        self.0[0]
183    }
184
185    /// 32-bit value (wasm32, `armeabi-v7a`, `arm64_32`): what Dart / TypeScript / Java readers use.
186    pub const fn p32(self) -> usize {
187        self.0[1]
188    }
189
190    /// i386 System V value.
191    pub const fn i386(self) -> usize {
192        self.0[2]
193    }
194
195    /// The value when every model agrees.
196    pub const fn fixed(self) -> Option<usize> {
197        let [a, b, c] = self.0;
198        if a == b && b == c { Some(a) } else { None }
199    }
200
201    fn zip(self, other: Self, f: impl Fn(usize, usize) -> usize) -> Self {
202        Self([
203            f(self.0[0], other.0[0]),
204            f(self.0[1], other.0[1]),
205            f(self.0[2], other.0[2]),
206        ])
207    }
208
209    /// [`Self::zip`] for arithmetic that can overflow `usize`.
210    fn try_zip(
211        self,
212        other: Self,
213        f: impl Fn(usize, usize) -> Option<usize>,
214        ctx: &str,
215    ) -> Result<Self, CodegenError> {
216        let mut out = [0; 3];
217        for (i, slot) in out.iter_mut().enumerate() {
218            *slot = f(self.0[i], other.0[i])
219                .ok_or_else(|| bad_type(ctx, "layout arithmetic overflows usize"))?;
220        }
221        Ok(Self(out))
222    }
223}
224
225/// Size and alignment of one type.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227struct Shape {
228    size: Width,
229    align: Width,
230}
231
232impl Shape {
233    const fn same(size: usize) -> Self {
234        Self {
235            size: Width::same(size),
236            align: Width::same(size),
237        }
238    }
239    const POINTER: Self = Self {
240        size: Width([8, 4, 4]),
241        align: Width([8, 4, 4]),
242    };
243}
244
245/// One field of a [`RecordLayout`].
246#[derive(Debug, Clone, Copy)]
247pub struct FieldLayout<'a> {
248    pub desc: &'a AbiFieldDescriptor,
249    pub ty: Ty<'a>,
250    pub offset: Width,
251}
252
253impl FieldLayout<'_> {
254    pub fn name(&self) -> &str {
255        self.desc.name
256    }
257}
258
259/// C layout of one struct or union on both pointer widths.
260#[derive(Debug, Clone)]
261pub struct RecordLayout<'a> {
262    pub name: &'a str,
263    pub doc: Option<&'a str>,
264    pub is_union: bool,
265    pub size: Width,
266    pub align: Width,
267    pub fields: Vec<FieldLayout<'a>>,
268    /// Rust `#[repr(C, align(N <= 16))]`, reproduced in C with `NV_ALIGNAS(N)` (`_Alignas` /
269    /// `alignas`) whenever it exceeds some data model's natural alignment.
270    pub alignas: Option<usize>,
271    /// Rust `align(N)` that only aligns Rust-owned slabs (it changes no size and no containing
272    /// layout), so C keeps the natural alignment Swift's ClangImporter imports as a plain value.
273    pub slab_align: Option<usize>,
274    /// Alignment from the fields alone (before any `alignas`).
275    pub natural_align: Width,
276}
277
278impl RecordLayout<'_> {
279    /// `true` when no size or offset depends on the pointer width.
280    pub fn is_fixed(&self) -> bool {
281        self.size.fixed().is_some() && self.fields.iter().all(|f| f.offset.fixed().is_some())
282    }
283}
284
285/// Computes the layout of every record of `files`, in declaration order, and checks it against
286/// `rustc` and the declared contracts.
287pub fn layout_records<'a>(
288    files: &[&'a AbiFileDescriptor],
289) -> Result<Vec<RecordLayout<'a>>, CodegenError> {
290    layout_records_on(&[], &[], files)
291}
292
293/// [`layout_records`] for files whose records may store records, aliases, or callbacks of an
294/// already laid out header they include (`base`, `base_files`), e.g. the runtime ABI storing
295/// `NvStrSlice` by value.
296pub fn layout_records_on<'a>(
297    base: &[RecordLayout<'a>],
298    base_files: &[&'a AbiFileDescriptor],
299    files: &[&'a AbiFileDescriptor],
300) -> Result<Vec<RecordLayout<'a>>, CodegenError> {
301    let mut shapes: BTreeMap<&'a str, Shape> = base
302        .iter()
303        .map(|r| (r.name, Shape { size: r.size, align: r.align }))
304        .collect();
305    let mut enums: BTreeSet<&'a str> = BTreeSet::new();
306    let mut callbacks: BTreeSet<&'a str> = BTreeSet::new();
307    let embedded = embedded_by_value(base_files, files);
308
309    // Enums have no storable shape (C enums are `int`-sized), so every by-value use, also through
310    // an array or an alias, is rejected; they are collected before any alias is shaped.
311    for e in base_files.iter().chain(files).flat_map(|f| f.enums) {
312        Scalar::parse(e.repr).ok_or_else(|| bad_type(e.repr, "enum repr"))?;
313        enums.insert(e.name);
314    }
315    for cb in base_files.iter().chain(files).flat_map(|f| f.callbacks) {
316        callbacks.insert(cb.name);
317        shapes.insert(cb.name, Shape::POINTER);
318    }
319    for alias in base_files.iter().chain(files).flat_map(|f| f.aliases) {
320        let shape = shape_of(Ty::parse(alias.target)?, &shapes, &enums, &callbacks, alias.name)?;
321        shapes.insert(alias.name, shape);
322        if let Some(rn) = alias.rust_name {
323            shapes.insert(rn, shape);
324        }
325    }
326    let mut out = Vec::new();
327    for file in files {
328        for record in file.records {
329            let layout = layout_record(record, &shapes, &enums, &callbacks, &embedded)?;
330            check_against_rustc(record, &layout)?;
331            shapes.insert(
332                layout.name,
333                Shape {
334                    size: layout.size,
335                    align: layout.align,
336                },
337            );
338            out.push(layout);
339        }
340    }
341    Ok(out)
342}
343
344fn shape_of(
345    ty: Ty<'_>,
346    shapes: &BTreeMap<&str, Shape>,
347    enums: &BTreeSet<&str>,
348    callbacks: &BTreeSet<&str>,
349    ctx: &str,
350) -> Result<Shape, CodegenError> {
351    Ok(match ty {
352        // A pointer's size does not depend on its pointee, so the pointee is not walked.
353        Ty::Ptr { .. } => Shape::POINTER,
354        Ty::Nullable(inner) if callbacks.contains(inner) => Shape::POINTER,
355        Ty::Nullable(inner) => {
356            return Err(CodegenError::validation(format!(
357                "`{ctx}`: `Option<{inner}>` is only valid for declared callback typedefs"
358            )));
359        }
360        Ty::Named(name) if enums.contains(name) => {
361            return Err(CodegenError::validation(format!(
362                "`{ctx}` stores enum `{name}` by value: C enums are `int`-sized whatever the Rust repr; store its integer repr"
363            )));
364        }
365        Ty::Scalar(s) => s.shape(),
366        Ty::Array { len: 0, .. } => {
367            return Err(bad_type(ctx, "zero-length arrays are not valid C"));
368        }
369        Ty::Array { elem, len } => {
370            let e = shape_of(Ty::parse(elem)?, shapes, enums, callbacks, ctx)?;
371            let mut size = [0; 3];
372            for (out, n) in size.iter_mut().zip(e.size.0) {
373                *out = n
374                    .checked_mul(len)
375                    .ok_or_else(|| bad_type(ctx, "array size overflows usize"))?;
376            }
377            Shape {
378                size: Width(size),
379                align: e.align,
380            }
381        }
382        Ty::Named(name) => *shapes.get(name).ok_or_else(|| {
383            CodegenError::validation(format!("`{ctx}` uses `{name}` before it is declared"))
384        })?,
385        Ty::Unit | Ty::Void => {
386            return Err(bad_type(ctx, "`()` / `c_void` cannot be stored by value"));
387        }
388    })
389}
390
391/// Names of records some other record stores by value (`T`, `[T; N]`, or through a type alias),
392/// so their alignment is part of a containing layout.
393fn embedded_by_value<'a>(
394    base_files: &[&'a AbiFileDescriptor],
395    files: &[&'a AbiFileDescriptor],
396) -> BTreeSet<&'a str> {
397    let mut aliases: BTreeMap<&str, &str> = BTreeMap::new();
398    for a in base_files.iter().chain(files).flat_map(|f| f.aliases) {
399        aliases.insert(a.name, a.target);
400        if let Some(rn) = a.rust_name {
401            aliases.insert(rn, a.target);
402        }
403    }
404    let mut out = BTreeSet::new();
405    for record in files.iter().flat_map(|f| f.records) {
406        let fields = match record {
407            AbiRecordDescriptor::Struct(s) => s.fields,
408            AbiRecordDescriptor::Union(u) => u.fields,
409        };
410        for f in fields {
411            let mut ty = Ty::parse(f.abi_type());
412            for _ in 0..=aliases.len() {
413                while let Ok(Ty::Array { elem, .. }) = ty {
414                    ty = Ty::parse(elem);
415                }
416                let Ok(Ty::Named(name)) = ty else { break };
417                match aliases.get(name) {
418                    Some(target) => ty = Ty::parse(target),
419                    None => {
420                        out.insert(name);
421                        break;
422                    }
423                }
424            }
425        }
426    }
427    out
428}
429
430fn layout_record<'a>(
431    record: &'a AbiRecordDescriptor,
432    shapes: &BTreeMap<&str, Shape>,
433    enums: &BTreeSet<&str>,
434    callbacks: &BTreeSet<&str>,
435    embedded: &BTreeSet<&str>,
436) -> Result<RecordLayout<'a>, CodegenError> {
437    let (name, doc, is_union, descs, explicit_align) = match record {
438        AbiRecordDescriptor::Struct(s) => (s.name, s.doc, false, s.fields, s.explicit_align),
439        AbiRecordDescriptor::Union(u) => (u.name, u.doc, true, u.fields, u.explicit_align),
440    };
441    let mut fields = Vec::with_capacity(descs.len());
442    let (mut end, mut align) = (Width::same(0), Width::same(1));
443    for desc in descs {
444        let ty = Ty::parse(desc.abi_type())?;
445        let ctx = name;
446        let shape = shape_of(ty, shapes, enums, callbacks, ctx)?;
447        let offset = if is_union {
448            Width::same(0)
449        } else {
450            end.try_zip(shape.align, round_up, ctx)?
451        };
452        end = end.zip(
453            offset.try_zip(shape.size, usize::checked_add, ctx)?,
454            usize::max,
455        );
456        align = align.zip(shape.align, usize::max);
457        fields.push(FieldLayout { desc, ty, offset });
458    }
459    let natural_align = align;
460    let natural_size = end.try_zip(align, round_up, name)?;
461    let (mut alignas, mut slab_align) = (None, None);
462    if let Some(explicit) = explicit_align {
463        if !explicit.is_power_of_two() {
464            return Err(bad_type(name, "`align(N)` must be a non-zero power of two"));
465        }
466        if align.0.iter().any(|&n| explicit > n) {
467            let over = align.zip(Width::same(explicit), usize::max);
468            if explicit <= MAX_C_ALIGNAS {
469                alignas = Some(explicit);
470                align = over;
471            } else if natural_size.try_zip(over, round_up, name)? == natural_size
472                && !embedded.contains(name)
473            {
474                slab_align = Some(explicit);
475            } else {
476                return Err(bad_type(
477                    name,
478                    &format!(
479                        "`align({explicit})` changes the C layout, and C / Swift hosts cannot over-align past {MAX_C_ALIGNAS}"
480                    ),
481                ));
482            }
483        }
484    }
485    let size = end.try_zip(align, round_up, name)?;
486    Ok(RecordLayout {
487        name,
488        doc,
489        is_union,
490        size,
491        align,
492        fields,
493        alignas,
494        slab_align,
495        natural_align,
496    })
497}
498
499/// Largest `align(N)` C reproduces with `NV_ALIGNAS(N)` (Swift's ClangImporter rejects more).
500pub const MAX_C_ALIGNAS: usize = 16;
501
502/// `n` rounded up to `align` (a power of two, so never 0), or `None` on overflow.
503fn round_up(n: usize, align: usize) -> Option<usize> {
504    n.div_ceil(align).checked_mul(align)
505}
506
507/// `rustc`'s offsets are those of the running build; every declared contract must hold too.
508fn check_against_rustc(
509    record: &AbiRecordDescriptor,
510    layout: &RecordLayout<'_>,
511) -> Result<(), CodegenError> {
512    let (size, align, expected_size, expected_size_64) = match record {
513        AbiRecordDescriptor::Struct(s) => (s.size, s.align, s.expected_size, s.expected_size_64),
514        AbiRecordDescriptor::Union(u) => (u.size, u.align, u.expected_size, u.expected_size_64),
515    };
516    let host = Model::host();
517    let fail = |what: String| {
518        Err(CodegenError::validation(format!(
519            "`{}` C layout drifted from `rustc`: {what}",
520            layout.name
521        )))
522    };
523    if layout.size.at(host) != size {
524        return fail(format!("size {} != rustc {size}", layout.size.at(host)));
525    }
526    let c_align = layout.align.at(host);
527    if c_align.max(layout.slab_align.unwrap_or(1)) != align {
528        return fail(format!("alignment {c_align} != rustc {align}"));
529    }
530    if expected_size.is_some_and(|n| layout.size.fixed() != Some(n)) {
531        return fail(format!(
532            "size {:?} breaks the `size = {expected_size:?}` contract",
533            layout.size
534        ));
535    }
536    if expected_size_64.is_some_and(|n| layout.size.p64() != n) {
537        return fail(format!(
538            "64-bit size {} breaks `size_64 = {expected_size_64:?}`",
539            layout.size.p64()
540        ));
541    }
542    for f in &layout.fields {
543        let d = f.desc;
544        if f.offset.at(host) != d.offset {
545            return fail(format!(
546                "`{}` offset {} != rustc {}",
547                d.name,
548                f.offset.at(host),
549                d.offset
550            ));
551        }
552        if d.expected_offset
553            .is_some_and(|n| f.offset.fixed() != Some(n))
554        {
555            return fail(format!(
556                "`{}` offset {:?} breaks `offset = {:?}`",
557                d.name, f.offset, d.expected_offset
558            ));
559        }
560        if d.expected_offset_64.is_some_and(|n| f.offset.p64() != n) {
561            return fail(format!(
562                "`{}` 64-bit offset {} breaks `offset64`",
563                d.name,
564                f.offset.p64()
565            ));
566        }
567    }
568    Ok(())
569}
570
571mod vtable;
572
573pub use vtable::{VtableHeaderLayout, layout_vtable_headers_on};
574
575#[cfg(test)]
576mod tests;