Rollup merge of #38699 - japaric:lsan, r=alexcrichton

LeakSanitizer, ThreadSanitizer, AddressSanitizer and MemorySanitizer support

```
$ cargo new --bin leak && cd $_

$ edit Cargo.toml && tail -n3 $_
```

``` toml
[profile.dev]
opt-level = 1
```

```
$ edit src/main.rs && cat $_
```

``` rust
use std::mem;

fn main() {
    let xs = vec![0, 1, 2, 3];
    mem::forget(xs);
}
```

```
$ RUSTFLAGS="-Z sanitizer=leak" cargo run --target x86_64-unknown-linux-gnu; echo $?
    Finished dev [optimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/leak`

=================================================================
==10848==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 16 byte(s) in 1 object(s) allocated from:
    #0 0x557c3488db1f in __interceptor_malloc /shared/rust/checkouts/lsan/src/compiler-rt/lib/lsan/lsan_interceptors.cc:55
    #1 0x557c34888aaa in alloc::heap::exchange_malloc::h68f3f8b376a0da42 /shared/rust/checkouts/lsan/src/liballoc/heap.rs:138
    #2 0x557c34888afc in leak::main::hc56ab767de6d653a $PWD/src/main.rs:4
    #3 0x557c348c0806 in __rust_maybe_catch_panic ($PWD/target/debug/leak+0x3d806)

SUMMARY: LeakSanitizer: 16 byte(s) leaked in 1 allocation(s).
23
```

```
$ cargo new --bin racy && cd $_

$ edit src/main.rs && cat $_
```

``` rust
use std::thread;

static mut ANSWER: i32 = 0;

fn main() {
    let t1 = thread::spawn(|| unsafe { ANSWER = 42 });
    unsafe {
        ANSWER = 24;
    }
    t1.join().ok();
}
```

```
$ RUSTFLAGS="-Z sanitizer=thread" cargo run --target x86_64-unknown-linux-gnu; echo $?
==================
WARNING: ThreadSanitizer: data race (pid=12019)
  Write of size 4 at 0x562105989bb4 by thread T1:
    #0 racy::main::_$u7b$$u7b$closure$u7d$$u7d$::hbe13ea9e8ac73f7e $PWD/src/main.rs:6 (racy+0x000000010e3f)
    #1 _$LT$std..panic..AssertUnwindSafe$LT$F$GT$$u20$as$u20$core..ops..FnOnce$LT$$LP$$RP$$GT$$GT$::call_once::h2e466a92accacc78 /shared/rust/checkouts/lsan/src/libstd/panic.rs:296 (racy+0x000000010cc5)
    #2 std::panicking::try::do_call::h7f4d2b38069e4042 /shared/rust/checkouts/lsan/src/libstd/panicking.rs:460 (racy+0x00000000c8f2)
    #3 __rust_maybe_catch_panic <null> (racy+0x0000000b4e56)
    #4 std::panic::catch_unwind::h31ca45621ad66d5a /shared/rust/checkouts/lsan/src/libstd/panic.rs:361 (racy+0x00000000b517)
    #5 std:🧵:Builder::spawn::_$u7b$$u7b$closure$u7d$$u7d$::hccfc37175dea0b01 /shared/rust/checkouts/lsan/src/libstd/thread/mod.rs:357 (racy+0x00000000c226)
    #6 _$LT$F$u20$as$u20$alloc..boxed..FnBox$LT$A$GT$$GT$::call_box::hd880bbf91561e033 /shared/rust/checkouts/lsan/src/liballoc/boxed.rs:605 (racy+0x00000000f27e)
    #7 std::sys:👿🧵:Thread:🆕:thread_start::hebdfc4b3d17afc85 <null> (racy+0x0000000abd40)

  Previous write of size 4 at 0x562105989bb4 by main thread:
    #0 racy::main::h23e6e5ca46d085c3 $PWD/src/main.rs:8 (racy+0x000000010d7c)
    #1 __rust_maybe_catch_panic <null> (racy+0x0000000b4e56)
    #2 __libc_start_main <null> (libc.so.6+0x000000020290)

  Location is global 'racy::ANSWER::h543d2b139f819b19' of size 4 at 0x562105989bb4 (racy+0x0000002f8bb4)

  Thread T1 (tid=12028, running) created by main thread at:
    #0 pthread_create /shared/rust/checkouts/lsan/src/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:902 (racy+0x00000001aedb)
    #1 std::sys:👿🧵:Thread:🆕:hce44187bf4a36222 <null> (racy+0x0000000ab9ae)
    #2 std:🧵:spawn::he382608373eb667e /shared/rust/checkouts/lsan/src/libstd/thread/mod.rs:412 (racy+0x00000000b5aa)
    #3 racy::main::h23e6e5ca46d085c3 $PWD/src/main.rs:6 (racy+0x000000010d5c)
    #4 __rust_maybe_catch_panic <null> (racy+0x0000000b4e56)
    #5 __libc_start_main <null> (libc.so.6+0x000000020290)

SUMMARY: ThreadSanitizer: data race $PWD/src/main.rs:6 in racy::main::_$u7b$$u7b$closure$u7d$$u7d$::hbe13ea9e8ac73f7e
==================
ThreadSanitizer: reported 1 warnings
66
```

```
$ cargo new --bin oob && cd $_

$ edit src/main.rs && cat $_
```

``` rust
fn main() {
    let xs = [0, 1, 2, 3];
    let y = unsafe { *xs.as_ptr().offset(4) };
}
```

```
$ RUSTFLAGS="-Z sanitizer=address" cargo run --target x86_64-unknown-linux-gnu; echo $?
=================================================================
==13328==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fff29f3ecd0 at pc 0x55802dc6bf7e bp 0x7fff29f3ec90 sp 0x7fff29f3ec88
READ of size 4 at 0x7fff29f3ecd0 thread T0
    #0 0x55802dc6bf7d in oob::main::h0adc7b67e5feb2e7 $PWD/src/main.rs:3
    #1 0x55802dd60426 in __rust_maybe_catch_panic ($PWD/target/debug/oob+0xfe426)
    #2 0x55802dd58dd9 in std::rt::lang_start::hb2951fc8a59d62a7 ($PWD/target/debug/oob+0xf6dd9)
    #3 0x55802dc6c002 in main ($PWD/target/debug/oob+0xa002)
    #4 0x7fad8c3b3290 in __libc_start_main (/usr/lib/libc.so.6+0x20290)
    #5 0x55802dc6b719 in _start ($PWD/target/debug/oob+0x9719)

