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

UB: unaligned pointers #1

Open
cavemanloverboy opened this issue Apr 28, 2024 · 0 comments
Open

UB: unaligned pointers #1

cavemanloverboy opened this issue Apr 28, 2024 · 0 comments

Comments

@cavemanloverboy
Copy link

cavemanloverboy commented Apr 28, 2024

This crate has UB.

A pointer to 32 bytes with 1-byte alignment defined here

let bytes: &[u8; 32] = input.as_ref().try_into().unwrap();

is cast into a slice that require 4 byte alignment on many architectures.

fd_bs58/src/encode_32.rs

Lines 20 to 26 in 4c66dec

let bytes_as_u32: &[u32] = unsafe {
// Cast a reference to bytes as a reference to u32
std::slice::from_raw_parts(
bytes.as_ptr() as *const u32,
bytes.len() / std::mem::size_of::<u32>(),
)
};

The reads that follow are thus potentially unaligned.

To fix, we can change the reads from

for i in 0..BINARY_SZ_32 {
    binary[i] = bytes_as_u32[i].to_be(); // Convert to big-endian (network byte order)
}

to

for i in 0..BINARY_SZ_32 {
    unsafe {
        binary[i] = core::ptr::read_unaligned(&bytes_as_u32[i]).to_be(); // Convert to big-endian (network byte order)
    }
}
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