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

Use #[repr(C)] so the offset of every union field is 0. #42

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

anforowicz
Copy link

According to
https://rust-lang.github.io/unsafe-code-guidelines/layout/unions.html#unions-with-default-layout-reprrust "the default layout of Rust unions is, in general, unspecified" and "there are no general guarantees about the offset of the fields, [and] whether all fields have the same offset".

This commit explicitly annotates union A with #[repr(C)] so that both of its fields are at offset 0 - this ensures that transmuting one field into the other is valid. This change is based on https://rust-lang.github.io/unsafe-code-guidelines/layout/unions.html#c-compatible-layout-repr-c which says that "the offset of every field is 0".

According to
https://rust-lang.github.io/unsafe-code-guidelines/layout/unions.html#unions-with-default-layout-reprrust
"the default layout of Rust unions is, in general, unspecified" and
"there are no general guarantees about the offset of the fields, [and]
whether all fields have the same offset".

This commit explicitly annotates `union A` with `#[repr(C)]` so that
both of its fields are at offset 0 - this ensures that transmuting
one field into the other is valid.  This change is based on
https://rust-lang.github.io/unsafe-code-guidelines/layout/unions.html#c-compatible-layout-repr-c
which says that "the offset of every field is 0".
@anforowicz
Copy link
Author

Credit for finding the lack of offset guarantees goes to @danakj - this PR is based on the comments at https://chromium-review.googlesource.com/c/chromium/src/+/4723145/31/third_party/rust/chromium_crates_io/vendor/crc32fast-1.4.2/src/specialized/pclmulqdq.rs#69

This initial PR proposal is a fairly minimal change to address the problem. I've also considered the following alternative approaches for fixing this issue:

  • Do nothing:
    • The modified code is behind if false and therefore is not used
    • This issue would still be present if the code is uncommented + would still be brought up in future reviews/audits
  • Switch to std::mem::transmute
  • Delete the unused code altogether

WDYT?

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

Successfully merging this pull request may close these issues.

1 participant