Address 0x7fff29f3ecd0 is located in stack of thread T0 at offset 48 in frame
    #0 0x55802dc6bd5f in oob::main::h0adc7b67e5feb2e7 $PWD/src/main.rs:1

  This frame has 1 object(s):
    [32, 48) 'xs' <== Memory access at offset 48 overflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
      (longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-overflow $PWD/src/main.rs:3 in oob::main::h0adc7b67e5feb2e7
Shadow bytes around the buggy address:
  0x1000653dfd40: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000653dfd50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000653dfd60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000653dfd70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000653dfd80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x1000653dfd90: 00 00 00 00 f1 f1 f1 f1 00 00[f3]f3 00 00 00 00
  0x1000653dfda0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000653dfdb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000653dfdc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000653dfdd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000653dfde0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Heap right redzone:      fb
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack partial redzone:   f4
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==13328==ABORTING
1
```

```
$ cargo new --bin uninit && cd $_

$ edit src/main.rs && cat $_
```

``` rust
use std::mem;

fn main() {
    let xs: [u8; 4] = unsafe { mem::uninitialized() };
    let y = xs[0] + xs[1];
}
```

```
$ RUSTFLAGS="-Z sanitizer=memory" cargo run; echo $?
==30198==WARNING: MemorySanitizer: use-of-uninitialized-value
    #0 0x563f4b6867da in uninit::main::hc2731cd4f2ed48f8 $PWD/src/main.rs:5
    #1 0x563f4b7033b6 in __rust_maybe_catch_panic ($PWD/target/debug/uninit+0x873b6)
    #2 0x563f4b6fbd69 in std::rt::lang_start::hb2951fc8a59d62a7 ($PWD/target/debug/uninit+0x7fd69)
    #3 0x563f4b6868a9 in main ($PWD/target/debug/uninit+0xa8a9)
    #4 0x7fe844354290 in __libc_start_main (/usr/lib/libc.so.6+0x20290)
    #5 0x563f4b6864f9 in _start ($PWD/target/debug/uninit+0xa4f9)

SUMMARY: MemorySanitizer: use-of-uninitialized-value $PWD/src/main.rs:5 in uninit::main::hc2731cd4f2ed48f8
Exiting
77
```
This commit is contained in:
Corey Farwell 2017-02-08 23:55:43 -05:00 committed by GitHub
commit 3053494a9a
50 changed files with 765 additions and 7 deletions

1
configure vendored
View File

@ -649,6 +649,7 @@ opt codegen-tests 1 "run the src/test/codegen tests"
opt option-checking 1 "complain about unrecognized options in this configure script" opt option-checking 1 "complain about unrecognized options in this configure script"
opt ninja 0 "build LLVM using the Ninja generator (for MSVC, requires building in the correct environment)" opt ninja 0 "build LLVM using the Ninja generator (for MSVC, requires building in the correct environment)"
opt vendor 0 "enable usage of vendored Rust crates" opt vendor 0 "enable usage of vendored Rust crates"
opt sanitizers 0 "build the sanitizer runtimes (asan, lsan, msan, tsan)"
# Optimization and debugging options. These may be overridden by the release channel, etc. # Optimization and debugging options. These may be overridden by the release channel, etc.
opt_nosave optimize 1 "build optimized rust code" opt_nosave optimize 1 "build optimized rust code"

44
src/Cargo.lock generated
View File

@ -277,6 +277,16 @@ name = "rustc-serialize"
version = "0.3.19" version = "0.3.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "rustc_asan"
version = "0.0.0"
dependencies = [
"alloc_system 0.0.0",
"build_helper 0.1.0",
"cmake 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
"core 0.0.0",
]
[[package]] [[package]]
name = "rustc_back" name = "rustc_back"
version = "0.0.0" version = "0.0.0"
@ -410,6 +420,16 @@ dependencies = [
"rustc_bitflags 0.0.0", "rustc_bitflags 0.0.0",
] ]
[[package]]
name = "rustc_lsan"
version = "0.0.0"
dependencies = [
"alloc_system 0.0.0",
"build_helper 0.1.0",
"cmake 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
"core 0.0.0",
]
[[package]] [[package]]
name = "rustc_metadata" name = "rustc_metadata"
version = "0.0.0" version = "0.0.0"
@ -444,6 +464,16 @@ dependencies = [
"syntax_pos 0.0.0", "syntax_pos 0.0.0",
] ]
[[package]]
name = "rustc_msan"
version = "0.0.0"
dependencies = [
"alloc_system 0.0.0",
"build_helper 0.1.0",
"cmake 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
"core 0.0.0",
]
[[package]] [[package]]
name = "rustc_passes" name = "rustc_passes"
version = "0.0.0" version = "0.0.0"
@ -525,6 +555,16 @@ dependencies = [
"syntax_pos 0.0.0", "syntax_pos 0.0.0",
] ]
[[package]]
name = "rustc_tsan"
version = "0.0.0"
dependencies = [
"alloc_system 0.0.0",
"build_helper 0.1.0",
"cmake 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
"core 0.0.0",
]
[[package]] [[package]]
name = "rustc_typeck" name = "rustc_typeck"
version = "0.0.0" version = "0.0.0"
@ -586,6 +626,10 @@ dependencies = [
"panic_abort 0.0.0", "panic_abort 0.0.0",
"panic_unwind 0.0.0", "panic_unwind 0.0.0",
"rand 0.0.0", "rand 0.0.0",
"rustc_asan 0.0.0",
"rustc_lsan 0.0.0",
"rustc_msan 0.0.0",
"rustc_tsan 0.0.0",
"std_unicode 0.0.0", "std_unicode 0.0.0",
"unwind 0.0.0", "unwind 0.0.0",
] ]

View File

@ -242,6 +242,10 @@ pub fn compiletest(build: &Build,
cmd.env("RUSTC_BOOTSTRAP", "1"); cmd.env("RUSTC_BOOTSTRAP", "1");
build.add_rust_test_threads(&mut cmd); build.add_rust_test_threads(&mut cmd);
if build.config.sanitizers {
cmd.env("SANITIZER_SUPPORT", "1");
}
cmd.arg("--adb-path").arg("adb"); cmd.arg("--adb-path").arg("adb");
cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR); cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
if target.contains("android") { if target.contains("android") {

View File

@ -51,6 +51,17 @@ pub fn std(build: &Build, target: &str, compiler: &Compiler) {
if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc { if compiler.stage == 0 && build.local_rebuild && !build.config.use_jemalloc {
features.push_str(" force_alloc_system"); features.push_str(" force_alloc_system");
} }
if compiler.stage != 0 && build.config.sanitizers {
// This variable is used by the sanitizer runtime crates, e.g.
// rustc_lsan, to build the sanitizer runtime from C code
// When this variable is missing, those crates won't compile the C code,
// so we don't set this variable during stage0 where llvm-config is
// missing
// We also only build the runtimes when --enable-sanitizers (or its
// config.toml equivalent) is used
cargo.env("LLVM_CONFIG", build.llvm_config(target));
}
cargo.arg("--features").arg(features) cargo.arg("--features").arg(features)
.arg("--manifest-path") .arg("--manifest-path")
.arg(build.src.join("src/rustc/std_shim/Cargo.toml")); .arg(build.src.join("src/rustc/std_shim/Cargo.toml"));

View File

@ -48,6 +48,7 @@ pub struct Config {
pub target_config: HashMap<String, Target>, pub target_config: HashMap<String, Target>,
pub full_bootstrap: bool, pub full_bootstrap: bool,
pub extended: bool, pub extended: bool,
pub sanitizers: bool,
// llvm codegen options // llvm codegen options
pub llvm_assertions: bool, pub llvm_assertions: bool,
@ -149,6 +150,7 @@ struct Build {
python: Option<String>, python: Option<String>,
full_bootstrap: Option<bool>, full_bootstrap: Option<bool>,
extended: Option<bool>, extended: Option<bool>,
sanitizers: Option<bool>,
} }
/// TOML representation of various global install decisions. /// TOML representation of various global install decisions.
@ -294,6 +296,7 @@ impl Config {
set(&mut config.vendor, build.vendor); set(&mut config.vendor, build.vendor);
set(&mut config.full_bootstrap, build.full_bootstrap); set(&mut config.full_bootstrap, build.full_bootstrap);
set(&mut config.extended, build.extended); set(&mut config.extended, build.extended);
set(&mut config.sanitizers, build.sanitizers);
if let Some(ref install) = toml.install { if let Some(ref install) = toml.install {
config.prefix = install.prefix.clone().map(PathBuf::from); config.prefix = install.prefix.clone().map(PathBuf::from);
@ -438,6 +441,7 @@ impl Config {
("VENDOR", self.vendor), ("VENDOR", self.vendor),
("FULL_BOOTSTRAP", self.full_bootstrap), ("FULL_BOOTSTRAP", self.full_bootstrap),
("EXTENDED", self.extended), ("EXTENDED", self.extended),
("SANITIZERS", self.sanitizers),
} }
match key { match key {

View File

@ -124,6 +124,9 @@
# disabled by default. # disabled by default.
#extended = false #extended = false
# Build the sanitizer runtimes
#sanitizers = false
# ============================================================================= # =============================================================================
# General install configuration options # General install configuration options
# ============================================================================= # =============================================================================

View File

@ -599,7 +599,8 @@ impl Build {
/// Get the space-separated set of activated features for the standard /// Get the space-separated set of activated features for the standard
/// library. /// library.
fn std_features(&self) -> String { fn std_features(&self) -> String {
let mut features = "panic-unwind".to_string(); let mut features = "panic-unwind asan lsan msan tsan".to_string();
if self.config.debug_jemalloc { if self.config.debug_jemalloc {
features.push_str(" debug-jemalloc"); features.push_str(" debug-jemalloc");
} }

View File

@ -63,6 +63,11 @@ RUN ./build-git.sh
COPY build-cmake.sh /tmp/ COPY build-cmake.sh /tmp/
RUN ./build-cmake.sh RUN ./build-cmake.sh
# for sanitizers, we need kernel headers files newer than the ones CentOS ships
# with so we install newer ones here
COPY build-headers.sh /tmp/
RUN ./build-headers.sh
RUN curl -Lo /rustroot/dumb-init \ RUN curl -Lo /rustroot/dumb-init \
https://github.com/Yelp/dumb-init/releases/download/v1.2.0/dumb-init_1.2.0_amd64 && \ https://github.com/Yelp/dumb-init/releases/download/v1.2.0/dumb-init_1.2.0_amd64 && \
chmod +x /rustroot/dumb-init chmod +x /rustroot/dumb-init
@ -76,5 +81,5 @@ RUN curl -L https://api.pub.build.mozilla.org/tooltool/sha512/$SCCACHE_DIGEST |
ENV HOSTS=i686-unknown-linux-gnu ENV HOSTS=i686-unknown-linux-gnu
ENV HOSTS=$HOSTS,x86_64-unknown-linux-gnu ENV HOSTS=$HOSTS,x86_64-unknown-linux-gnu
ENV RUST_CONFIGURE_ARGS --host=$HOSTS --enable-extended ENV RUST_CONFIGURE_ARGS --host=$HOSTS --enable-extended --enable-sanitizers
ENV SCRIPT python2.7 ../x.py dist --host $HOSTS --target $HOSTS ENV SCRIPT python2.7 ../x.py dist --host $HOSTS --target $HOSTS

View File

@ -0,0 +1,25 @@
#!/bin/bash
# Copyright 2017 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
set -ex
source shared.sh
curl https://cdn.kernel.org/pub/linux/kernel/v3.x/linux-3.2.84.tar.xz | unxz | tar x
cd linux-3.2.84
hide_output make mrproper
hide_output make INSTALL_HDR_PATH=dest headers_install
find dest/include \( -name .install -o -name ..install.cmd \) -delete
yes | cp -fr dest/include/* /usr/include
cd ..
rm -rf linux-3.2.84

View File

@ -22,5 +22,5 @@ RUN curl -OL https://github.com/Yelp/dumb-init/releases/download/v1.2.0/dumb-ini
rm dumb-init_*.deb rm dumb-init_*.deb
ENTRYPOINT ["/usr/bin/dumb-init", "--"] ENTRYPOINT ["/usr/bin/dumb-init", "--"]
ENV RUST_CONFIGURE_ARGS --build=x86_64-unknown-linux-gnu ENV RUST_CONFIGURE_ARGS --build=x86_64-unknown-linux-gnu --enable-sanitizers
ENV SCRIPT python2.7 ../x.py test && python2.7 ../x.py dist ENV SCRIPT python2.7 ../x.py test && python2.7 ../x.py dist

@ -1 +1 @@
Subproject commit a8fc4c169fac43a5dc204d4fd56ddb1739f8c178 Subproject commit d30da544a8afc5d78391dee270bdf40e74a215d3

View File

@ -229,6 +229,7 @@ pub trait CrateStore<'tcx> {
fn is_allocator(&self, cnum: CrateNum) -> bool; fn is_allocator(&self, cnum: CrateNum) -> bool;
fn is_panic_runtime(&self, cnum: CrateNum) -> bool; fn is_panic_runtime(&self, cnum: CrateNum) -> bool;
fn is_compiler_builtins(&self, cnum: CrateNum) -> bool; fn is_compiler_builtins(&self, cnum: CrateNum) -> bool;
fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool;
fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy; fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy;
fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>; fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>;
/// The name of the crate as it is referred to in source code of the current /// The name of the crate as it is referred to in source code of the current
@ -390,6 +391,7 @@ impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
fn is_allocator(&self, cnum: CrateNum) -> bool { bug!("is_allocator") } fn is_allocator(&self, cnum: CrateNum) -> bool { bug!("is_allocator") }
fn is_panic_runtime(&self, cnum: CrateNum) -> bool { bug!("is_panic_runtime") } fn is_panic_runtime(&self, cnum: CrateNum) -> bool { bug!("is_panic_runtime") }
fn is_compiler_builtins(&self, cnum: CrateNum) -> bool { bug!("is_compiler_builtins") } fn is_compiler_builtins(&self, cnum: CrateNum) -> bool { bug!("is_compiler_builtins") }
fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool { bug!("is_sanitizer_runtime") }
fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy { fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
bug!("panic_strategy") bug!("panic_strategy")
} }

View File

@ -51,6 +51,14 @@ pub struct Config {
pub uint_type: UintTy, pub uint_type: UintTy,
} }
#[derive(Clone)]
pub enum Sanitizer {
Address,
Leak,
Memory,
Thread,
}
#[derive(Clone, Copy, PartialEq, Hash)] #[derive(Clone, Copy, PartialEq, Hash)]
pub enum OptLevel { pub enum OptLevel {
No, // -O0 No, // -O0
@ -626,11 +634,13 @@ macro_rules! options {
Some("a number"); Some("a number");
pub const parse_panic_strategy: Option<&'static str> = pub const parse_panic_strategy: Option<&'static str> =
Some("either `panic` or `abort`"); Some("either `panic` or `abort`");
pub const parse_sanitizer: Option<&'static str> =
Some("one of: `address`, `leak`, `memory` or `thread`");
} }
#[allow(dead_code)] #[allow(dead_code)]
mod $mod_set { mod $mod_set {
use super::{$struct_name, Passes, SomePasses, AllPasses}; use super::{$struct_name, Passes, SomePasses, AllPasses, Sanitizer};
use rustc_back::PanicStrategy; use rustc_back::PanicStrategy;
$( $(
@ -751,6 +761,17 @@ macro_rules! options {
} }
true true
} }
fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
match v {
Some("address") => *slote = Some(Sanitizer::Address),
Some("leak") => *slote = Some(Sanitizer::Leak),
Some("memory") => *slote = Some(Sanitizer::Memory),
Some("thread") => *slote = Some(Sanitizer::Thread),
_ => return false,
}
true
}
} }
) } ) }
@ -949,6 +970,8 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
"encode MIR of all functions into the crate metadata"), "encode MIR of all functions into the crate metadata"),
osx_rpath_install_name: bool = (false, parse_bool, [TRACKED], osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
"pass `-install_name @rpath/...` to the OSX linker"), "pass `-install_name @rpath/...` to the OSX linker"),
sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [UNTRACKED],
"Use a sanitizer"),
} }
pub fn default_lib_output() -> CrateType { pub fn default_lib_output() -> CrateType {

View File

@ -0,0 +1,17 @@
[package]
authors = ["The Rust Project Developers"]
build = "build.rs"
name = "rustc_asan"
version = "0.0.0"
[lib]
name = "rustc_asan"
path = "lib.rs"
[build-dependencies]
build_helper = { path = "../build_helper" }
cmake = "0.1.18"
[dependencies]
alloc_system = { path = "../liballoc_system" }
core = { path = "../libcore" }

View File

@ -0,0 +1,39 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate build_helper;
extern crate cmake;
use std::path::PathBuf;
use std::env;
use cmake::Config;
fn main() {
if let Some(llvm_config) = env::var_os("LLVM_CONFIG") {
let dst = Config::new("../compiler-rt")
.define("COMPILER_RT_BUILD_SANITIZERS", "ON")
.define("COMPILER_RT_BUILD_BUILTINS", "OFF")
.define("COMPILER_RT_BUILD_XRAY", "OFF")
.define("LLVM_CONFIG_PATH", llvm_config)
.build_target("asan")
.build();
println!("cargo:rustc-link-search=native={}",
dst.join("build/lib/linux").display());
println!("cargo:rustc-link-lib=static=clang_rt.asan-x86_64");
build_helper::rerun_if_changed_anything_in_dir(&PathBuf::from(env::var("CARGO_MANIFEST_DIR")
.unwrap())
.join("../compiler-rt"));
}
println!("cargo:rerun-if-changed=build.rs");
}

20
src/librustc_asan/lib.rs Normal file
View File

@ -0,0 +1,20 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![cfg_attr(not(stage0), feature(sanitizer_runtime))]
#![cfg_attr(not(stage0), sanitizer_runtime)]
#![feature(alloc_system)]
#![feature(staged_api)]
#![no_std]
#![unstable(feature = "sanitizer_runtime_lib",
reason = "internal implementation detail of sanitizers",
issue = "0")]
extern crate alloc_system;

View File

@ -126,6 +126,9 @@ pub enum Attribute {
UWTable = 17, UWTable = 17,
ZExt = 18, ZExt = 18,
InReg = 19, InReg = 19,
SanitizeThread = 20,
SanitizeAddress = 21,
SanitizeMemory = 22,
} }
/// LLVMIntPredicate /// LLVMIntPredicate

View File

@ -0,0 +1,17 @@
[package]
authors = ["The Rust Project Developers"]
build = "build.rs"
name = "rustc_lsan"
version = "0.0.0"
[lib]
name = "rustc_lsan"
path = "lib.rs"
[build-dependencies]
build_helper = { path = "../build_helper" }
cmake = "0.1.18"
[dependencies]
alloc_system = { path = "../liballoc_system" }
core = { path = "../libcore" }

View File

@ -0,0 +1,39 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate build_helper;
extern crate cmake;
use std::path::PathBuf;
use std::env;
use cmake::Config;
fn main() {
if let Some(llvm_config) = env::var_os("LLVM_CONFIG") {
let dst = Config::new("../compiler-rt")
.define("COMPILER_RT_BUILD_SANITIZERS", "ON")
.define("COMPILER_RT_BUILD_BUILTINS", "OFF")
.define("COMPILER_RT_BUILD_XRAY", "OFF")
.define("LLVM_CONFIG_PATH", llvm_config)
.build_target("lsan")
.build();
println!("cargo:rustc-link-search=native={}",
dst.join("build/lib/linux").display());
println!("cargo:rustc-link-lib=static=clang_rt.lsan-x86_64");
build_helper::rerun_if_changed_anything_in_dir(&PathBuf::from(env::var("CARGO_MANIFEST_DIR")
.unwrap())
.join("../compiler-rt"));
}
println!("cargo:rerun-if-changed=build.rs");
}

20
src/librustc_lsan/lib.rs Normal file
View File

@ -0,0 +1,20 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![cfg_attr(not(stage0), feature(sanitizer_runtime))]
#![cfg_attr(not(stage0), sanitizer_runtime)]
#![feature(alloc_system)]
#![feature(staged_api)]
#![no_std]
#![unstable(feature = "sanitizer_runtime_lib",
reason = "internal implementation detail of sanitizers",
issue = "0")]
extern crate alloc_system;

View File

@ -17,7 +17,8 @@ use schema::CrateRoot;
use rustc::hir::def_id::{CrateNum, DefIndex}; use rustc::hir::def_id::{CrateNum, DefIndex};
use rustc::hir::svh::Svh; use rustc::hir::svh::Svh;
use rustc::middle::cstore::DepKind; use rustc::middle::cstore::DepKind;
use rustc::session::{config, Session}; use rustc::session::Session;
use rustc::session::config::{Sanitizer, self};
use rustc_back::PanicStrategy; use rustc_back::PanicStrategy;
use rustc::session::search_paths::PathKind; use rustc::session::search_paths::PathKind;
use rustc::middle; use rustc::middle;
@ -786,6 +787,64 @@ impl<'a> CrateLoader<'a> {
&|data| data.needs_panic_runtime()); &|data| data.needs_panic_runtime());
} }
fn inject_sanitizer_runtime(&mut self) {
if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
// Sanitizers can only be used with x86_64 Linux executables linked
// to `std`
if self.sess.target.target.llvm_target != "x86_64-unknown-linux-gnu" {
self.sess.err(&format!("Sanitizers only work with the \
`x86_64-unknown-linux-gnu` target."));
return
}
if !self.sess.crate_types.borrow().iter().all(|ct| {
match *ct {
// Link the runtime
config::CrateTypeExecutable => true,
// This crate will be compiled with the required
// instrumentation pass
config::CrateTypeRlib => false,
_ => {
self.sess.err(&format!("Only executables and rlibs can be \
compiled with `-Z sanitizer`"));
false
}
}
}) {
return
}
let mut uses_std = false;
self.cstore.iter_crate_data(|_, data| {
if data.name == "std" {
uses_std = true;
}
});
if uses_std {
let name = match *sanitizer {
Sanitizer::Address => "rustc_asan",
Sanitizer::Leak => "rustc_lsan",
Sanitizer::Memory => "rustc_msan",
Sanitizer::Thread => "rustc_tsan",
};
info!("loading sanitizer: {}", name);
let symbol = Symbol::intern(name);
let dep_kind = DepKind::Implicit;
let (_, data) =
self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
PathKind::Crate, dep_kind);
// Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
if !data.is_sanitizer_runtime() {
self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
name));
}
}
}
}
fn inject_allocator_crate(&mut self) { fn inject_allocator_crate(&mut self) {
// Make sure that we actually need an allocator, if none of our // Make sure that we actually need an allocator, if none of our
// dependencies need one then we definitely don't! // dependencies need one then we definitely don't!
@ -982,6 +1041,9 @@ impl<'a> CrateLoader<'a> {
impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> { impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
fn postprocess(&mut self, krate: &ast::Crate) { fn postprocess(&mut self, krate: &ast::Crate) {
// inject the sanitizer runtime before the allocator runtime because all
// sanitizers force the use of the `alloc_system` allocator
self.inject_sanitizer_runtime();
self.inject_allocator_crate(); self.inject_allocator_crate();
self.inject_panic_runtime(krate); self.inject_panic_runtime(krate);

View File

@ -297,6 +297,11 @@ impl CrateMetadata {
attr::contains_name(&attrs, "compiler_builtins") attr::contains_name(&attrs, "compiler_builtins")
} }
pub fn is_sanitizer_runtime(&self) -> bool {
let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
attr::contains_name(&attrs, "sanitizer_runtime")
}
pub fn is_no_builtins(&self) -> bool { pub fn is_no_builtins(&self) -> bool {
let attrs = self.get_item_attrs(CRATE_DEF_INDEX); let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
attr::contains_name(&attrs, "no_builtins") attr::contains_name(&attrs, "no_builtins")

View File

@ -297,6 +297,10 @@ impl<'tcx> CrateStore<'tcx> for cstore::CStore {
self.get_crate_data(cnum).is_compiler_builtins() self.get_crate_data(cnum).is_compiler_builtins()
} }
fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool {
self.get_crate_data(cnum).is_sanitizer_runtime()
}
fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy { fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
self.get_crate_data(cnum).panic_strategy() self.get_crate_data(cnum).panic_strategy()
} }

View File

@ -0,0 +1,17 @@
[package]
authors = ["The Rust Project Developers"]
build = "build.rs"
name = "rustc_msan"
version = "0.0.0"
[lib]
name = "rustc_msan"
path = "lib.rs"
[build-dependencies]
build_helper = { path = "../build_helper" }
cmake = "0.1.18"
[dependencies]
alloc_system = { path = "../liballoc_system" }
core = { path = "../libcore" }

View File

@ -0,0 +1,39 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate build_helper;
extern crate cmake;
use std::path::PathBuf;
use std::env;
use cmake::Config;
fn main() {
if let Some(llvm_config) = env::var_os("LLVM_CONFIG") {
let dst = Config::new("../compiler-rt")
.define("COMPILER_RT_BUILD_SANITIZERS", "ON")
.define("COMPILER_RT_BUILD_BUILTINS", "OFF")
.define("COMPILER_RT_BUILD_XRAY", "OFF")
.define("LLVM_CONFIG_PATH", llvm_config)
.build_target("msan")
.build();
println!("cargo:rustc-link-search=native={}",
dst.join("build/lib/linux").display());
println!("cargo:rustc-link-lib=static=clang_rt.msan-x86_64");
build_helper::rerun_if_changed_anything_in_dir(&PathBuf::from(env::var("CARGO_MANIFEST_DIR")
.unwrap())
.join("../compiler-rt"));
}
println!("cargo:rerun-if-changed=build.rs");
}

20
src/librustc_msan/lib.rs Normal file
View File

@ -0,0 +1,20 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![cfg_attr(not(stage0), feature(sanitizer_runtime))]
#![cfg_attr(not(stage0), sanitizer_runtime)]
#![feature(alloc_system)]
#![feature(staged_api)]
#![no_std]
#![unstable(feature = "sanitizer_runtime_lib",
reason = "internal implementation detail of sanitizers",
issue = "0")]
extern crate alloc_system;

View File

@ -1031,6 +1031,9 @@ fn add_upstream_rust_crates(cmd: &mut Linker,
// symbols from the dylib. // symbols from the dylib.
let src = sess.cstore.used_crate_source(cnum); let src = sess.cstore.used_crate_source(cnum);
match data[cnum.as_usize() - 1] { match data[cnum.as_usize() - 1] {
_ if sess.cstore.is_sanitizer_runtime(cnum) => {
link_sanitizer_runtime(cmd, sess, tmpdir, cnum);
}
// compiler-builtins are always placed last to ensure that they're // compiler-builtins are always placed last to ensure that they're
// linked correctly. // linked correctly.
_ if sess.cstore.is_compiler_builtins(cnum) => { _ if sess.cstore.is_compiler_builtins(cnum) => {
@ -1048,6 +1051,8 @@ fn add_upstream_rust_crates(cmd: &mut Linker,
} }
} }
// compiler-builtins are always placed last to ensure that they're
// linked correctly.
// We must always link the `compiler_builtins` crate statically. Even if it // We must always link the `compiler_builtins` crate statically. Even if it
// was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic` // was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic`
// is used) // is used)
@ -1064,6 +1069,34 @@ fn add_upstream_rust_crates(cmd: &mut Linker,
} }
} }
// We must link the sanitizer runtime using -Wl,--whole-archive but since
// it's packed in a .rlib, it contains stuff that are not objects that will
// make the linker error. So we must remove those bits from the .rlib before
// linking it.
fn link_sanitizer_runtime(cmd: &mut Linker,
sess: &Session,
tmpdir: &Path,
cnum: CrateNum) {
let src = sess.cstore.used_crate_source(cnum);
let cratepath = &src.rlib.unwrap().0;
let dst = tmpdir.join(cratepath.file_name().unwrap());
let cfg = archive_config(sess, &dst, Some(cratepath));
let mut archive = ArchiveBuilder::new(cfg);
archive.update_symbols();
for f in archive.src_files() {
if f.ends_with("bytecode.deflate") ||
f == sess.cstore.metadata_filename() {
archive.remove_file(&f);
continue
}
}
archive.build();
cmd.link_whole_rlib(&dst);
}
// Adds the static "rlib" versions of all crates to the command line. // Adds the static "rlib" versions of all crates to the command line.
// There's a bit of magic which happens here specifically related to LTO and // There's a bit of magic which happens here specifically related to LTO and
// dynamic libraries. Specifically: // dynamic libraries. Specifically:

