From e998b33739512996ae86f9d17639cf4b17ca2437 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 18:15:58 -0800 Subject: [PATCH 01/12] chore(quest): claim quest/m1/ffi-packed-fields.md Quest-Claim: 769918d4897dc390 From cc2f82b624e0a80e7cf9bb62d17a1a38c04da378 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 19:30:24 -0800 Subject: [PATCH 02/12] feat(ffi): read a packed record's fields without a reference A repr(packed) struct's field that may lie unaligned is no reference's target (E0793), so the getter copies a Copy one out and reads any other unaligned into a ManuallyDrop its clone comes from. A lent field of one is refused unless aligned to 1. Co-Authored-By: Claude Sonnet 5.5 --- ffi/README.md | 2 +- ffi/fixtures/api/examples/transcript.rs | 21 ++++++++ ffi/fixtures/api/src/lib.rs | 68 +++++++++++++++++++++++++ ffi/fixtures/reject/expected.txt | 2 + ffi/fixtures/reject/src/lib.rs | 18 +++++++ ffi/src/collect.rs | 37 ++++++++++++-- ffi/src/glue.rs | 25 ++++++--- ffi/src/help.rs | 3 ++ ffi/src/ir.rs | 22 ++++++++ ffi/surface/api/c.h | 35 ++++++++++++- ffi/surface/api/cpp.hpp | 39 ++++++++++++++ ffi/surface/api/dart.dart | 31 +++++++++++ ffi/surface/api/go.txt | 36 +++++++++++++ ffi/surface/api/kotlin.kt | 39 ++++++++++++++ ffi/surface/api/python.pyi | 40 ++++++++++++++- ffi/surface/api/swift.swift | 30 +++++++++++ ffi/surface/api/web.d.ts | 46 +++++++++++++++++ ffi/tests/api.c | 36 +++++++++++++ quest/m1/ffi-packed-fields.md | 25 --------- 19 files changed, 517 insertions(+), 38 deletions(-) delete mode 100644 quest/m1/ffi-packed-fields.md diff --git a/ffi/README.md b/ffi/README.md index 8240ec21b..d51e68471 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -93,7 +93,7 @@ public path names, or an error taken by value, is held by value as an opaque han | any other type | an object: an opaque handle to an `Arc`, freed with `_free`; one that is `Copy`, such as std's `Instant`, whose padding a `rustc` may place anywhere, is copied out of its handle where Rust takes it by value, and a closure neither takes nor returns one by value; one that is not `Send`, such as kio's `clock::Entered`, stays on the thread that made it, as [the C ABI](#the-c-abi)'s threads say | | a type whose only generic parameters are lifetimes, such as `Path<'a>` | an object holding its `'static` form | | a generic type, at each instance it infers | that instance as any other type, with each method whose impl and own bounds it meets; any other instance is refused | -| a `pub` field of an object or opaque value | a getter returning a copy, and a setter assigning in place, as `x.field = value` does | +| a `pub` field of an object or opaque value | a getter returning a copy, and a setter assigning in place, as `x.field = value` does; a `repr(packed)` struct's field that may lie unaligned, which rustc lets no reference point at, is copied out if `Copy`, else read unaligned into a `ManuallyDrop`, which the struct still owns and drops, so one that must be lent instead, a field that is not `Clone`, is refused unless aligned to 1 | | a `pub` trait | a callback interface: a table of C functions and their data; a trait C cannot implement, such as one with a blanket impl, an associated type, or a supertrait but a marker, is left out, since C never passes one, and a signature taking one from C is refused | | a type parameter or `impl` bounded by `Fn`, `FnMut`, or `FnOnce` alone, taking what a callback takes, objects by reference, or opaque values, and returning a scalar, a `String`, an opaque value, an `Option` of one, or a `Result` of one and a `String` | a C function and its `void *` data; one a lifetime bound or the return lets outlive the call, as kio's `clock::drive` and a spawned task's are, adds a `free` Rust calls once it drops it; a closure of any other signature is refused | | a type parameter or `impl` taken by value and bounded by `Future` or `IntoFuture`, whose every bound `Pin + Send>>` meets, as kio's `clock::timeout` takes, or taken as `Pin<&mut F>` by a poll, as kio's `Waiter::poll_future` takes | `_foreign_future`: a future of `()` C implements, which Rust takes as that type, or which the future the poll makes owns and pins; a future of another output is refused | diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 5d2146ab2..4e1fee073 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -405,6 +405,27 @@ fn main() { let mut counted = kept; let same = api::Hits::eq(&mut counted, kept); println!("counted {same} {}", counted.hits); + // A packed value's fields are read into locals, as a reference to one is refused. + let mut regs = api::Regs::new(1, u64::MAX, Point { x: 3, y: -4 }); + let saved = regs; + regs.fcw = 9; + regs.at = Point { x: 5, y: 6 }; + let fcw = regs.fcw; + let wide = regs.wide; + let at = regs.at; + let tag = regs.tag; + let old_fcw = saved.fcw; + let old_wide = saved.wide; + let old_at = saved.at; + println!( + "regs {fcw} {wide} {} {} {tag} {} {old_fcw} {old_wide} {} {} {}", + at.x, + at.y, + regs.seed(), + old_at.x, + old_at.y, + regs == saved + ); let mut extent = api::Extent::new(5, 3); let start = extent; let old = extent.slide(10); diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 3cccad019..b79b01075 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -2165,6 +2165,74 @@ impl Hits { } } +/// A packed value, as redox_syscall's `FloatRegisters` is: its fields lie unaligned, which +/// rustc lets no reference point at, so a getter copies out its `u16`, `u64`, and record, +/// and borrows the `u8`, which no packing misaligns. +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(C, packed)] +pub struct Regs { + pub fcw: u16, + pub wide: u64, + pub at: Point, + pub tag: u8, + seed: u8, +} + +impl Regs { + pub fn new(fcw: u16, wide: u64, at: Point) -> Self { + Self { + fcw, + wide, + at, + tag: 7, + seed: 1, + } + } + + pub fn seed(&self) -> u8 { + self.seed + } +} + +/// A packed object: its `String` and `Option` lie unaligned, so a getter clones what it +/// reads out of the field without dropping the original, and its hasp, aligned to 1, is +/// lent from the folio in place. +#[repr(C, packed)] +pub struct Folio { + pub page: u16, + pub title: String, + pub note: Option, + pub hasp: Hasp, + seed: u8, +} + +impl Folio { + pub fn new(page: u16, title: &str) -> Self { + Self { + page, + title: title.to_string(), + note: None, + hasp: Hasp::default(), + seed: 3, + } + } + + pub fn seed(&self) -> u8 { + self.seed + } +} + +/// A flag that is not `Clone` and one byte wide, so aligned wherever it lies. +#[derive(Default)] +pub struct Hasp(std::sync::atomic::AtomicBool); + +impl Hasp { + /// Sets the flag, returning whether it was set already. + pub fn set(&self) -> bool { + self.0.swap(true, std::sync::atomic::Ordering::Relaxed) + } +} + /// A span whose `pub` start sits beside a private length, which no record could hold. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Extent { diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index a74489c77..1c8742983 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -156,6 +156,8 @@ fixtures/reject/src/lib.rs:1623:2: rust2-ffi: cannot export method `Knot>`: type argument `std::vec::Vec` help: instantiate it at types that map, such as integers, `String`, or an exported type; `&str`, `Cow`, and other borrows do not fixtures/reject/src/lib.rs:167:1: rust2-ffi: cannot export instance `Cell`: type argument `tls::held::Cert` diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index a40e5fcbe..ff87ea8e2 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1635,3 +1635,21 @@ impl Rope>> { #[allow(dead_code, reason = "private, so no part of the API")] fn private(&self) {} } + +/// A packed object whose field is not `Clone` and lies unaligned, so a getter has no copy to +/// return and no aligned field to lend: the getter is refused, the setter kept. +#[repr(C, packed)] +pub struct Packed { + pub lone: Lone, + seed: u8, +} + +pub fn packed() -> Packed { + Packed { lone: Lone(2), seed: 0 } +} + +impl Packed { + pub fn seed(&self) -> u8 { + self.seed + } +} diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 3d7c1ca1b..9b429022f 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -30,7 +30,7 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _ use crate::ir::{ Access, Api, Callback, Closure, Collection, Constant, Dyn, Enum, Family, Field, Function, Held, Home, Int, Jni, - Literal, Mutability, Object, On, Order, Param, Path, Receiver, Record, Task, TaskKind, Traits, Type, Variant, + Literal, Mutability, Object, On, Order, Param, Path, Read, Receiver, Record, Task, TaskKind, Traits, Type, Variant, }; /// Why something is refused: a construct, ranked by the census, and what it names. @@ -77,6 +77,9 @@ pub(crate) const UNHELD: [&str; 5] = [ /// implements and C cannot: no value C holds could be passed for it. const UNMET: &str = "bound no type C holds meets"; +/// The construct of a field lent from a `repr(packed)` struct, where it may lie unaligned. +const UNALIGNED: &str = "lent unaligned field"; + fn why(construct: &'static str, detail: impl Into) -> Why { Why { construct, @@ -2975,9 +2978,14 @@ impl<'tcx> Collector<'tcx> { let lends = handle && !self.is_clone(held) && matches!(object.kind(), ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))); + let how = self.field_read(site, ty); let mapped = { self.lending.set(lends); - let get = self.ty(read, Pos::Return); + // A lent field is the field itself, which an unaligned one cannot be. + let get = match lends && how != Read::Borrow { + true => Err(why(UNALIGNED, ty.to_string())), + false => self.ty(read, Pos::Return), + }; self.lending.set(false); // A handle outlives every call, so a reference it holds is `'static`, which // C's borrow for the call is not. @@ -2992,7 +3000,9 @@ impl<'tcx> Collector<'tcx> { // crate's is not, is still written: its getter alone is refused, and the // setter keeps the type in the API, so one no export returns leaves out // both. - (Err(get), Ok(Some(set))) if get.construct == "borrowed return that is not Clone" => { + (Err(get), Ok(Some(set))) + if get.construct == "borrowed return that is not Clone" || get.construct == UNALIGNED => + { self.refuse(&shown, "field", span, vec![get]); Ok((None, Some(set))) } @@ -3046,6 +3056,7 @@ impl<'tcx> Collector<'tcx> { access: Access::Field { set, through: !assigned, + read: how, }, instance: None, home: Home::default(), @@ -3071,6 +3082,26 @@ impl<'tcx> Collector<'tcx> { accessors } + /// How the glue reads a field of type `ty` of the struct `site`: rustc refuses a reference + /// to a `repr(packed)` struct's field whose alignment exceeds the packing (E0793), so + /// that one is copied out by value if it is `Copy`, else read unaligned into a + /// `ManuallyDrop`, which the getter takes its clone from, leaving the struct its owner. + fn field_read(&self, site: &Site<'tcx>, ty: Ty<'tcx>) -> Read { + let tcx = self.tcx; + let Some(pack) = tcx.adt_def(site.key.def_id).repr().pack else { + return Read::Borrow; + }; + let ty = tcx.erase_and_anonymize_regions(ty); + let input = TypingEnv::fully_monomorphized().as_query_input(ty); + if tcx.layout_of(input).is_ok_and(|layout| layout.align <= pack) { + return Read::Borrow; + } + match implements(tcx, ty, site.key.def_id, sym::Copy) { + true => Read::Copy, + false => Read::Take, + } + } + /// A value's methods, refusing each through `&mut self`: C passes the value as a copy, /// so what the method changes would be lost. fn unmutated(&mut self, methods: Vec) -> Vec { diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index a9f7d3505..b58e85131 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -16,7 +16,7 @@ use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, CFG, Ty}; use crate::config::Package; use crate::ir::{ - Access, Closure, Collection, Family, Function, Held, Jni, Literal, Mutability, On, Opaque, Receiver, Task, + Access, Closure, Collection, Family, Function, Held, Jni, Literal, Mutability, On, Opaque, Read, Receiver, Task, TaskKind, Traits, Type, }; @@ -2929,12 +2929,23 @@ impl Gen<'_> { ) } Access::Call => format!("{callee}({})", args.join(", ")), - Access::Field { set: false, through } => format!( - "&{}({}).{}", - if through { "*" } else { "" }, - args[0], - ident(function.name()) - ), + Access::Field { + set: false, + through, + read, + } => { + let deref = if through { "*" } else { "" }; + let field = format!("({}).{}", args[0], ident(function.name())); + // An unaligned field of a packed struct is no reference's target: it is + // copied out, or read into a `ManuallyDrop` that the struct still owns. + match read { + Read::Borrow => format!("&{deref}{field}"), + Read::Copy => format!("&{deref}{{ {field} }}"), + Read::Take => format!( + "&{deref}*::std::mem::ManuallyDrop::new(unsafe {{ ::std::ptr::addr_of!({field}).read_unaligned() }})" + ), + } + } Access::Field { set: true, .. } => format!("({}).{} = {}", args[0], ident(function.name()), args[1]), Access::Const => callee, Access::Parse => format!( diff --git a/ffi/src/help.rs b/ffi/src/help.rs index 9eaafa9a1..5c0e2c50e 100644 --- a/ffi/src/help.rs +++ b/ffi/src/help.rs @@ -133,6 +133,9 @@ pub(crate) fn of(construct: &str) -> Option<&'static str> { "borrowed return that is not Clone" => { "return an owned value or a `Clone` type, since a borrowed return crosses as a clone" } + "lent unaligned field" => { + "make the field `Clone` or a type aligned to 1, or take `repr(packed)` off the struct, since rustc refuses a reference to an unaligned field and a handle cannot be lent from a copy" + } "&mut of a slice" => { "take `&[u8]` and return the changed `Vec`, or hold the buffer in an object; C lends no buffer mutably" } diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 2922fd0ba..771156348 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -577,6 +577,8 @@ pub(crate) enum Access { set: bool, #[serde(default, skip_serializing_if = "std::ops::Not::not")] through: bool, + #[serde(default, skip_serializing_if = "Read::is_borrow")] + read: Read, }, /// It reads a constant that is not a `bool` or integer. Const, @@ -587,6 +589,26 @@ pub(crate) enum Access { Text, } +/// How a getter reads a field in Rust, which the field's struct decides: a `repr(packed)` +/// one's field may lie unaligned, which rustc refuses a reference to. +#[derive(Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(crate) enum Read { + /// It borrows the field. + #[default] + Borrow, + /// It copies the field out, as `Copy` allows of an unaligned one. + Copy, + /// It reads the field out unaligned into a `ManuallyDrop`, which never drops it: the + /// struct still owns and drops the original. + Take, +} + +impl Read { + fn is_borrow(&self) -> bool { + *self == Self::Borrow + } +} + impl Function { pub(crate) fn name(&self) -> &str { self.path.last().expect("a function has a name") diff --git a/ffi/surface/api/c.h b/ffi/surface/api/c.h index 6714df3f7..c659d6249 100644 --- a/ffi/surface/api/c.h +++ b/ffi/surface/api/c.h @@ -17,7 +17,7 @@ #ifdef __cplusplus extern "C" { #endif -#define API_CONTRACT ((uint64_t)0xd3f64c00ea2877f9ULL) +#define API_CONTRACT ((uint64_t)0x3906a14bfdda8e36ULL) uint64_t api_contract(void); uint32_t api_target(void); typedef int32_t api_status; @@ -114,6 +114,7 @@ typedef struct api_Waiter api_Waiter; typedef struct api_Feed api_Feed; typedef struct api_Countdown api_Countdown; typedef struct api_Retired api_Retired; +typedef struct api_Folio api_Folio; typedef struct api_Logger api_Logger; typedef struct api_Journal api_Journal; typedef struct api_Local api_Local; @@ -146,6 +147,7 @@ typedef struct api_Channel api_Channel; typedef struct api_Gap api_Gap; typedef struct api_Berth api_Berth; typedef struct api_Mark api_Mark; +typedef struct api_Hasp api_Hasp; typedef struct api_Message api_Message; typedef struct api_Node api_Node; typedef struct api_Tally api_Tally; @@ -725,6 +727,9 @@ typedef struct api_Rated { typedef struct api_Hits { uint64_t opaque[2]; } api_Hits; +typedef struct api_Regs { + uint8_t opaque[20]; +} api_Regs; typedef struct api_Extent { uint64_t opaque[2]; } api_Extent; @@ -1323,6 +1328,18 @@ void api_Hits_misses_set(api_Hits *self, uint64_t value); api_Hits api_Hits_of(uint64_t hits, uint64_t misses); void api_Hits_add(api_Hits *self, api_Hits other); bool api_Hits_eq_(api_Hits *self, api_Hits other); +bool api_Regs_eq(const api_Regs *a, const api_Regs *b); +API_MUST_USE api_buf api_Regs_debug(const api_Regs *self); +uint16_t api_Regs_fcw_get(const api_Regs *self); +void api_Regs_fcw_set(api_Regs *self, uint16_t value); +uint64_t api_Regs_wide_get(const api_Regs *self); +void api_Regs_wide_set(api_Regs *self, uint64_t value); +api_Point api_Regs_at_get(const api_Regs *self); +void api_Regs_at_set(api_Regs *self, api_Point value); +uint8_t api_Regs_tag_get(const api_Regs *self); +void api_Regs_tag_set(api_Regs *self, uint8_t value); +api_Regs api_Regs_new(uint16_t fcw, uint64_t wide, api_Point at); +uint8_t api_Regs_seed(const api_Regs *self); bool api_Extent_eq(const api_Extent *a, const api_Extent *b); API_MUST_USE api_buf api_Extent_debug(const api_Extent *self); uint64_t api_Extent_start_get(const api_Extent *self); @@ -1678,6 +1695,18 @@ API_MUST_USE api_Retired_next_future *api_Retired_next(api_Retired *self, api_st API_MUST_USE api_poll api_Retired_next_start(api_Retired *self, api_option_u32 *out, api_Retired_next_future **future, api_status *status); API_MUST_USE api_poll api_Retired_next_poll(api_Retired_next_future *future, api_waker waker, api_option_u32 *out); void api_Retired_next_future_free(api_Retired_next_future *future); +void api_Folio_free(api_Folio *self); +void api_Folio_drop(api_Folio *self, api_status *status); +uint16_t api_Folio_page_get(const api_Folio *self, api_status *status); +void api_Folio_page_set(api_Folio *self, uint16_t value, api_status *status); +API_MUST_USE api_buf api_Folio_title_get(const api_Folio *self, api_status *status); +void api_Folio_title_set(api_Folio *self, api_buf value, api_status *status); +API_MUST_USE api_buf api_Folio_note_get(const api_Folio *self, api_status *status); +void api_Folio_note_set(api_Folio *self, api_buf value, api_status *status); +API_MUST_USE api_Hasp *api_Folio_hasp_get(const api_Folio *self, api_status *status); +void api_Folio_hasp_set(api_Folio *self, api_Hasp *value, api_status *status); +API_MUST_USE api_Folio *api_Folio_new(uint16_t page, api_buf title); +uint8_t api_Folio_seed(const api_Folio *self, api_status *status); void api_Logger_free(api_Logger *self); API_MUST_USE api_Logger *api_Logger_new(api_Log sink); bool api_Logger_write(const api_Logger *self, api_buf line); @@ -1985,6 +2014,10 @@ API_MUST_USE api_buf api_Mark_debug(const api_Mark *self, api_status *status); API_MUST_USE api_Mark *api_Mark_of(uint64_t count); uint64_t api_Mark_count(const api_Mark *self, api_status *status); void api_Mark_add(api_Mark *self, uint64_t by, api_status *status); +void api_Hasp_free(api_Hasp *self); +void api_Hasp_drop(api_Hasp *self, api_status *status); +API_MUST_USE api_Hasp *api_Hasp_default(void); +bool api_Hasp_set(const api_Hasp *self, api_status *status); void api_Message_free(api_Message *self); void api_Message_drop(api_Message *self, api_status *status); API_MUST_USE api_Message *api_Message_clone(const api_Message *self, api_status *status); diff --git a/ffi/surface/api/cpp.hpp b/ffi/surface/api/cpp.hpp index 3c09ce4fc..5747e840a 100644 --- a/ffi/surface/api/cpp.hpp +++ b/ffi/surface/api/cpp.hpp @@ -162,6 +162,20 @@ namespace api { static ::api::Retired new_(::std::uint32_t from); [[deprecated("count with `Countdown`")]] RUST2_FFI_CALLABLE ::api::Retired_next_future next(); }; + class RUST2_FFI_CONSUMABLE Folio { + RUST2_FFI_UNCONSUMED Folio(Folio &&other RUST2_FFI_MOVED_FROM) noexcept = default; + Folio &operator=(Folio &&other) noexcept = default; + RUST2_FFI_CALLABLE ::std::uint16_t page_get() const; + RUST2_FFI_CALLABLE void page_set(::std::uint16_t value); + RUST2_FFI_CALLABLE ::api::buf title_get() const; + RUST2_FFI_CALLABLE void title_set(::api::input value); + RUST2_FFI_CALLABLE ::std::optional<::api::buf> note_get() const; + RUST2_FFI_CALLABLE void note_set(::std::optional<::api::input> value); + RUST2_FFI_CALLABLE ::api::Hasp hasp_get() const; + RUST2_FFI_CALLABLE void hasp_set(::api::Hasp value); + static ::api::Folio new_(::std::uint16_t page, ::api::input title); + RUST2_FFI_CALLABLE ::std::uint8_t seed() const; + }; class RUST2_FFI_CONSUMABLE Logger { RUST2_FFI_UNCONSUMED Logger(Logger &&other RUST2_FFI_MOVED_FROM) noexcept = default; Logger &operator=(Logger &&other) noexcept = default; @@ -476,6 +490,12 @@ namespace api { RUST2_FFI_CALLABLE ::std::uint64_t count() const; RUST2_FFI_CALLABLE void add(::std::uint64_t by); }; + class RUST2_FFI_CONSUMABLE Hasp { + RUST2_FFI_UNCONSUMED Hasp(Hasp &&other RUST2_FFI_MOVED_FROM) noexcept = default; + Hasp &operator=(Hasp &&other) noexcept = default; + static Hasp default_(); + RUST2_FFI_CALLABLE bool set() const; + }; class RUST2_FFI_CONSUMABLE Message { RUST2_FFI_UNCONSUMED Message(Message &&other RUST2_FFI_MOVED_FROM) noexcept = default; Message &operator=(Message &&other) noexcept = default; @@ -948,6 +968,21 @@ namespace api { void add(const ::api::Hits &other); bool eq_(const ::api::Hits &other); }; + class Regs { + friend bool operator==(const Regs &a__, const Regs &b_); + friend bool operator!=(const Regs &a__, const Regs &b_); + ::api::buf debug() const; + ::std::uint16_t fcw_get() const; + void fcw_set(::std::uint16_t value); + ::std::uint64_t wide_get() const; + void wide_set(::std::uint64_t value); + ::api::Point at_get() const; + void at_set(const ::api::Point &value); + ::std::uint8_t tag_get() const; + void tag_set(::std::uint8_t value); + static ::api::Regs new_(::std::uint16_t fcw, ::std::uint64_t wide, const ::api::Point &at); + ::std::uint8_t seed() const; + }; class Extent { friend bool operator==(const Extent &a__, const Extent &b_); friend bool operator!=(const Extent &a__, const Extent &b_); @@ -1448,6 +1483,7 @@ namespace api { inline bool operator==(const Clocked &a__, const Clocked &b_); inline bool operator==(const Rated &a__, const Rated &b_); inline bool operator==(const Hits &a__, const Hits &b_); + inline bool operator==(const Regs &a__, const Regs &b_); inline bool operator==(const Extent &a__, const Extent &b_); inline bool operator==(const Pair_Size_u8 &a__, const Pair_Size_u8 &b_); inline bool operator==(const Pair_non_zero_u16 &a__, const Pair_non_zero_u16 &b_); @@ -2209,6 +2245,7 @@ namespace api { class Rated; class Score; class Hits; + class Regs; class Extent; struct Pair_Size_u8; struct Pair_non_zero_u16; @@ -2271,6 +2308,7 @@ namespace api { class Feed; class Countdown; class Retired; + class Folio; class Logger; class Journal; class Local; @@ -2303,6 +2341,7 @@ namespace api { class Gap; class Berth; class Mark; + class Hasp; class Message; class Node; class Tally; diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index 3cf6eadf5..5cbf0d566 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -370,6 +370,21 @@ final class Hits { Hits add(Hits other); (Hits, bool) eq(Hits other); } +final class Regs { + String debug(); + @override bool operator ==(Object other); + @override int get hashCode; + int get fcwGet; + Regs fcwSet(int value); + U64 get wideGet; + Regs wideSet(U64 value); + Point get atGet; + Regs atSet(Point value); + int get tagGet; + Regs tagSet(int value); + factory Regs(int fcw, U64 wide, Point at); + int seed(); +} final class Extent { String debug(); @override bool operator ==(Object other); @@ -1189,6 +1204,18 @@ final class Retired extends _Object { @Deprecated('count with `Countdown`') Cancelable next(); @Deprecated('count with `Countdown`') dasync.Stream asStream(); } +final class Folio extends _Object { + int get pageGet; + void pageSet(int value); + String get titleGet; + void titleSet(String value); + String? get noteGet; + void noteSet(String? value); + Hasp get haspGet; + void haspSet(Hasp value); + factory Folio(int page, String title); + int seed(); +} final class Logger extends _Object { factory Logger(Log sink); bool write(String line); @@ -1446,6 +1473,10 @@ final class Mark extends _Object { U64 count(); void add(U64 by); } +final class Hasp extends _Object { + factory Hasp.default_(); + bool set(); +} final class Message extends _Object { String debug(); Message clone(); diff --git a/ffi/surface/api/go.txt b/ffi/surface/api/go.txt index 578002b54..705b341e6 100644 --- a/ffi/surface/api/go.txt +++ b/ffi/surface/api/go.txt @@ -964,6 +964,20 @@ type FiledReceipt struct { func (self *FiledReceipt) Clone() (*FiledReceipt, error) func (self *FiledReceipt) Close() error func (self *FiledReceipt) Count() (uint32, error) +type Folio struct { + Handle_ *p_rt.Handle_ +} +func NewFolio(page uint16, title string) (*Folio, error) +func (self *Folio) Close() error +func (self *Folio) HaspGet() (*Hasp, error) +func (self *Folio) HaspSet(value *Hasp) error +func (self *Folio) NoteGet() (*string, error) +func (self *Folio) NoteSet(value *string) error +func (self *Folio) PageGet() (uint16, error) +func (self *Folio) PageSet(value uint16) error +func (self *Folio) Seed() (uint8, error) +func (self *Folio) TitleGet() (string, error) +func (self *Folio) TitleSet(value string) error type Forged struct { Handle_ *p_rt.Handle_ } @@ -1003,6 +1017,12 @@ func (self *Handle) Count() (uint32, error) type Hasher struct { Seed uint8 } +type Hasp struct { + Handle_ *p_rt.Handle_ +} +func HaspDefault() *Hasp +func (self *Hasp) Close() error +func (self *Hasp) Set() (bool, error) type Hits struct { Bytes_ [2]uint64 Made_ bool @@ -1607,6 +1627,22 @@ func (self *Registry) FirstGet() (*Counter, error) func (self *Registry) FirstSet(value *Counter) error func (self *Registry) Last() (*Counter, error) func (self *Registry) Push(counter *Counter) error +type Regs struct { + Bytes_ [20]uint8 + Made_ bool +} +func NewRegs(fcw uint16, wide uint64, at Point) Regs +func (self Regs) AtGet() Point +func (self *Regs) AtSet(value Point) +func (self Regs) Equal(other Regs) bool +func (self Regs) FcwGet() uint16 +func (self *Regs) FcwSet(value uint16) +func (self Regs) GoString() string +func (self Regs) Seed() uint8 +func (self Regs) TagGet() uint8 +func (self *Regs) TagSet(value uint8) +func (self Regs) WideGet() uint64 +func (self *Regs) WideSet(value uint64) type Resolving struct { Handle_ *p_rt.Handle_ } diff --git a/ffi/surface/api/kotlin.kt b/ffi/surface/api/kotlin.kt index 2b4e931e3..c30b0e51b 100644 --- a/ffi/surface/api/kotlin.kt +++ b/ffi/surface/api/kotlin.kt @@ -249,6 +249,23 @@ class Hits internal constructor() { @kotlin.jvm.JvmStatic fun of(hits: kotlin.ULong, misses: kotlin.ULong): api.Hits } } +class Regs internal constructor() { + fun debug(): kotlin.String + override fun equals(other: kotlin.Any?): kotlin.Boolean + override fun hashCode(): kotlin.Int + val fcwGet: kotlin.UShort + fun fcwSet(value: kotlin.UShort): api.Regs + val wideGet: kotlin.ULong + fun wideSet(value: kotlin.ULong): api.Regs + val atGet: api.Point + fun atSet(value: api.Point): api.Regs + val tagGet: kotlin.UByte + fun tagSet(value: kotlin.UByte): api.Regs + fun seed(): kotlin.UByte + companion object { + @kotlin.jvm.JvmStatic fun new(fcw: kotlin.UShort, wide: kotlin.ULong, at: api.Point): api.Regs + } +} class Extent internal constructor() { fun debug(): kotlin.String override fun equals(other: kotlin.Any?): kotlin.Boolean @@ -752,6 +769,21 @@ class Retired internal constructor(raw: Long, lent: Boolean = false) : AutoClose @kotlin.jvm.JvmStatic fun new(from: kotlin.UInt): api.Retired } } +class Folio internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { + override fun close() + val pageGet: kotlin.UShort + fun pageSet(value: kotlin.UShort) + val titleGet: kotlin.String + fun titleSet(value: kotlin.String) + val noteGet: kotlin.String? + fun noteSet(value: kotlin.String?) + val haspGet: api.Hasp + fun haspSet(value: api.Hasp) + fun seed(): kotlin.UByte + companion object { + @kotlin.jvm.JvmStatic fun new(page: kotlin.UShort, title: kotlin.String): api.Folio + } +} class Logger internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { override fun close() fun write(line: kotlin.String): kotlin.Boolean @@ -1102,6 +1134,13 @@ class Mark internal constructor(raw: Long, lent: Boolean = false) : AutoCloseabl @kotlin.jvm.JvmStatic fun of(count: kotlin.ULong): api.Mark } } +class Hasp internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { + override fun close() + fun set(): kotlin.Boolean + companion object { + @kotlin.jvm.JvmStatic fun default(): api.Hasp + } +} class Message internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { override fun close() fun debug(): kotlin.String diff --git a/ffi/surface/api/python.pyi b/ffi/surface/api/python.pyi index 1fef00d2e..e8aa606c2 100644 --- a/ffi/surface/api/python.pyi +++ b/ffi/surface/api/python.pyi @@ -1,5 +1,5 @@ # api.py -__all__ = ['A', 'Area', 'Array', 'ArrayU8x4', 'Atlas', 'B', 'BOXED', 'Batch', 'Batch2', 'Beat', 'Berth', 'Board', 'Booth', 'Bound', 'BoundU64', 'BoundsU64', 'BoundsU64Exception', 'BoxedU16', 'BoxedU8', 'Builtin', 'C', 'CancellationError', 'Cancelled', 'Channel', 'Choice', 'Clash', 'ClashAny', 'ClashBreak', 'ClashCandidate', 'ClashEmptyString', 'ClashErrno', 'ClashEscaped', 'ClashLevel', 'ClashMalformed', 'ClashMalformedException', 'ClashReader', 'ClashSeed', 'ClashSource', 'ClashSpan', 'ClashStore', 'ClashTag', 'ClashTone', 'ClashTone_', 'Clocked', 'Codecs', 'Core', 'Countdown', 'Counter', 'Cursor', 'Deprecated', 'Der', 'Dial', 'Digest', 'DoubleArray', 'Draft', 'Duration', 'EOF', 'Error', 'ErrorException', 'Event', 'Extent', 'FAR', 'Family', 'Fault', 'FaultException', 'Feed', 'FiledReceipt', 'ForeignReader', 'Forged', 'GREETINGS', 'Gap', 'Gauge', 'Handle', 'Hasher', 'Hits', 'Holder', 'Hooked', 'InnerU8', 'Instant', 'Journal', 'Json', 'JvmField', 'JvmStatic', 'Key', 'Knob', 'LIMIT', 'Label', 'Labeled', 'Labelled', 'Latch', 'Layered', 'Ledger', 'LeftRightU8', 'LeftU8', 'Level', 'LimitsBytes', 'LimitsDuration', 'ListClashToneException', 'Local', 'LocalWaiter', 'Log', 'LogCount', 'LogThread', 'Logger', 'LongArray', 'MacrosStreams', 'Mark', 'Marker', 'Measure', 'Message', 'Meter', 'Meters', 'Moment', 'Mut', 'Name', 'Node', 'NonZeros', 'Note', 'Numbers', 'OptIn', 'OuterInnerU8', 'PRIMES', 'Packaged', 'Packet', 'PadU16', 'PadU8', 'Page', 'PairNonZeroU16', 'PairSizeU8', 'PairU32', 'PairU8Size', 'Parcel', 'Part', 'Pass', 'Peer', 'Pinned', 'Placement', 'Plain', 'Platform', 'Point', 'PolarPoint', 'PolarTurn', 'Polar_Turn', 'Qualifiers', 'Quantity', 'Rank', 'Rated', 'Reading', 'Receipt', 'Refusal', 'RefusalException', 'Registry', 'Resolving', 'Retired', 'Retry', 'RightLeftU8', 'RightU8', 'STEP', 'Scan', 'Score', 'Seat', 'Shadowed', 'Shape', 'Sheet', 'Site', 'Size', 'Slip', 'SlotU32', 'SlotU8', 'Span', 'Spawned', 'Spot', 'Stack', 'Stage', 'Stamp', 'Stamped', 'StartSeekable', 'Status', 'StdIoError', 'StringException', 'Tab', 'Tallies', 'Tally', 'Ticket', 'Tier', 'TlsCert', 'TlsCodec', 'TlsConfig', 'TlsPolicyLifetime', 'TlsResolver', 'TlsSession', 'Token', 'Trail', 'Turner', 'URL', 'Undo', 'Url', 'VecClashTone', 'Verbosity', 'Version', 'Waiter', 'Waker', 'Weighted', 'Wide', 'Window', 'Worker', 'WrapU32', '__all___', '_deprecated_', 'admit', 'advance', 'after', 'alpn', 'alpn_lent', 'apply_non_zero_u16', 'apply_u32', 'area', 'assert_', 'attempt', 'beats', 'below', 'booth_count', 'boxed_counter', 'boxed_floats', 'boxed_name', 'boxed_tuple', 'breadth', 'bump_both', 'bump_either', 'byte_len', 'byte_limits', 'capacities_2_2', 'capacities_2_4', 'capacities_4_2', 'capacities_4_4', 'cert_der', 'cert_len', 'certify', 'chain_len', 'choose', 'chunks', 'clash_any', 'clash_audible', 'clash_audio_encoder_finish', 'clash_audio_encoder_finish_', 'clash_candidate', 'clash_empty', 'clash_ignore', 'clash_nested', 'clash_waited', 'clocked_after', 'coordinates', 'corner', 'corner_later', 'count', 'counted', 'counters', 'crammed', 'cross', 'crowded', 'deprecated', 'describe', 'describe_non_zeros', 'digit', 'divide', 'doubled', 'doubled_i64', 'doubled_ttl', 'drain_2', 'drain_4', 'drive', 'dropped', 'each', 'either', 'either_later', 'emit', 'emit_from_thread', 'emit_later', 'encode', 'end', 'ends', 'entries', 'erased', 'errno', 'excuse', 'extended', 'failure', 'failure_kind', 'failure_message', 'farther_hop', 'file', 'fill_2', 'fill_4', 'filter', 'find', 'fingerprint', 'first_of', 'flip', 'greet', 'grow', 'halved', 'halves', 'has_instant', 'has_text', 'heft', 'held_count', 'hex', 'hook', 'host', 'is_family', 'is_kept', 'jam', 'jni_one', 'join_words', 'joined', 'jvm_sum', 'keep_point', 'keeper_point', 'keeps', 'kept_counter', 'kept_or_point', 'kept_point', 'kept_polar_point', 'kept_size', 'kept_wrap_u32', 'knob', 'lasting', 'later', 'layer_name', 'least', 'len', 'lent_back', 'less', 'level_later', 'local_after', 'local_later', 'local_or_new', 'local_or_new_later', 'locals_dropped', 'log_counts', 'log_later', 'log_on_drop', 'log_waker', 'longer', 'longest', 'louder', 'macros_streamed', 'made', 'marked', 'moment_at', 'named', 'next_char', 'next_hop', 'next_ips', 'next_packet', 'nexts', 'non_zeros', 'now', 'nudge', 'nudge_by', 'numbered', 'offered_len', 'offset', 'offsetof', 'on_first_thread', 'only', 'page', 'pair', 'parents', 'parse_cert', 'parse_later', 'peek', 'placement', 'platform', 'pointer_bits', 'polar_point', 'poll_tripled', 'port', 'ports', 'prefixed', 'push_counted', 'put_number', 'queued_hex', 'reach', 'read_len', 'reading', 'reading_bump', 'reading_debug', 'reading_echo', 'reasons', 'refuse', 'reissue', 'reissue_lent', 'relay', 'report_non_zero_u16', 'report_u32', 'resolve', 'resolved', 'resolver', 'resume', 'return_moved', 'return_values', 'rooted_name', 'rows', 'same', 'same_char', 'same_duration', 'same_ip_addr', 'same_isize', 'same_labelled', 'same_path', 'same_socket_addr', 'same_socket_addr_v4', 'same_socket_addr_v6', 'same_string', 'same_u128', 'same_u64', 'same_usize', 'sample_hex', 'scaled', 'scanned', 'seat', 'second_later', 'sections', 'secure', 'seeds_counter_counter', 'seeds_counter_point', 'seeds_counter_polar_point', 'seeds_counter_size', 'seeds_counter_wrap_u32', 'seeds_point_counter', 'seeds_point_point', 'seeds_point_polar_point', 'seeds_point_size', 'seeds_point_wrap_u32', 'seek_to', 'sentence', 'shift', 'shifted', 'since', 'span', 'spell', 'spend', 'split_last', 'spread', 'stamp_at', 'stored', 'stored_text', 'stray', 'sum_all', 'sum_lists', 'sum_u32', 'summed', 'summed_up_receipt', 'sums', 'swapped', 'tag', 'tagged', 'tail', 'tallied', 'tally_log_count', 'tick_name', 'tickets', 'timed_hex', 'title', 'token_bytes', 'token_slice', 'total', 'turned', 'undone', 'unescaped', 'unescaped_later', 'unescaped_maybe', 'unhook', 'unnamed', 'unzeroed', 'verify', 'visit_chunks', 'visit_stray', 'walk', 'wasm_log', 'wasm_only', 'wasm_take', 'watch', 'weigh_all_counter', 'weigh_point', 'wexitstatus', 'wide', 'widen', 'widths', 'wind', 'within', 'words', 'worth', 'yielded'] +__all__ = ['A', 'Area', 'Array', 'ArrayU8x4', 'Atlas', 'B', 'BOXED', 'Batch', 'Batch2', 'Beat', 'Berth', 'Board', 'Booth', 'Bound', 'BoundU64', 'BoundsU64', 'BoundsU64Exception', 'BoxedU16', 'BoxedU8', 'Builtin', 'C', 'CancellationError', 'Cancelled', 'Channel', 'Choice', 'Clash', 'ClashAny', 'ClashBreak', 'ClashCandidate', 'ClashEmptyString', 'ClashErrno', 'ClashEscaped', 'ClashLevel', 'ClashMalformed', 'ClashMalformedException', 'ClashReader', 'ClashSeed', 'ClashSource', 'ClashSpan', 'ClashStore', 'ClashTag', 'ClashTone', 'ClashTone_', 'Clocked', 'Codecs', 'Core', 'Countdown', 'Counter', 'Cursor', 'Deprecated', 'Der', 'Dial', 'Digest', 'DoubleArray', 'Draft', 'Duration', 'EOF', 'Error', 'ErrorException', 'Event', 'Extent', 'FAR', 'Family', 'Fault', 'FaultException', 'Feed', 'FiledReceipt', 'Folio', 'ForeignReader', 'Forged', 'GREETINGS', 'Gap', 'Gauge', 'Handle', 'Hasher', 'Hasp', 'Hits', 'Holder', 'Hooked', 'InnerU8', 'Instant', 'Journal', 'Json', 'JvmField', 'JvmStatic', 'Key', 'Knob', 'LIMIT', 'Label', 'Labeled', 'Labelled', 'Latch', 'Layered', 'Ledger', 'LeftRightU8', 'LeftU8', 'Level', 'LimitsBytes', 'LimitsDuration', 'ListClashToneException', 'Local', 'LocalWaiter', 'Log', 'LogCount', 'LogThread', 'Logger', 'LongArray', 'MacrosStreams', 'Mark', 'Marker', 'Measure', 'Message', 'Meter', 'Meters', 'Moment', 'Mut', 'Name', 'Node', 'NonZeros', 'Note', 'Numbers', 'OptIn', 'OuterInnerU8', 'PRIMES', 'Packaged', 'Packet', 'PadU16', 'PadU8', 'Page', 'PairNonZeroU16', 'PairSizeU8', 'PairU32', 'PairU8Size', 'Parcel', 'Part', 'Pass', 'Peer', 'Pinned', 'Placement', 'Plain', 'Platform', 'Point', 'PolarPoint', 'PolarTurn', 'Polar_Turn', 'Qualifiers', 'Quantity', 'Rank', 'Rated', 'Reading', 'Receipt', 'Refusal', 'RefusalException', 'Registry', 'Regs', 'Resolving', 'Retired', 'Retry', 'RightLeftU8', 'RightU8', 'STEP', 'Scan', 'Score', 'Seat', 'Shadowed', 'Shape', 'Sheet', 'Site', 'Size', 'Slip', 'SlotU32', 'SlotU8', 'Span', 'Spawned', 'Spot', 'Stack', 'Stage', 'Stamp', 'Stamped', 'StartSeekable', 'Status', 'StdIoError', 'StringException', 'Tab', 'Tallies', 'Tally', 'Ticket', 'Tier', 'TlsCert', 'TlsCodec', 'TlsConfig', 'TlsPolicyLifetime', 'TlsResolver', 'TlsSession', 'Token', 'Trail', 'Turner', 'URL', 'Undo', 'Url', 'VecClashTone', 'Verbosity', 'Version', 'Waiter', 'Waker', 'Weighted', 'Wide', 'Window', 'Worker', 'WrapU32', '__all___', '_deprecated_', 'admit', 'advance', 'after', 'alpn', 'alpn_lent', 'apply_non_zero_u16', 'apply_u32', 'area', 'assert_', 'attempt', 'beats', 'below', 'booth_count', 'boxed_counter', 'boxed_floats', 'boxed_name', 'boxed_tuple', 'breadth', 'bump_both', 'bump_either', 'byte_len', 'byte_limits', 'capacities_2_2', 'capacities_2_4', 'capacities_4_2', 'capacities_4_4', 'cert_der', 'cert_len', 'certify', 'chain_len', 'choose', 'chunks', 'clash_any', 'clash_audible', 'clash_audio_encoder_finish', 'clash_audio_encoder_finish_', 'clash_candidate', 'clash_empty', 'clash_ignore', 'clash_nested', 'clash_waited', 'clocked_after', 'coordinates', 'corner', 'corner_later', 'count', 'counted', 'counters', 'crammed', 'cross', 'crowded', 'deprecated', 'describe', 'describe_non_zeros', 'digit', 'divide', 'doubled', 'doubled_i64', 'doubled_ttl', 'drain_2', 'drain_4', 'drive', 'dropped', 'each', 'either', 'either_later', 'emit', 'emit_from_thread', 'emit_later', 'encode', 'end', 'ends', 'entries', 'erased', 'errno', 'excuse', 'extended', 'failure', 'failure_kind', 'failure_message', 'farther_hop', 'file', 'fill_2', 'fill_4', 'filter', 'find', 'fingerprint', 'first_of', 'flip', 'greet', 'grow', 'halved', 'halves', 'has_instant', 'has_text', 'heft', 'held_count', 'hex', 'hook', 'host', 'is_family', 'is_kept', 'jam', 'jni_one', 'join_words', 'joined', 'jvm_sum', 'keep_point', 'keeper_point', 'keeps', 'kept_counter', 'kept_or_point', 'kept_point', 'kept_polar_point', 'kept_size', 'kept_wrap_u32', 'knob', 'lasting', 'later', 'layer_name', 'least', 'len', 'lent_back', 'less', 'level_later', 'local_after', 'local_later', 'local_or_new', 'local_or_new_later', 'locals_dropped', 'log_counts', 'log_later', 'log_on_drop', 'log_waker', 'longer', 'longest', 'louder', 'macros_streamed', 'made', 'marked', 'moment_at', 'named', 'next_char', 'next_hop', 'next_ips', 'next_packet', 'nexts', 'non_zeros', 'now', 'nudge', 'nudge_by', 'numbered', 'offered_len', 'offset', 'offsetof', 'on_first_thread', 'only', 'page', 'pair', 'parents', 'parse_cert', 'parse_later', 'peek', 'placement', 'platform', 'pointer_bits', 'polar_point', 'poll_tripled', 'port', 'ports', 'prefixed', 'push_counted', 'put_number', 'queued_hex', 'reach', 'read_len', 'reading', 'reading_bump', 'reading_debug', 'reading_echo', 'reasons', 'refuse', 'reissue', 'reissue_lent', 'relay', 'report_non_zero_u16', 'report_u32', 'resolve', 'resolved', 'resolver', 'resume', 'return_moved', 'return_values', 'rooted_name', 'rows', 'same', 'same_char', 'same_duration', 'same_ip_addr', 'same_isize', 'same_labelled', 'same_path', 'same_socket_addr', 'same_socket_addr_v4', 'same_socket_addr_v6', 'same_string', 'same_u128', 'same_u64', 'same_usize', 'sample_hex', 'scaled', 'scanned', 'seat', 'second_later', 'sections', 'secure', 'seeds_counter_counter', 'seeds_counter_point', 'seeds_counter_polar_point', 'seeds_counter_size', 'seeds_counter_wrap_u32', 'seeds_point_counter', 'seeds_point_point', 'seeds_point_polar_point', 'seeds_point_size', 'seeds_point_wrap_u32', 'seek_to', 'sentence', 'shift', 'shifted', 'since', 'span', 'spell', 'spend', 'split_last', 'spread', 'stamp_at', 'stored', 'stored_text', 'stray', 'sum_all', 'sum_lists', 'sum_u32', 'summed', 'summed_up_receipt', 'sums', 'swapped', 'tag', 'tagged', 'tail', 'tallied', 'tally_log_count', 'tick_name', 'tickets', 'timed_hex', 'title', 'token_bytes', 'token_slice', 'total', 'turned', 'undone', 'unescaped', 'unescaped_later', 'unescaped_maybe', 'unhook', 'unnamed', 'unzeroed', 'verify', 'visit_chunks', 'visit_stray', 'walk', 'wasm_log', 'wasm_only', 'wasm_take', 'watch', 'weigh_all_counter', 'weigh_point', 'wexitstatus', 'wide', 'widen', 'widths', 'wind', 'within', 'words', 'worth', 'yielded'] class Waker: def __init__(self, wake: _typing.Callable[[], _object], loop: _asyncio.AbstractEventLoop | None=None) -> None: ... def wake(self) -> None: ... @@ -229,6 +229,24 @@ class Hits(_n.Value): def of(hits: _int, misses: _int) -> Hits: ... def add(self, other: Hits) -> Hits: ... def eq(self, other: Hits) -> _tuple[Hits, _bool]: ... +class Regs(_n.Value): + def __eq__(self, other: _object) -> _bool: ... + def __repr__(self) -> _str: ... + @_property + def fcw_get(self) -> _int: ... + def fcw_set(self, value: _int) -> Regs: ... + @_property + def wide_get(self) -> _int: ... + def wide_set(self, value: _int) -> Regs: ... + @_property + def at_get(self) -> Point: ... + def at_set(self, value: Point) -> Regs: ... + @_property + def tag_get(self) -> _int: ... + def tag_set(self, value: _int) -> Regs: ... + @_staticmethod + def new(fcw: _int, wide: _int, at: Point) -> Regs: ... + def seed(self) -> _int: ... class Extent(_n.Value): def __eq__(self, other: _object) -> _bool: ... def __repr__(self) -> _str: ... @@ -950,6 +968,22 @@ class Retired(_n.Object): async def __anext__(self) -> _int: ... @_staticmethod def new(from_: _int) -> Retired: ... +class Folio(_n.Object): + @_property + def page_get(self) -> _int: ... + def page_set(self, value: _int) -> None: ... + @_property + def title_get(self) -> _str: ... + def title_set(self, value: _str) -> None: ... + @_property + def note_get(self) -> _str | None: ... + def note_set(self, value: _str | None) -> None: ... + @_property + def hasp_get(self) -> Hasp: ... + def hasp_set(self, value: Hasp) -> None: ... + @_staticmethod + def new(page: _int, title: _str) -> Folio: ... + def seed(self) -> _int: ... class Logger(_n.Object): @_staticmethod def new(sink: Log) -> Logger: ... @@ -1233,6 +1267,10 @@ class Mark(_n.Object): def of(count: _int) -> Mark: ... def count(self) -> _int: ... def add(self, by: _int) -> None: ... +class Hasp(_n.Object): + @_staticmethod + def default() -> Hasp: ... + def set(self) -> _bool: ... class Message(_n.Object): def __repr__(self) -> _str: ... def clone(self) -> Message: ... diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index 2fd527399..cdeb2c2f4 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -361,6 +361,20 @@ public struct Hits: Sendable, CustomDebugStringConvertible, Equatable { @inlinable public mutating func add(_ other: Hits) @inlinable public mutating func eq(_ other: Hits) -> Swift.Bool } +public struct Regs: Sendable, CustomDebugStringConvertible, Equatable { + @inlinable public var debugDescription: Swift.String { get } + @inlinable public static func == (a: Regs, b: Regs) -> Swift.Bool + @inlinable public var fcwGet: Swift.UInt16 { get } + @inlinable public mutating func fcwSet(_ value: Swift.UInt16) + @inlinable public var wideGet: Swift.UInt64 { get } + @inlinable public mutating func wideSet(_ value: Swift.UInt64) + @inlinable public var atGet: Point { get } + @inlinable public mutating func atSet(_ value: Point) + @inlinable public var tagGet: Swift.UInt8 { get } + @inlinable public mutating func tagSet(_ value: Swift.UInt8) + @inlinable public static func new(_ fcw: Swift.UInt16, _ wide: Swift.UInt64, _ at: Point) -> Regs + @inlinable public func seed() -> Swift.UInt8 +} public struct Extent: Sendable, CustomDebugStringConvertible, Equatable { @inlinable public var debugDescription: Swift.String { get } @inlinable public static func == (a: Extent, b: Extent) -> Swift.Bool @@ -1005,6 +1019,18 @@ public struct Retired: ~Copyable, @unchecked Sendable { @available(*, deprecated, message: "count with `Countdown`") @inlinable nonisolated(nonsending) public mutating func next() async throws -> Swift.UInt32? @available(*, deprecated, message: "count with `Countdown`") @inlinable public consuming func stream() -> RetiredStream } +public struct Folio: ~Copyable, @unchecked Sendable { + @inlinable public var pageGet: Swift.UInt16 { get } + @inlinable public mutating func pageSet(_ value: Swift.UInt16) throws + @inlinable public var titleGet: Swift.String { get } + @inlinable public mutating func titleSet(_ value: Swift.String) throws + @inlinable public var noteGet: Swift.String? { get } + @inlinable public mutating func noteSet(_ value: Swift.String?) throws + @inlinable public func haspGet() throws -> Hasp + @inlinable public mutating func haspSet(_ value: consuming Hasp) throws + @inlinable public static func new(_ page: Swift.UInt16, _ title: Swift.String) -> Folio + @inlinable public func seed() throws -> Swift.UInt8 +} public struct Logger: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ sink: any Log) -> Logger @inlinable public func write(_ line: Swift.String) -> Swift.Bool @@ -1264,6 +1290,10 @@ public final class Mark: @unchecked Sendable { @inlinable public func count() throws -> Swift.UInt64 @inlinable public func add(_ by: Swift.UInt64) throws } +public struct Hasp: ~Copyable, @unchecked Sendable { + @inlinable public static func `default`() -> Hasp + @inlinable public func set() throws -> Swift.Bool +} public struct Message: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @inlinable public func clone() throws -> Message diff --git a/ffi/surface/api/web.d.ts b/ffi/surface/api/web.d.ts index d1a511c4a..95cce1c58 100644 --- a/ffi/surface/api/web.d.ts +++ b/ffi/surface/api/web.d.ts @@ -576,6 +576,22 @@ export type FiledReceipt = rt.Handle<"FiledReceipt">; export declare function clone(self: FiledReceipt): FiledReceipt; export declare function count(self: FiledReceipt): number; +// Folio.ts +import * as rt from "./rt.ts"; +import type { Hasp } from "./Hasp.ts"; +export type Folio = rt.Handle<"Folio">; +export declare function pageGet(self: Folio): number; +export declare function pageSet(self: Folio, value: number): void; +export declare function titleGet(self: Folio): string; +export declare function titleSet(self: Folio, value: string): void; +export declare function noteGet(self: Folio): string | undefined; +export declare function noteSet(self: Folio, value: string | undefined): void; +export declare function haspGet(self: Folio): Hasp; +export declare function haspSet(self: Folio, value: Hasp): void; +export declare function new$(page: number, title: string): Folio; +export declare function seed(self: Folio): number; +export { new$ as new }; + // Gap.ts import * as rt from "./rt.ts"; export type Gap = rt.Handle<"Gap">; @@ -611,6 +627,13 @@ export type Hasher = { seed: number; }; +// Hasp.ts +import * as rt from "./rt.ts"; +export type Hasp = rt.Handle<"Hasp">; +export declare function default$(): Hasp; +export declare function set(self: Hasp): boolean; +export { default$ as default }; + // Hits.ts import * as rt from "./rt.ts"; export type Hits = rt.Opaque<"Hits">; @@ -1308,6 +1331,24 @@ export declare function push(self: Registry, counter: Counter): void; export declare function edit(self: Registry, edit: (a0: Counter) => boolean): boolean; export { default$ as default, new$ as new }; +// Regs.ts +import * as rt from "./rt.ts"; +import type { Point } from "./Point.ts"; +export type Regs = rt.Opaque<"Regs">; +export declare function debug(self: Regs): string; +export declare function eq(a: Regs, b: Regs): boolean; +export declare function fcwGet(self: Regs): number; +export declare function fcwSet(self: Regs, value: number): Regs; +export declare function wideGet(self: Regs): rt.u64; +export declare function wideSet(self: Regs, value: rt.u64): Regs; +export declare function atGet(self: Regs): Point; +export declare function atSet(self: Regs, value: Point): Regs; +export declare function tagGet(self: Regs): number; +export declare function tagSet(self: Regs, value: number): Regs; +export declare function new$(fcw: number, wide: rt.u64, at: Point): Regs; +export declare function seed(self: Regs): number; +export { new$ as new }; + // Resolving.ts import * as rt from "./rt.ts"; import type { TlsResolver } from "./TlsResolver.ts"; @@ -1838,6 +1879,7 @@ import type { Rank } from "./Rank.ts"; import type { Rated } from "./Rated.ts"; import type { Reading } from "./Reading.ts"; import type { Refusal } from "./Refusal.ts"; +import type { Regs } from "./Regs.ts"; import type { RightLeftU8 } from "./RightLeftU8.ts"; import type { RightU8 } from "./RightU8.ts"; import type { Score } from "./Score.ts"; @@ -1909,9 +1951,11 @@ export declare const k_Draft: rt.Kind; export declare const k_Fault: rt.Kind; export declare const k_Feed: rt.Kind; export declare const k_Filed_Receipt: rt.Kind; +export declare const k_Folio: rt.Kind; export declare const k_Gap: rt.Kind; export declare const k_Gauge: rt.Kind; export declare const k_Handle: rt.Kind; +export declare const k_Hasp: rt.Kind; export declare const k_Holder: rt.Kind; export declare const k_Instant: rt.Kind; export declare const k_Journal: rt.Kind; @@ -2044,6 +2088,7 @@ export declare function r_Platform(p: number, o: boolean): Platform; export declare function r_Point(p: number, o: boolean): Point; export declare function r_Rated(p: number, o: boolean): Rated; export declare function r_Reading(p: number, o: boolean): Reading; +export declare function r_Regs(p: number, o: boolean): Regs; export declare function r_Score(p: number, o: boolean): Score; export declare function r_Seat(p: number, o: boolean): Seat; export declare function r_Size(p: number, o: boolean): Size; @@ -2240,6 +2285,7 @@ export declare function w_Qualifiers(p: number, v: Qualifiers): void; export declare function w_Rank(p: number, v: Rank): void; export declare function w_Rated(p: number, v: Rated): void; export declare function w_Reading(p: number, v: Reading): void; +export declare function w_Regs(p: number, v: Regs): void; export declare function w_Right_Left_u8(p: number, v: RightLeftU8): void; export declare function w_Right_u8(p: number, v: RightU8): void; export declare function w_Score(p: number, v: Score): void; diff --git a/ffi/tests/api.c b/ffi/tests/api.c index e0d72fc26..63613d960 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1559,6 +1559,42 @@ static int statuses(void) { api_Meter_free(first); api_Meters_free(meters); + /* A packed object's fields are read and written where they lie unaligned: a `String` is + * cloned from its field and the folio still drops the original, and its latch, which + * no packing misaligns, is lent in place. */ + status = 0; + api_Folio *folio = api_Folio_new(5, str("title")); + api_buf title = api_Folio_title_get(folio, &status); + if (status != 0 || title.len != 5 || memcmp(title.ptr, "title", 5) != 0) { + fprintf(stderr, "a packed folio's title is %.*s\n", (int)title.len, (const char *)title.ptr); + failed = 1; + } + api_buf_free(title); + api_Folio_title_set(folio, str("renamed"), &status); + api_Folio_note_set(folio, str("a note"), &status); + api_Folio_page_set(folio, 9, &status); + title = api_Folio_title_get(folio, &status); + api_buf note = api_Folio_note_get(folio, &status); + if (status != 0 || api_Folio_page_get(folio, &status) != 9 || api_Folio_seed(folio, &status) != 3 || + title.len != 7 || memcmp(title.ptr, "renamed", 7) != 0 || note.len != 6 || + memcmp(note.ptr, "a note", 6) != 0) { + fprintf(stderr, "a packed folio's fields read %.*s %.*s, status %d\n", (int)title.len, + (const char *)title.ptr, (int)note.len, (const char *)note.ptr, status); + failed = 1; + } + api_buf_free(title); + api_buf_free(note); + api_Hasp *hasp = api_Folio_hasp_get(folio, &status); + api_Hasp *again = api_Folio_hasp_get(folio, &status); + bool first_set = api_Hasp_set(hasp, &status); + if (first_set || !api_Hasp_set(again, &status) || status != 0) { + fprintf(stderr, "a packed folio's hasp is not the one it holds, status %d\n", status); + failed = 1; + } + api_Hasp_free(hasp); + api_Hasp_free(again); + api_Folio_free(folio); + /* A counter moved in beside a dropped mark, alone or held in a record or an enum, is * refused before the move, so the counter is still there; once every mark is live, * the call moves it. */ diff --git a/quest/m1/ffi-packed-fields.md b/quest/m1/ffi-packed-fields.md deleted file mode 100644 index 82d182b12..000000000 --- a/quest/m1/ffi-packed-fields.md +++ /dev/null @@ -1,25 +0,0 @@ -# [S] Read a packed record's fields without a reference - -## Goal - -A `#[repr(packed)]` record's field binds: the glue that reads one, as Python's field -getters do, builds, so redox_syscall's `FloatRegisters` binds in every language. - -## Plan - -Decided with the maintainer on 2026-11-19, in the pick of [#919](https://github.com/kixel-ai/rust2/pull/919): ✅ kept as planned (rejected: dropping it). - -Found by the corpus on 2026-11-20, binding redox_syscall without the items its census -refuses: the Python glue's getter of `FloatRegisters::fcw` is `&(&a_self).fcw`, which rustc -refuses as a reference to a packed struct's field (E0793). - -Recommended: reduce it to a packed record in the api fixture, with a `Copy` field and one -that is not, such as a `String`, since `repr(packed)` makes no field `Copy`. Wherever the -glue now borrows a packed field, copy a `Copy` one out by value, `{ a_self.fcw }`, and read -any other unaligned into a `ManuallyDrop` to take what the getter takes from it, as its -clone, so the record still owns and drops the original. A getter that lends the field, as -`Collector::accessors` lends a non-`Clone` object field from the receiver's handle, has no -copy to lend from: it lends the field itself only where rustc allows the reference, a field -aligned to 1, and refuses any other with the field's span. - -Public API: none. From 3daf4d7eebe8cc0dc04f50a6801375ee8295cf17 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 19:47:46 -0800 Subject: [PATCH 03/12] fix(ffi): lend through a packed struct's reference field Co-Authored-By: Claude Sonnet 5.5 --- ffi/fixtures/api/src/lib.rs | 9 +++++++-- ffi/src/collect.rs | 5 +++-- ffi/surface/api/c.h | 3 ++- ffi/surface/api/cpp.hpp | 1 + ffi/surface/api/dart.dart | 1 + ffi/surface/api/go.txt | 1 + ffi/surface/api/kotlin.kt | 1 + ffi/surface/api/python.pyi | 2 ++ ffi/surface/api/swift.swift | 1 + ffi/surface/api/web.d.ts | 1 + ffi/tests/api.c | 9 +++++++++ 11 files changed, 29 insertions(+), 5 deletions(-) diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index b79b01075..5a97c0bb5 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -2195,17 +2195,21 @@ impl Regs { } /// A packed object: its `String` and `Option` lie unaligned, so a getter clones what it -/// reads out of the field without dropping the original, and its hasp, aligned to 1, is -/// lent from the folio in place. +/// reads out of the field without dropping the original, its hasp, aligned to 1, is +/// lent from the folio in place, and its dock is lent through the reference it holds, which +/// is copied out. #[repr(C, packed)] pub struct Folio { pub page: u16, pub title: String, pub note: Option, pub hasp: Hasp, + pub dock: &'static Hasp, seed: u8, } +static DOCK: Hasp = Hasp(std::sync::atomic::AtomicBool::new(false)); + impl Folio { pub fn new(page: u16, title: &str) -> Self { Self { @@ -2213,6 +2217,7 @@ impl Folio { title: title.to_string(), note: None, hasp: Hasp::default(), + dock: &DOCK, seed: 3, } } diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 9b429022f..7aacc9546 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2981,8 +2981,9 @@ impl<'tcx> Collector<'tcx> { let how = self.field_read(site, ty); let mapped = { self.lending.set(lends); - // A lent field is the field itself, which an unaligned one cannot be. - let get = match lends && how != Read::Borrow { + // A lent field is the field itself, which an unaligned one cannot be; one lent + // through a reference it holds is its pointee, which the copied reference reaches. + let get = match lends && assigned && how != Read::Borrow { true => Err(why(UNALIGNED, ty.to_string())), false => self.ty(read, Pos::Return), }; diff --git a/ffi/surface/api/c.h b/ffi/surface/api/c.h index c659d6249..0741e7f1f 100644 --- a/ffi/surface/api/c.h +++ b/ffi/surface/api/c.h @@ -17,7 +17,7 @@ #ifdef __cplusplus extern "C" { #endif -#define API_CONTRACT ((uint64_t)0x3906a14bfdda8e36ULL) +#define API_CONTRACT ((uint64_t)0x145f81d2ea707190ULL) uint64_t api_contract(void); uint32_t api_target(void); typedef int32_t api_status; @@ -1705,6 +1705,7 @@ API_MUST_USE api_buf api_Folio_note_get(const api_Folio *self, api_status *statu void api_Folio_note_set(api_Folio *self, api_buf value, api_status *status); API_MUST_USE api_Hasp *api_Folio_hasp_get(const api_Folio *self, api_status *status); void api_Folio_hasp_set(api_Folio *self, api_Hasp *value, api_status *status); +API_MUST_USE api_Hasp *api_Folio_dock_get(const api_Folio *self, api_status *status); API_MUST_USE api_Folio *api_Folio_new(uint16_t page, api_buf title); uint8_t api_Folio_seed(const api_Folio *self, api_status *status); void api_Logger_free(api_Logger *self); diff --git a/ffi/surface/api/cpp.hpp b/ffi/surface/api/cpp.hpp index 5747e840a..d4bf51fbc 100644 --- a/ffi/surface/api/cpp.hpp +++ b/ffi/surface/api/cpp.hpp @@ -173,6 +173,7 @@ namespace api { RUST2_FFI_CALLABLE void note_set(::std::optional<::api::input> value); RUST2_FFI_CALLABLE ::api::Hasp hasp_get() const; RUST2_FFI_CALLABLE void hasp_set(::api::Hasp value); + RUST2_FFI_CALLABLE ::api::Hasp dock_get() const; static ::api::Folio new_(::std::uint16_t page, ::api::input title); RUST2_FFI_CALLABLE ::std::uint8_t seed() const; }; diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index 5cbf0d566..b1ec61ef1 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -1213,6 +1213,7 @@ final class Folio extends _Object { void noteSet(String? value); Hasp get haspGet; void haspSet(Hasp value); + Hasp get dockGet; factory Folio(int page, String title); int seed(); } diff --git a/ffi/surface/api/go.txt b/ffi/surface/api/go.txt index 705b341e6..6557d985f 100644 --- a/ffi/surface/api/go.txt +++ b/ffi/surface/api/go.txt @@ -969,6 +969,7 @@ type Folio struct { } func NewFolio(page uint16, title string) (*Folio, error) func (self *Folio) Close() error +func (self *Folio) DockGet() (*Hasp, error) func (self *Folio) HaspGet() (*Hasp, error) func (self *Folio) HaspSet(value *Hasp) error func (self *Folio) NoteGet() (*string, error) diff --git a/ffi/surface/api/kotlin.kt b/ffi/surface/api/kotlin.kt index c30b0e51b..a6be47b78 100644 --- a/ffi/surface/api/kotlin.kt +++ b/ffi/surface/api/kotlin.kt @@ -779,6 +779,7 @@ class Folio internal constructor(raw: Long, lent: Boolean = false) : AutoCloseab fun noteSet(value: kotlin.String?) val haspGet: api.Hasp fun haspSet(value: api.Hasp) + val dockGet: api.Hasp fun seed(): kotlin.UByte companion object { @kotlin.jvm.JvmStatic fun new(page: kotlin.UShort, title: kotlin.String): api.Folio diff --git a/ffi/surface/api/python.pyi b/ffi/surface/api/python.pyi index e8aa606c2..a93d7db05 100644 --- a/ffi/surface/api/python.pyi +++ b/ffi/surface/api/python.pyi @@ -981,6 +981,8 @@ class Folio(_n.Object): @_property def hasp_get(self) -> Hasp: ... def hasp_set(self, value: Hasp) -> None: ... + @_property + def dock_get(self) -> Hasp: ... @_staticmethod def new(page: _int, title: _str) -> Folio: ... def seed(self) -> _int: ... diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index cdeb2c2f4..c79935def 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -1028,6 +1028,7 @@ public struct Folio: ~Copyable, @unchecked Sendable { @inlinable public mutating func noteSet(_ value: Swift.String?) throws @inlinable public func haspGet() throws -> Hasp @inlinable public mutating func haspSet(_ value: consuming Hasp) throws + @inlinable public func dockGet() throws -> Hasp @inlinable public static func new(_ page: Swift.UInt16, _ title: Swift.String) -> Folio @inlinable public func seed() throws -> Swift.UInt8 } diff --git a/ffi/surface/api/web.d.ts b/ffi/surface/api/web.d.ts index 95cce1c58..e57188567 100644 --- a/ffi/surface/api/web.d.ts +++ b/ffi/surface/api/web.d.ts @@ -588,6 +588,7 @@ export declare function noteGet(self: Folio): string | undefined; export declare function noteSet(self: Folio, value: string | undefined): void; export declare function haspGet(self: Folio): Hasp; export declare function haspSet(self: Folio, value: Hasp): void; +export declare function dockGet(self: Folio): Hasp; export declare function new$(page: number, title: string): Folio; export declare function seed(self: Folio): number; export { new$ as new }; diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 63613d960..c362a5db2 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1593,6 +1593,15 @@ static int statuses(void) { } api_Hasp_free(hasp); api_Hasp_free(again); + api_Hasp *dock = api_Folio_dock_get(folio, &status); + api_Hasp *docked = api_Folio_dock_get(folio, &status); + bool dock_first = api_Hasp_set(dock, &status); + if (dock_first || !api_Hasp_set(docked, &status) || status != 0) { + fprintf(stderr, "a packed folio's dock is not the one it points to, status %d\n", status); + failed = 1; + } + api_Hasp_free(dock); + api_Hasp_free(docked); api_Folio_free(folio); /* A counter moved in beside a dropped mark, alone or held in a record or an enum, is From 999f3fca11dd044278191fd0ce543f22b32395b5 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 21 Nov 2026 01:56:01 -0800 Subject: [PATCH 04/12] fix(ffi): refuse an unaligned interior-mutable field's getter, and say the packing, not 1 A packed struct's field read unaligned into a ManuallyDrop is a non-atomic copy, which races a write through &self of an atomic it holds inline: refuse it unless the type is Freeze. The README and help text said a field aligned to 1 lends, but one aligned within the packing does. Co-Authored-By: Claude Sonnet 5.5 --- ffi/README.md | 2 +- ffi/fixtures/reject/expected.txt | 4 +++- ffi/fixtures/reject/src/lib.rs | 36 ++++++++++++++++++++++++++++++++ ffi/src/collect.rs | 21 +++++++++++++++---- ffi/src/help.rs | 5 ++++- 5 files changed, 61 insertions(+), 7 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index 08a2d392c..79f4cb8a0 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -93,7 +93,7 @@ public path names, or an error taken by value, is held by value as an opaque han | any other type | an object: an opaque handle to an `Arc`, freed with `_free`; one that is `Copy`, such as std's `Instant`, whose padding a `rustc` may place anywhere, is copied out of its handle where Rust takes it by value, and a closure neither takes nor returns one by value; one that is not `Send`, such as kio's `clock::Entered`, stays on the thread that made it, as [the C ABI](#the-c-abi)'s threads say | | a type whose only generic parameters are lifetimes, such as `Path<'a>` | an object holding its `'static` form | | a generic type, at each instance it infers | that instance as any other type, with each method whose impl and own bounds it meets; any other instance is refused | -| a `pub` field of an object or opaque value | a getter returning a copy, and a setter assigning in place, as `x.field = value` does; a `repr(packed)` struct's field that may lie unaligned, which rustc lets no reference point at, is copied out if `Copy`, else read unaligned into a `ManuallyDrop`, which the struct still owns and drops, so one that must be lent instead, a field that is not `Clone`, is refused unless aligned to 1 | +| a `pub` field of an object or opaque value | a getter returning a copy, and a setter assigning in place, as `x.field = value` does; a `repr(packed)` struct's field that may lie unaligned, which rustc lets no reference point at, is copied out if `Copy`, else read unaligned into a `ManuallyDrop`, which the struct still owns and drops, so one that must be lent instead, a field that is not `Clone`, is refused unless aligned within the packing, as is one holding an atomic or `Cell` inline, whose unaligned copy would race a write through `&self` | | a `pub` trait | a callback interface: a table of C functions and their data; a trait C cannot implement, such as one with a blanket impl, an associated type, or a supertrait but a marker, is left out, since C never passes one, and a signature taking one from C is refused | | a type parameter or `impl` bounded by `Fn`, `FnMut`, or `FnOnce` alone, taking what a callback takes, objects by reference, or opaque values, and returning a scalar, a `String`, an opaque value, an `Option` of one, or a `Result` of one and a `String` | a C function and its `void *` data; one a lifetime bound or the return lets outlive the call, as kio's `clock::drive` and a spawned task's are, adds a `free` Rust calls once it drops it; a closure of any other signature is refused | | a type parameter or `impl` taken by value and bounded by `Future` or `IntoFuture`, whose every bound `Pin + Send>>` meets, as kio's `clock::timeout` takes, or taken as `Pin<&mut F>` by a poll, as kio's `Waiter::poll_future` takes | `_foreign_future`: a future of `()` C implements, which Rust takes as that type, or which the future the poll makes owns and pins; a future of another output is refused | diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 1c8742983..35f93ed3a 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -157,7 +157,9 @@ fixtures/reject/src/lib.rs:1623:2: rust2-ffi: cannot export method `Knot` or a `Box`, or take `repr(packed)` off the struct, since copying out an atomic or `Cell` unaligned would race a write through `&self` fixtures/reject/src/lib.rs:167:1: rust2-ffi: cannot export instance `Cell>`: type argument `std::vec::Vec` help: instantiate it at types that map, such as integers, `String`, or an exported type; `&str`, `Cow`, and other borrows do not fixtures/reject/src/lib.rs:167:1: rust2-ffi: cannot export instance `Cell`: type argument `tls::held::Cert` diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index ff87ea8e2..7101b58c0 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1653,3 +1653,39 @@ impl Packed { self.seed } } + +/// A `Clone` object holding an atomic, which another `&self` method may write while a getter +/// copies its bytes out unaligned: that read is non-atomic, so the getter is refused. +pub struct Dial(std::sync::atomic::AtomicU32); + +impl Clone for Dial { + fn clone(&self) -> Self { + Self(std::sync::atomic::AtomicU32::new(self.0.load(std::sync::atomic::Ordering::Relaxed))) + } +} + +pub fn dial() -> Dial { + Dial(std::sync::atomic::AtomicU32::new(0)) +} + +impl Dial { + pub fn hit(&self) { + self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +#[repr(C, packed)] +pub struct Ledger { + pub dial: Dial, + seed: u8, +} + +pub fn ledger() -> Ledger { + Ledger { dial: Dial(std::sync::atomic::AtomicU32::new(0)), seed: 0 } +} + +impl Ledger { + pub fn seed(&self) -> u8 { + self.seed + } +} diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 2257e1f93..43d999033 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -79,6 +79,7 @@ const UNMET: &str = "bound no type C holds meets"; /// The construct of a field lent from a `repr(packed)` struct, where it may lie unaligned. const UNALIGNED: &str = "lent unaligned field"; +const RACY: &str = "unaligned interior-mutable field"; fn why(construct: &'static str, detail: impl Into) -> Why { Why { @@ -2997,9 +2998,10 @@ impl<'tcx> Collector<'tcx> { self.lending.set(lends); // A lent field is the field itself, which an unaligned one cannot be; one lent // through a reference it holds is its pointee, which the copied reference reaches. - let get = match lends && assigned && how != Read::Borrow { - true => Err(why(UNALIGNED, ty.to_string())), - false => self.ty(read, Pos::Return), + let get = match (lends && assigned && how != Read::Borrow, self.racy(how, ty)) { + (true, _) => Err(why(UNALIGNED, ty.to_string())), + (_, true) => Err(why(RACY, ty.to_string())), + _ => self.ty(read, Pos::Return), }; self.lending.set(false); // A handle outlives every call, so a reference it holds is `'static`, which @@ -3016,7 +3018,9 @@ impl<'tcx> Collector<'tcx> { // setter keeps the type in the API, so one no export returns leaves out // both. (Err(get), Ok(Some(set))) - if get.construct == "borrowed return that is not Clone" || get.construct == UNALIGNED => + if get.construct == "borrowed return that is not Clone" + || get.construct == UNALIGNED + || get.construct == RACY => { self.refuse(&shown, "field", span, vec![get]); Ok((None, Some(set))) @@ -3124,6 +3128,15 @@ impl<'tcx> Collector<'tcx> { } } + /// Whether reading a field of type `ty` out unaligned, as `how` says, would race: a type + /// holding an `UnsafeCell` inline, such as an atomic, may be written through `&self` + /// while the read copies its bytes, and a non-atomic read of that is undefined behavior. + fn racy(&self, how: Read, ty: Ty<'tcx>) -> bool { + let tcx = self.tcx; + let ty = tcx.erase_and_anonymize_regions(ty); + how == Read::Take && !ty.is_freeze(tcx, TypingEnv::fully_monomorphized()) + } + /// A value's methods, refusing each through `&mut self`: C passes the value as a copy, /// so what the method changes would be lost. fn unmutated(&mut self, methods: Vec) -> Vec { diff --git a/ffi/src/help.rs b/ffi/src/help.rs index 5c0e2c50e..ab99af3f4 100644 --- a/ffi/src/help.rs +++ b/ffi/src/help.rs @@ -134,7 +134,10 @@ pub(crate) fn of(construct: &str) -> Option<&'static str> { "return an owned value or a `Clone` type, since a borrowed return crosses as a clone" } "lent unaligned field" => { - "make the field `Clone` or a type aligned to 1, or take `repr(packed)` off the struct, since rustc refuses a reference to an unaligned field and a handle cannot be lent from a copy" + "make the field `Clone` or a type aligned within the packing, or take `repr(packed)` off the struct, since rustc refuses a reference to an unaligned field and a handle cannot be lent from a copy" + } + "unaligned interior-mutable field" => { + "hold the field behind an `Arc` or a `Box`, or take `repr(packed)` off the struct, since copying out an atomic or `Cell` unaligned would race a write through `&self`" } "&mut of a slice" => { "take `&[u8]` and return the changed `Vec`, or hold the buffer in an object; C lends no buffer mutably" From d2cb79f1f76b8add7ffd120d0460751e24a80768 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 21 Nov 2026 01:57:19 -0800 Subject: [PATCH 05/12] style(ffi): format the reject fixture Co-Authored-By: Claude Sonnet 5.5 --- ffi/fixtures/reject/expected.txt | 4 ++-- ffi/fixtures/reject/src/lib.rs | 9 +++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 35f93ed3a..0b00c3f59 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -158,12 +158,12 @@ fixtures/reject/src/lib.rs:162:1: rust2-ffi: cannot export fn `measure`: foreign help: use a type that maps, such as `BTreeMap` for a `HashMap` and `Vec` for an iterator, or wrap it in a type of your own whose methods take and return mapped types fixtures/reject/src/lib.rs:1643:2: rust2-ffi: cannot export field `Packed::lone`: lent unaligned field `Lone` help: make the field `Clone` or a type aligned within the packing, or take `repr(packed)` off the struct, since rustc refuses a reference to an unaligned field and a handle cannot be lent from a copy -fixtures/reject/src/lib.rs:1679:2: rust2-ffi: cannot export field `Ledger::dial`: unaligned interior-mutable field `Dial` - help: hold the field behind an `Arc` or a `Box`, or take `repr(packed)` off the struct, since copying out an atomic or `Cell` unaligned would race a write through `&self` fixtures/reject/src/lib.rs:167:1: rust2-ffi: cannot export instance `Cell>`: type argument `std::vec::Vec` help: instantiate it at types that map, such as integers, `String`, or an exported type; `&str`, `Cow`, and other borrows do not fixtures/reject/src/lib.rs:167:1: rust2-ffi: cannot export instance `Cell`: type argument `tls::held::Cert` help: instantiate it at types that map, such as integers, `String`, or an exported type; `&str`, `Cow`, and other borrows do not +fixtures/reject/src/lib.rs:1681:2: rust2-ffi: cannot export field `Ledger::dial`: unaligned interior-mutable field `Dial` + help: hold the field behind an `Arc` or a `Box`, or take `repr(packed)` off the struct, since copying out an atomic or `Cell` unaligned would race a write through `&self` fixtures/reject/src/lib.rs:16:1: rust2-ffi: cannot export fn `generic`: generic parameter `std::marker::Copy` help: bound it by a trait the exporter maps, such as `Into`, `AsRef`, `Fn(..)`, or `IntoIterator`, or one of the crate's own traits, or take a concrete type fixtures/reject/src/lib.rs:170:1: rust2-ffi: cannot export fn `sealed`: refused type `reject::Cell` diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index 7101b58c0..5ed772433 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1660,7 +1660,9 @@ pub struct Dial(std::sync::atomic::AtomicU32); impl Clone for Dial { fn clone(&self) -> Self { - Self(std::sync::atomic::AtomicU32::new(self.0.load(std::sync::atomic::Ordering::Relaxed))) + Self(std::sync::atomic::AtomicU32::new( + self.0.load(std::sync::atomic::Ordering::Relaxed), + )) } } @@ -1681,7 +1683,10 @@ pub struct Ledger { } pub fn ledger() -> Ledger { - Ledger { dial: Dial(std::sync::atomic::AtomicU32::new(0)), seed: 0 } + Ledger { + dial: Dial(std::sync::atomic::AtomicU32::new(0)), + seed: 0, + } } impl Ledger { From a4900273a2c10126c6307f3b585d5b91dc754bbc Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 21 Nov 2026 03:33:13 -0800 Subject: [PATCH 06/12] fix(ffi): merge a packed field's getter across targets whatever read each needs A repr(packed) struct's field may be aligned on one target and not another, so the getter reads it by another mode on each. The merge matched getters by read mode, so it kept two for one field, each on a subset of targets, whose glue defined one symbol twice. It now matches by field and reads by the greater mode, which both accept. Co-Authored-By: Claude Sonnet 5.5 --- ffi/src/ir.rs | 7 ++- ffi/src/merge.rs | 111 +++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 114 insertions(+), 4 deletions(-) diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 4dc02261d..588e54126 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -597,7 +597,12 @@ pub(crate) enum Access { /// How a getter reads a field in Rust, which the field's struct decides: a `repr(packed)` /// one's field may lie unaligned, which rustc refuses a reference to. -#[derive(Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +/// +/// A getter's value is the same through any mode that compiles, and the order is how far one +/// reaches: `Take` reads any field on any layout, `Copy` any `Copy` one, and a field's two +/// targets mean the same type, so the merge of their getters reads it the greater of theirs, +/// which each target accepts. +#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] pub(crate) enum Read { /// It borrows the field. #[default] diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index 933fe88a9..5275c3ffe 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -13,7 +13,8 @@ use rustc_span::source_map::SourceMap; use rustc_span::{DUMMY_SP, Span}; use crate::ir::{ - Api, Callback, Constant, Enum, Field, Function, Home, Object, On, Record, TaskKind, Traits, Type, Variant, + Access, Api, Callback, Constant, Enum, Field, Function, Home, Object, On, Read, Record, TaskKind, Traits, Type, + Variant, }; /// A target's API, as a check writes it for the export of several targets. @@ -202,6 +203,22 @@ fn bare(item: &T, clear: impl Fn(&mut T)) -> T { item } +/// Whether two functions read alike, which a field's two targets do whichever way its +/// layout makes each getter read it. +fn same_access(a: &Access, b: &Access) -> bool { + match (a, b) { + ( + Access::Field { set, through, .. }, + Access::Field { + set: other, + through: through_other, + .. + }, + ) => set == other && through == through_other, + _ => a == b, + } +} + pub(crate) fn bare_function(f: &Function) -> Function { bare(f, |f| { f.span = DUMMY_SP; @@ -210,6 +227,10 @@ pub(crate) fn bare_function(f: &Function) -> Function { f.on = On::ALL; // Merged apart, as a trait's leaves are. f.leaf = false; + // Merged to the greatest, as a target's layout may decide it. + if let Access::Field { read, .. } = &mut f.access { + *read = Read::Borrow; + } }) } @@ -574,7 +595,7 @@ impl Merged { // A field's getter and setter share its path. let Some(at) = ours .iter() - .position(|f| f.shown == function.shown && f.access == function.access) + .position(|f| f.shown == function.shown && same_access(&f.access, &function.access)) else { ours.push(function); continue; @@ -583,6 +604,14 @@ impl Merged { let what = format!("fn `{}`", function.shown.join("::")); self.differ(what, (ours[at].on, ours[at].span), (function.on, function.span)); } + // One getter serves a field on every target, though `repr(packed)` may make one + // target's layout need another read than the next's: it reads by the mode that + // accepts both, whose value is the same. + if let (Access::Field { read: ours, .. }, Access::Field { read: theirs, .. }) = + (&mut ours[at].access, &function.access) + { + *ours = (*ours).max(*theirs); + } ours[at].on.0 |= function.on.0; ours[at].leaf &= function.leaf; linked(&mut ours[at].docs, function.docs); @@ -844,7 +873,7 @@ mod tests { use rustc_span::DUMMY_SP; use super::{On, cycle, linked, order_crates}; - use crate::ir::{Api, Enum, Field, Home, Traits, Type, Variant}; + use crate::ir::{Access, Api, Enum, Field, Function, Home, Read, Traits, Type, Variant}; /// Docs keep the target's whose links resolve more, as one lacking an item does not. #[test] @@ -956,4 +985,80 @@ mod tests { let (_, differs) = super::merge(vec![api("x", true), api("y", true)]); assert!(differs.is_empty()); } + + /// A packed struct's field may read another way on each target, by its layout there: the + /// merge keeps one getter for it, reading the way both accept, and no difference. + #[test] + fn merges_a_fields_getter_across_read_modes() { + let getter = |read: Read| Function { + path: ["f", "Regs", "n"].map(String::from).to_vec(), + shown: ["f", "Regs", "n"].map(String::from).to_vec(), + span: DUMMY_SP, + on: On::ALL, + docs: String::new(), + deprecated: None, + receiver: Some(crate::ir::Receiver::Ref), + params: Vec::new(), + units: Vec::new(), + ok: Type::Int(crate::ir::Int::Usize), + err: None, + future: false, + eager: false, + holds: false, + task: None, + send: true, + collect: false, + lends: false, + lends_mut: false, + derefs: 0, + leaf: true, + ties: false, + access: Access::Field { + set: false, + through: false, + read, + }, + instance: None, + home: Home::default(), + }; + let api = |target: &str, read: Read| { + let path = ["f", "Regs"].map(String::from).to_vec(); + let record = crate::ir::Record { + path: path.clone(), + home: Home::default(), + shown: path, + args: Vec::new(), + span: DUMMY_SP, + on: On::ALL, + docs: String::new(), + deprecated: None, + fields: Vec::new(), + tuple: false, + methods: vec![getter(read)], + traits: Traits::default(), + opaque: None, + sizes: BTreeMap::new(), + }; + Api { + records: vec![record], + enums: Vec::new(), + objects: Vec::new(), + callbacks: Vec::new(), + functions: Vec::new(), + constants: Vec::new(), + crates: vec!["f".into()], + reached: Vec::new(), + targets: vec![target.into()], + links: Default::default(), + } + }; + for (first, second) in [(Read::Borrow, Read::Copy), (Read::Copy, Read::Borrow)] { + let (merged, differs) = super::merge(vec![api("x", first), api("y", second)]); + assert!(differs.is_empty()); + let methods = &merged.records[0].methods; + assert_eq!(methods.len(), 1, "one getter for the field"); + assert_eq!(methods[0].on.0, 3); + assert!(matches!(methods[0].access, Access::Field { read: Read::Copy, .. })); + } + } } From e378a471781b6f38865e3152ee650701071183a2 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 21 Nov 2026 03:54:54 -0800 Subject: [PATCH 07/12] fix(ffi): refuse to merge an unaligned read with a target whose field holds an atomic Co-Authored-By: Claude Sonnet 5.5 --- ffi/src/collect.rs | 10 +++++++ ffi/src/glue.rs | 1 + ffi/src/ir.rs | 12 ++++++--- ffi/src/merge.rs | 65 +++++++++++++++++++++++++++++++++++++++------- 4 files changed, 75 insertions(+), 13 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 43d999033..876e42219 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -3083,6 +3083,7 @@ impl<'tcx> Collector<'tcx> { set, through: !assigned, read: how, + unfrozen: self.unfrozen(site, ty), }, instance: None, home: Home::default(), @@ -3137,6 +3138,15 @@ impl<'tcx> Collector<'tcx> { how == Read::Take && !ty.is_freeze(tcx, TypingEnv::fully_monomorphized()) } + /// Whether the field of type `ty` of the struct `site` is a `repr(packed)` one holding an + /// `UnsafeCell` inline: another target of the same field may read it unaligned, which + /// would race there. + fn unfrozen(&self, site: &Site<'tcx>, ty: Ty<'tcx>) -> bool { + let tcx = self.tcx; + let ty = tcx.erase_and_anonymize_regions(ty); + tcx.adt_def(site.key.def_id).repr().pack.is_some() && !ty.is_freeze(tcx, TypingEnv::fully_monomorphized()) + } + /// A value's methods, refusing each through `&mut self`: C passes the value as a copy, /// so what the method changes would be lost. fn unmutated(&mut self, methods: Vec) -> Vec { diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 6c9b467dd..711af842c 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -3030,6 +3030,7 @@ impl Gen<'_> { set: false, through, read, + .. } => { let deref = if through { "*" } else { "" }; let field = format!("({}).{}", args[0], ident(function.name())); diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 588e54126..03b22c060 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -585,6 +585,11 @@ pub(crate) enum Access { through: bool, #[serde(default, skip_serializing_if = "Read::is_borrow")] read: Read, + /// Whether the field of a `repr(packed)` struct holds an `UnsafeCell` inline, so that + /// reading it unaligned, as `Take` does, would race: no target where it does may merge + /// with one reading it that way. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + unfrozen: bool, }, /// It reads a constant that is not a `bool` or integer. Const, @@ -599,9 +604,10 @@ pub(crate) enum Access { /// one's field may lie unaligned, which rustc refuses a reference to. /// /// A getter's value is the same through any mode that compiles, and the order is how far one -/// reaches: `Take` reads any field on any layout, `Copy` any `Copy` one, and a field's two -/// targets mean the same type, so the merge of their getters reads it the greater of theirs, -/// which each target accepts. +/// reaches: `Take` reads any field on any layout, `Copy` any `Copy` one. The merge of two +/// targets' getters of a field reads it the greater of theirs, unless that reads out unaligned +/// what the other target holds an `UnsafeCell` in (`Access::Field`'s `unfrozen`), which is a +/// difference between the targets. #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] pub(crate) enum Read { /// It borrows the field. diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index 5275c3ffe..cce1baa46 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -228,8 +228,9 @@ pub(crate) fn bare_function(f: &Function) -> Function { // Merged apart, as a trait's leaves are. f.leaf = false; // Merged to the greatest, as a target's layout may decide it. - if let Access::Field { read, .. } = &mut f.access { + if let Access::Field { read, unfrozen, .. } = &mut f.access { *read = Read::Borrow; + *unfrozen = false; } }) } @@ -606,11 +607,38 @@ impl Merged { } // One getter serves a field on every target, though `repr(packed)` may make one // target's layout need another read than the next's: it reads by the mode that - // accepts both, whose value is the same. - if let (Access::Field { read: ours, .. }, Access::Field { read: theirs, .. }) = - (&mut ours[at].access, &function.access) - { - *ours = (*ours).max(*theirs); + // accepts both, whose value is the same, unless that is an unaligned read of what + // a target holds an `UnsafeCell` in, which would race there. + let races = match (&mut ours[at].access, &function.access) { + ( + Access::Field { + read: ours, + unfrozen: ours_unfrozen, + .. + }, + Access::Field { + read: theirs, + unfrozen: theirs_unfrozen, + .. + }, + ) => { + let read = (*ours).max(*theirs); + let races = read == Read::Take + && ((*ours != read && *ours_unfrozen) || (*theirs != read && *theirs_unfrozen)); + if !races { + *ours = read; + *ours_unfrozen |= *theirs_unfrozen; + } + races + } + _ => false, + }; + if races { + let what = format!( + "fn `{}`, which one target reads out unaligned and another holds an atomic or `Cell` in", + function.shown.join("::") + ); + self.differ(what, (ours[at].on, ours[at].span), (function.on, function.span)); } ours[at].on.0 |= function.on.0; ours[at].leaf &= function.leaf; @@ -990,7 +1018,7 @@ mod tests { /// merge keeps one getter for it, reading the way both accept, and no difference. #[test] fn merges_a_fields_getter_across_read_modes() { - let getter = |read: Read| Function { + let getter = |read: Read, unfrozen: bool| Function { path: ["f", "Regs", "n"].map(String::from).to_vec(), shown: ["f", "Regs", "n"].map(String::from).to_vec(), span: DUMMY_SP, @@ -1017,11 +1045,12 @@ mod tests { set: false, through: false, read, + unfrozen, }, instance: None, home: Home::default(), }; - let api = |target: &str, read: Read| { + let api = |target: &str, read: Read, unfrozen: bool| { let path = ["f", "Regs"].map(String::from).to_vec(); let record = crate::ir::Record { path: path.clone(), @@ -1034,7 +1063,7 @@ mod tests { deprecated: None, fields: Vec::new(), tuple: false, - methods: vec![getter(read)], + methods: vec![getter(read, unfrozen)], traits: Traits::default(), opaque: None, sizes: BTreeMap::new(), @@ -1053,12 +1082,28 @@ mod tests { } }; for (first, second) in [(Read::Borrow, Read::Copy), (Read::Copy, Read::Borrow)] { - let (merged, differs) = super::merge(vec![api("x", first), api("y", second)]); + let (merged, differs) = super::merge(vec![api("x", first, false), api("y", second, false)]); assert!(differs.is_empty()); let methods = &merged.records[0].methods; assert_eq!(methods.len(), 1, "one getter for the field"); assert_eq!(methods[0].on.0, 3); assert!(matches!(methods[0].access, Access::Field { read: Read::Copy, .. })); } + // An unaligned read of what one target holds an atomic in would race there. + let (merged, differs) = super::merge(vec![api("x", Read::Borrow, false), api("y", Read::Take, false)]); + assert!(differs.is_empty()); + assert!(matches!( + merged.records[0].methods[0].access, + Access::Field { read: Read::Take, .. } + )); + for (first, second) in [ + (api("x", Read::Borrow, true), api("y", Read::Take, false)), + (api("x", Read::Take, false), api("y", Read::Borrow, true)), + ] { + let (merged, differs) = super::merge(vec![first, second]); + assert_eq!(differs.len(), 1); + assert_eq!((differs[0].first.0.as_str(), differs[0].second.0.as_str()), ("x", "y")); + assert_eq!(merged.records[0].methods.len(), 1); + } } } From a43cbc6a23d0ea458076180ca6eedde3d3d29d12 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 21 Nov 2026 04:02:44 -0800 Subject: [PATCH 08/12] fix(ffi): record a field's interior mutability whatever its struct's packing on this target Co-Authored-By: Claude Sonnet 5.5 --- ffi/src/collect.rs | 11 +++++------ ffi/src/ir.rs | 6 +++--- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 876e42219..7f90b38fb 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -3083,7 +3083,7 @@ impl<'tcx> Collector<'tcx> { set, through: !assigned, read: how, - unfrozen: self.unfrozen(site, ty), + unfrozen: self.unfrozen(ty), }, instance: None, home: Home::default(), @@ -3138,13 +3138,12 @@ impl<'tcx> Collector<'tcx> { how == Read::Take && !ty.is_freeze(tcx, TypingEnv::fully_monomorphized()) } - /// Whether the field of type `ty` of the struct `site` is a `repr(packed)` one holding an - /// `UnsafeCell` inline: another target of the same field may read it unaligned, which - /// would race there. - fn unfrozen(&self, site: &Site<'tcx>, ty: Ty<'tcx>) -> bool { + /// Whether a field of type `ty` holds an `UnsafeCell` inline: another target of the same + /// field, whose packing may differ, may read it unaligned, which would race there. + fn unfrozen(&self, ty: Ty<'tcx>) -> bool { let tcx = self.tcx; let ty = tcx.erase_and_anonymize_regions(ty); - tcx.adt_def(site.key.def_id).repr().pack.is_some() && !ty.is_freeze(tcx, TypingEnv::fully_monomorphized()) + !ty.is_freeze(tcx, TypingEnv::fully_monomorphized()) } /// A value's methods, refusing each through `&mut self`: C passes the value as a copy, diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 03b22c060..0b5f30a6e 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -585,9 +585,9 @@ pub(crate) enum Access { through: bool, #[serde(default, skip_serializing_if = "Read::is_borrow")] read: Read, - /// Whether the field of a `repr(packed)` struct holds an `UnsafeCell` inline, so that - /// reading it unaligned, as `Take` does, would race: no target where it does may merge - /// with one reading it that way. + /// Whether the field holds an `UnsafeCell` inline, so that reading it unaligned, as + /// `Take` does, would race: no target where it does may merge with one reading it that + /// way, as its struct's packing may differ between targets. #[serde(default, skip_serializing_if = "std::ops::Not::not")] unfrozen: bool, }, From bf277443f5c28b218fed60bac98be323c888ecab Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 21 Nov 2026 04:11:07 -0800 Subject: [PATCH 09/12] fix(ffi): a field's setter takes no part in the unaligned-read race check Co-Authored-By: Claude Sonnet 5.5 --- ffi/src/merge.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index cce1baa46..28b07eb05 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -612,6 +612,7 @@ impl Merged { let races = match (&mut ours[at].access, &function.access) { ( Access::Field { + set, read: ours, unfrozen: ours_unfrozen, .. @@ -623,7 +624,9 @@ impl Merged { }, ) => { let read = (*ours).max(*theirs); - let races = read == Read::Take + // A setter assigns and never reads the field, so it cannot race. + let races = !*set + && read == Read::Take && ((*ours != read && *ours_unfrozen) || (*theirs != read && *theirs_unfrozen)); if !races { *ours = read; @@ -1105,5 +1108,20 @@ mod tests { assert_eq!((differs[0].first.0.as_str(), differs[0].second.0.as_str()), ("x", "y")); assert_eq!(merged.records[0].methods.len(), 1); } + // A setter never reads the field, so the same pair merges without a difference. + let setter = |mut api: Api| { + if let Access::Field { set, .. } = &mut api.records[0].methods[0].access { + *set = true; + } + api + }; + for (first, second) in [ + (api("x", Read::Borrow, true), api("y", Read::Take, true)), + (api("x", Read::Take, true), api("y", Read::Borrow, true)), + ] { + let (merged, differs) = super::merge(vec![setter(first), setter(second)]); + assert!(differs.is_empty()); + assert_eq!(merged.records[0].methods.len(), 1); + } } } From b26cbb0be3245cd770841d57963a20e224e1c1e9 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 21 Nov 2026 04:30:58 -0800 Subject: [PATCH 10/12] fix(ffi): the merge test's api names the new profiles field Co-Authored-By: Claude Sonnet 5.5 --- ffi/src/merge.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index 17a7d58e2..eabc7a861 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -1083,6 +1083,7 @@ mod tests { constants: Vec::new(), crates: vec!["f".into()], reached: Vec::new(), + profiles: Default::default(), targets: vec![target.into()], links: Default::default(), } From a131b1aa3a9e22c7866c4fd8db93e9403cc769cc Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 21 Nov 2026 04:44:28 -0800 Subject: [PATCH 11/12] fix(ffi): a merge reads by Copy only where each target that borrows the field has it Copy Co-Authored-By: Claude Sonnet 5.5 --- ffi/src/collect.rs | 10 +++++++++- ffi/src/ir.rs | 11 ++++++++--- ffi/src/merge.rs | 47 +++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 78e010777..243ee7e86 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -3089,6 +3089,7 @@ impl<'tcx> Collector<'tcx> { through: !assigned, read: how, unfrozen: self.unfrozen(ty), + copy: self.copies(site, ty), }, instance: None, home: Home::default(), @@ -3128,12 +3129,19 @@ impl<'tcx> Collector<'tcx> { if tcx.layout_of(input).is_ok_and(|layout| layout.align <= pack) { return Read::Borrow; } - match implements(tcx, ty, site.key.def_id, sym::Copy) { + match self.copies(site, ty) { true => Read::Copy, false => Read::Take, } } + /// Whether a field of type `ty` of the struct `site` is `Copy` on this target: another + /// target of the same field, which reads it by `Copy`, may not have it so. + fn copies(&self, site: &Site<'tcx>, ty: Ty<'tcx>) -> bool { + let ty = self.tcx.erase_and_anonymize_regions(ty); + implements(self.tcx, ty, site.key.def_id, sym::Copy) + } + /// Whether reading a field of type `ty` out unaligned, as `how` says, would race: a type /// holding an `UnsafeCell` inline, such as an atomic, may be written through `&self` /// while the read copies its bytes, and a non-atomic read of that is undefined behavior. diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 92b7fe870..ebdb5e396 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -616,6 +616,10 @@ pub(crate) enum Access { /// way, as its struct's packing may differ between targets. #[serde(default, skip_serializing_if = "std::ops::Not::not")] unfrozen: bool, + /// Whether the field's type is `Copy` on its target, which `Copy` reads it by: a merge + /// reads it that way for a target that borrows it only where that target has it so. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + copy: bool, }, /// It reads a constant that is not a `bool` or integer. Const, @@ -631,9 +635,10 @@ pub(crate) enum Access { /// /// A getter's value is the same through any mode that compiles, and the order is how far one /// reaches: `Take` reads any field on any layout, `Copy` any `Copy` one. The merge of two -/// targets' getters of a field reads it the greater of theirs, unless that reads out unaligned -/// what the other target holds an `UnsafeCell` in (`Access::Field`'s `unfrozen`), which is a -/// difference between the targets. +/// targets' getters of a field reads it the greater of theirs, but by `Take` rather than `Copy` +/// where a target that borrows the field does not have it `Copy` (`Access::Field`'s `copy`), +/// and not at all where that reads out unaligned what the other target holds an `UnsafeCell` +/// in (`unfrozen`), which is a difference between the targets. #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] pub(crate) enum Read { /// It borrows the field. diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index eabc7a861..d668046f0 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -228,9 +228,13 @@ pub(crate) fn bare_function(f: &Function) -> Function { // Merged apart, as a trait's leaves are. f.leaf = false; // Merged to the greatest, as a target's layout may decide it. - if let Access::Field { read, unfrozen, .. } = &mut f.access { + if let Access::Field { + read, unfrozen, copy, .. + } = &mut f.access + { *read = Read::Borrow; *unfrozen = false; + *copy = false; } }) } @@ -609,22 +613,31 @@ impl Merged { // One getter serves a field on every target, though `repr(packed)` may make one // target's layout need another read than the next's: it reads by the mode that // accepts both, whose value is the same, unless that is an unaligned read of what - // a target holds an `UnsafeCell` in, which would race there. + // a target holds an `UnsafeCell` in, which would race there. A target that + // borrows a field that is not `Copy` there is not served by a `Copy` read, so + // that merges to `Take`. let races = match (&mut ours[at].access, &function.access) { ( Access::Field { set, read: ours, unfrozen: ours_unfrozen, + copy: ours_copy, .. }, Access::Field { read: theirs, unfrozen: theirs_unfrozen, + copy: theirs_copy, .. }, ) => { - let read = (*ours).max(*theirs); + let mut read = (*ours).max(*theirs); + if read == Read::Copy + && ((*ours == Read::Borrow && !*ours_copy) || (*theirs == Read::Borrow && !*theirs_copy)) + { + read = Read::Take; + } // A setter assigns and never reads the field, so it cannot race. let races = !*set && read == Read::Take @@ -632,6 +645,7 @@ impl Merged { if !races { *ours = read; *ours_unfrozen |= *theirs_unfrozen; + *ours_copy &= *theirs_copy; } races } @@ -1052,6 +1066,7 @@ mod tests { through: false, read, unfrozen, + copy: read != Read::Take, }, instance: None, home: Home::default(), @@ -1112,6 +1127,32 @@ mod tests { assert_eq!((differs[0].first.0.as_str(), differs[0].second.0.as_str()), ("x", "y")); assert_eq!(merged.records[0].methods.len(), 1); } + // A target that borrows what is not `Copy` there is not served by a `Copy` read: the + // merge reads by `Take`, and it still reports a field the other target holds an atomic in. + let uncopied = |mut api: Api| { + if let Access::Field { copy, .. } = &mut api.records[0].methods[0].access { + *copy = false; + } + api + }; + for (first, second) in [ + (uncopied(api("x", Read::Borrow, false)), api("y", Read::Copy, false)), + (api("x", Read::Copy, false), uncopied(api("y", Read::Borrow, false))), + ] { + let (merged, differs) = super::merge(vec![first, second]); + assert!(differs.is_empty()); + assert!(matches!( + merged.records[0].methods[0].access, + Access::Field { + read: Read::Take, + copy: false, + .. + } + )); + } + let (merged, differs) = super::merge(vec![uncopied(api("x", Read::Borrow, true)), api("y", Read::Copy, false)]); + assert_eq!(differs.len(), 1); + assert_eq!(merged.records[0].methods.len(), 1); // A setter never reads the field, so the same pair merges without a difference. let setter = |mut api: Api| { if let Access::Field { set, .. } = &mut api.records[0].methods[0].access { From d124e7af5e7636713ef906dde556e49a6abe5c06 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 21 Nov 2026 04:45:06 -0800 Subject: [PATCH 12/12] style(ffi): format the merge test Co-Authored-By: Claude Sonnet 5.5 --- ffi/src/merge.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index d668046f0..e48344d3b 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -1150,7 +1150,10 @@ mod tests { } )); } - let (merged, differs) = super::merge(vec![uncopied(api("x", Read::Borrow, true)), api("y", Read::Copy, false)]); + let (merged, differs) = super::merge(vec![ + uncopied(api("x", Read::Borrow, true)), + api("y", Read::Copy, false), + ]); assert_eq!(differs.len(), 1); assert_eq!(merged.records[0].methods.len(), 1); // A setter never reads the field, so the same pair merges without a difference.