Skip to Content
Course content

244: Miri for Detecting Undefined Behavior

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've been spending a lot of time lately optimizing some low-level buffer logic using unsafe. As you know, the compiler is great at protecting us in safe Rust, but the moment we drop into unsafe, we're essentially telling the compiler, "Trust me, I know what I'm doing." The problem is, sometimes I don't actually know what I'm doing, and the compiler is more than happy to let me walk right off a cliff.

When the compiler lets you get away with murder

I wrote this little snippet to try and access an element in an array using some raw pointer arithmetic. I wanted to see if I could manually offset a pointer to a specific index without using the standard indexing syntax. It looks innocent enough:


fn main() {
    let data = [10, 20, 30, 40, 50];
    let ptr = data.as_ptr();
    
    unsafe {
        // I'm trying to get the 6th element (which doesn't exist)
        let bad_ptr = ptr.add(5); 
        println!("Value at index 5: {}", *bad_ptr);
    }
}

I ran this with cargo run. To my surprise, it didn't crash. It actually printed a value—some random garbage number from memory. Now, if I were just glancing at this, I might think, "Cool, it works." But in Rust, this is a disaster. We've just triggered Undefined Behavior (UB). The program didn't crash this time, but LLVM is now free to optimize this code in ways that could make the rest of my program behave like a haunted house.

Bringing in the interpreter

Since the standard compiler doesn't catch UB at runtime (it just assumes you're following the rules), I need something that actually tracks the state of memory. That's where Miri comes in. Miri isn't a compiler; it's an interpreter for Rust's Mid-level Intermediate Representation (MIR). It basically simulates your code execution on a "virtual" machine that keeps a strict ledger of every memory allocation and pointer move.

First, I have to install it, since it's not part of the standard toolchain:

rustup component add miri

Now, instead of cargo run, I'll run my code through Miri:

cargo miri run

Reading the crime scene report

Miri didn't just run the code; it screamed at me. The output was an absolute goldmine of information. It didn't just say "Error"; it told me exactly why the operation was illegal:


error: Undefined Behavior: memory access failed: 
allocation 1 contains 5 elements, but 5 was accessed

This is the "aha!" moment. Miri knows that data is an array of 5 elements. When I called ptr.add(5), I created a pointer that points exactly one element past the end of the allocation. While creating a pointer to one-past-the-end is actually allowed in some contexts, dereferencing it is a strict violation. Miri caught the exact instruction where I crossed the line.

Verifying the fix

I'll adjust the code to stay within bounds and run it through Miri again. I want to make sure that my "fix" isn't just masking another problem.


fn main() {
    let data = [10, 20, 30, 40, 50];
    let ptr = data.as_ptr();
    
    unsafe {
        // Now we stay within the 0-4 index range
        let safe_ptr = ptr.add(4); 
        println!("Value at index 4: {}", *safe_ptr);
    }
}

Running cargo miri run now yields a clean exit. No warnings, no errors. It's a strange feeling—I'm not just trusting my eyes or the fact that the program "doesn't crash"; I have a mathematical guarantee from the interpreter that I haven't violated the memory model in this specific execution path.

One thing to keep in mind: Miri is slow. Because it's interpreting every single operation and tracking every byte of memory, it's significantly slower than native execution. You don't run your whole test suite through it every time you save a file; you use it when you're writing unsafe blocks or when you have a bug that only appears in release mode (which is a classic sign of UB).




📋 Practical Task

Hunting Out-of-Bounds Pointers in a Circular Buffer

You have been handed a simplified implementation of a circular buffer that uses unsafe for performance. The original author claimed it was optimized, but it's behaving erratically in production. Your task is to use Miri to identify the Undefined Behavior and fix it.

The Buggy Code:


struct SimpleBuffer {
    data: Vec<u8>,
    head: usize,
}

impl SimpleBuffer {
    fn new(size: usize) -> Self {
        Self {
            data: vec![0; size],
            head: 0,
        }
    }

    unsafe fn read_next(&mut self) -> u8 {
        let ptr = self.data.as_ptr();
        // BUG: The author forgot to wrap the index using modulo
        let val = *ptr.add(self.head); 
        self.head += 1;
        val
    }
}

fn main() {
    let mut buffer = SimpleBuffer::new(3);
    unsafe {
        println!("Read 1: {}", buffer.read_next());
        println!("Read 2: {}", buffer.read_next());
        println!("Read 3: {}", buffer.read_next());
        // This fourth call should trigger UB
        println!("Read 4: {}", buffer.read_next());
    }
}

Your Instructions:

  1. Set up a new Rust project and paste the code above into main.rs.
  2. Run the program using cargo run. Observe if it crashes or prints a value.
  3. Install Miri via rustup component add miri.
  4. Run the program using cargo miri run and analyze the error message to confirm exactly where the memory violation occurs.
  5. Fix the read_next method so that the head index wraps around the buffer size, ensuring the pointer never exceeds the allocation bounds.
  6. Verify the fix by running cargo miri run again until it completes without errors.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.