View File

@ -12,7 +12,7 @@ use back::lto;
use back::link::{get_linker, remove}; use back::link::{get_linker, remove};
use back::symbol_export::ExportedSymbols; use back::symbol_export::ExportedSymbols;
use rustc_incremental::{save_trans_partition, in_incr_comp_dir}; use rustc_incremental::{save_trans_partition, in_incr_comp_dir};
use session::config::{OutputFilenames, OutputTypes, Passes, SomePasses, AllPasses}; use session::config::{OutputFilenames, OutputTypes, Passes, SomePasses, AllPasses, Sanitizer};
use session::Session; use session::Session;
use session::config::{self, OutputType}; use session::config::{self, OutputType};
use llvm; use llvm;
@ -679,6 +679,22 @@ pub fn run_passes(sess: &Session,
let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone()); let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
let mut metadata_config = ModuleConfig::new(tm, vec![]); let mut metadata_config = ModuleConfig::new(tm, vec![]);
if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
match *sanitizer {
Sanitizer::Address => {
modules_config.passes.push("asan".to_owned());
modules_config.passes.push("asan-module".to_owned());
}
Sanitizer::Memory => {
modules_config.passes.push("msan".to_owned())
}
Sanitizer::Thread => {
modules_config.passes.push("tsan".to_owned())
}
_ => {}
}
}
modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize)); modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize)); modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));

