Skip to content

Transmuting enums is UB #92

@Pzixel

Description

@Pzixel

Looking at code I found that you are performing UB conversion from primitive to enum

anne-key/src/protocol.rs

Lines 10 to 35 in ac02810

#[repr(u8)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum MsgType {
Reserved = 0,
Error = 1,
System = 2,
Ack = 3,
Reboot = 4,
Macro = 5,
Ble = 6,
Keyboard = 7,
Keyup = 8,
Led = 9,
FwInfo = 10,
FwUp = 11,
CustomLed = 12,
CustomKey = 13,
}
impl From<u8> for MsgType {
#[inline]
fn from(b: u8) -> Self {
unsafe { transmute(b) }
}
}

#[repr(u8)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum MsgType {
    Reserved = 0,
    Error = 1,
    System = 2,
    Ack = 3,
    Reboot = 4,
    Macro = 5,
    Ble = 6,
    Keyboard = 7,
    Keyup = 8,
    Led = 9,
    FwInfo = 10,
    FwUp = 11,
    CustomLed = 12,
    CustomKey = 13,
}

impl From<u8> for MsgType {
    #[inline]
    fn from(b: u8) -> Self {
        unsafe { transmute(b) }
    }
}

You may argue "Hey, but there is an attribute", but in fact it doesn't work the way you expect and may produce panics in safe Rust:

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=dd880f555dff38824b094dd8dec2f6f2

I'd better to be replaced with num_derive:

#[repr(u8)]
#[derive(Debug, Copy, Clone, FromPrimitive)]
pub enum MsgType {

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