3 The tracking issues for this feature are:
5 * [#39699](https://github.com/rust-lang/rust/issues/39699).
6 * [#89653](https://github.com/rust-lang/rust/issues/89653).
8 ------------------------
10 This feature allows for use of one of following sanitizers:
12 * [AddressSanitizer][clang-asan] a fast memory error detector.
13 * [ControlFlowIntegrity][clang-cfi] LLVM Control Flow Integrity (CFI) provides
14 forward-edge control flow protection.
15 * [HWAddressSanitizer][clang-hwasan] a memory error detector similar to
16 AddressSanitizer, but based on partial hardware assistance.
17 * [LeakSanitizer][clang-lsan] a run-time memory leak detector.
18 * [MemorySanitizer][clang-msan] a detector of uninitialized reads.
19 * [ThreadSanitizer][clang-tsan] a fast data race detector.
21 To enable a sanitizer compile with `-Zsanitizer=address`,`-Zsanitizer=cfi`,
22 `-Zsanitizer=hwaddress`, `-Zsanitizer=leak`, `-Zsanitizer=memory` or
27 AddressSanitizer is a memory error detector. It can detect the following types
30 * Out of bound accesses to heap, stack and globals
32 * Use after return (runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1`)
34 * Double-free, invalid free
37 The memory leak detection is enabled by default on Linux, and can be enabled
38 with runtime flag `ASAN_OPTIONS=detect_leaks=1` on macOS.
40 AddressSanitizer is supported on the following targets:
42 * `aarch64-apple-darwin`
44 * `aarch64-unknown-linux-gnu`
45 * `x86_64-apple-darwin`
47 * `x86_64-unknown-freebsd`
48 * `x86_64-unknown-linux-gnu`
50 AddressSanitizer works with non-instrumented code although it will impede its
51 ability to detect some bugs. It is not expected to produce false positive
56 Stack buffer overflow:
60 let xs = [0, 1, 2, 3];
61 let _y = unsafe { *xs.as_ptr().offset(4) };
66 $ export RUSTFLAGS=-Zsanitizer=address RUSTDOCFLAGS=-Zsanitizer=address
67 $ cargo run -Zbuild-std --target x86_64-unknown-linux-gnu
68 ==37882==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffe400e6250 at pc 0x5609a841fb20 bp 0x7ffe400e6210 sp 0x7ffe400e6208
69 READ of size 4 at 0x7ffe400e6250 thread T0
70 #0 0x5609a841fb1f in example::main::h628ffc6626ed85b2 /.../src/main.rs:3:23
73 Address 0x7ffe400e6250 is located in stack of thread T0 at offset 48 in frame
74 #0 0x5609a841f8af in example::main::h628ffc6626ed85b2 /.../src/main.rs:1
76 This frame has 1 object(s):
77 [32, 48) 'xs' (line 2) <== Memory access at offset 48 overflows this variable
78 HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
79 (longjmp and C++ exceptions *are* supported)
80 SUMMARY: AddressSanitizer: stack-buffer-overflow /.../src/main.rs:3:23 in example::main::h628ffc6626ed85b2
81 Shadow bytes around the buggy address:
82 0x100048014bf0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
83 0x100048014c00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
84 0x100048014c10: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
85 0x100048014c20: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
86 0x100048014c30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
87 =>0x100048014c40: 00 00 00 00 f1 f1 f1 f1 00 00[f3]f3 00 00 00 00
88 0x100048014c50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
89 0x100048014c60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
90 0x100048014c70: f1 f1 f1 f1 00 00 f3 f3 00 00 00 00 00 00 00 00
91 0x100048014c80: 00 00 00 00 00 00 00 00 00 00 00 00 f1 f1 f1 f1
92 0x100048014c90: 00 00 f3 f3 00 00 00 00 00 00 00 00 00 00 00 00
93 Shadow byte legend (one shadow byte represents 8 application bytes):
95 Partially addressable: 01 02 03 04 05 06 07
98 Stack left redzone: f1
100 Stack right redzone: f3
101 Stack after return: f5
102 Stack use after scope: f8
104 Global init order: f6
106 Container overflow: fc
108 Intra object redzone: bb
110 Left alloca redzone: ca
111 Right alloca redzone: cb
116 Use of a stack object after its scope has already ended:
119 static mut P: *mut usize = std::ptr::null_mut();
127 std::ptr::write_volatile(P, 123);
133 $ export RUSTFLAGS=-Zsanitizer=address RUSTDOCFLAGS=-Zsanitizer=address
134 $ cargo run -Zbuild-std --target x86_64-unknown-linux-gnu
135 =================================================================
136 ==39249==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7ffc7ed3e1a0 at pc 0x55c98b262a8e bp 0x7ffc7ed3e050 sp 0x7ffc7ed3e048
137 WRITE of size 8 at 0x7ffc7ed3e1a0 thread T0
138 #0 0x55c98b262a8d in core::ptr::write_volatile::he21f1df5a82f329a /.../src/rust/src/libcore/ptr/mod.rs:1048:5
139 #1 0x55c98b262cd2 in example::main::h628ffc6626ed85b2 /.../src/main.rs:9:9
142 Address 0x7ffc7ed3e1a0 is located in stack of thread T0 at offset 32 in frame
143 #0 0x55c98b262bdf in example::main::h628ffc6626ed85b2 /.../src/main.rs:3
145 This frame has 1 object(s):
146 [32, 40) 'x' (line 6) <== Memory access at offset 32 is inside this variable
147 HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
148 (longjmp and C++ exceptions *are* supported)
149 SUMMARY: AddressSanitizer: stack-use-after-scope /.../src/rust/src/libcore/ptr/mod.rs:1048:5 in core::ptr::write_volatile::he21f1df5a82f329a
150 Shadow bytes around the buggy address:
151 0x10000fd9fbe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
152 0x10000fd9fbf0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
153 0x10000fd9fc00: 00 00 00 00 00 00 00 00 00 00 00 00 f1 f1 f1 f1
154 0x10000fd9fc10: f8 f8 f3 f3 00 00 00 00 00 00 00 00 00 00 00 00
155 0x10000fd9fc20: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
156 =>0x10000fd9fc30: f1 f1 f1 f1[f8]f3 f3 f3 00 00 00 00 00 00 00 00
157 0x10000fd9fc40: 00 00 00 00 00 00 00 00 00 00 00 00 f1 f1 f1 f1
158 0x10000fd9fc50: 00 00 f3 f3 00 00 00 00 00 00 00 00 00 00 00 00
159 0x10000fd9fc60: 00 00 00 00 00 00 00 00 f1 f1 f1 f1 00 00 f3 f3
160 0x10000fd9fc70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
161 0x10000fd9fc80: 00 00 00 00 f1 f1 f1 f1 00 00 f3 f3 00 00 00 00
162 Shadow byte legend (one shadow byte represents 8 application bytes):
164 Partially addressable: 01 02 03 04 05 06 07
165 Heap left redzone: fa
166 Freed heap region: fd
167 Stack left redzone: f1
168 Stack mid redzone: f2
169 Stack right redzone: f3
170 Stack after return: f5
171 Stack use after scope: f8
173 Global init order: f6
175 Container overflow: fc
177 Intra object redzone: bb
179 Left alloca redzone: ca
180 Right alloca redzone: cb
185 # ControlFlowIntegrity
187 The LLVM Control Flow Integrity (CFI) support in the Rust compiler initially
188 provides forward-edge control flow protection for Rust-compiled code only by
189 aggregating function pointers in groups identified by their number of arguments.
191 Forward-edge control flow protection for C or C++ and Rust -compiled code "mixed
192 binaries" (i.e., for when C or C++ and Rust -compiled code share the same
193 virtual address space) will be provided in later work by defining and using
194 compatible type identifiers (see Type metadata in the design document in the
195 tracking issue [#89653](https://github.com/rust-lang/rust/issues/89653)).
197 LLVM CFI can be enabled with -Zsanitizer=cfi and requires LTO (i.e., -Clto).
202 #![feature(asm, naked_functions)]
206 fn add_one(x: i32) -> i32 {
211 pub extern "C" fn add_two(x: i32) {
212 // x + 2 preceeded by a landing pad/nop block
233 fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
238 let answer = do_twice(add_one, 5);
240 println!("The answer is: {}", answer);
242 println!("With CFI enabled, you should not see the next answer");
243 let f: fn(i32) -> i32 = unsafe {
244 // Offsets 0-8 make it land in the landing pad/nop block, and offsets 1-8 are
245 // invalid branch/call destinations (i.e., within the body of the function).
246 mem::transmute::<*const u8, fn(i32) -> i32>((add_two as *const u8).offset(5))
248 let next_answer = do_twice(f, 5);
250 println!("The next answer is: {}", next_answer);
253 Fig. 1. Modified example from the [Advanced Functions and
254 Closures][rust-book-ch19-05] chapter of the [The Rust Programming
255 Language][rust-book] book.
257 [//]: # (FIXME: Replace with output from cargo using nightly when #89652 is merged)
260 $ rustc rust_cfi.rs -o rust_cfi
263 With CFI enabled, you should not see the next answer
264 The next answer is: 14
267 Fig. 2. Build and execution of the modified example with LLVM CFI disabled.
269 [//]: # (FIXME: Replace with output from cargo using nightly when #89652 is merged)
272 $ rustc -Clto -Zsanitizer=cfi rust_cfi.rs -o rust_cfi
275 With CFI enabled, you should not see the next answer
279 Fig. 3. Build and execution of the modified example with LLVM CFI enabled.
281 When LLVM CFI is enabled, if there are any attempts to change/hijack control
282 flow using an indirect branch/call to an invalid destination, the execution is
283 terminated (see Fig. 3).
288 fn add_one(x: i32) -> i32 {
292 fn add_two(x: i32, _y: i32) -> i32 {
296 fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
301 let answer = do_twice(add_one, 5);
303 println!("The answer is: {}", answer);
305 println!("With CFI enabled, you should not see the next answer");
306 let f: fn(i32) -> i32 =
307 unsafe { mem::transmute::<*const u8, fn(i32) -> i32>(add_two as *const u8) };
308 let next_answer = do_twice(f, 5);
310 println!("The next answer is: {}", next_answer);
313 Fig. 4. Another modified example from the [Advanced Functions and
314 Closures][rust-book-ch19-05] chapter of the [The Rust Programming
315 Language][rust-book] book.
317 [//]: # (FIXME: Replace with output from cargo using nightly when #89652 is merged)
320 $ rustc rust_cfi.rs -o rust_cfi
323 With CFI enabled, you should not see the next answer
324 The next answer is: 14
327 Fig. 5. Build and execution of the modified example with LLVM CFI disabled.
329 [//]: # (FIXME: Replace with output from cargo using nightly when #89652 is merged)
332 $ rustc -Clto -Zsanitizer=cfi rust_cfi.rs -o rust_cfi
335 With CFI enabled, you should not see the next answer
339 Fig. 6. Build and execution of the modified example with LLVM CFI enabled.
341 When LLVM CFI is enabled, if there are any attempts to change/hijack control
342 flow using an indirect branch/call to a function with different number of
343 arguments than intended/passed in the call/branch site, the execution is also
344 terminated (see Fig. 6).
346 Forward-edge control flow protection not only by aggregating function pointers
347 in groups identified by their number of arguments, but also their argument
348 types, will also be provided in later work by defining and using compatible type
349 identifiers (see Type metadata in the design document in the tracking
350 issue [#89653](https://github.com/rust-lang/rust/issues/89653)).
352 [rust-book-ch19-05]: https://doc.rust-lang.org/book/ch19-05-advanced-functions-and-closures.html
353 [rust-book]: https://doc.rust-lang.org/book/title-page.html
357 HWAddressSanitizer is a newer variant of AddressSanitizer that consumes much
360 HWAddressSanitizer is supported on the following targets:
362 * `aarch64-linux-android`
363 * `aarch64-unknown-linux-gnu`
365 HWAddressSanitizer requires `tagged-globals` target feature to instrument
366 globals. To enable this target feature compile with `-C
367 target-feature=+tagged-globals`
371 Heap buffer overflow:
375 let xs = vec![0, 1, 2, 3];
376 let _y = unsafe { *xs.as_ptr().offset(4) };
381 $ rustc main.rs -Zsanitizer=hwaddress -C target-feature=+tagged-globals -C
382 linker=aarch64-linux-gnu-gcc -C link-arg=-fuse-ld=lld --target
383 aarch64-unknown-linux-gnu
388 ==241==ERROR: HWAddressSanitizer: tag-mismatch on address 0xefdeffff0050 at pc 0xaaaae0ae4a98
389 READ of size 4 at 0xefdeffff0050 tags: 2c/00 (ptr/mem) in thread T0
390 #0 0xaaaae0ae4a94 (/.../main+0x54a94)
393 [0xefdeffff0040,0xefdeffff0060) is a small allocated heap chunk; size: 32 offset: 16
394 0xefdeffff0050 is located 0 bytes to the right of 16-byte region [0xefdeffff0040,0xefdeffff0050)
396 #0 0xaaaae0acb80c (/.../main+0x3b80c)
399 Thread: T0 0xeffe00002000 stack: [0xffffc28ad000,0xffffc30ad000) sz: 8388608 tls: [0xffffaa10a020,0xffffaa10a7d0)
400 Memory tags around the buggy address (one tag corresponds to 16 bytes):
401 0xfefcefffef80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
402 0xfefcefffef90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
403 0xfefcefffefa0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
404 0xfefcefffefb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
405 0xfefcefffefc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
406 0xfefcefffefd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
407 0xfefcefffefe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
408 0xfefcefffeff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
409 =>0xfefceffff000: d7 d7 05 00 2c [00] 00 00 00 00 00 00 00 00 00 00
410 0xfefceffff010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
411 0xfefceffff020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
412 0xfefceffff030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
413 0xfefceffff040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
414 0xfefceffff050: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
415 0xfefceffff060: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
416 0xfefceffff070: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
417 0xfefceffff080: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
418 Tags for short granules around the buggy address (one tag corresponds to 16 bytes):
419 0xfefcefffeff0: .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
420 =>0xfefceffff000: .. .. 8c .. .. [..] .. .. .. .. .. .. .. .. .. ..
421 0xfefceffff010: .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..
422 See https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html#short-granules for a description of short granule tags
423 Registers where the failure occurred (pc 0xaaaae0ae4a98):
424 x0 2c00efdeffff0050 x1 0000000000000004 x2 0000000000000004 x3 0000000000000000
425 x4 0000fffefc30ac37 x5 000000000000005d x6 00000ffffc30ac37 x7 0000efff00000000
426 x8 2c00efdeffff0050 x9 0200efff00000000 x10 0000000000000000 x11 0200efff00000000
427 x12 0200effe00000310 x13 0200effe00000310 x14 0000000000000008 x15 5d00ffffc30ac360
428 x16 0000aaaae0ad062c x17 0000000000000003 x18 0000000000000001 x19 0000ffffc30ac658
429 x20 4e00ffffc30ac6e0 x21 0000aaaae0ac5e10 x22 0000000000000000 x23 0000000000000000
430 x24 0000000000000000 x25 0000000000000000 x26 0000000000000000 x27 0000000000000000
431 x28 0000000000000000 x29 0000ffffc30ac5a0 x30 0000aaaae0ae4a98
432 SUMMARY: HWAddressSanitizer: tag-mismatch (/.../main+0x54a94)
437 LeakSanitizer is run-time memory leak detector.
439 LeakSanitizer is supported on the following targets:
441 * `aarch64-apple-darwin`
442 * `aarch64-unknown-linux-gnu`
443 * `x86_64-apple-darwin`
444 * `x86_64-unknown-linux-gnu`
448 MemorySanitizer is detector of uninitialized reads.
450 MemorySanitizer is supported on the following targets:
452 * `aarch64-unknown-linux-gnu`
453 * `x86_64-unknown-freebsd`
454 * `x86_64-unknown-linux-gnu`
456 MemorySanitizer requires all program code to be instrumented. C/C++ dependencies
457 need to be recompiled using Clang with `-fsanitize=memory` option. Failing to
458 achieve that will result in false positive reports.
462 Detecting the use of uninitialized memory. The `-Zbuild-std` flag rebuilds and
463 instruments the standard library, and is strictly necessary for the correct
464 operation of the tool. The `-Zsanitizer-memory-track-origins` enables tracking
465 of the origins of uninitialized memory:
468 use std::mem::MaybeUninit;
472 let a = MaybeUninit::<[usize; 4]>::uninit();
473 let a = a.assume_init();
474 println!("{}", a[2]);
481 RUSTFLAGS='-Zsanitizer=memory -Zsanitizer-memory-track-origins' \
482 RUSTDOCFLAGS='-Zsanitizer=memory -Zsanitizer-memory-track-origins'
484 $ cargo run -Zbuild-std --target x86_64-unknown-linux-gnu
485 ==9416==WARNING: MemorySanitizer: use-of-uninitialized-value
486 #0 0x560c04f7488a in core::fmt::num::imp::fmt_u64::haa293b0b098501ca $RUST/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/src/rust/src/libcore/fmt/num.rs:202:16
488 Uninitialized value was stored to memory at
489 #0 0x560c04ae898a in __msan_memcpy.part.0 $RUST/src/llvm-project/compiler-rt/lib/msan/msan_interceptors.cc:1558:3
490 #1 0x560c04b2bf88 in memory::main::hd2333c1899d997f5 $CWD/src/main.rs:6:16
492 Uninitialized value was created by an allocation of 'a' in the stack frame of function '_ZN6memory4main17hd2333c1899d997f5E'
493 #0 0x560c04b2bc50 in memory::main::hd2333c1899d997f5 $CWD/src/main.rs:3
498 ThreadSanitizer is a data race detection tool. It is supported on the following
501 * `aarch64-apple-darwin`
502 * `aarch64-unknown-linux-gnu`
503 * `x86_64-apple-darwin`
504 * `x86_64-unknown-freebsd`
505 * `x86_64-unknown-linux-gnu`
507 To work correctly ThreadSanitizer needs to be "aware" of all synchronization
508 operations in a program. It generally achieves that through combination of
509 library interception (for example synchronization performed through
510 `pthread_mutex_lock` / `pthread_mutex_unlock`) and compile time instrumentation
511 (e.g. atomic operations). Using it without instrumenting all the program code
512 can lead to false positive reports.
514 ThreadSanitizer does not support atomic fences `std::sync::atomic::fence`,
515 nor synchronization performed using inline assembly code.
520 static mut A: usize = 0;
523 let t = std::thread::spawn(|| {
533 $ export RUSTFLAGS=-Zsanitizer=thread RUSTDOCFLAGS=-Zsanitizer=thread
534 $ cargo run -Zbuild-std --target x86_64-unknown-linux-gnu
536 WARNING: ThreadSanitizer: data race (pid=10574)
537 Read of size 8 at 0x5632dfe3d030 by thread T1:
538 #0 example::main::_$u7b$$u7b$closure$u7d$$u7d$::h23f64b0b2f8c9484 ../src/main.rs:5:18 (example+0x86cec)
541 Previous write of size 8 at 0x5632dfe3d030 by main thread:
542 #0 example::main::h628ffc6626ed85b2 /.../src/main.rs:7:14 (example+0x868c8)
544 #11 main <null> (example+0x86a1a)
546 Location is global 'example::A::h43ac149ddf992709' of size 8 at 0x5632dfe3d030 (example+0x000000bd9030)
549 # Instrumentation of external dependencies and std
551 The sanitizers to varying degrees work correctly with partially instrumented
552 code. On the one extreme is LeakSanitizer that doesn't use any compile time
553 instrumentation, on the other is MemorySanitizer that requires that all program
554 code to be instrumented (failing to achieve that will inevitably result in
557 It is strongly recommended to combine sanitizers with recompiled and
558 instrumented standard library, for example using [cargo `-Zbuild-std`
559 functionality][build-std].
561 [build-std]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-std
563 # Build scripts and procedural macros
565 Use of sanitizers together with build scripts and procedural macros is
566 technically possible, but in almost all cases it would be best avoided. This
567 is especially true for procedural macros which would require an instrumented
570 In more practical terms when using cargo always remember to pass `--target`
571 flag, so that rustflags will not be applied to build scripts and procedural
574 # Symbolizing the Reports
576 Sanitizers produce symbolized stacktraces when llvm-symbolizer binary is in `PATH`.
578 # Additional Information
580 * [Sanitizers project page](https://github.com/google/sanitizers/wiki/)
581 * [AddressSanitizer in Clang][clang-asan]
582 * [ControlFlowIntegrity in Clang][clang-cfi]
583 * [HWAddressSanitizer in Clang][clang-hwasan]
584 * [LeakSanitizer in Clang][clang-lsan]
585 * [MemorySanitizer in Clang][clang-msan]
586 * [ThreadSanitizer in Clang][clang-tsan]
588 [clang-asan]: https://clang.llvm.org/docs/AddressSanitizer.html
589 [clang-cfi]: https://clang.llvm.org/docs/ControlFlowIntegrity.html
590 [clang-hwasan]: https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html
591 [clang-lsan]: https://clang.llvm.org/docs/LeakSanitizer.html
592 [clang-msan]: https://clang.llvm.org/docs/MemorySanitizer.html
593 [clang-tsan]: https://clang.llvm.org/docs/ThreadSanitizer.html