View File

@ -23,6 +23,7 @@
use llvm::{self, ValueRef}; use llvm::{self, ValueRef};
use llvm::AttributePlace::Function; use llvm::AttributePlace::Function;
use rustc::ty; use rustc::ty;
use rustc::session::config::Sanitizer;
use abi::{Abi, FnType}; use abi::{Abi, FnType};
use attributes; use attributes;
use context::CrateContext; use context::CrateContext;
@ -72,6 +73,21 @@ fn declare_raw_fn(ccx: &CrateContext, name: &str, callconv: llvm::CallConv, ty:
llvm::Attribute::NoRedZone.apply_llfn(Function, llfn); llvm::Attribute::NoRedZone.apply_llfn(Function, llfn);
} }
if let Some(ref sanitizer) = ccx.tcx().sess.opts.debugging_opts.sanitizer {
match *sanitizer {
Sanitizer::Address => {
llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
},
Sanitizer::Memory => {
llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
},
Sanitizer::Thread => {
llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
},
_ => {}
}
}
// If we're compiling the compiler-builtins crate, e.g. the equivalent of // If we're compiling the compiler-builtins crate, e.g. the equivalent of
// compiler-rt, then we want to implicitly compile everything with hidden // compiler-rt, then we want to implicitly compile everything with hidden
// visibility as we're going to link this object all over the place but // visibility as we're going to link this object all over the place but

