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;
18 use std::ffi::OsString;
21 use std::fs::{self, File};
22 use std::path::{PathBuf, Path};
23 use std::process::Command;
26 use build_helper::{self, output};
28 use {Build, Compiler, Mode};
30 use util::{self, dylib_path, dylib_path_var, exe};
32 const ADB_TEST_DIR: &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) {
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) {
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 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.initial_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 compiler = &Compiler::new(stage, host);
123 let mut cargo = build.cargo(compiler, Mode::Tool, host, "test");
124 cargo.arg("--manifest-path").arg(build.src.join("src/tools/cargo/Cargo.toml"));
125 if !build.fail_fast {
126 cargo.arg("--no-fail-fast");
129 // Don't build tests dynamically, just a pain to work with
130 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
132 // Don't run cross-compile tests, we may not have cross-compiled libstd libs
134 cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
136 try_run(build, cargo.env("PATH", &path_for_cargo(build, compiler)));
139 /// Runs `cargo test` for the rls.
140 pub fn rls(build: &Build, stage: u32, host: &str) {
141 let compiler = &Compiler::new(stage, host);
143 let mut cargo = build.cargo(compiler, Mode::Tool, host, "test");
144 cargo.arg("--manifest-path").arg(build.src.join("src/tools/rls/Cargo.toml"));
146 // Don't build tests dynamically, just a pain to work with
147 cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
149 build.add_rustc_lib_path(compiler, &mut cargo);
151 try_run(build, &mut cargo);
154 fn path_for_cargo(build: &Build, compiler: &Compiler) -> OsString {
155 // Configure PATH to find the right rustc. NB. we have to use PATH
156 // and not RUSTC because the Cargo test suite has tests that will
157 // fail if rustc is not spelled `rustc`.
158 let path = build.sysroot(compiler).join("bin");
159 let old_path = env::var_os("PATH").unwrap_or_default();
160 env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
163 /// Runs the `tidy` tool as compiled in `stage` by the `host` compiler.
165 /// This tool in `src/tools` checks up on various bits and pieces of style and
166 /// otherwise just implements a few lint-like checks that are specific to the
168 pub fn tidy(build: &Build, host: &str) {
169 let _folder = build.fold_output(|| "tidy");
170 println!("tidy check ({})", host);
171 let compiler = Compiler::new(0, host);
172 let mut cmd = build.tool_cmd(&compiler, "tidy");
173 cmd.arg(build.src.join("src"));
174 if !build.config.vendor {
175 cmd.arg("--no-vendor");
177 if build.config.quiet_tests {
180 try_run(build, &mut cmd);
183 fn testdir(build: &Build, host: &str) -> PathBuf {
184 build.out.join(host).join("test")
187 /// Executes the `compiletest` tool to run a suite of tests.
189 /// Compiles all tests with `compiler` for `target` with the specified
190 /// compiletest `mode` and `suite` arguments. For example `mode` can be
191 /// "run-pass" or `suite` can be something like `debuginfo`.
192 pub fn compiletest(build: &Build,
197 let _folder = build.fold_output(|| format!("test_{}", suite));
198 println!("Check compiletest suite={} mode={} ({} -> {})",
199 suite, mode, compiler.host, target);
200 let mut cmd = Command::new(build.tool(&Compiler::new(0, compiler.host),
202 build.prepare_tool_cmd(compiler, &mut cmd);
204 // compiletest currently has... a lot of arguments, so let's just pass all
207 cmd.arg("--compile-lib-path").arg(build.rustc_libdir(compiler));
208 cmd.arg("--run-lib-path").arg(build.sysroot_libdir(compiler, target));
209 cmd.arg("--rustc-path").arg(build.compiler_path(compiler));
210 cmd.arg("--rustdoc-path").arg(build.rustdoc(compiler));
211 cmd.arg("--src-base").arg(build.src.join("src/test").join(suite));
212 cmd.arg("--build-base").arg(testdir(build, compiler.host).join(suite));
213 cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
214 cmd.arg("--mode").arg(mode);
215 cmd.arg("--target").arg(target);
216 cmd.arg("--host").arg(compiler.host);
217 cmd.arg("--llvm-filecheck").arg(build.llvm_filecheck(&build.build));
219 if let Some(ref nodejs) = build.config.nodejs {
220 cmd.arg("--nodejs").arg(nodejs);
223 let mut flags = vec!["-Crpath".to_string()];
224 if build.config.rust_optimize_tests {
225 flags.push("-O".to_string());
227 if build.config.rust_debuginfo_tests {
228 flags.push("-g".to_string());
231 let mut hostflags = build.rustc_flags(&compiler.host);
232 hostflags.extend(flags.clone());
233 cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
235 let mut targetflags = build.rustc_flags(&target);
236 targetflags.extend(flags);
237 targetflags.push(format!("-Lnative={}",
238 build.test_helpers_out(target).display()));
239 cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
241 cmd.arg("--docck-python").arg(build.python());
243 if build.build.ends_with("apple-darwin") {
244 // Force /usr/bin/python on macOS for LLDB tests because we're loading the
245 // LLDB plugin's compiled module which only works with the system python
246 // (namely not Homebrew-installed python)
247 cmd.arg("--lldb-python").arg("/usr/bin/python");
249 cmd.arg("--lldb-python").arg(build.python());
252 if let Some(ref gdb) = build.config.gdb {
253 cmd.arg("--gdb").arg(gdb);
255 if let Some(ref vers) = build.lldb_version {
256 cmd.arg("--lldb-version").arg(vers);
258 if let Some(ref dir) = build.lldb_python_dir {
259 cmd.arg("--lldb-python-dir").arg(dir);
261 let llvm_config = build.llvm_config(target);
262 let llvm_version = output(Command::new(&llvm_config).arg("--version"));
263 cmd.arg("--llvm-version").arg(llvm_version);
264 if !build.is_rust_llvm(target) {
265 cmd.arg("--system-llvm");
268 cmd.args(&build.flags.cmd.test_args());
270 if build.is_verbose() {
271 cmd.arg("--verbose");
274 if build.config.quiet_tests {
278 // Only pass correct values for these flags for the `run-make` suite as it
279 // requires that a C++ compiler was configured which isn't always the case.
280 if suite == "run-make" {
281 let llvm_components = output(Command::new(&llvm_config).arg("--components"));
282 let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
283 cmd.arg("--cc").arg(build.cc(target))
284 .arg("--cxx").arg(build.cxx(target).unwrap())
285 .arg("--cflags").arg(build.cflags(target).join(" "))
286 .arg("--llvm-components").arg(llvm_components.trim())
287 .arg("--llvm-cxxflags").arg(llvm_cxxflags.trim());
289 cmd.arg("--cc").arg("")
290 .arg("--cxx").arg("")
291 .arg("--cflags").arg("")
292 .arg("--llvm-components").arg("")
293 .arg("--llvm-cxxflags").arg("");
296 if build.remote_tested(target) {
297 cmd.arg("--remote-test-client")
298 .arg(build.tool(&Compiler::new(0, &build.build),
299 "remote-test-client"));
302 // Running a C compiler on MSVC requires a few env vars to be set, to be
303 // sure to set them here.
305 // Note that if we encounter `PATH` we make sure to append to our own `PATH`
306 // rather than stomp over it.
307 if target.contains("msvc") {
308 for &(ref k, ref v) in build.cc[target].0.env() {
314 cmd.env("RUSTC_BOOTSTRAP", "1");
315 build.add_rust_test_threads(&mut cmd);
317 if build.config.sanitizers {
318 cmd.env("SANITIZER_SUPPORT", "1");
321 if build.config.profiler {
322 cmd.env("PROFILER_SUPPORT", "1");
325 cmd.arg("--adb-path").arg("adb");
326 cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
327 if target.contains("android") {
328 // Assume that cc for this target comes from the android sysroot
329 cmd.arg("--android-cross-path")
330 .arg(build.cc(target).parent().unwrap().parent().unwrap());
332 cmd.arg("--android-cross-path").arg("");
335 build.ci_env.force_coloring_in_ci(&mut cmd);
337 let _time = util::timeit();
338 try_run(build, &mut cmd);
341 /// Run `rustdoc --test` for all documentation in `src/doc`.
343 /// This will run all tests in our markdown documentation (e.g. the book)
344 /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to
346 pub fn docs(build: &Build, compiler: &Compiler) {
347 // Do a breadth-first traversal of the `src/doc` directory and just run
348 // tests for all files that end in `*.md`
349 let mut stack = vec![build.src.join("src/doc")];
350 let _time = util::timeit();
351 let _folder = build.fold_output(|| "test_docs");
353 while let Some(p) = stack.pop() {
355 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
359 if p.extension().and_then(|s| s.to_str()) != Some("md") {
363 // The nostarch directory in the book is for no starch, and so isn't
364 // guaranteed to build. We don't care if it doesn't build, so skip it.
365 if p.to_str().map_or(false, |p| p.contains("nostarch")) {
369 markdown_test(build, compiler, &p);
373 /// Run the error index generator tool to execute the tests located in the error
376 /// The `error_index_generator` tool lives in `src/tools` and is used to
377 /// generate a markdown file from the error indexes of the code base which is
378 /// then passed to `rustdoc --test`.
379 pub fn error_index(build: &Build, compiler: &Compiler) {
380 let _folder = build.fold_output(|| "test_error_index");
381 println!("Testing error-index stage{}", compiler.stage);
383 let dir = testdir(build, compiler.host);
384 t!(fs::create_dir_all(&dir));
385 let output = dir.join("error-index.md");
387 let _time = util::timeit();
388 build.run(build.tool_cmd(&Compiler::new(0, compiler.host),
389 "error_index_generator")
392 .env("CFG_BUILD", &build.build));
394 markdown_test(build, compiler, &output);
397 fn markdown_test(build: &Build, compiler: &Compiler, markdown: &Path) {
398 let mut file = t!(File::open(markdown));
399 let mut contents = String::new();
400 t!(file.read_to_string(&mut contents));
401 if !contents.contains("```") {
405 println!("doc tests for: {}", markdown.display());
406 let mut cmd = Command::new(build.rustdoc(compiler));
407 build.add_rustc_lib_path(compiler, &mut cmd);
408 build.add_rust_test_threads(&mut cmd);
411 cmd.env("RUSTC_BOOTSTRAP", "1");
413 let test_args = build.flags.cmd.test_args().join(" ");
414 cmd.arg("--test-args").arg(test_args);
416 if build.config.quiet_tests {
417 try_run_quiet(build, &mut cmd);
419 try_run(build, &mut cmd);
423 /// Run all unit tests plus documentation tests for an entire crate DAG defined
424 /// by a `Cargo.toml`
426 /// This is what runs tests for crates like the standard library, compiler, etc.
427 /// It essentially is the driver for running `cargo test`.
429 /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
430 /// arguments, and those arguments are discovered from `cargo metadata`.
431 pub fn krate(build: &Build,
436 krate: Option<&str>) {
437 let (name, path, features, root) = match mode {
439 ("libstd", "src/libstd", build.std_features(), "std")
442 ("libtest", "src/libtest", String::new(), "test")
445 ("librustc", "src/rustc", build.rustc_features(), "rustc-main")
447 _ => panic!("can only test libraries"),
449 let _folder = build.fold_output(|| {
450 format!("{}_stage{}-{}", test_kind.subcommand(), compiler.stage, name)
452 println!("{} {} stage{} ({} -> {})", test_kind, name, compiler.stage,
453 compiler.host, target);
455 // If we're not doing a full bootstrap but we're testing a stage2 version of
456 // libstd, then what we're actually testing is the libstd produced in
457 // stage1. Reflect that here by updating the compiler that we're working
458 // with automatically.
459 let compiler = if build.force_use_stage1(compiler, target) {
460 Compiler::new(1, compiler.host)
465 // Build up the base `cargo test` command.
467 // Pass in some standard flags then iterate over the graph we've discovered
468 // in `cargo metadata` with the maps above and figure out what `-p`
469 // arguments need to get passed.
470 let mut cargo = build.cargo(&compiler, mode, target, test_kind.subcommand());
471 cargo.arg("--manifest-path")
472 .arg(build.src.join(path).join("Cargo.toml"))
473 .arg("--features").arg(features);
474 if test_kind.subcommand() == "test" && !build.fail_fast {
475 cargo.arg("--no-fail-fast");
480 cargo.arg("-p").arg(krate);
483 let mut visited = HashSet::new();
484 let mut next = vec![root];
485 while let Some(name) = next.pop() {
486 // Right now jemalloc is our only target-specific crate in the
487 // sense that it's not present on all platforms. Custom skip it
488 // here for now, but if we add more this probably wants to get
491 // Also skip `build_helper` as it's not compiled normally for
492 // target during the bootstrap and it's just meant to be a
493 // helper crate, not tested. If it leaks through then it ends up
494 // messing with various mtime calculations and such.
495 if !name.contains("jemalloc") && name != "build_helper" {
496 cargo.arg("-p").arg(&format!("{}:0.0.0", name));
498 for dep in build.crates[name].deps.iter() {
499 if visited.insert(dep) {
507 // The tests are going to run with the *target* libraries, so we need to
508 // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
510 // Note that to run the compiler we need to run with the *host* libraries,
511 // but our wrapper scripts arrange for that to be the case anyway.
512 let mut dylib_path = dylib_path();
513 dylib_path.insert(0, build.sysroot_libdir(&compiler, target));
514 cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
516 if target.contains("emscripten") || build.remote_tested(target) {
517 cargo.arg("--no-run");
522 if build.config.quiet_tests {
523 cargo.arg("--quiet");
526 let _time = util::timeit();
528 if target.contains("emscripten") {
529 build.run(&mut cargo);
530 krate_emscripten(build, &compiler, target, mode);
531 } else if build.remote_tested(target) {
532 build.run(&mut cargo);
533 krate_remote(build, &compiler, target, mode);
535 cargo.args(&build.flags.cmd.test_args());
536 try_run(build, &mut cargo);
540 fn krate_emscripten(build: &Build,
544 let out_dir = build.cargo_out(compiler, mode, target);
545 let tests = find_tests(&out_dir.join("deps"), target);
547 let nodejs = build.config.nodejs.as_ref().expect("nodejs not configured");
549 println!("running {}", test.display());
550 let mut cmd = Command::new(nodejs);
552 if build.config.quiet_tests {
555 try_run(build, &mut cmd);
559 fn krate_remote(build: &Build,
563 let out_dir = build.cargo_out(compiler, mode, target);
564 let tests = find_tests(&out_dir.join("deps"), target);
566 let tool = build.tool(&Compiler::new(0, &build.build),
567 "remote-test-client");
569 let mut cmd = Command::new(&tool);
572 if build.config.quiet_tests {
575 cmd.args(&build.flags.cmd.test_args());
576 try_run(build, &mut cmd);
580 fn find_tests(dir: &Path, target: &str) -> Vec<PathBuf> {
581 let mut dst = Vec::new();
582 for e in t!(dir.read_dir()).map(|e| t!(e)) {
583 let file_type = t!(e.file_type());
584 if !file_type.is_file() {
587 let filename = e.file_name().into_string().unwrap();
588 if (target.contains("windows") && filename.ends_with(".exe")) ||
589 (!target.contains("windows") && !filename.contains(".")) ||
590 (target.contains("emscripten") &&
591 filename.ends_with(".js") &&
592 !filename.ends_with(".asm.js")) {
599 pub fn remote_copy_libs(build: &Build, compiler: &Compiler, target: &str) {
600 if !build.remote_tested(target) {
604 println!("REMOTE copy libs to emulator ({})", target);
605 t!(fs::create_dir_all(build.out.join("tmp")));
607 let server = build.cargo_out(compiler, Mode::Tool, target)
608 .join(exe("remote-test-server", target));
610 // Spawn the emulator and wait for it to come online
611 let tool = build.tool(&Compiler::new(0, &build.build),
612 "remote-test-client");
613 let mut cmd = Command::new(&tool);
614 cmd.arg("spawn-emulator")
617 .arg(build.out.join("tmp"));
618 if let Some(rootfs) = build.qemu_rootfs(target) {
623 // Push all our dylibs to the emulator
624 for f in t!(build.sysroot_libdir(compiler, target).read_dir()) {
626 let name = f.file_name().into_string().unwrap();
627 if util::is_dylib(&name) {
628 build.run(Command::new(&tool)
635 /// Run "distcheck", a 'make check' from a tarball
636 pub fn distcheck(build: &Build) {
637 if build.build != "x86_64-unknown-linux-gnu" {
640 if !build.config.host.iter().any(|s| s == "x86_64-unknown-linux-gnu") {
643 if !build.config.target.iter().any(|s| s == "x86_64-unknown-linux-gnu") {
647 println!("Distcheck");
648 let dir = build.out.join("tmp").join("distcheck");
649 let _ = fs::remove_dir_all(&dir);
650 t!(fs::create_dir_all(&dir));
652 let mut cmd = Command::new("tar");
654 .arg(dist::rust_src_location(build))
655 .arg("--strip-components=1")
658 build.run(Command::new("./configure")
659 .args(&build.config.configure_args)
660 .arg("--enable-vendor")
662 build.run(Command::new(build_helper::make(&build.build))
666 // Now make sure that rust-src has all of libstd's dependencies
667 println!("Distcheck rust-src");
668 let dir = build.out.join("tmp").join("distcheck-src");
669 let _ = fs::remove_dir_all(&dir);
670 t!(fs::create_dir_all(&dir));
672 let mut cmd = Command::new("tar");
674 .arg(dist::rust_src_installer(build))
675 .arg("--strip-components=1")
679 let toml = dir.join("rust-src/lib/rustlib/src/rust/src/libstd/Cargo.toml");
680 build.run(Command::new(&build.initial_cargo)
681 .arg("generate-lockfile")
682 .arg("--manifest-path")
687 /// Test the build system itself
688 pub fn bootstrap(build: &Build) {
689 let mut cmd = Command::new(&build.initial_cargo);
691 .current_dir(build.src.join("src/bootstrap"))
692 .env("CARGO_TARGET_DIR", build.out.join("bootstrap"))
693 .env("RUSTC_BOOTSTRAP", "1")
694 .env("RUSTC", &build.initial_rustc);
695 if !build.fail_fast {
696 cmd.arg("--no-fail-fast");
698 cmd.arg("--").args(&build.flags.cmd.test_args());
699 try_run(build, &mut cmd);