Stream: t-lang/wg-unsafe-code-guidelines

Topic: potential misuse of &mut


Gankro (May 28 2019 at 17:20, on Zulip):

So I'm reviewing a janky-but-optimized replacement for bincode for webrender, and I ran into this interesting case where things blow up: https://github.com/djg/peek-poke/issues/1#issuecomment-496605658

Gankro (May 28 2019 at 17:23, on Zulip):

specifically even if they properly use MaybeUninit, and properly deny needs_drop types, they still have the problem that they can be doing

let x = MaybeUninit::<bool>::uninit();
let ptr = &mut *x.as_mut_ptr();
*ptr = true;
Some(x.assume_init())

RalfJ (May 28 2019 at 17:30, on Zulip):

and refactoring that to not use references is hard?

RalfJ (May 28 2019 at 17:31, on Zulip):

they can avoid the drop issue by using ptr::write even when using references, right?

Gankro (May 28 2019 at 17:31, on Zulip):

No it should be fairly easy to refactor, just annoying

Gankro (May 28 2019 at 17:32, on Zulip):

Yes you can ptr::write a reference but you have not made it clear that x: &mut bool = &mut mem::uninitialized() isn't UB

RalfJ (May 28 2019 at 17:33, on Zulip):

yes that is the other problem

RalfJ (May 28 2019 at 17:34, on Zulip):

I was going from "UB in the implementation" to "UB in the spec" ;)

RalfJ (May 28 2019 at 17:35, on Zulip):

depending on how annoying it is to avoid the &mut bool pointing to uninit memory, this might be a data pointer for https://github.com/rust-lang/unsafe-code-guidelines/issues/77

Gankro (May 28 2019 at 17:36, on Zulip):

I've given them several alternatives to avoid it. It's more just a "unsafe programmers sure don't expect it" sorta thing

Gankro (May 28 2019 at 17:38, on Zulip):

Also since I have your attention, it is totally defined to do transmute<&mut u64, &mut [u8; 8]>(val) to deserialize native-endian values, right?

Gankro (May 28 2019 at 17:38, on Zulip):

Like there's not a weird rule here that will break?

Gankro (May 28 2019 at 17:39, on Zulip):

(the alignment only weakens, and we just pass the reference to a method and forget about it instantly)

RalfJ (May 28 2019 at 17:39, on Zulip):

yes taht seems toally okay. though transmutes with lifetimes always make me nervous

RalfJ (May 28 2019 at 17:40, on Zulip):

but this should even be a safe function:

fn u64_bytes(x: &mut u64) -> &mut [u8; 8] {  unsafe { mem::transmute(x) } }
RalfJ (May 28 2019 at 17:40, on Zulip):

and then you can do whatever you want with that function :D

Gankro (May 28 2019 at 17:41, on Zulip):

cool

RalfJ (May 28 2019 at 17:41, on Zulip):

sometimes I have good news ;)

RalfJ (May 28 2019 at 17:41, on Zulip):

I've given them several alternatives to avoid it. It's more just a "unsafe programmers sure don't expect it" sorta thing

yeah fair. that's one reason why I am arguing for not enforcing validity below references.

RalfJ (May 28 2019 at 17:41, on Zulip):

OTOH, optimizing away &self methods implemented for ! is nice^^

Last update: Nov 19 2019 at 18:50UTC