1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Implementation of the test-related targets of the build system.
13 //! This file implements the various regression test suites that we execute on
16 use std::collections::HashSet;
20 use std::fs::{self, File};
21 use std::path::{PathBuf, Path};
22 use std::process::Command;
25 use build_helper::{self, output};
27 use {Build, Compiler, Mode};
29 use util::{self, dylib_path, dylib_path_var, exe};
31 const ADB_TEST_DIR: &str = "/data/tmp/work";
33 /// The two modes of the test runner; tests or benchmarks.
34 #[derive(Copy, Clone)]
43 // Return the cargo subcommand for this test kind
44 fn subcommand(self) -> &'static str {
46 TestKind::Test => "test",
47 TestKind::Bench => "bench",
52 impl fmt::Display for TestKind {
53 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54 f.write_str(match *self {
55 TestKind::Test => "Testing",
56 TestKind::Bench => "Benchmarking",
61 fn try_run(build: &Build, cmd: &mut Command) {
63 if !build.try_run(cmd) {
64 let failures = build.delayed_failures.get();
65 build.delayed_failures.set(failures + 1);
72 fn try_run_quiet(build: &Build, cmd: &mut Command) {
74 if !build.try_run_quiet(cmd) {
75 let failures = build.delayed_failures.get();
76 build.delayed_failures.set(failures + 1);
83 /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
85 /// This tool in `src/tools` will verify the validity of all our links in the
86 /// documentation to ensure we don't have a bunch of dead ones.
87 pub fn linkcheck(build: &Build, host: &str) {
88 println!("Linkcheck ({})", host);
89 let compiler = Compiler::new(0, host);
91 let _time = util::timeit();
92 try_run(build, build.tool_cmd(&compiler, "linkchecker")
93 .arg(build.out.join(host).join("doc")));
96 /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
98 /// This tool in `src/tools` will check out a few Rust projects and run `cargo
99 /// test` to ensure that we don't regress the test suites there.
100 pub fn cargotest(build: &Build, stage: u32, host: &str) {
101 let compiler = Compiler::new(stage, host);
103 // Note that this is a short, cryptic, and not scoped directory name. This
104 // is currently to minimize the length of path on Windows where we otherwise
105 // quickly run into path name limit constraints.
106 let out_dir = build.out.join("ct");
107 t!(fs::create_dir_all(&out_dir));
109 let _time = util::timeit();
110 let mut cmd = Command::new(build.tool(&Compiler::new(0, host), "cargotest"));
111 build.prepare_tool_cmd(&compiler, &mut cmd);
112 try_run(build, cmd.arg(&build.initial_cargo)
114 .env("RUSTC", build.compiler_path(&compiler))
115 .env("RUSTDOC", build.rustdoc(&compiler)));
118 /// Runs `cargo test` for `cargo` packaged with Rust.
119 pub fn cargo(build: &Build, stage: u32, host: &str) {
120 let ref compiler = Compiler::new(stage, host);
122 // Configure PATH to find the right rustc. NB. we have to use PATH
123 // and not RUSTC because the Cargo test suite has tests that will
124 // fail if rustc is not spelled `rustc`.
125 let path = build.sysroot(compiler).join("bin");
126 let old_path = env::var_os("PATH").unwrap_or_default();
127 let newpath = env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("");
129 let mut cargo = build.cargo(compiler, Mode::Tool, host, "test");
130 cargo.arg("--manifest-path").arg(build.src.join("src/tools/cargo/Cargo.toml"));
131 if !build.fail_fast {
132 cargo.arg("--no-fail-fast");
135 // Don't build tests dynamically, just a pain to work with
136 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
138 // Don't run cross-compile tests, we may not have cross-compiled libstd libs
140 cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
142 try_run(build, cargo.env("PATH", newpath));
145 /// Runs the `tidy` tool as compiled in `stage` by the `host` compiler.
147 /// This tool in `src/tools` checks up on various bits and pieces of style and
148 /// otherwise just implements a few lint-like checks that are specific to the
150 pub fn tidy(build: &Build, host: &str) {
151 let _folder = build.fold_output(|| "tidy");
152 println!("tidy check ({})", host);
153 let compiler = Compiler::new(0, host);
154 let mut cmd = build.tool_cmd(&compiler, "tidy");
155 cmd.arg(build.src.join("src"));
156 if !build.config.vendor {
157 cmd.arg("--no-vendor");
159 if build.config.quiet_tests {
162 try_run(build, &mut cmd);
165 fn testdir(build: &Build, host: &str) -> PathBuf {
166 build.out.join(host).join("test")
169 /// Executes the `compiletest` tool to run a suite of tests.
171 /// Compiles all tests with `compiler` for `target` with the specified
172 /// compiletest `mode` and `suite` arguments. For example `mode` can be
173 /// "run-pass" or `suite` can be something like `debuginfo`.
174 pub fn compiletest(build: &Build,
179 let _folder = build.fold_output(|| format!("test_{}", suite));
180 println!("Check compiletest suite={} mode={} ({} -> {})",
181 suite, mode, compiler.host, target);
182 let mut cmd = Command::new(build.tool(&Compiler::new(0, compiler.host),
184 build.prepare_tool_cmd(compiler, &mut cmd);
186 // compiletest currently has... a lot of arguments, so let's just pass all
189 cmd.arg("--compile-lib-path").arg(build.rustc_libdir(compiler));
190 cmd.arg("--run-lib-path").arg(build.sysroot_libdir(compiler, target));
191 cmd.arg("--rustc-path").arg(build.compiler_path(compiler));
192 cmd.arg("--rustdoc-path").arg(build.rustdoc(compiler));
193 cmd.arg("--src-base").arg(build.src.join("src/test").join(suite));
194 cmd.arg("--build-base").arg(testdir(build, compiler.host).join(suite));
195 cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
196 cmd.arg("--mode").arg(mode);
197 cmd.arg("--target").arg(target);
198 cmd.arg("--host").arg(compiler.host);
199 cmd.arg("--llvm-filecheck").arg(build.llvm_filecheck(&build.build));
201 if let Some(ref nodejs) = build.config.nodejs {
202 cmd.arg("--nodejs").arg(nodejs);
205 let mut flags = vec!["-Crpath".to_string()];
206 if build.config.rust_optimize_tests {
207 flags.push("-O".to_string());
209 if build.config.rust_debuginfo_tests {
210 flags.push("-g".to_string());
213 let mut hostflags = build.rustc_flags(&compiler.host);
214 hostflags.extend(flags.clone());
215 cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
217 let mut targetflags = build.rustc_flags(&target);
218 targetflags.extend(flags);
219 targetflags.push(format!("-Lnative={}",
220 build.test_helpers_out(target).display()));
221 cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
223 cmd.arg("--docck-python").arg(build.python());
225 if build.build.ends_with("apple-darwin") {
226 // Force /usr/bin/python on macOS for LLDB tests because we're loading the
227 // LLDB plugin's compiled module which only works with the system python
228 // (namely not Homebrew-installed python)
229 cmd.arg("--lldb-python").arg("/usr/bin/python");
231 cmd.arg("--lldb-python").arg(build.python());
234 if let Some(ref gdb) = build.config.gdb {
235 cmd.arg("--gdb").arg(gdb);
237 if let Some(ref vers) = build.lldb_version {
238 cmd.arg("--lldb-version").arg(vers);
240 if let Some(ref dir) = build.lldb_python_dir {
241 cmd.arg("--lldb-python-dir").arg(dir);
243 let llvm_config = build.llvm_config(target);
244 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
245 cmd.arg("--llvm-version").arg(llvm_version);
246 if !build.is_rust_llvm(target) {
247 cmd.arg("--system-llvm");
250 cmd.args(&build.flags.cmd.test_args());
252 if build.is_verbose() {
253 cmd.arg("--verbose");
256 if build.config.quiet_tests {
260 // Only pass correct values for these flags for the `run-make` suite as it
261 // requires that a C++ compiler was configured which isn't always the case.
262 if suite == "run-make" {
263 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
264 let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
265 cmd.arg("--cc").arg(build.cc(target))
266 .arg("--cxx").arg(build.cxx(target).unwrap())
267 .arg("--cflags").arg(build.cflags(target).join(" "))
268 .arg("--llvm-components").arg(llvm_components.trim())
269 .arg("--llvm-cxxflags").arg(llvm_cxxflags.trim());
271 cmd.arg("--cc").arg("")
272 .arg("--cxx").arg("")
273 .arg("--cflags").arg("")
274 .arg("--llvm-components").arg("")
275 .arg("--llvm-cxxflags").arg("");
278 if build.remote_tested(target) {
279 cmd.arg("--remote-test-client")
280 .arg(build.tool(&Compiler::new(0, &build.build),
281 "remote-test-client"));
284 // Running a C compiler on MSVC requires a few env vars to be set, to be
285 // sure to set them here.
287 // Note that if we encounter `PATH` we make sure to append to our own `PATH`
288 // rather than stomp over it.
289 if target.contains("msvc") {
290 for &(ref k, ref v) in build.cc[target].0.env() {
296 cmd.env("RUSTC_BOOTSTRAP", "1");
297 build.add_rust_test_threads(&mut cmd);
299 if build.config.sanitizers {
300 cmd.env("SANITIZER_SUPPORT", "1");
303 if build.config.profiler {
304 cmd.env("PROFILER_SUPPORT", "1");
307 cmd.arg("--adb-path").arg("adb");
308 cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
309 if target.contains("android") {
310 // Assume that cc for this target comes from the android sysroot
311 cmd.arg("--android-cross-path")
312 .arg(build.cc(target).parent().unwrap().parent().unwrap());
314 cmd.arg("--android-cross-path").arg("");
317 build.ci_env.force_coloring_in_ci(&mut cmd);
319 let _time = util::timeit();
320 try_run(build, &mut cmd);
323 /// Run `rustdoc --test` for all documentation in `src/doc`.
325 /// This will run all tests in our markdown documentation (e.g. the book)
326 /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to
328 pub fn docs(build: &Build, compiler: &Compiler) {
329 // Do a breadth-first traversal of the `src/doc` directory and just run
330 // tests for all files that end in `*.md`
331 let mut stack = vec![build.src.join("src/doc")];
332 let _time = util::timeit();
333 let _folder = build.fold_output(|| "test_docs");
335 while let Some(p) = stack.pop() {
337 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
341 if p.extension().and_then(|s| s.to_str()) != Some("md") {
345 // The nostarch directory in the book is for no starch, and so isn't
346 // guaranteed to build. We don't care if it doesn't build, so skip it.
347 if p.to_str().map_or(false, |p| p.contains("nostarch")) {
351 markdown_test(build, compiler, &p);
355 /// Run the error index generator tool to execute the tests located in the error
358 /// The `error_index_generator` tool lives in `src/tools` and is used to
359 /// generate a markdown file from the error indexes of the code base which is
360 /// then passed to `rustdoc --test`.
361 pub fn error_index(build: &Build, compiler: &Compiler) {
362 let _folder = build.fold_output(|| "test_error_index");
363 println!("Testing error-index stage{}", compiler.stage);
365 let dir = testdir(build, compiler.host);
366 t!(fs::create_dir_all(&dir));
367 let output = dir.join("error-index.md");
369 let _time = util::timeit();
370 build.run(build.tool_cmd(&Compiler::new(0, compiler.host),
371 "error_index_generator")
374 .env("CFG_BUILD", &build.build));
376 markdown_test(build, compiler, &output);
379 fn markdown_test(build: &Build, compiler: &Compiler, markdown: &Path) {
380 let mut file = t!(File::open(markdown));
381 let mut contents = String::new();
382 t!(file.read_to_string(&mut contents));
383 if !contents.contains("```") {
387 println!("doc tests for: {}", markdown.display());
388 let mut cmd = Command::new(build.rustdoc(compiler));
389 build.add_rustc_lib_path(compiler, &mut cmd);
390 build.add_rust_test_threads(&mut cmd);
393 cmd.env("RUSTC_BOOTSTRAP", "1");
395 let test_args = build.flags.cmd.test_args().join(" ");
396 cmd.arg("--test-args").arg(test_args);
398 if build.config.quiet_tests {
399 try_run_quiet(build, &mut cmd);
401 try_run(build, &mut cmd);
405 /// Run all unit tests plus documentation tests for an entire crate DAG defined
406 /// by a `Cargo.toml`
408 /// This is what runs tests for crates like the standard library, compiler, etc.
409 /// It essentially is the driver for running `cargo test`.
411 /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
412 /// arguments, and those arguments are discovered from `cargo metadata`.
413 pub fn krate(build: &Build,
418 krate: Option<&str>) {
419 let (name, path, features, root) = match mode {
421 ("libstd", "src/libstd", build.std_features(), "std")
424 ("libtest", "src/libtest", String::new(), "test")
427 ("librustc", "src/rustc", build.rustc_features(), "rustc-main")
429 _ => panic!("can only test libraries"),
431 let _folder = build.fold_output(|| {
432 format!("{}_stage{}-{}", test_kind.subcommand(), compiler.stage, name)
434 println!("{} {} stage{} ({} -> {})", test_kind, name, compiler.stage,
435 compiler.host, target);
437 // If we're not doing a full bootstrap but we're testing a stage2 version of
438 // libstd, then what we're actually testing is the libstd produced in
439 // stage1. Reflect that here by updating the compiler that we're working
440 // with automatically.
441 let compiler = if build.force_use_stage1(compiler, target) {
442 Compiler::new(1, compiler.host)
447 // Build up the base `cargo test` command.
449 // Pass in some standard flags then iterate over the graph we've discovered
450 // in `cargo metadata` with the maps above and figure out what `-p`
451 // arguments need to get passed.
452 let mut cargo = build.cargo(&compiler, mode, target, test_kind.subcommand());
453 cargo.arg("--manifest-path")
454 .arg(build.src.join(path).join("Cargo.toml"))
455 .arg("--features").arg(features);
456 if test_kind.subcommand() == "test" && !build.fail_fast {
457 cargo.arg("--no-fail-fast");
462 cargo.arg("-p").arg(krate);
465 let mut visited = HashSet::new();
466 let mut next = vec![root];
467 while let Some(name) = next.pop() {
468 // Right now jemalloc is our only target-specific crate in the
469 // sense that it's not present on all platforms. Custom skip it
470 // here for now, but if we add more this probably wants to get
473 // Also skip `build_helper` as it's not compiled normally for
474 // target during the bootstrap and it's just meant to be a
475 // helper crate, not tested. If it leaks through then it ends up
476 // messing with various mtime calculations and such.
477 if !name.contains("jemalloc") && name != "build_helper" {
478 cargo.arg("-p").arg(&format!("{}:0.0.0", name));
480 for dep in build.crates[name].deps.iter() {
481 if visited.insert(dep) {
489 // The tests are going to run with the *target* libraries, so we need to
490 // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
492 // Note that to run the compiler we need to run with the *host* libraries,
493 // but our wrapper scripts arrange for that to be the case anyway.
494 let mut dylib_path = dylib_path();
495 dylib_path.insert(0, build.sysroot_libdir(&compiler, target));
496 cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
498 if target.contains("emscripten") || build.remote_tested(target) {
499 cargo.arg("--no-run");
504 if build.config.quiet_tests {
505 cargo.arg("--quiet");
508 let _time = util::timeit();
510 if target.contains("emscripten") {
511 build.run(&mut cargo);
512 krate_emscripten(build, &compiler, target, mode);
513 } else if build.remote_tested(target) {
514 build.run(&mut cargo);
515 krate_remote(build, &compiler, target, mode);
517 cargo.args(&build.flags.cmd.test_args());
518 try_run(build, &mut cargo);
522 fn krate_emscripten(build: &Build,
526 let out_dir = build.cargo_out(compiler, mode, target);
527 let tests = find_tests(&out_dir.join("deps"), target);
529 let nodejs = build.config.nodejs.as_ref().expect("nodejs not configured");
531 println!("running {}", test.display());
532 let mut cmd = Command::new(nodejs);
534 if build.config.quiet_tests {
537 try_run(build, &mut cmd);
541 fn krate_remote(build: &Build,
545 let out_dir = build.cargo_out(compiler, mode, target);
546 let tests = find_tests(&out_dir.join("deps"), target);
548 let tool = build.tool(&Compiler::new(0, &build.build),
549 "remote-test-client");
551 let mut cmd = Command::new(&tool);
554 if build.config.quiet_tests {
557 cmd.args(&build.flags.cmd.test_args());
558 try_run(build, &mut cmd);
562 fn find_tests(dir: &Path, target: &str) -> Vec<PathBuf> {
563 let mut dst = Vec::new();
564 for e in t!(dir.read_dir()).map(|e| t!(e)) {
565 let file_type = t!(e.file_type());
566 if !file_type.is_file() {
569 let filename = e.file_name().into_string().unwrap();
570 if (target.contains("windows") && filename.ends_with(".exe")) ||
571 (!target.contains("windows") && !filename.contains(".")) ||
572 (target.contains("emscripten") &&
573 filename.ends_with(".js") &&
574 !filename.ends_with(".asm.js")) {
581 pub fn remote_copy_libs(build: &Build, compiler: &Compiler, target: &str) {
582 if !build.remote_tested(target) {
586 println!("REMOTE copy libs to emulator ({})", target);
587 t!(fs::create_dir_all(build.out.join("tmp")));
589 let server = build.cargo_out(compiler, Mode::Tool, target)
590 .join(exe("remote-test-server", target));
592 // Spawn the emulator and wait for it to come online
593 let tool = build.tool(&Compiler::new(0, &build.build),
594 "remote-test-client");
595 let mut cmd = Command::new(&tool);
596 cmd.arg("spawn-emulator")
599 .arg(build.out.join("tmp"));
600 if let Some(rootfs) = build.qemu_rootfs(target) {
605 // Push all our dylibs to the emulator
606 for f in t!(build.sysroot_libdir(compiler, target).read_dir()) {
608 let name = f.file_name().into_string().unwrap();
609 if util::is_dylib(&name) {
610 build.run(Command::new(&tool)
617 /// Run "distcheck", a 'make check' from a tarball
618 pub fn distcheck(build: &Build) {
619 if build.build != "x86_64-unknown-linux-gnu" {
622 if !build.config.host.iter().any(|s| s == "x86_64-unknown-linux-gnu") {
625 if !build.config.target.iter().any(|s| s == "x86_64-unknown-linux-gnu") {
629 println!("Distcheck");
630 let dir = build.out.join("tmp").join("distcheck");
631 let _ = fs::remove_dir_all(&dir);
632 t!(fs::create_dir_all(&dir));
634 let mut cmd = Command::new("tar");
636 .arg(dist::rust_src_location(build))
637 .arg("--strip-components=1")
640 build.run(Command::new("./configure")
641 .args(&build.config.configure_args)
642 .arg("--enable-vendor")
644 build.run(Command::new(build_helper::make(&build.build))
648 // Now make sure that rust-src has all of libstd's dependencies
649 println!("Distcheck rust-src");
650 let dir = build.out.join("tmp").join("distcheck-src");
651 let _ = fs::remove_dir_all(&dir);
652 t!(fs::create_dir_all(&dir));
654 let mut cmd = Command::new("tar");
656 .arg(dist::rust_src_installer(build))
657 .arg("--strip-components=1")
661 let toml = dir.join("rust-src/lib/rustlib/src/rust/src/libstd/Cargo.toml");
662 build.run(Command::new(&build.initial_cargo)
663 .arg("generate-lockfile")
664 .arg("--manifest-path")
669 /// Test the build system itself
670 pub fn bootstrap(build: &Build) {
671 let mut cmd = Command::new(&build.initial_cargo);
673 .current_dir(build.src.join("src/bootstrap"))
674 .env("CARGO_TARGET_DIR", build.out.join("bootstrap"))
675 .env("RUSTC_BOOTSTRAP", "1")
676 .env("RUSTC", &build.initial_rustc);
677 if !build.fail_fast {
678 cmd.arg("--no-fail-fast");
680 cmd.arg("--").args(&build.flags.cmd.test_args());
681 try_run(build, &mut cmd);