Sub topic 5
Reading a Miri error report
This chapter assumes you can run cargo miri run and cargo miri test from the previous chapter, and that you know what undefined behavior (UB) is. Here you learn to read what Miri prints when it stops. A report names the kind of failure, the source location, and often the earlier event that caused it. Reading all three parts is usually the difference between a quick fix and a long guessing session.
Miri stops at the first error
Miri interprets your program step by step. When it detects UB, it prints one report and halts the interpretation. Under cargo miri test, that test fails and the other tests still run. Under cargo miri run, the process exits with a nonzero status.
Because execution stops, one report is not a complete list of problems. After you fix the reported bug, run Miri again. A second bug further along the same path will then appear.
Anatomy of a report
Take the out-of-bounds read from earlier in the tutorial.
fn main() {
let v = vec![1, 2, 3];
let p = v.as_ptr();
let x = unsafe { *p.add(3) };
println!("{x}");
}Natively this often prints a garbage number. Under Miri you get a report shaped like this. The exact wording changes between Miri versions, and the allocation ids and addresses differ from run to run.
error: Undefined Behavior: memory access failed: expected a pointer to 4 bytes of memory, but got alloc171+0xc which is at or beyond the end of the allocation of size 12 bytes
--> src/main.rs:4:22
|
4 | let x = unsafe { *p.add(3) };
| ^^^^^^^^^ Undefined Behavior occurred here
|
= 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
help: alloc171 was allocated here:
--> src/main.rs:2:13
|
2 | let v = vec![1, 2, 3];
| ^^^^^^^^^^^^^
= note: BACKTRACE (of the failing thread):
= note: inside `main` at src/main.rs:4:22: 4:31The report has five parts, and each answers a different question.
- The headline begins with
error: Undefined Behavior:and then a description. It says what rule was broken. - The primary span is the arrow and the carets. It points at the operation that triggered the error, which is not always the line with the root cause.
- The help lines say that this is a bug in your program, not in Miri, and link to the Rust reference list of UB.
- Secondary help blocks, such as
alloc171 was allocated here, show earlier events that matter. They carry the history of the memory involved. - The backtrace lists the call stack of the failing thread, from the failing operation outward to
mainor the thread entry point.
The headline here contains alloc171+0xc. An allocN name is Miri's label for one allocation, and +0xc is a byte offset into it. The vector holds three i32 values, which is 12 bytes, so offset 0xc is 12. The read starts at the first byte after the end.
Classifying the headline
Most headlines fall into a few families. Recognizing the family tells you which later chapter section applies.
| Headline fragment | Meaning | Typical cause |
|---|---|---|
| `memory access failed ... beyond the end of the allocation` | Out-of-bounds access | Index or pointer offset too large |
| `pointer not dereferenceable ... has been freed` | Use-after-free | Pointer outlived its owner |
| `constructing invalid value` | Invalid value | `transmute` or `from_raw` creating a bad `bool`, `char`, reference or enum |
| `using uninitialized data` | Uninitialized read | `assume_init` before writing |
| `attempting a read/write access using <tag> ... but that tag does not exist in the borrow stack` | Stacked Borrows violation | Using a pointer after a conflicting reference was created |
| `reborrow through ... is forbidden` or `this error occurs as part of ... access` | Tree Borrows violation | Same family of aliasing mistake, different model |
| `Data race detected between` | Data race | Unsynchronized access from two threads |
Two headlines look similar but are not UB. unsupported operation means Miri cannot emulate something, such as a foreign function call, and tells you nothing about your code's correctness. A memory-leak error at program exit is also a Miri diagnostic, not UB. Check the first words after error: before assuming the program is broken.
Following the history: use-after-free
The most informative reports include the history of the memory. Here is the use-after-free example.
fn main() {
let p = Box::into_raw(Box::new(5));
unsafe {
drop(Box::from_raw(p));
println!("{}", *p);
}
}The report has the same layout, with three events instead of one.
error: Undefined Behavior: memory access failed: alloc171 has been freed, so this pointer is dangling
--> src/main.rs:5:24
|
5 | println!("{}", *p);
| ^^ Undefined Behavior occurred here
|
help: alloc171 was allocated here:
--> src/main.rs:2:30
|
2 | let p = Box::into_raw(Box::new(5));
| ^^^^^^^^^^^
help: alloc171 was deallocated here:
--> src/main.rs:4:14
|
4 | drop(Box::from_raw(p));
| ^^^^^^^^^^^^^^^^
= note: BACKTRACE (of the failing thread):
= note: inside `main` at src/main.rs:5:24: 5:26Read it as a story: allocated on line 2, freed on line 4, accessed on line 5. The span is the access, but the decision that was wrong is usually the free, or the pointer that was kept. Without the middle block you would have to find the free yourself, which is hard when the three events live in different functions.
Following the history: aliasing
Aliasing reports add tag events. A tag is the identity Miri attaches to each pointer and reference so it can track which ones are still allowed to access memory. This program breaks the rules.
fn main() {
let mut x = 10;
let raw = &mut x as *mut i32;
let r = &mut x;
unsafe { *raw = 20; }
*r += 1;
}Under the default Stacked Borrows model, the report has the shape below. Tag numbers and wording vary.
error: Undefined Behavior: attempting a write access using <2> at alloc171[0x0], but that tag does not exist in the borrow stack for this location
--> src/main.rs:5:14
|
5 | unsafe { *raw = 20; }
| ^^^^^^^^^ this error occurs as part of an access at alloc171[0x0..0x4]
|
help: <2> was created by a SharedReadWrite retag at offsets [0x0..0x4]
--> src/main.rs:3:15
|
3 | let raw = &mut x as *mut i32;
| ^^^^^^
help: <2> was later invalidated at offsets [0x0..0x4] by a Unique retag
--> src/main.rs:4:13
|
4 | let r = &mut x;
| ^^^^^^Again there are three events: the pointer was created (line 3), invalidated (line 4), and used (line 5). The fix is to stop using raw after creating r, or to derive r from raw so that one pointer remains the parent. A later chapter covers the models in detail. For now, learn the pattern: created here, invalidated here, used here.
If you switch models with MIRIFLAGS="-Zmiri-tree-borrows", the same program produces a differently worded report. Tree Borrows describes the permission state of the tag at the failing access instead of a stack. The three-event reading still applies.
Using the backtrace
The BACKTRACE note lists frames from the failing operation outward. Frames inside the standard library appear too, for example core::ptr::... or alloc::vec::.... Your own code is usually the first frame without a core or std path. That frame is where your program passed bad input to the library, and it is the place to start.
By default Miri trims frames to keep reports short. If a deep call chain hides the context, set MIRIFLAGS="-Zmiri-backtrace=full" to print every frame, including internal ones.
MIRIFLAGS="-Zmiri-backtrace=full" cargo +nightly miri testFor a test run, the report is printed once for the failing test, followed by the usual FAILED summary from the test harness. The harness lines only name the test. All diagnostic detail is in the Miri block.
Common mistakes when reading reports
- Fixing the span instead of the cause. In the use-after-free example, deleting the
println!removes the error but leaves the dangling pointer in the program. Look at the help blocks first. - Assuming the number is stable.
alloc171and tag<2>change between runs and versions. Use them only within one report to match events together. - Treating a one-past-the-end offset as safe. Computing
p.add(3)for three elements is allowed. Reading through it is not. The report tells you which operation failed. - Stopping after one fix. Miri stops at the first error, so rerun until the run is clean.
- Blaming Miri for
unsupported operation. Miri is saying it cannot run that call, not that your code is wrong.
Exercise
A Miri report says alloc42 has been freed, so this pointer is dangling, with the primary span on line 20. It has help blocks alloc42 was allocated here pointing to line 5 and alloc42 was deallocated here pointing to line 12. Which line do you examine first to fix the bug, and why?
Show answer
Examine line 12 first. The span on line 20 only shows where the dangling pointer was used. The deallocation on line 12 is where the memory's lifetime ended, so it shows the real decision to fix. Either the free happens too early, or the pointer that survives it should not have been kept. Line 5 explains where the memory came from, which helps you check who is supposed to own it.
Exercise
You run Miri and get error: unsupported operation: can't call foreign function. Does this mean your code has undefined behavior? What can you do?
Show answer
No. It means Miri cannot emulate that foreign (C) function, so it does not know whether your code is correct. You can avoid the call under Miri with #[cfg(miri)] and substitute a pure Rust version, or skip the test with #[cfg_attr(miri, ignore)].