View File

@ -0,0 +1,17 @@
[package]
authors = ["The Rust Project Developers"]
build = "build.rs"
name = "rustc_tsan"
version = "0.0.0"
[lib]
name = "rustc_tsan"
path = "lib.rs"
[build-dependencies]
build_helper = { path = "../build_helper" }
cmake = "0.1.18"
[dependencies]
alloc_system = { path = "../liballoc_system" }
core = { path = "../libcore" }

View File

@ -0,0 +1,39 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate build_helper;
extern crate cmake;
use std::path::PathBuf;
use std::env;
use cmake::Config;
fn main() {
if let Some(llvm_config) = env::var_os("LLVM_CONFIG") {
let dst = Config::new("../compiler-rt")
.define("COMPILER_RT_BUILD_SANITIZERS", "ON")
.define("COMPILER_RT_BUILD_BUILTINS", "OFF")
.define("COMPILER_RT_BUILD_XRAY", "OFF")
.define("LLVM_CONFIG_PATH", llvm_config)
.build_target("tsan")
.build();
println!("cargo:rustc-link-search=native={}",
dst.join("build/lib/linux").display());
println!("cargo:rustc-link-lib=static=clang_rt.tsan-x86_64");
build_helper::rerun_if_changed_anything_in_dir(&PathBuf::from(env::var("CARGO_MANIFEST_DIR")
.unwrap())
.join("../compiler-rt"));
}
println!("cargo:rerun-if-changed=build.rs");
}

