Skip to content

[Undefined Behavior] Misaligned Raw Pointer with transmute_slice #877

@shinmao

Description

@shinmao

Hello, we are reviewing the previous advisories. We find that the following function transmute_slice can trigger undefined behavior by creating misaligned pointer. We consider that we should not allow users to decide two generic types (v and U) by themselves.

Fyrox/fyrox-core/src/lib.rs

Lines 366 to 369 in ebffbe6

unsafe {
std::slice::from_raw_parts(
v.as_ptr() as *const U,
std::mem::size_of_val(v) / std::mem::size_of::<U>(),

Check the safety doc.

data must be non-null, valid for reads for len * size_of::() many bytes, and it must be properly aligned.

Following is the PoC:

use fyrox_core::transmute_slice;

fn main() {
    let data: Vec<u8> = vec![1, 2, 3, 4, 5];
    let bytes: &[u32] = transmute_slice(&data);
    println!("Byte length: {}", bytes.len());
}

Miri's result:

error: Undefined Behavior: constructing invalid value: encountered an unaligned reference (required 4 byte alignment but found 1)
   --> /root/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/fyrox-core-0.36.2/src/lib.rs:338:9
    |
338 | /         std::slice::from_raw_parts(
339 | |             v.as_ptr() as *const U,
340 | |             std::mem::size_of_val(v) / std::mem::size_of::<U>(),
341 | |         )
    | |_________^ Undefined Behavior occurred here
    |
    = 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 `fyrox_core::transmute_slice::<u8, u32>` at /root/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/fyrox-core-0.36.2/src/lib.rs:338:9: 341:10

We suggest to add assertion of alignment check.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions