You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fnmain(){letmut buf = magic_buffer::MagicBuffer::new(4096).unwrap();let a = buf[0..4096][0];
buf[1..4097][4095] = 1;let b = buf[0..4096][0];println!("a = {a}");println!("b = {b}");let c = buf[0..4096][0];println!("c = {c}");}
Output in debug mode:
a = 0
b = 1
c = 1
Output in release mode:
a = 0
b = 0
c = 1
The key here is that we're violating LLVM's memory model (and from what I understand from @RalfJung, probably gcc's memory model as well) by aliasing the physical memory in virtual memory. Seen post-optimisation, we're basically doing this:
let a = *buf.ptr;*buf.ptr.add(4096) = 1;let b = *buf.ptr;
As far as LLVM is concerned, *buf.ptr and *buf.ptr.add(4096) don't alias, so this code is equivalent:
let a = *buf.ptr;*buf.ptr.add(4096) = 1;let b = a;
(and as for why c shows up correctly: print is heavy enough to clobber all the registers, so LLVM chooses to reload)
Empirically, compiler_fence(AcqRel) inhibits the memory reorderings this PoC relies on, but I'm not 100% confident that this is actually safe. Having asm!("/* {ptr} */", ptr = in(reg) = buf.ptr, options(nostack, preserves_flags)) represent the "virtual memcpy" plays it a little safer (and, AIUI, implies the fence), but I'm not confident even that is formally correct.
I would recommend using an inline asm block, since a compiler fence is fundamentally the wrong tool for this (see the compiler_fence docs for an explanation).
Activity
edef1c commentedon Nov 26, 2024
AFAICT this is the same underlying issue as gnzlbg/slice_deque#88, though I haven't taken the time to write a PoC for that crate. If it works there, it presumably applies to https://github.com/LiquidityC/slice_ring_buffer (the maintained fork of that crate) as well.
Empirically,
compiler_fence(AcqRel)inhibits the memory reorderings this PoC relies on, but I'm not 100% confident that this is actually safe. Havingasm!("/* {ptr} */", ptr = in(reg) = buf.ptr, options(nostack, preserves_flags))represent the "virtual memcpy" plays it a little safer (and, AIUI, implies the fence), but I'm not confident even that is formally correct.RalfJung commentedon Nov 26, 2024
I would recommend using an inline asm block, since a compiler fence is fundamentally the wrong tool for this (see the
compiler_fencedocs for an explanation).