20
src/librustc_tsan/lib.rs Normal file
View File

@ -0,0 +1,20 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![cfg_attr(not(stage0), feature(sanitizer_runtime))]
#![cfg_attr(not(stage0), sanitizer_runtime)]
#![feature(alloc_system)]
#![feature(staged_api)]
#![no_std]
#![unstable(feature = "sanitizer_runtime_lib",
reason = "internal implementation detail of sanitizers",
issue = "0")]
extern crate alloc_system;

View File

@ -23,13 +23,23 @@ compiler_builtins = { path = "../libcompiler_builtins" }
std_unicode = { path = "../libstd_unicode" } std_unicode = { path = "../libstd_unicode" }
unwind = { path = "../libunwind" } unwind = { path = "../libunwind" }
[target.x86_64-unknown-linux-gnu.dependencies]
rustc_asan = { path = "../librustc_asan", optional = true }
rustc_lsan = { path = "../librustc_lsan", optional = true }
rustc_msan = { path = "../librustc_msan", optional = true }
rustc_tsan = { path = "../librustc_tsan", optional = true }
[build-dependencies] [build-dependencies]
build_helper = { path = "../build_helper" } build_helper = { path = "../build_helper" }
gcc = "0.3.27" gcc = "0.3.27"
[features] [features]
asan = ["rustc_asan"]
backtrace = [] backtrace = []
debug-jemalloc = ["alloc_jemalloc/debug"] debug-jemalloc = ["alloc_jemalloc/debug"]
jemalloc = ["alloc_jemalloc"] jemalloc = ["alloc_jemalloc"]
force_alloc_system = [] force_alloc_system = []
lsan = ["rustc_lsan"]
msan = ["rustc_msan"]
panic-unwind = ["panic_unwind"] panic-unwind = ["panic_unwind"]
tsan = ["rustc_tsan"]

