Skip to content

DynamicMessage deallocates aligned storage with the wrong layout, causing UB #661

Description

@coolcmyk

steps to reproduce:

cargo new repro
cd repro
#paste the code below as main.rs
rustup toolchain install nightly --component miri
cargo +nightly miri run
use std::alloc::{Layout, alloc_zeroed, handle_alloc_error};

//see ros2_rust/rclrs/src/dynamic_message.rs:293-302
//for this bug's POC reference
fn buggy_aligned_box(size: usize) -> Box<[u8]> {
    let layout = Layout::from_size_align(size, 8).unwrap();

    unsafe {
        let ptr = alloc_zeroed(layout);

        if ptr.is_null() {
            handle_alloc_error(layout);
        }

        let slice = std::ptr::slice_from_raw_parts_mut(ptr, size);
        Box::from_raw(slice)
    }
}

fn main() {
    let storage = buggy_aligned_box(64);

    // Box<[u8]> deallocates using size 64, alignment 1.
    // well there's no explicit drop written anywhere else,
    // it's just implicitly inserted by rust by the end of the scope.
    drop(storage);
}
Image

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