Unsound implementation of `from_bytes`
The source of unsoundness
Hi, we are the researchers from Sun Security Lab. When we tried to run our bug detector through crates.io, we found that your crate might cover some unsound implementation. Following is the source of unsoundness:
pub fn from_bytes(bytes: &[u8]) -> Self{
debug_assert!(bytes.len() >= mem::size_of::<T>());
$e(unsafe{*(bytes.as_ptr() as *const T)})
}
https://gitlab.com/ertos/endian-type-rs/-/blob/master/src/lib.rs?ref_type=heads#L55-L57
In the unsafe block, the code tried to create a misaligned pointer with casting u8 slice to the type with larger alignment. The `debug_assert!` here could only make sure the uninitialized memory would not be included in the return type. `from_bytes` is implemented on both `BigEndian` and `LittleEndian`, both of them could be unsound.
To reproduce the bug
use endian_type_rs::BigEndian;
fn main() {
let u8_arr: [u8; 4] = [1; 4];
let be: BigEndian<u16> = BigEndian::from_bytes(&u8_arr);
println!("{:?}", be);
}
run with miri,
error: Undefined Behavior: accessing memory with alignment 1, but alignment 2 is required
--> /${HOME}/.cargo/registry/src/github.com-1ecc6299db9ec823/endian-type-rs-0.1.4/src/lib.rs:126:1
|
126 | impl_Endian!(for BigEndian);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ accessing memory with alignment 1, but alignment 2 is required
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
= note: BACKTRACE:
= note: inside `endian_type_rs::BigEndian::<u16>::from_bytes` at /Users/rafaelchen/.cargo/registry/src/github.com-1ecc6299db9ec823/endian-type-rs-0.1.4/src/lib.rs:57:15: 57:44