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 extern crate build_helper;
18 use std::collections::HashSet;
21 use std::fs::{self, File};
22 use std::path::{PathBuf, Path};
23 use std::process::Command;
26 use build_helper::output;
28 use {Build, Compiler, Mode};
30 use util::{self, dylib_path, dylib_path_var, exe};
32 const ADB_TEST_DIR: &'static str = "/data/tmp/work";
34 /// The two modes of the test runner; tests or benchmarks.
35 #[derive(Copy, Clone)]
44 // Return the cargo subcommand for this test kind
45 fn subcommand(self) -> &'static str {
47 TestKind::Test => "test",
48 TestKind::Bench => "bench",
53 impl fmt::Display for TestKind {
54 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 f.write_str(match *self {
56 TestKind::Test => "Testing",
57 TestKind::Bench => "Benchmarking",
62 fn try_run(build: &Build, cmd: &mut Command) {
63 if build.flags.cmd.no_fail_fast() {
64 if !build.try_run(cmd) {
65 let failures = build.delayed_failures.get();
66 build.delayed_failures.set(failures + 1);
73 fn try_run_quiet(build: &Build, cmd: &mut Command) {
74 if build.flags.cmd.no_fail_fast() {
75 if !build.try_run_quiet(cmd) {
76 let failures = build.delayed_failures.get();
77 build.delayed_failures.set(failures + 1);
84 /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
86 /// This tool in `src/tools` will verify the validity of all our links in the
87 /// documentation to ensure we don't have a bunch of dead ones.
88 pub fn linkcheck(build: &Build, host: &str) {
89 println!("Linkcheck ({})", host);
90 let compiler = Compiler::new(0, host);
92 let _time = util::timeit();
93 try_run(build, build.tool_cmd(&compiler, "linkchecker")
94 .arg(build.out.join(host).join("doc")));
97 /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
99 /// This tool in `src/tools` will check out a few Rust projects and run `cargo
100 /// test` to ensure that we don't regress the test suites there.
101 pub fn cargotest(build: &Build, stage: u32, host: &str) {
102 let ref compiler = Compiler::new(stage, host);
104 // Note that this is a short, cryptic, and not scoped directory name. This
105 // is currently to minimize the length of path on Windows where we otherwise
106 // quickly run into path name limit constraints.
107 let out_dir = build.out.join("ct");
108 t!(fs::create_dir_all(&out_dir));
110 let _time = util::timeit();
111 let mut cmd = Command::new(build.tool(&Compiler::new(0, host), "cargotest"));
112 build.prepare_tool_cmd(compiler, &mut cmd);
113 try_run(build, cmd.arg(&build.cargo)
115 .env("RUSTC", build.compiler_path(compiler))
116 .env("RUSTDOC", build.rustdoc(compiler)));
119 /// Runs `cargo test` for `cargo` packaged with Rust.
120 pub fn cargo(build: &Build, stage: u32, host: &str) {
121 let ref compiler = Compiler::new(stage, host);
123 // Configure PATH to find the right rustc. NB. we have to use PATH
124 // and not RUSTC because the Cargo test suite has tests that will
125 // fail if rustc is not spelled `rustc`.
126 let path = build.sysroot(compiler).join("bin");
127 let old_path = ::std::env::var("PATH").expect("");
128 let sep = if cfg!(windows) { ";" } else {":" };
129 let ref newpath = format!("{}{}{}", path.display(), sep, old_path);
131 let mut cargo = build.cargo(compiler, Mode::Tool, host, "test");
132 cargo.arg("--manifest-path").arg(build.src.join("src/tools/cargo/Cargo.toml"));
133 if build.flags.cmd.no_fail_fast() {
134 cargo.arg("--no-fail-fast");
137 // Don't build tests dynamically, just a pain to work with
138 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
140 // Don't run cross-compile tests, we may not have cross-compiled libstd libs
142 cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
144 try_run(build, cargo.env("PATH", newpath));
147 /// Runs the `tidy` tool as compiled in `stage` by the `host` compiler.
149 /// This tool in `src/tools` checks up on various bits and pieces of style and
150 /// otherwise just implements a few lint-like checks that are specific to the
152 pub fn tidy(build: &Build, host: &str) {
153 let _folder = build.fold_output(|| "tidy");
154 println!("tidy check ({})", host);
155 let compiler = Compiler::new(0, host);
156 let mut cmd = build.tool_cmd(&compiler, "tidy");
157 cmd.arg(build.src.join("src"));
158 if !build.config.vendor {
159 cmd.arg("--no-vendor");
161 if build.config.quiet_tests {
164 try_run(build, &mut cmd);
167 fn testdir(build: &Build, host: &str) -> PathBuf {
168 build.out.join(host).join("test")
171 /// Executes the `compiletest` tool to run a suite of tests.
173 /// Compiles all tests with `compiler` for `target` with the specified
174 /// compiletest `mode` and `suite` arguments. For example `mode` can be
175 /// "run-pass" or `suite` can be something like `debuginfo`.
176 pub fn compiletest(build: &Build,
181 let _folder = build.fold_output(|| format!("test_{}", suite));
182 println!("Check compiletest suite={} mode={} ({} -> {})",
183 suite, mode, compiler.host, target);
184 let mut cmd = Command::new(build.tool(&Compiler::new(0, compiler.host),
186 build.prepare_tool_cmd(compiler, &mut cmd);
188 // compiletest currently has... a lot of arguments, so let's just pass all
191 cmd.arg("--compile-lib-path").arg(build.rustc_libdir(compiler));
192 cmd.arg("--run-lib-path").arg(build.sysroot_libdir(compiler, target));
193 cmd.arg("--rustc-path").arg(build.compiler_path(compiler));
194 cmd.arg("--rustdoc-path").arg(build.rustdoc(compiler));
195 cmd.arg("--src-base").arg(build.src.join("src/test").join(suite));
196 cmd.arg("--build-base").arg(testdir(build, compiler.host).join(suite));
197 cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
198 cmd.arg("--mode").arg(mode);
199 cmd.arg("--target").arg(target);
200 cmd.arg("--host").arg(compiler.host);
201 cmd.arg("--llvm-filecheck").arg(build.llvm_filecheck(&build.config.build));
203 if let Some(nodejs) = build.config.nodejs.as_ref() {
204 cmd.arg("--nodejs").arg(nodejs);
207 let mut flags = vec!["-Crpath".to_string()];
208 if build.config.rust_optimize_tests {
209 flags.push("-O".to_string());
211 if build.config.rust_debuginfo_tests {
212 flags.push("-g".to_string());
215 let mut hostflags = build.rustc_flags(&compiler.host);
216 hostflags.extend(flags.clone());
217 cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
219 let mut targetflags = build.rustc_flags(&target);
220 targetflags.extend(flags);
221 targetflags.push(format!("-Lnative={}",
222 build.test_helpers_out(target).display()));
223 cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
225 cmd.arg("--docck-python").arg(build.python());
227 if build.config.build.ends_with("apple-darwin") {
228 // Force /usr/bin/python on macOS for LLDB tests because we're loading the
229 // LLDB plugin's compiled module which only works with the system python
230 // (namely not Homebrew-installed python)
231 cmd.arg("--lldb-python").arg("/usr/bin/python");
233 cmd.arg("--lldb-python").arg(build.python());
236 if let Some(ref gdb) = build.config.gdb {
237 cmd.arg("--gdb").arg(gdb);
239 if let Some(ref vers) = build.lldb_version {
240 cmd.arg("--lldb-version").arg(vers);
242 if let Some(ref dir) = build.lldb_python_dir {
243 cmd.arg("--lldb-python-dir").arg(dir);
245 let llvm_config = build.llvm_config(target);
246 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
247 cmd.arg("--llvm-version").arg(llvm_version);
248 if !build.is_rust_llvm(target) {
249 cmd.arg("--system-llvm");
252 cmd.args(&build.flags.cmd.test_args());
254 if build.config.verbose() || build.flags.verbose() {
255 cmd.arg("--verbose");
258 if build.config.quiet_tests {
262 // Only pass correct values for these flags for the `run-make` suite as it
263 // requires that a C++ compiler was configured which isn't always the case.
264 if suite == "run-make" {
265 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
266 let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
267 cmd.arg("--cc").arg(build.cc(target))
268 .arg("--cxx").arg(build.cxx(target).unwrap())
269 .arg("--cflags").arg(build.cflags(target).join(" "))
270 .arg("--llvm-components").arg(llvm_components.trim())
271 .arg("--llvm-cxxflags").arg(llvm_cxxflags.trim());
273 cmd.arg("--cc").arg("")
274 .arg("--cxx").arg("")
275 .arg("--cflags").arg("")
276 .arg("--llvm-components").arg("")
277 .arg("--llvm-cxxflags").arg("");
280 if build.remote_tested(target) {
281 cmd.arg("--remote-test-client")
282 .arg(build.tool(&Compiler::new(0, &build.config.build),
283 "remote-test-client"));
286 // Running a C compiler on MSVC requires a few env vars to be set, to be
287 // sure to set them here.
289 // Note that if we encounter `PATH` we make sure to append to our own `PATH`
290 // rather than stomp over it.
291 if target.contains("msvc") {
292 for &(ref k, ref v) in build.cc[target].0.env() {
298 cmd.env("RUSTC_BOOTSTRAP", "1");
299 build.add_rust_test_threads(&mut cmd);
301 if build.config.sanitizers {
302 cmd.env("SANITIZER_SUPPORT", "1");
305 if build.config.profiler {
306 cmd.env("PROFILER_SUPPORT", "1");
309 cmd.arg("--adb-path").arg("adb");
310 cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
311 if target.contains("android") {
312 // Assume that cc for this target comes from the android sysroot
313 cmd.arg("--android-cross-path")
314 .arg(build.cc(target).parent().unwrap().parent().unwrap());
316 cmd.arg("--android-cross-path").arg("");
319 build.ci_env.force_coloring_in_ci(&mut cmd);
321 let _time = util::timeit();
322 try_run(build, &mut cmd);
325 /// Run `rustdoc --test` for all documentation in `src/doc`.
327 /// This will run all tests in our markdown documentation (e.g. the book)
328 /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to
330 pub fn docs(build: &Build, compiler: &Compiler) {
331 // Do a breadth-first traversal of the `src/doc` directory and just run
332 // tests for all files that end in `*.md`
333 let mut stack = vec![build.src.join("src/doc")];
334 let _time = util::timeit();
335 let _folder = build.fold_output(|| "test_docs");
337 while let Some(p) = stack.pop() {
339 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()).filter(|p| {
340 p.extension().and_then(|s| s.to_str()) == Some("md") &&
341 // The nostarch directory in the book is for no starch, and so isn't guaranteed to
342 // build. We don't care if it doesn't build, so skip it.
343 p.to_str().map_or(true, |p| !p.contains("nostarch"))
348 markdown_test(build, compiler, &p);
352 /// Run the error index generator tool to execute the tests located in the error
355 /// The `error_index_generator` tool lives in `src/tools` and is used to
356 /// generate a markdown file from the error indexes of the code base which is
357 /// then passed to `rustdoc --test`.
358 pub fn error_index(build: &Build, compiler: &Compiler) {
359 let _folder = build.fold_output(|| "test_error_index");
360 println!("Testing error-index stage{}", compiler.stage);
362 let dir = testdir(build, compiler.host);
363 t!(fs::create_dir_all(&dir));
364 let output = dir.join("error-index.md");
366 let _time = util::timeit();
367 build.run(build.tool_cmd(&Compiler::new(0, compiler.host),
368 "error_index_generator")
371 .env("CFG_BUILD", &build.config.build));
373 markdown_test(build, compiler, &output);
376 fn markdown_test(build: &Build, compiler: &Compiler, markdown: &Path) {
377 let mut file = t!(File::open(markdown));
378 let mut contents = String::new();
379 t!(file.read_to_string(&mut contents));
380 if !contents.contains("```") {
384 println!("doc tests for: {}", markdown.display());
385 let mut cmd = Command::new(build.rustdoc(compiler));
386 build.add_rustc_lib_path(compiler, &mut cmd);
387 build.add_rust_test_threads(&mut cmd);
390 cmd.env("RUSTC_BOOTSTRAP", "1");
392 let test_args = build.flags.cmd.test_args().join(" ");
393 cmd.arg("--test-args").arg(test_args);
395 if build.config.quiet_tests {
396 try_run_quiet(build, &mut cmd);
398 try_run(build, &mut cmd);
402 /// Run all unit tests plus documentation tests for an entire crate DAG defined
403 /// by a `Cargo.toml`
405 /// This is what runs tests for crates like the standard library, compiler, etc.
406 /// It essentially is the driver for running `cargo test`.
408 /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
409 /// arguments, and those arguments are discovered from `cargo metadata`.
410 pub fn krate(build: &Build,
415 krate: Option<&str>) {
416 let (name, path, features, root) = match mode {
418 ("libstd", "src/libstd", build.std_features(), "std")
421 ("libtest", "src/libtest", String::new(), "test")
424 ("librustc", "src/rustc", build.rustc_features(), "rustc-main")
426 _ => panic!("can only test libraries"),
428 let _folder = build.fold_output(|| {
429 format!("{}_stage{}-{}", test_kind.subcommand(), compiler.stage, name)
431 println!("{} {} stage{} ({} -> {})", test_kind, name, compiler.stage,
432 compiler.host, target);
434 // If we're not doing a full bootstrap but we're testing a stage2 version of
435 // libstd, then what we're actually testing is the libstd produced in
436 // stage1. Reflect that here by updating the compiler that we're working
437 // with automatically.
438 let compiler = if build.force_use_stage1(compiler, target) {
439 Compiler::new(1, compiler.host)
444 // Build up the base `cargo test` command.
446 // Pass in some standard flags then iterate over the graph we've discovered
447 // in `cargo metadata` with the maps above and figure out what `-p`
448 // arguments need to get passed.
449 let mut cargo = build.cargo(&compiler, mode, target, test_kind.subcommand());
450 cargo.arg("--manifest-path")
451 .arg(build.src.join(path).join("Cargo.toml"))
452 .arg("--features").arg(features);
453 if test_kind.subcommand() == "test" && build.flags.cmd.no_fail_fast() {
454 cargo.arg("--no-fail-fast");
459 cargo.arg("-p").arg(krate);
462 let mut visited = HashSet::new();
463 let mut next = vec![root];
464 while let Some(name) = next.pop() {
465 // Right now jemalloc is our only target-specific crate in the
466 // sense that it's not present on all platforms. Custom skip it
467 // here for now, but if we add more this probably wants to get
470 // Also skip `build_helper` as it's not compiled normally for
471 // target during the bootstrap and it's just meant to be a
472 // helper crate, not tested. If it leaks through then it ends up
473 // messing with various mtime calculations and such.
474 if !name.contains("jemalloc") && name != "build_helper" {
475 cargo.arg("-p").arg(&format!("{}:0.0.0", name));
477 for dep in build.crates[name].deps.iter() {
478 if visited.insert(dep) {
486 // The tests are going to run with the *target* libraries, so we need to
487 // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
489 // Note that to run the compiler we need to run with the *host* libraries,
490 // but our wrapper scripts arrange for that to be the case anyway.
491 let mut dylib_path = dylib_path();
492 dylib_path.insert(0, build.sysroot_libdir(&compiler, target));
493 cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
495 if target.contains("emscripten") || build.remote_tested(target) {
496 cargo.arg("--no-run");
501 if build.config.quiet_tests {
502 cargo.arg("--quiet");
505 let _time = util::timeit();
507 if target.contains("emscripten") {
508 build.run(&mut cargo);
509 krate_emscripten(build, &compiler, target, mode);
510 } else if build.remote_tested(target) {
511 build.run(&mut cargo);
512 krate_remote(build, &compiler, target, mode);
514 cargo.args(&build.flags.cmd.test_args());
515 try_run(build, &mut cargo);
519 fn krate_emscripten(build: &Build,
523 let mut tests = Vec::new();
524 let out_dir = build.cargo_out(compiler, mode, target);
525 find_tests(&out_dir.join("deps"), target, &mut tests);
528 let test_file_name = test.to_string_lossy().into_owned();
529 println!("running {}", test_file_name);
530 let nodejs = build.config.nodejs.as_ref().expect("nodejs not configured");
531 let mut cmd = Command::new(nodejs);
532 cmd.arg(&test_file_name);
533 if build.config.quiet_tests {
536 try_run(build, &mut cmd);
540 fn krate_remote(build: &Build,
544 let mut tests = Vec::new();
545 let out_dir = build.cargo_out(compiler, mode, target);
546 find_tests(&out_dir.join("deps"), target, &mut tests);
548 let tool = build.tool(&Compiler::new(0, &build.config.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,
564 dst: &mut Vec<PathBuf>) {
565 for e in t!(dir.read_dir()).map(|e| t!(e)) {
566 let file_type = t!(e.file_type());
567 if !file_type.is_file() {
570 let filename = e.file_name().into_string().unwrap();
571 if (target.contains("windows") && filename.ends_with(".exe")) ||
572 (!target.contains("windows") && !filename.contains(".")) ||
573 (target.contains("emscripten") &&
574 filename.ends_with(".js") &&
575 !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.config.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.config.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.config.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.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.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.rustc);
677 if build.flags.cmd.no_fail_fast() {
678 cmd.arg("--no-fail-fast");
680 cmd.arg("--").args(&build.flags.cmd.test_args());
681 try_run(build, &mut cmd);