Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Union transmutes should be "variance"-aware #19

Open
jswrenn opened this issue Sep 14, 2024 · 0 comments
Open

Union transmutes should be "variance"-aware #19

jswrenn opened this issue Sep 14, 2024 · 0 comments

Comments

@jswrenn
Copy link
Member

jswrenn commented Sep 14, 2024

The exact validity rules of unions are unsettled. However, we can support unions by implementing both the most permissive and most restrictive possibilities, depending on whether the union appears in source or destination position.

At minimum, a union's bit-validity must accept all instances assignable by field writes. For example, this union:

#[repr(C)] enum Foo { A = 1 }
#[repr(C)] enum Bar { B = 2 }

#[repr(C)] union Baz {
  a: Foo,
  b: Bar
}

...must accept both 0x01 and 0x02 as bit valid instances, because baz.a = Foo::A and baz.b = Bar::B can be written in safe code today. In other words, the bit-validity of a union is at least the union of the validity of its variants.

Complicating matters, union variants may be partially initialized. For example:

#[repr(C)] union Baz {
  a: (Foo, Bar),
  b: (Bar, Foo),
}

let baz = Baz { a: (Foo::A, Bar::B) };
baz.b.0 = Bar::B;

Now, baz's bits do not correspond, wholly, to either variant a or variant b, but rather a mix. In other words, the bit-validity of a union is at least the set of all bit validities possible through recursive field assignment.

On the other hand, it might be decided that all unions implicitly admit initialized bytes. If this is the case, we will need to treat all unions as bags of uninitialized bytes.

Until this is decided, we can't pick any definition in all cases. If TransmuteFrom treats unions as always implicitly admitting uninit, then it will accept transmutations whose soundness might change out from under us.

I think we can work around this by using the permissive bit-validity possibility for unions appearing in source position, and a more restrictive version for unions appearing in destination position.

@jswrenn jswrenn changed the title Union transmutes should be variance-aware Union transmutes should be "variance"-aware Sep 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant