Stream: t-lang/wg-unsafe-code-guidelines

Topic: repr(C) structs and unions


bluss (Dec 22 2018 at 13:22, on Zulip):

I would like to know and specify that the repr(C) layout rules apply, even if we use non-C compatible types in the struct or union fields.

Given #[repr(C)] union Foo<T> { empty: (), value: ManuallyDrop<T> } one can say that the types Foo<String> or Foo<Rc<dyn std::fmt::Display>> are not meaningfully C compatible, yet it would be important to know that representation rules for offset from the start of the type and field order still apply. I assume they do, but I think it has not been clear what "C-compatible" means when faced with blatant c-incompatibility.

Same question with #[repr(C)] struct Bar<T: ?Sized> { value: T } and the type Bar<str>.

Edit: Even type () in itself is also incompatible, strictly speaking.

gnzlbg (Dec 22 2018 at 13:48, on Zulip):

@bluss repr(C) does not apply recursively / transitively to the types of the struct / union fields

gnzlbg (Dec 22 2018 at 13:49, on Zulip):

it only applies to the layout of the struct that's actually repr(C), the layout of the fields is irrelevant

gnzlbg (Dec 22 2018 at 13:50, on Zulip):

e.g. given struct Foo; and #[repr(C)] struct Bar(Foo); we have to be able to write to both Bar's field 0 and Foos via a &mut Foo without knowing where the &mut Foo actually points to (a single Foo, or a Foo inside a Bar).

bluss (Dec 22 2018 at 14:00, on Zulip):

Sure, there is no question about being recursive. Existing recommendations seem to be written in terms of guaranteeing compatibility with an equivalent struct in C. My question is, can we also use the guarantees of repr(C) layout even when there can be no equivalent C struct.

RalfJ (Dec 22 2018 at 15:05, on Zulip):

per https://github.com/rust-rfcs/unsafe-code-guidelines/blob/master/reference/src/representation/unions.md, the offset of all fields in a repr(C) union is 0

gnzlbg (Dec 22 2018 at 17:22, on Zulip):

that's independent from whatever we'll end up doing with ZSTs in repr(C) types

bluss (Dec 22 2018 at 18:47, on Zulip):

Great, so there is no implied restriction to certain C-compatible types and we apply the layout rule to all unions/structs.

gnzlbg (Dec 22 2018 at 22:03, on Zulip):

Exactly, in particular, repr(C) is orthogonal to whether a type is "C FFI safe"/"proper ctype" etc.

Last update: Nov 19 2019 at 19:00UTC