]> git.lizzy.rs Git - rust.git/blob - src/doc/unstable-book/src/compiler-flags/sanitizer.md
Rollup merge of #89876 - AlexApps99:const_ops, r=oli-obk
[rust.git] / src / doc / unstable-book / src / compiler-flags / sanitizer.md
1 # `sanitizer`
2
3 The tracking issues for this feature are:
4
5 * [#39699](https://github.com/rust-lang/rust/issues/39699).
6 * [#89653](https://github.com/rust-lang/rust/issues/89653).
7
8 ------------------------
9
10 This feature allows for use of one of following sanitizers:
11
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.
20
21 To enable a sanitizer compile with `-Zsanitizer=address`,`-Zsanitizer=cfi`,
22 `-Zsanitizer=hwaddress`, `-Zsanitizer=leak`, `-Zsanitizer=memory` or
23 `-Zsanitizer=thread`.
24
25 # AddressSanitizer
26
27 AddressSanitizer is a memory error detector. It can detect the following types
28 of bugs:
29
30 * Out of bound accesses to heap, stack and globals
31 * Use after free
32 * Use after return (runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1`)
33 * Use after scope
34 * Double-free, invalid free
35 * Memory leaks
36
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.
39
40 AddressSanitizer is supported on the following targets:
41
42 * `aarch64-apple-darwin`
43 * `aarch64-fuchsia`
44 * `aarch64-unknown-linux-gnu`
45 * `x86_64-apple-darwin`
46 * `x86_64-fuchsia`
47 * `x86_64-unknown-freebsd`
48 * `x86_64-unknown-linux-gnu`
49
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
52 reports.
53
54 ## Examples
55
56 Stack buffer overflow:
57
58 ```rust
59 fn main() {
60     let xs = [0, 1, 2, 3];
61     let _y = unsafe { *xs.as_ptr().offset(4) };
62 }
63 ```
64
65 ```shell
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
71     ...
72
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
75
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):
94   Addressable:           00
95   Partially addressable: 01 02 03 04 05 06 07
96   Heap left redzone:       fa
97   Freed heap region:       fd
98   Stack left redzone:      f1
99   Stack mid redzone:       f2
100   Stack right redzone:     f3
101   Stack after return:      f5
102   Stack use after scope:   f8
103   Global redzone:          f9
104   Global init order:       f6
105   Poisoned by user:        f7
106   Container overflow:      fc
107   Array cookie:            ac
108   Intra object redzone:    bb
109   ASan internal:           fe
110   Left alloca redzone:     ca
111   Right alloca redzone:    cb
112   Shadow gap:              cc
113 ==37882==ABORTING
114 ```
115
116 Use of a stack object after its scope has already ended:
117
118 ```rust
119 static mut P: *mut usize = std::ptr::null_mut();
120
121 fn main() {
122     unsafe {
123         {
124             let mut x = 0;
125             P = &mut x;
126         }
127         std::ptr::write_volatile(P, 123);
128     }
129 }
130 ```
131
132 ```shell
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
140     ...
141
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
144
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):
163   Addressable:           00
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
172   Global redzone:          f9
173   Global init order:       f6
174   Poisoned by user:        f7
175   Container overflow:      fc
176   Array cookie:            ac
177   Intra object redzone:    bb
178   ASan internal:           fe
179   Left alloca redzone:     ca
180   Right alloca redzone:    cb
181   Shadow gap:              cc
182 ==39249==ABORTING
183 ```
184
185 # ControlFlowIntegrity
186
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.
190
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)).
196
197 LLVM CFI can be enabled with -Zsanitizer=cfi and requires LTO (i.e., -Clto).
198
199 ## Example
200
201 ```text
202 #![feature(asm, naked_functions)]
203
204 use std::mem;
205
206 fn add_one(x: i32) -> i32 {
207     x + 1
208 }
209
210 #[naked]
211 pub extern "C" fn add_two(x: i32) {
212     // x + 2 preceeded by a landing pad/nop block
213     unsafe {
214         asm!(
215             "
216              nop
217              nop
218              nop
219              nop
220              nop
221              nop
222              nop
223              nop
224              nop
225              lea rax, [rdi+2]
226              ret
227         ",
228             options(noreturn)
229         );
230     }
231 }
232
233 fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
234     f(arg) + f(arg)
235 }
236
237 fn main() {
238     let answer = do_twice(add_one, 5);
239
240     println!("The answer is: {}", answer);
241
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))
247     };
248     let next_answer = do_twice(f, 5);
249
250     println!("The next answer is: {}", next_answer);
251 }
252 ```
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.
256
257 [//]: # (FIXME: Replace with output from cargo using nightly when #89652 is merged)
258
259 ```shell
260 $ rustc rust_cfi.rs -o rust_cfi
261 $ ./rust_cfi
262 The answer is: 12
263 With CFI enabled, you should not see the next answer
264 The next answer is: 14
265 $
266 ```
267 Fig. 2. Build and execution of the modified example with LLVM CFI disabled.
268
269 [//]: # (FIXME: Replace with output from cargo using nightly when #89652 is merged)
270
271 ```shell
272 $ rustc -Clto -Zsanitizer=cfi rust_cfi.rs -o rust_cfi
273 $ ./rust_cfi
274 The answer is: 12
275 With CFI enabled, you should not see the next answer
276 Illegal instruction
277 $
278 ```
279 Fig. 3. Build and execution of the modified example with LLVM CFI enabled.
280
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).
284
285 ```rust
286 use std::mem;
287
288 fn add_one(x: i32) -> i32 {
289     x + 1
290 }
291
292 fn add_two(x: i32, _y: i32) -> i32 {
293     x + 2
294 }
295
296 fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
297     f(arg) + f(arg)
298 }
299
300 fn main() {
301     let answer = do_twice(add_one, 5);
302
303     println!("The answer is: {}", answer);
304
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);
309
310     println!("The next answer is: {}", next_answer);
311 }
312 ```
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.
316
317 [//]: # (FIXME: Replace with output from cargo using nightly when #89652 is merged)
318
319 ```shell
320 $ rustc rust_cfi.rs -o rust_cfi
321 $ ./rust_cfi
322 The answer is: 12
323 With CFI enabled, you should not see the next answer
324 The next answer is: 14
325 $
326 ```
327 Fig. 5. Build and execution of the modified example with LLVM CFI disabled.
328
329 [//]: # (FIXME: Replace with output from cargo using nightly when #89652 is merged)
330
331 ```shell
332 $ rustc -Clto -Zsanitizer=cfi rust_cfi.rs -o rust_cfi
333 $ ./rust_cfi
334 The answer is: 12
335 With CFI enabled, you should not see the next answer
336 Illegal instruction
337 $
338 ```
339 Fig. 6. Build and execution of the modified example with LLVM CFI enabled.
340
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).
345
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)).
351
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
354
355 # HWAddressSanitizer
356
357 HWAddressSanitizer is a newer variant of AddressSanitizer that consumes much
358 less memory.
359
360 HWAddressSanitizer is supported on the following targets:
361
362 * `aarch64-linux-android`
363 * `aarch64-unknown-linux-gnu`
364
365 HWAddressSanitizer requires `tagged-globals` target feature to instrument
366 globals. To enable this target feature compile with `-C
367 target-feature=+tagged-globals`
368
369 ## Example
370
371 Heap buffer overflow:
372
373 ```rust
374 fn main() {
375     let xs = vec![0, 1, 2, 3];
376     let _y = unsafe { *xs.as_ptr().offset(4) };
377 }
378 ```
379
380 ```shell
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
384 ```
385
386 ```shell
387 $ ./main
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)
391     ...
392
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)
395 allocated here:
396     #0 0xaaaae0acb80c  (/.../main+0x3b80c)
397     ...
398
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)
433 ```
434
435 # LeakSanitizer
436
437 LeakSanitizer is run-time memory leak detector.
438
439 LeakSanitizer is supported on the following targets:
440
441 * `aarch64-apple-darwin`
442 * `aarch64-unknown-linux-gnu`
443 * `x86_64-apple-darwin`
444 * `x86_64-unknown-linux-gnu`
445
446 # MemorySanitizer
447
448 MemorySanitizer is detector of uninitialized reads.
449
450 MemorySanitizer is supported on the following targets:
451
452 * `aarch64-unknown-linux-gnu`
453 * `x86_64-unknown-freebsd`
454 * `x86_64-unknown-linux-gnu`
455
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.
459
460 ## Example
461
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:
466
467 ```rust
468 use std::mem::MaybeUninit;
469
470 fn main() {
471     unsafe {
472         let a = MaybeUninit::<[usize; 4]>::uninit();
473         let a = a.assume_init();
474         println!("{}", a[2]);
475     }
476 }
477 ```
478
479 ```shell
480 $ export \
481   RUSTFLAGS='-Zsanitizer=memory -Zsanitizer-memory-track-origins' \
482   RUSTDOCFLAGS='-Zsanitizer=memory -Zsanitizer-memory-track-origins'
483 $ cargo clean
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
487 ...
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
491
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
494 ```
495
496 # ThreadSanitizer
497
498 ThreadSanitizer is a data race detection tool. It is supported on the following
499 targets:
500
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`
506
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.
513
514 ThreadSanitizer does not support atomic fences `std::sync::atomic::fence`,
515 nor synchronization performed using inline assembly code.
516
517 ## Example
518
519 ```rust
520 static mut A: usize = 0;
521
522 fn main() {
523     let t = std::thread::spawn(|| {
524         unsafe { A += 1 };
525     });
526     unsafe { A += 1 };
527
528     t.join().unwrap();
529 }
530 ```
531
532 ```shell
533 $ export RUSTFLAGS=-Zsanitizer=thread RUSTDOCFLAGS=-Zsanitizer=thread
534 $ cargo run -Zbuild-std --target x86_64-unknown-linux-gnu
535 ==================
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)
539     ...
540
541   Previous write of size 8 at 0x5632dfe3d030 by main thread:
542     #0 example::main::h628ffc6626ed85b2 /.../src/main.rs:7:14 (example+0x868c8)
543     ...
544     #11 main <null> (example+0x86a1a)
545
546   Location is global 'example::A::h43ac149ddf992709' of size 8 at 0x5632dfe3d030 (example+0x000000bd9030)
547 ```
548
549 # Instrumentation of external dependencies and std
550
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
555 false positives).
556
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].
560
561 [build-std]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-std
562
563 # Build scripts and procedural macros
564
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
568 version of rustc.
569
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
572 macros.
573
574 # Symbolizing the Reports
575
576 Sanitizers produce symbolized stacktraces when llvm-symbolizer binary is in `PATH`.
577
578 # Additional Information
579
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]
587
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