Skip to content

Incorrect (and probably unsound) transmutes #40

@niklasf

Description

@niklasf

The code contains several transmutes similar to this:

#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct VendorInfo {
    ebx: u32,
    edx: u32,
    ecx: u32,
}

impl VendorInfo {
    /// Return vendor identification as human readable string.
    pub fn as_string<'a>(&'a self) -> &'a str {
        unsafe {
            let brand_string_start = self as *const VendorInfo as *const u8;
            let slice = slice::from_raw_parts(brand_string_start, 3 * 4);
            let byte_array: &'a [u8] = transmute(slice);
            str::from_utf8_unchecked(byte_array)
        }
    }
}

Reading about transmutes in the nomicon, this is not correct, because the Rust compiler is free to reorder the fields of the struct.

It is also probably unsound, because I believe the Rust compiler is technically even free to add padding.

Adding #[repr(C)] may be a fix. However I am not sure what role endianness plays here (same question as #39). is a fix. I'll submit a pull request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions