Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,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 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<Box<dyn Future<Output = ()> + Send>>` meets, as kio's `clock::timeout` takes, or taken as `Pin<&mut F>` by a poll, as kio's `Waiter::poll_future` takes | `<prefix>_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 |
Expand Down
21 changes: 21 additions & 0 deletions ffi/fixtures/api/examples/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
73 changes: 73 additions & 0 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2165,6 +2165,79 @@ 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, 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<String>,
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 {
page,
title: title.to_string(),
note: None,
hasp: Hasp::default(),
dock: &DOCK,
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 {
Expand Down
4 changes: 4 additions & 0 deletions ffi/fixtures/reject/expected.txt
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,14 @@ fixtures/reject/src/lib.rs:1623:2: rust2-ffi: cannot export method `Knot<reject:
help: spell the instance in a signature of its own, such as a function returning it, or stop nesting generic types in a method's signature
fixtures/reject/src/lib.rs:162:1: rust2-ffi: cannot export fn `measure`: foreign type `tls::held::Local`
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:167:1: rust2-ffi: cannot export instance `Cell<std::vec::Vec<String>>`: type argument `std::vec::Vec<String>`
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<tls::held::Cert>`: 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<T>` or a `Box<T>`, 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<String>`, `AsRef<str>`, `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<tls::held::Cert>`
Expand Down
59 changes: 59 additions & 0 deletions ffi/fixtures/reject/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1635,3 +1635,62 @@ impl<T> Rope<Knot<Tie<T>>> {
#[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
}
}

/// 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
}
}
68 changes: 65 additions & 3 deletions ffi/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -77,6 +77,10 @@ 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";
const RACY: &str = "unaligned interior-mutable field";

fn why(construct: &'static str, detail: impl Into<String>) -> Why {
Why {
construct,
Expand Down Expand Up @@ -2994,9 +2998,16 @@ 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; one lent
// through a reference it holds is its pointee, which the copied reference reaches.
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
// C's borrow for the call is not.
Expand All @@ -3011,7 +3022,11 @@ 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
|| get.construct == RACY =>
{
self.refuse(&shown, "field", span, vec![get]);
Ok((None, Some(set)))
}
Expand Down Expand Up @@ -3072,6 +3087,9 @@ impl<'tcx> Collector<'tcx> {
access: Access::Field {
set,
through: !assigned,
read: how,
Comment thread
kixelated marked this conversation as resolved.
Resolved
unfrozen: self.unfrozen(ty),
copy: self.copies(site, ty),
},
instance: None,
home: Home::default(),
Expand All @@ -3097,6 +3115,50 @@ 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 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.
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())
}

/// 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);
!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<Function>) -> Vec<Function> {
Expand Down
26 changes: 19 additions & 7 deletions ffi/src/glue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};

Expand Down Expand Up @@ -3102,12 +3102,24 @@ 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() }})"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
),
}
}
Access::Field { set: true, .. } => format!("({}).{} = {}", args[0], ident(function.name()), args[1]),
Access::Const => callee,
Access::Parse => format!(
Expand Down
6 changes: 6 additions & 0 deletions ffi/src/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ 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 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<T>` or a `Box<T>`, 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<u8>`, or hold the buffer in an object; C lends no buffer mutably"
}
Expand Down
Loading