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

Unsound assumption about the alignment of u32 and f32 #194

Closed
anforowicz opened this issue Aug 29, 2023 · 0 comments
Closed

Unsound assumption about the alignment of u32 and f32 #194

anforowicz opened this issue Aug 29, 2023 · 0 comments

Comments

@anforowicz
Copy link
Contributor

An unsafe transmute between &[f32] and &[u32] is performed here:

byteorder/src/lib.rs

Lines 1202 to 1208 in 8d9f0c0

#[inline]
fn read_f32_into(src: &[u8], dst: &mut [f32]) {
let dst = unsafe {
slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u32, dst.len())
};
Self::read_u32_into(src, dst);
}
.

The transmute may lead to Undefined Behavior if &[u32] has stricter alignment requirements than &[f32]. Primitive types (e.g. u32 or f32) are usually aligned to their size, but this is a platform specific behavior. A platform could in theory define f32 to be aligned on a 2 byte boundary, while saying that u32 must be aligned on 4 bytes. That would make read_u32_into an unaligned write.

One way to avoid the unsound assumptions is to enforce them at compile time as follows:

const _CHECK_ALIGN: () = assert!(align_of::<u32>() <= align_of::<f32>());

Many thanks to @kupiakos for finding this issue and suggesting the compile-time assertion above.

@anforowicz anforowicz changed the title Unsound assumption that the alignment of u32 and f32 Unsound assumption about the alignment of u32 and f32 Aug 29, 2023
anforowicz added a commit to anforowicz/byteorder that referenced this issue Aug 29, 2023
BurntSushi pushed a commit that referenced this issue Oct 5, 2023
BurntSushi added a commit that referenced this issue Oct 5, 2023
This is seemingly needed for the soundness fix for #194. I spent zero
time trying to find what the real MSRV was or to find another way to fix
the soundness bug while maintaining the 1.41 MSRV because I didn't care
to. Rust 1.60 is conservative enough as it is.
BurntSushi added a commit that referenced this issue Oct 6, 2023
This is seemingly needed for the soundness fix for #194. I spent zero
time trying to find what the real MSRV was or to find another way to fix
the soundness bug while maintaining the 1.41 MSRV because I didn't care
to. Rust 1.60 is conservative enough as it is.
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 a pull request may close this issue.

1 participant