skip to content

A Rust parser transmutes wire bytes into a `#[repr(C)]` header with a `bool` field; why is a byte of 2 undefined behaviour?

level: middleimportance: should knowfreq 42%

answer

  1. validity is per type
  2. bool is exactly 0 or 1
  3. transmute checks size only
  4. validate bytes, then build
  5. E0512 for mismatched sizes

basics

~20 s

A bool may only hold 0 or 1, and producing any other value is immediate undefined behaviour. mem::transmute checks only that the sizes match, so the parser must validate the byte and build the header field by field.

solid answer

~40 s

The Reference lists *producing an invalid value* as undefined behaviour, and for `bool` the only valid bytes are 0 and 1. `std::mem::transmute::<[u8; 4], Header>` compiles because both types are four bytes, and that equal-size check (E0512 when it fails) is all it verifies: its docs require the value to be valid at both the source and the destination type. A byte of 2 in the `compressed` position therefore creates an invalid `Header` the moment `transmute` returns, even if the code never reads that field. Miri reports "encountered 0x02, but expected a boolean". The fix is to keep untrusted bytes as integers: match the byte against 0 and 1, return an error for anything else, and construct the struct from checked fields, or use `u32::from_le_bytes` style methods for numeric fields.

code

rust · 19 lines
rust
#[derive(Debug, Clone, Copy)]
#[repr(C)]
struct Header {
    version: u8,
    compressed: bool,
    kind: u8,
    flags: u8,
}

fn parse(bytes: [u8; 4]) -> Header {
    // SAFETY claim (wrong): Header is four one-byte fields.
    unsafe { std::mem::transmute::<[u8; 4], Header>(bytes) }
}

fn main() {
    let wire = [1u8, 2, 7, 0]; // byte 1 is 2: not a valid bool
    let h = parse(wire);
    println!("version {}", h.version);
}

go deeper

for a junior

Recall that a bool is exactly 0 or 1 and that some types have bit patterns that are never allowed, even in unsafe code.

for a middle

Explain that transmute verifies only equal size (E0512 otherwise) and that producing an invalid value is UB at once, not when it is used.

for a senior

Treat every external byte buffer as untrusted: parse integers with from_le_bytes, map flags and tags with match or TryFrom, and keep transmute out of parsers.

for a principal

Ask whether the parser needs unsafe at all; a safe field-by-field decode costs little and removes a whole class of review burden from code that handles hostile input.

## The rule: every value must be valid for its type The Rust Reference says the compiler **assumes that all values produced during program execution are valid**, and producing an invalid value is **immediate undefined behaviour**. "Producing" covers assigning, reading, passing to a function and returning from one, so it is not only reading the field that counts. Validity depends on the type: - a **`bool`** must be `false` (0) or `true` (1); - a **`char`** must not be a surrogate (`0xD800..=0xDFFF`) and must be at most `char::MAX`; - an **enum** must have a valid discriminant, and the fields of that variant must be valid; - a **reference or `Box<T>`** must be aligned, non-null and not dangling; - an **integer, float or raw pointer** must be initialised; - a **struct, tuple or array** requires every field or element to be valid; - **`NonNull<T>`** and the `NonZero` integers must stay in their custom valid range. The compiler exploits these facts. Because a `bool` can only be 0 or 1, the compiler may fit `Option<bool>` into one byte by giving `None` another bit pattern, and generated code may use the bool as a table index without a bounds check. If the byte is 2, those assumptions are simply false. ## What `mem::transmute` actually checks `std::mem::transmute::<Src, Dst>` reinterprets the bits of a value as another type. Its documentation states two things: 1. **Both types must have the same size**, and compilation fails if that is not guaranteed. `transmute::<u32, u16>` is rejected with `error[E0512]: cannot transmute between types of different sizes, or dependently-sized types`. 2. **Both the argument and the result must be valid at their types**; violating this is UB, and the docs call `transmute` *incredibly unsafe* and *the absolute last resort*. So the size rule is the only part the compiler checks. Validity is entirely your job. ## The parser in this question | Field | Type | Valid bytes | Byte on the wire | |---|---|---|---| | `version` | `u8` | any | 1 | | `compressed` | `bool` | 0 or 1 | **2** | | `kind` | `u8` | any | 7 | | `flags` | `u8` | any | 0 | The header is `#[repr(C)]`, so its four one-byte fields sit in declaration order and the sizes match; `transmute` compiles and, in a normal build, the program prints the version and appears to work. But the second byte is 2, so the `Header` that `transmute` returns is invalid. Miri stops on the `transmute` line with *constructing invalid value of type Header: at .compressed, encountered 0x02, but expected a boolean*. (Without `repr(C)` the field order would not be guaranteed at all; field ordering and padding are the subject of the lesson on type layout.) A wire format is **untrusted input**: any byte can arrive, so any type with invalid bit patterns (`bool`, `char`, enums, references, `NonZero`) must never be produced from it directly. ## The fix: validate, then construct - Read numeric fields with `u16::from_le_bytes`, `u32::from_be_bytes` and similar, which are safe and accept every bit pattern. - Turn a flag byte into a `bool` with a `match` on 0 and 1 and an error for anything else. - Turn a tag byte into an enum with a `TryFrom<u8>` implementation that matches the known discriminants. - Build the struct from the checked fields with an ordinary struct expression. The second snippet does exactly that and needs no `unsafe` at all; it returns an `Err` for the byte 2 and runs clean under Miri. ## Other hazards of reading structs out of bytes Even when every field is an integer, casting a `&[u8]` pointer to `*const Header` and dereferencing it can be UB for a different reason: if `Header` has an alignment above 1 (say it contains a `u32`), a pointer into the middle of a byte buffer may be **misaligned**, and the Reference lists accessing a place based on a misaligned pointer as UB. `std::ptr::read_unaligned` exists for that case. Clippy's `transmute_int_to_bool` lint flags transmuting an integer into a `bool`, and rustc's `unnecessary_transmutes` lint flags transmutes a safe method could replace, such as bytes into an integer; the general alternatives to `transmute` (`from_ne_bytes`, `to_bits`, pointer casts) are listed in its own documentation.

  • Would the transmute be sound if the header held only `u8` fields?
    Yes for this conversion: every byte is a valid `u8`, the struct is `repr(C)` with four one-byte fields, so `[u8; 4]` and the header have the same size and every input is valid at both types. It would still be pointless, since the fields can be copied out safely. The danger returns as soon as a field type has invalid bit patterns, or when you reinterpret a borrowed buffer through a pointer instead of transmuting an owned array.
  • What does rustc say if you transmute a `u32` into a `u16`?
    It refuses to compile: `error[E0512]: cannot transmute between types of different sizes, or dependently-sized types`, with notes giving the source type as `u32` (32 bits) and the target as `u16` (16 bits). The size check is the only property `transmute` verifies at compile time.
  • How should a tag byte become a Rust enum?
    Implement `TryFrom<u8>` for the enum with a `match` that maps each known discriminant to its variant and returns an error otherwise. Transmuting the byte into the enum is undefined behaviour whenever the byte is not one of the declared discriminants, because the Reference requires an enum to have a valid discriminant.

  • Says the transmute is fine as long as the bool field is never read.
  • Believes transmute checks that the bytes are valid for the target type.
  • Thinks a bool of 2 simply behaves as true.
  • Treats a wire buffer as trusted because the sender is our own service.
  • Fixes the size error by transmuting through a larger intermediate type.