Skip to content

Undefined Behaviour #6

Open
Open

Description

@edef1c

Demonstration code:

fn main() {
    let mut 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)

Activity

  1. edef1c commented on Nov 26, 2024

    @edef1c
    ContributorAuthor

    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. 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.

  2. RalfJung commented on Nov 26, 2024

    @RalfJung

    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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions