bitmaps icon indicating copy to clipboard operation
bitmaps copied to clipboard

Undefined behaviour with bool storage type

Open zroug opened this issue 9 months ago • 0 comments

This is because boolean values don't support all bit patterns.

An object with the boolean type has a size and alignment of 1 each. The value false has the bit pattern 0x00 and the value true has the bit pattern 0x01. It is undefined behavior for an object with the boolean type to have any other bit pattern.

https://doc.rust-lang.org/reference/types/boolean.html

Both these tests fail when run with Miri:

#[test]
fn test1() {
    let _ = Bitmap::<1>::try_from([0xff].as_slice());
}

#[test]
fn test2() {
    let mut bm = Bitmap::<1>::new();
    bm.as_mut()[0] = 0xff;
    let _ = bm.into_value();
}
test test1 ... error: Undefined Behavior: constructing invalid value at .value: encountered 0xff, but expected a boolean
   --> /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/bitmaps-3.2.1/src/bitmap.rs:144:27
    |
144 |                     data: data.assume_init(),
    |                           ^^^^^^^^^^^^^^^^^^ constructing invalid value at .value: encountered 0xff, but expected a boolean
    |
    = 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 on thread `test1`:
    = note: inside `<bitmaps::Bitmap<1> as std::convert::TryFrom<&[u8]>>::try_from` at /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/bitmaps-3.2.1/src/bitmap.rs:144:27: 144:45
test test2 ... error: Undefined Behavior: constructing invalid value at .data: encountered 0xff, but expected a boolean
 --> lib.rs:9:10
  |
9 |     let _ = bm.into_value();
  |             ^^ constructing invalid value at .data: encountered 0xff, but expected a boolean
  |
  = 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 on thread `test2`:
  = note: inside `test2` at lib.rs:9:10: 9:12

zroug avatar May 14 '24 12:05 zroug