View File

@ -328,6 +328,10 @@ declare_features! (
// `extern "msp430-interrupt" fn()` // `extern "msp430-interrupt" fn()`
(active, abi_msp430_interrupt, "1.16.0", Some(38487)), (active, abi_msp430_interrupt, "1.16.0", Some(38487)),
// Used to identify crates that contain sanitizer runtimes
// rustc internal
(active, sanitizer_runtime, "1.17.0", None),
); );
declare_features! ( declare_features! (
@ -647,6 +651,12 @@ pub const BUILTIN_ATTRIBUTES: &'static [(&'static str, AttributeType, AttributeG
contains compiler-rt intrinsics and will never be \ contains compiler-rt intrinsics and will never be \
stable", stable",
cfg_fn!(compiler_builtins))), cfg_fn!(compiler_builtins))),
("sanitizer_runtime", Whitelisted, Gated(Stability::Unstable,
"sanitizer_runtime",
"the `#[sanitizer_runtime]` attribute is used to \
identify crates that contain the runtime of a \
sanitizer and will never be stable",
cfg_fn!(sanitizer_runtime))),
("allow_internal_unstable", Normal, Gated(Stability::Unstable, ("allow_internal_unstable", Normal, Gated(Stability::Unstable,
"allow_internal_unstable", "allow_internal_unstable",

View File

@ -35,8 +35,12 @@ core = { path = "../../libcore" }
# Reexport features from std # Reexport features from std
[features] [features]
asan = ["std/asan"]
backtrace = ["std/backtrace"] backtrace = ["std/backtrace"]
debug-jemalloc = ["std/debug-jemalloc"] debug-jemalloc = ["std/debug-jemalloc"]
jemalloc = ["std/jemalloc"] jemalloc = ["std/jemalloc"]
force_alloc_system = ["std/force_alloc_system"] force_alloc_system = ["std/force_alloc_system"]
lsan = ["std/lsan"]
msan = ["std/msan"]
panic-unwind = ["std/panic-unwind"] panic-unwind = ["std/panic-unwind"]
tsan = ["std/tsan"]

View File

@ -148,6 +148,12 @@ static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
return Attribute::ZExt; return Attribute::ZExt;
case InReg: case InReg:
return Attribute::InReg; return Attribute::InReg;
case SanitizeThread:
return Attribute::SanitizeThread;
case SanitizeAddress:
return Attribute::SanitizeAddress;
case SanitizeMemory:
return Attribute::SanitizeMemory;
} }
llvm_unreachable("bad AttributeKind"); llvm_unreachable("bad AttributeKind");
} }

