SSheldon/malloc_buf

UB: Deference of misaligned pointer (DUMMY_PTR)

saethlin opened this issue · 1 comments

cargo miri test on this library produces this error:

test tests::test_null_buf ... error: Undefined Behavior: accessing memory with alignment 1, but alignment 4 is required
   --> /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/core/src/slice/raw.rs:91:14
    |
91  |     unsafe { &*ptr::slice_from_raw_parts(data, len) }
    |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ accessing memory with alignment 1, but alignment 4 is required
    |
    = 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: inside `core::slice::from_raw_parts::<u32>` at /home/ben/.rustup/toolchains/miri/lib/rustlib/src/rust/library/core/src/slice/raw.rs:91:14
note: inside `Malloc::<[u32]>::from_array` at src/lib.rs:48:21
   --> src/lib.rs:48:21
    |
48  |         let slice = slice::from_raw_parts(ptr, len);
    |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: inside `tests::test_null_buf` at src/lib.rs:129:13
   --> src/lib.rs:129:13
    |
129 |             Malloc::<[u32]>::from_array(ptr::null_mut(), 0)
    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: inside closure at src/lib.rs:127:5
   --> src/lib.rs:127:5
    |
126 |       #[test]
    |       ------- in this procedural macro expansion
127 | /     fn test_null_buf() {
128 | |         let buf = unsafe {
129 | |             Malloc::<[u32]>::from_array(ptr::null_mut(), 0)
130 | |         };
131 | |         assert!(&*buf == []);
132 | |         assert!(Some(&*buf) == Some(&[]));
133 | |     }
    | |_____^
    = note: this error originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info)

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

error: aborting due to previous error

error: test failed, to rerun pass '--lib'

This isn't something specific to Miri either, this is detected at runtime by the debug assertions I am trying to add to the standard library: rust-lang/rust#92686.

The problem is that DUMMY_PTR is not correctly aligned for most types. The way everyone else gets around this problem is calling core::ptr::NonNull::dangling() which just does core::mem::align_of::<T>() as *mut T. But this library cannot use this pattern, because here, T: ?Sized.

I can't figure out how to fix this. Normally I'd open a PR with a fix. Maybe you have better ideas?

@SSheldon Is this crate still maintained? I can help fix it.