View File

@ -98,6 +98,9 @@ enum LLVMRustAttribute {
UWTable = 17, UWTable = 17,
ZExt = 18, ZExt = 18,
InReg = 19, InReg = 19,
SanitizeThread = 20,
SanitizeAddress = 21,
SanitizeMemory = 22,
}; };
typedef struct OpaqueRustString *RustStringRef; typedef struct OpaqueRustString *RustStringRef;

View File

@ -0,0 +1,13 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![sanitizer_runtime] //~ ERROR the `#[sanitizer_runtime]` attribute is
fn main() {}

View File

@ -0,0 +1,11 @@
-include ../tools.mk
# NOTE the address sanitizer only supports x86_64 linux
ifdef SANITIZER_SUPPORT
all:
$(RUSTC) -g -Z sanitizer=address -Z print-link-args overflow.rs | grep -q librustc_asan
$(TMPDIR)/overflow 2>&1 | grep -q stack-buffer-overflow
else
all:
endif

View File

@ -0,0 +1,14 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() {
let xs = [0, 1, 2, 3];
let y = unsafe { *xs.as_ptr().offset(4) };
}

View File

@ -0,0 +1,8 @@
-include ../tools.mk
ifeq ($(TARGET),x86_64-unknown-linux-gnu)
all:
$(RUSTC) -Z sanitizer=leak --crate-type dylib --target $(TARGET) hello.rs 2>&1 | grep -q 'Only executables and rlibs can be compiled with `-Z sanitizer`'
else
all:
endif

View File

@ -0,0 +1,13 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() {
println!("Hello, world!");
}

View File

@ -0,0 +1,4 @@
-include ../tools.mk
all:
$(RUSTC) -Z sanitizer=leak --target i686-unknown-linux-gnu hello.rs 2>&1 | grep -q 'Sanitizers only work with the `x86_64-unknown-linux-gnu` target'

View File

@ -0,0 +1,13 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(no_core)]
#![no_core]
#![no_main]

View File

@ -0,0 +1,10 @@
-include ../tools.mk
ifdef SANITIZER_SUPPORT
all:
$(RUSTC) -C opt-level=1 -g -Z sanitizer=leak -Z print-link-args leak.rs | grep -q librustc_lsan
$(TMPDIR)/leak 2>&1 | grep -q 'detected memory leaks'
else
all:
endif

View File

@ -0,0 +1,16 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
fn main() {
let xs = vec![1, 2, 3, 4];
mem::forget(xs);
}

View File

@ -0,0 +1,10 @@
-include ../tools.mk
ifdef SANITIZER_SUPPORT
all:
$(RUSTC) -g -Z sanitizer=memory -Z print-link-args uninit.rs | grep -q librustc_msan
$(TMPDIR)/uninit 2>&1 | grep -q use-of-uninitialized-value
else
all:
endif

View File

@ -0,0 +1,16 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
fn main() {
let xs: [u8; 4] = unsafe { mem::uninitialized() };
let y = xs[0] + xs[1];
}

View File

@ -0,0 +1,10 @@
-include ../tools.mk
ifdef SANITIZER_SUPPORT
all:
$(RUSTC) -g -Z sanitizer=thread -Z print-link-args racy.rs | grep -q librustc_tsan
$(TMPDIR)/racy 2>&1 | grep -q 'data race'
else
all:
endif

View File

@ -0,0 +1,21 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::thread;
static mut ANSWER: i32 = 0;
fn main() {
let t1 = thread::spawn(|| unsafe { ANSWER = 42 });
unsafe {
ANSWER = 24;
}
t1.join().ok();
}