]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/check.rs
16f14638b51c5bf21ae6268d5e456b572487c17b
[rust.git] / src / bootstrap / check.rs
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.
4 //
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.
10
11 //! Implementation of the test-related targets of the build system.
12 //!
13 //! This file implements the various regression test suites that we execute on
14 //! our CI.
15
16 use std::collections::HashSet;
17 use std::env;
18 use std::ffi::OsString;
19 use std::iter;
20 use std::fmt;
21 use std::fs::{self, File};
22 use std::path::{PathBuf, Path};
23 use std::process::Command;
24 use std::io::Read;
25
26 use build_helper::{self, output};
27
28 use {Build, Mode};
29 use dist;
30 use util::{self, dylib_path, dylib_path_var};
31
32 use compile;
33 use native;
34 use builder::{Kind, ShouldRun, Builder, Compiler, Step};
35 use tool::{self, Tool};
36 use cache::{INTERNER, Interned};
37
38 const ADB_TEST_DIR: &str = "/data/tmp/work";
39
40 /// The two modes of the test runner; tests or benchmarks.
41 #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
42 pub enum TestKind {
43     /// Run `cargo test`
44     Test,
45     /// Run `cargo bench`
46     Bench,
47 }
48
49 impl TestKind {
50     // Return the cargo subcommand for this test kind
51     fn subcommand(self) -> &'static str {
52         match self {
53             TestKind::Test => "test",
54             TestKind::Bench => "bench",
55         }
56     }
57 }
58
59 impl fmt::Display for TestKind {
60     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61         f.write_str(match *self {
62             TestKind::Test => "Testing",
63             TestKind::Bench => "Benchmarking",
64         })
65     }
66 }
67
68 fn try_run(build: &Build, cmd: &mut Command) {
69     if !build.fail_fast {
70         if !build.try_run(cmd) {
71             let failures = build.delayed_failures.get();
72             build.delayed_failures.set(failures + 1);
73         }
74     } else {
75         build.run(cmd);
76     }
77 }
78
79 fn try_run_quiet(build: &Build, cmd: &mut Command) {
80     if !build.fail_fast {
81         if !build.try_run_quiet(cmd) {
82             let failures = build.delayed_failures.get();
83             build.delayed_failures.set(failures + 1);
84         }
85     } else {
86         build.run_quiet(cmd);
87     }
88 }
89
90 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
91 pub struct Linkcheck {
92     host: Interned<String>,
93 }
94
95 impl Step for Linkcheck {
96     type Output = ();
97     const ONLY_HOSTS: bool = true;
98     const DEFAULT: bool = true;
99
100     /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
101     ///
102     /// This tool in `src/tools` will verify the validity of all our links in the
103     /// documentation to ensure we don't have a bunch of dead ones.
104     fn run(self, builder: &Builder) {
105         let build = builder.build;
106         let host = self.host;
107
108         println!("Linkcheck ({})", host);
109
110         builder.default_doc(None);
111
112         let _time = util::timeit();
113         try_run(build, builder.tool_cmd(Tool::Linkchecker)
114                             .arg(build.out.join(host).join("doc")));
115     }
116
117     fn should_run(run: ShouldRun) -> ShouldRun {
118         run.path("src/tools/linkchecker")
119     }
120
121     fn make_run(
122         builder: &Builder,
123         path: Option<&Path>,
124         host: Interned<String>,
125         _target: Interned<String>,
126     ) {
127         if path.is_some() {
128             builder.ensure(Linkcheck { host });
129         } else {
130             if builder.build.config.docs {
131                 builder.ensure(Linkcheck { host });
132             }
133         }
134     }
135 }
136
137 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
138 pub struct Cargotest {
139     stage: u32,
140     host: Interned<String>,
141 }
142
143 impl Step for Cargotest {
144     type Output = ();
145     const ONLY_HOSTS: bool = true;
146
147     fn should_run(run: ShouldRun) -> ShouldRun {
148         run.path("src/tools/cargotest")
149     }
150
151     fn make_run(
152         builder: &Builder,
153         _path: Option<&Path>,
154         host: Interned<String>,
155         _target: Interned<String>,
156     ) {
157         builder.ensure(Cargotest {
158             stage: builder.top_stage,
159             host: host,
160         });
161     }
162
163     /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
164     ///
165     /// This tool in `src/tools` will check out a few Rust projects and run `cargo
166     /// test` to ensure that we don't regress the test suites there.
167     fn run(self, builder: &Builder) {
168         let build = builder.build;
169         let compiler = builder.compiler(self.stage, self.host);
170         builder.ensure(compile::Rustc { compiler, target: compiler.host });
171
172         // Note that this is a short, cryptic, and not scoped directory name. This
173         // is currently to minimize the length of path on Windows where we otherwise
174         // quickly run into path name limit constraints.
175         let out_dir = build.out.join("ct");
176         t!(fs::create_dir_all(&out_dir));
177
178         let _time = util::timeit();
179         let mut cmd = builder.tool_cmd(Tool::CargoTest);
180         try_run(build, cmd.arg(&build.initial_cargo)
181                           .arg(&out_dir)
182                           .env("RUSTC", builder.rustc(compiler))
183                           .env("RUSTDOC", builder.rustdoc(compiler)));
184     }
185 }
186
187 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
188 pub struct Cargo {
189     stage: u32,
190     host: Interned<String>,
191 }
192
193 impl Step for Cargo {
194     type Output = ();
195     const ONLY_HOSTS: bool = true;
196
197     fn should_run(run: ShouldRun) -> ShouldRun {
198         run.path("src/tools/cargo")
199     }
200
201     fn make_run(
202         builder: &Builder,
203         _path: Option<&Path>,
204         _host: Interned<String>,
205         target: Interned<String>,
206     ) {
207         builder.ensure(Cargo {
208             stage: builder.top_stage,
209             host: target,
210         });
211     }
212
213     /// Runs `cargo test` for `cargo` packaged with Rust.
214     fn run(self, builder: &Builder) {
215         let build = builder.build;
216         let compiler = builder.compiler(self.stage, self.host);
217
218         builder.ensure(tool::Cargo { stage: self.stage, target: self.host });
219         let mut cargo = builder.cargo(compiler, Mode::Tool, self.host, "test");
220         cargo.arg("--manifest-path").arg(build.src.join("src/tools/cargo/Cargo.toml"));
221         if !build.fail_fast {
222             cargo.arg("--no-fail-fast");
223         }
224
225         // Don't build tests dynamically, just a pain to work with
226         cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
227
228         // Don't run cross-compile tests, we may not have cross-compiled libstd libs
229         // available.
230         cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
231
232         try_run(build, cargo.env("PATH", &path_for_cargo(builder, compiler)));
233     }
234 }
235
236 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
237 pub struct Rls {
238     stage: u32,
239     host: Interned<String>,
240 }
241
242 impl Step for Rls {
243     type Output = ();
244     const ONLY_HOSTS: bool = true;
245
246     fn should_run(run: ShouldRun) -> ShouldRun {
247         run.path("src/tools/rls")
248     }
249
250     fn make_run(
251         builder: &Builder,
252         _path: Option<&Path>,
253         _host: Interned<String>,
254         target: Interned<String>,
255     ) {
256         builder.ensure(Rls {
257             stage: builder.top_stage,
258             host: target,
259         });
260     }
261
262     /// Runs `cargo test` for the rls.
263     fn run(self, builder: &Builder) {
264         let build = builder.build;
265         let stage = self.stage;
266         let host = self.host;
267         let compiler = builder.compiler(stage, host);
268
269         builder.ensure(tool::Rls { stage: self.stage, target: self.host });
270         let mut cargo = builder.cargo(compiler, Mode::Tool, host, "test");
271         cargo.arg("--manifest-path").arg(build.src.join("src/tools/rls/Cargo.toml"));
272
273         // Don't build tests dynamically, just a pain to work with
274         cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
275
276         builder.add_rustc_lib_path(compiler, &mut cargo);
277
278         try_run(build, &mut cargo);
279     }
280 }
281
282 fn path_for_cargo(builder: &Builder, compiler: Compiler) -> OsString {
283     // Configure PATH to find the right rustc. NB. we have to use PATH
284     // and not RUSTC because the Cargo test suite has tests that will
285     // fail if rustc is not spelled `rustc`.
286     let path = builder.sysroot(compiler).join("bin");
287     let old_path = env::var_os("PATH").unwrap_or_default();
288     env::join_paths(iter::once(path).chain(env::split_paths(&old_path))).expect("")
289 }
290
291 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
292 pub struct Tidy {
293     host: Interned<String>,
294 }
295
296 impl Step for Tidy {
297     type Output = ();
298     const DEFAULT: bool = true;
299     const ONLY_HOSTS: bool = true;
300     const ONLY_BUILD: bool = true;
301
302     /// Runs the `tidy` tool as compiled in `stage` by the `host` compiler.
303     ///
304     /// This tool in `src/tools` checks up on various bits and pieces of style and
305     /// otherwise just implements a few lint-like checks that are specific to the
306     /// compiler itself.
307     fn run(self, builder: &Builder) {
308         let build = builder.build;
309         let host = self.host;
310
311         let _folder = build.fold_output(|| "tidy");
312         println!("tidy check ({})", host);
313         let mut cmd = builder.tool_cmd(Tool::Tidy);
314         cmd.arg(build.src.join("src"));
315         if !build.config.vendor {
316             cmd.arg("--no-vendor");
317         }
318         if build.config.quiet_tests {
319             cmd.arg("--quiet");
320         }
321         try_run(build, &mut cmd);
322     }
323
324     fn should_run(run: ShouldRun) -> ShouldRun {
325         run.path("src/tools/tidy")
326     }
327
328     fn make_run(
329         builder: &Builder,
330         _path: Option<&Path>,
331         _host: Interned<String>,
332         _target: Interned<String>,
333     ) {
334         builder.ensure(Tidy {
335             host: builder.build.build,
336         });
337     }
338 }
339
340 fn testdir(build: &Build, host: Interned<String>) -> PathBuf {
341     build.out.join(host).join("test")
342 }
343
344 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
345 struct Test {
346     path: &'static str,
347     mode: &'static str,
348     suite: &'static str,
349 }
350
351 static DEFAULT_COMPILETESTS: &[Test] = &[
352     Test { path: "src/test/ui", mode: "ui", suite: "ui" },
353     Test { path: "src/test/run-pass", mode: "run-pass", suite: "run-pass" },
354     Test { path: "src/test/compile-fail", mode: "compile-fail", suite: "compile-fail" },
355     Test { path: "src/test/parse-fail", mode: "parse-fail", suite: "parse-fail" },
356     Test { path: "src/test/run-fail", mode: "run-fail", suite: "run-fail" },
357     Test {
358         path: "src/test/run-pass-valgrind",
359         mode: "run-pass-valgrind",
360         suite: "run-pass-valgrind"
361     },
362     Test { path: "src/test/mir-opt", mode: "mir-opt", suite: "mir-opt" },
363     Test { path: "src/test/codegen", mode: "codegen", suite: "codegen" },
364     Test { path: "src/test/codegen-units", mode: "codegen-units", suite: "codegen-units" },
365     Test { path: "src/test/incremental", mode: "incremental", suite: "incremental" },
366
367     // What this runs varies depending on the native platform being apple
368     Test { path: "src/test/debuginfo", mode: "debuginfo-XXX", suite: "debuginfo" },
369 ];
370
371 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
372 pub struct DefaultCompiletest {
373     compiler: Compiler,
374     target: Interned<String>,
375     mode: &'static str,
376     suite: &'static str,
377 }
378
379 impl Step for DefaultCompiletest {
380     type Output = ();
381     const DEFAULT: bool = true;
382
383     fn should_run(mut run: ShouldRun) -> ShouldRun {
384         for test in DEFAULT_COMPILETESTS {
385             run = run.path(test.path);
386         }
387         run
388     }
389
390     fn make_run(
391         builder: &Builder,
392         path: Option<&Path>,
393         host: Interned<String>,
394         target: Interned<String>,
395     ) {
396         let compiler = builder.compiler(builder.top_stage, host);
397
398         let test = path.map(|path| {
399             DEFAULT_COMPILETESTS.iter().find(|&&test| {
400                 path.ends_with(test.path)
401             }).unwrap_or_else(|| {
402                 panic!("make_run in compile test to receive test path, received {:?}", path);
403             })
404         });
405
406         if let Some(test) = test {
407             builder.ensure(DefaultCompiletest {
408                 compiler,
409                 target,
410                 mode: test.mode,
411                 suite: test.suite,
412             });
413         } else {
414             for test in DEFAULT_COMPILETESTS {
415                 builder.ensure(DefaultCompiletest {
416                     compiler,
417                     target,
418                     mode: test.mode,
419                     suite: test.suite
420                 });
421             }
422         }
423     }
424
425     fn run(self, builder: &Builder) {
426         builder.ensure(Compiletest {
427             compiler: self.compiler,
428             target: self.target,
429             mode: self.mode,
430             suite: self.suite,
431         })
432     }
433 }
434
435 // Also default, but host-only.
436 static HOST_COMPILETESTS: &[Test] = &[
437     Test { path: "src/test/ui-fulldeps", mode: "ui", suite: "ui-fulldeps" },
438     Test { path: "src/test/run-pass-fulldeps", mode: "run-pass", suite: "run-pass-fulldeps" },
439     Test { path: "src/test/run-fail-fulldeps", mode: "run-fail", suite: "run-fail-fulldeps" },
440     Test {
441         path: "src/test/compile-fail-fulldeps",
442         mode: "compile-fail",
443         suite: "compile-fail-fulldeps",
444     },
445     Test { path: "src/test/run-make", mode: "run-make", suite: "run-make" },
446     Test { path: "src/test/rustdoc", mode: "rustdoc", suite: "rustdoc" },
447
448     Test { path: "src/test/pretty", mode: "pretty", suite: "pretty" },
449     Test { path: "src/test/run-pass/pretty", mode: "pretty", suite: "run-pass" },
450     Test { path: "src/test/run-fail/pretty", mode: "pretty", suite: "run-fail" },
451     Test { path: "src/test/run-pass-valgrind/pretty", mode: "pretty", suite: "run-pass-valgrind" },
452     Test { path: "src/test/run-pass-fulldeps/pretty", mode: "pretty", suite: "run-pass-fulldeps" },
453     Test { path: "src/test/run-fail-fulldeps/pretty", mode: "pretty", suite: "run-fail-fulldeps" },
454 ];
455
456 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
457 pub struct HostCompiletest {
458     compiler: Compiler,
459     target: Interned<String>,
460     mode: &'static str,
461     suite: &'static str,
462 }
463
464 impl Step for HostCompiletest {
465     type Output = ();
466     const DEFAULT: bool = true;
467     const ONLY_HOSTS: bool = true;
468
469     fn should_run(mut run: ShouldRun) -> ShouldRun {
470         for test in HOST_COMPILETESTS {
471             run = run.path(test.path);
472         }
473         run
474     }
475
476     fn make_run(
477         builder: &Builder,
478         path: Option<&Path>,
479         host: Interned<String>,
480         target: Interned<String>,
481     ) {
482         let compiler = builder.compiler(builder.top_stage, host);
483
484         let test = path.map(|path| {
485             HOST_COMPILETESTS.iter().find(|&&test| {
486                 path.ends_with(test.path)
487             }).unwrap_or_else(|| {
488                 panic!("make_run in compile test to receive test path, received {:?}", path);
489             })
490         });
491
492         if let Some(test) = test {
493             builder.ensure(HostCompiletest {
494                 compiler,
495                 target,
496                 mode: test.mode,
497                 suite: test.suite,
498             });
499         } else {
500             for test in HOST_COMPILETESTS {
501                 builder.ensure(HostCompiletest {
502                     compiler,
503                     target,
504                     mode: test.mode,
505                     suite: test.suite
506                 });
507             }
508         }
509     }
510
511     fn run(self, builder: &Builder) {
512         builder.ensure(Compiletest {
513             compiler: self.compiler,
514             target: self.target,
515             mode: self.mode,
516             suite: self.suite,
517         })
518     }
519 }
520
521 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
522 struct Compiletest {
523     compiler: Compiler,
524     target: Interned<String>,
525     mode: &'static str,
526     suite: &'static str,
527 }
528
529 impl Step for Compiletest {
530     type Output = ();
531
532     fn should_run(run: ShouldRun) -> ShouldRun {
533         run.never()
534     }
535
536     /// Executes the `compiletest` tool to run a suite of tests.
537     ///
538     /// Compiles all tests with `compiler` for `target` with the specified
539     /// compiletest `mode` and `suite` arguments. For example `mode` can be
540     /// "run-pass" or `suite` can be something like `debuginfo`.
541     fn run(self, builder: &Builder) {
542         let build = builder.build;
543         let compiler = self.compiler;
544         let target = self.target;
545         let mode = self.mode;
546         let suite = self.suite;
547
548         // Skip codegen tests if they aren't enabled in configuration.
549         if !build.config.codegen_tests && suite == "codegen" {
550             return;
551         }
552
553         if suite == "debuginfo" {
554             // Skip debuginfo tests on MSVC
555             if build.build.contains("msvc") {
556                 return;
557             }
558
559             if mode == "debuginfo-XXX" {
560                 return if build.build.contains("apple") {
561                     builder.ensure(Compiletest {
562                         mode: "debuginfo-lldb",
563                         ..self
564                     });
565                 } else {
566                     builder.ensure(Compiletest {
567                         mode: "debuginfo-gdb",
568                         ..self
569                     });
570                 };
571             }
572
573             builder.ensure(dist::DebuggerScripts {
574                 sysroot: builder.sysroot(compiler),
575                 target: target
576             });
577         }
578
579         if suite.ends_with("fulldeps") ||
580             // FIXME: Does pretty need librustc compiled? Note that there are
581             // fulldeps test suites with mode = pretty as well.
582             mode == "pretty" ||
583             mode == "rustdoc" ||
584             mode == "run-make" {
585             builder.ensure(compile::Rustc { compiler, target });
586         }
587
588         builder.ensure(compile::Test { compiler, target });
589         builder.ensure(native::TestHelpers { target });
590         builder.ensure(RemoteCopyLibs { compiler, target });
591
592         let _folder = build.fold_output(|| format!("test_{}", suite));
593         println!("Check compiletest suite={} mode={} ({} -> {})",
594                  suite, mode, &compiler.host, target);
595         let mut cmd = builder.tool_cmd(Tool::Compiletest);
596
597         // compiletest currently has... a lot of arguments, so let's just pass all
598         // of them!
599
600         cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(compiler));
601         cmd.arg("--run-lib-path").arg(builder.sysroot_libdir(compiler, target));
602         cmd.arg("--rustc-path").arg(builder.rustc(compiler));
603         cmd.arg("--rustdoc-path").arg(builder.rustdoc(compiler));
604         cmd.arg("--src-base").arg(build.src.join("src/test").join(suite));
605         cmd.arg("--build-base").arg(testdir(build, compiler.host).join(suite));
606         cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
607         cmd.arg("--mode").arg(mode);
608         cmd.arg("--target").arg(target);
609         cmd.arg("--host").arg(&*compiler.host);
610         cmd.arg("--llvm-filecheck").arg(build.llvm_filecheck(build.build));
611
612         if let Some(ref nodejs) = build.config.nodejs {
613             cmd.arg("--nodejs").arg(nodejs);
614         }
615
616         let mut flags = vec!["-Crpath".to_string()];
617         if build.config.rust_optimize_tests {
618             flags.push("-O".to_string());
619         }
620         if build.config.rust_debuginfo_tests {
621             flags.push("-g".to_string());
622         }
623
624         let mut hostflags = build.rustc_flags(compiler.host);
625         hostflags.extend(flags.clone());
626         cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
627
628         let mut targetflags = build.rustc_flags(target);
629         targetflags.extend(flags);
630         targetflags.push(format!("-Lnative={}",
631                                  build.test_helpers_out(target).display()));
632         cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
633
634         cmd.arg("--docck-python").arg(build.python());
635
636         if build.build.ends_with("apple-darwin") {
637             // Force /usr/bin/python on macOS for LLDB tests because we're loading the
638             // LLDB plugin's compiled module which only works with the system python
639             // (namely not Homebrew-installed python)
640             cmd.arg("--lldb-python").arg("/usr/bin/python");
641         } else {
642             cmd.arg("--lldb-python").arg(build.python());
643         }
644
645         if let Some(ref gdb) = build.config.gdb {
646             cmd.arg("--gdb").arg(gdb);
647         }
648         if let Some(ref vers) = build.lldb_version {
649             cmd.arg("--lldb-version").arg(vers);
650         }
651         if let Some(ref dir) = build.lldb_python_dir {
652             cmd.arg("--lldb-python-dir").arg(dir);
653         }
654         let llvm_config = build.llvm_config(target);
655         let llvm_version = output(Command::new(&llvm_config).arg("--version"));
656         cmd.arg("--llvm-version").arg(llvm_version);
657         if !build.is_rust_llvm(target) {
658             cmd.arg("--system-llvm");
659         }
660
661         cmd.args(&build.flags.cmd.test_args());
662
663         if build.is_verbose() {
664             cmd.arg("--verbose");
665         }
666
667         if build.config.quiet_tests {
668             cmd.arg("--quiet");
669         }
670
671         // Only pass correct values for these flags for the `run-make` suite as it
672         // requires that a C++ compiler was configured which isn't always the case.
673         if suite == "run-make" {
674             let llvm_components = output(Command::new(&llvm_config).arg("--components"));
675             let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
676             cmd.arg("--cc").arg(build.cc(target))
677                .arg("--cxx").arg(build.cxx(target).unwrap())
678                .arg("--cflags").arg(build.cflags(target).join(" "))
679                .arg("--llvm-components").arg(llvm_components.trim())
680                .arg("--llvm-cxxflags").arg(llvm_cxxflags.trim());
681         } else {
682             cmd.arg("--cc").arg("")
683                .arg("--cxx").arg("")
684                .arg("--cflags").arg("")
685                .arg("--llvm-components").arg("")
686                .arg("--llvm-cxxflags").arg("");
687         }
688
689         if build.remote_tested(target) {
690             cmd.arg("--remote-test-client").arg(builder.tool_exe(Tool::RemoteTestClient));
691         }
692
693         // Running a C compiler on MSVC requires a few env vars to be set, to be
694         // sure to set them here.
695         //
696         // Note that if we encounter `PATH` we make sure to append to our own `PATH`
697         // rather than stomp over it.
698         if target.contains("msvc") {
699             for &(ref k, ref v) in build.cc[&target].0.env() {
700                 if k != "PATH" {
701                     cmd.env(k, v);
702                 }
703             }
704         }
705         cmd.env("RUSTC_BOOTSTRAP", "1");
706         build.add_rust_test_threads(&mut cmd);
707
708         if build.config.sanitizers {
709             cmd.env("SANITIZER_SUPPORT", "1");
710         }
711
712         if build.config.profiler {
713             cmd.env("PROFILER_SUPPORT", "1");
714         }
715
716         cmd.arg("--adb-path").arg("adb");
717         cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
718         if target.contains("android") {
719             // Assume that cc for this target comes from the android sysroot
720             cmd.arg("--android-cross-path")
721                .arg(build.cc(target).parent().unwrap().parent().unwrap());
722         } else {
723             cmd.arg("--android-cross-path").arg("");
724         }
725
726         build.ci_env.force_coloring_in_ci(&mut cmd);
727
728         let _time = util::timeit();
729         try_run(build, &mut cmd);
730     }
731 }
732
733 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
734 pub struct Docs {
735     compiler: Compiler,
736 }
737
738 impl Step for Docs {
739     type Output = ();
740     const DEFAULT: bool = true;
741     const ONLY_HOSTS: bool = true;
742
743     fn should_run(run: ShouldRun) -> ShouldRun {
744         run.path("src/doc")
745     }
746
747     fn make_run(
748         builder: &Builder,
749         _path: Option<&Path>,
750         host: Interned<String>,
751         _target: Interned<String>,
752     ) {
753         builder.ensure(Docs {
754             compiler: builder.compiler(builder.top_stage, host),
755         });
756     }
757
758     /// Run `rustdoc --test` for all documentation in `src/doc`.
759     ///
760     /// This will run all tests in our markdown documentation (e.g. the book)
761     /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to
762     /// `compiler`.
763     fn run(self, builder: &Builder) {
764         let build = builder.build;
765         let compiler = self.compiler;
766
767         builder.ensure(compile::Test { compiler, target: compiler.host });
768
769         // Do a breadth-first traversal of the `src/doc` directory and just run
770         // tests for all files that end in `*.md`
771         let mut stack = vec![build.src.join("src/doc")];
772         let _time = util::timeit();
773         let _folder = build.fold_output(|| "test_docs");
774
775         while let Some(p) = stack.pop() {
776             if p.is_dir() {
777                 stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
778                 continue
779             }
780
781             if p.extension().and_then(|s| s.to_str()) != Some("md") {
782                 continue;
783             }
784
785             // The nostarch directory in the book is for no starch, and so isn't
786             // guaranteed to build. We don't care if it doesn't build, so skip it.
787             if p.to_str().map_or(false, |p| p.contains("nostarch")) {
788                 continue;
789             }
790
791             markdown_test(builder, compiler, &p);
792         }
793     }
794 }
795
796 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
797 pub struct ErrorIndex {
798     compiler: Compiler,
799 }
800
801 impl Step for ErrorIndex {
802     type Output = ();
803     const DEFAULT: bool = true;
804     const ONLY_HOSTS: bool = true;
805
806     fn should_run(run: ShouldRun) -> ShouldRun {
807         run.path("src/tools/error_index_generator")
808     }
809
810     fn make_run(
811         builder: &Builder,
812         _path: Option<&Path>,
813         host: Interned<String>,
814         _target: Interned<String>,
815     ) {
816         builder.ensure(ErrorIndex {
817             compiler: builder.compiler(builder.top_stage, host),
818         });
819     }
820
821     /// Run the error index generator tool to execute the tests located in the error
822     /// index.
823     ///
824     /// The `error_index_generator` tool lives in `src/tools` and is used to
825     /// generate a markdown file from the error indexes of the code base which is
826     /// then passed to `rustdoc --test`.
827     fn run(self, builder: &Builder) {
828         let build = builder.build;
829         let compiler = self.compiler;
830
831         builder.ensure(compile::Std { compiler, target: compiler.host });
832
833         let _folder = build.fold_output(|| "test_error_index");
834         println!("Testing error-index stage{}", compiler.stage);
835
836         let dir = testdir(build, compiler.host);
837         t!(fs::create_dir_all(&dir));
838         let output = dir.join("error-index.md");
839
840         let _time = util::timeit();
841         build.run(builder.tool_cmd(Tool::ErrorIndex)
842                     .arg("markdown")
843                     .arg(&output)
844                     .env("CFG_BUILD", &build.build));
845
846         markdown_test(builder, compiler, &output);
847     }
848 }
849
850 fn markdown_test(builder: &Builder, compiler: Compiler, markdown: &Path) {
851     let build = builder.build;
852     let mut file = t!(File::open(markdown));
853     let mut contents = String::new();
854     t!(file.read_to_string(&mut contents));
855     if !contents.contains("```") {
856         return;
857     }
858
859     println!("doc tests for: {}", markdown.display());
860     let mut cmd = Command::new(builder.rustdoc(compiler));
861     builder.add_rustc_lib_path(compiler, &mut cmd);
862     build.add_rust_test_threads(&mut cmd);
863     cmd.arg("--test");
864     cmd.arg(markdown);
865     cmd.env("RUSTC_BOOTSTRAP", "1");
866
867     let test_args = build.flags.cmd.test_args().join(" ");
868     cmd.arg("--test-args").arg(test_args);
869
870     if build.config.quiet_tests {
871         try_run_quiet(build, &mut cmd);
872     } else {
873         try_run(build, &mut cmd);
874     }
875 }
876
877 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
878 pub struct CrateLibrustc {
879     compiler: Compiler,
880     target: Interned<String>,
881     test_kind: TestKind,
882     krate: Option<Interned<String>>,
883 }
884
885 impl Step for CrateLibrustc {
886     type Output = ();
887     const DEFAULT: bool = true;
888     const ONLY_HOSTS: bool = true;
889
890     fn should_run(run: ShouldRun) -> ShouldRun {
891         run.krate("rustc-main")
892     }
893
894     fn make_run(
895         builder: &Builder,
896         path: Option<&Path>,
897         host: Interned<String>,
898         target: Interned<String>,
899     ) {
900         let compiler = builder.compiler(builder.top_stage, host);
901
902         let run = |name: Option<Interned<String>>| {
903             let test_kind = if builder.kind == Kind::Test {
904                 TestKind::Test
905             } else if builder.kind == Kind::Bench {
906                 TestKind::Bench
907             } else {
908                 panic!("unexpected builder.kind in crate: {:?}", builder.kind);
909             };
910
911             builder.ensure(CrateLibrustc {
912                 compiler,
913                 target,
914                 test_kind: test_kind,
915                 krate: name,
916             });
917         };
918
919         if let Some(path) = path {
920             for (name, krate_path) in builder.crates("rustc-main") {
921                 if path.ends_with(krate_path) {
922                     run(Some(name));
923                 }
924             }
925         } else {
926             run(None);
927         }
928     }
929
930
931     fn run(self, builder: &Builder) {
932         builder.ensure(Crate {
933             compiler: self.compiler,
934             target: self.target,
935             mode: Mode::Librustc,
936             test_kind: self.test_kind,
937             krate: self.krate,
938         });
939     }
940 }
941
942
943 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
944 pub struct Crate {
945     compiler: Compiler,
946     target: Interned<String>,
947     mode: Mode,
948     test_kind: TestKind,
949     krate: Option<Interned<String>>,
950 }
951
952 impl Step for Crate {
953     type Output = ();
954     const DEFAULT: bool = true;
955
956     fn should_run(run: ShouldRun) -> ShouldRun {
957         run.krate("std").krate("test")
958     }
959
960     fn make_run(
961         builder: &Builder,
962         path: Option<&Path>,
963         host: Interned<String>,
964         target: Interned<String>,
965     ) {
966         let compiler = builder.compiler(builder.top_stage, host);
967
968         let run = |mode: Mode, name: Option<Interned<String>>| {
969             let test_kind = if builder.kind == Kind::Test {
970                 TestKind::Test
971             } else if builder.kind == Kind::Bench {
972                 TestKind::Bench
973             } else {
974                 panic!("unexpected builder.kind in crate: {:?}", builder.kind);
975             };
976
977             builder.ensure(Crate {
978                 compiler, target,
979                 mode: mode,
980                 test_kind: test_kind,
981                 krate: name,
982             });
983         };
984
985         if let Some(path) = path {
986             for (name, krate_path) in builder.crates("std") {
987                 if path.ends_with(krate_path) {
988                     run(Mode::Libstd, Some(name));
989                 }
990             }
991             for (name, krate_path) in builder.crates("test") {
992                 if path.ends_with(krate_path) {
993                     run(Mode::Libtest, Some(name));
994                 }
995             }
996         } else {
997             run(Mode::Libstd, None);
998             run(Mode::Libtest, None);
999         }
1000     }
1001
1002     /// Run all unit tests plus documentation tests for an entire crate DAG defined
1003     /// by a `Cargo.toml`
1004     ///
1005     /// This is what runs tests for crates like the standard library, compiler, etc.
1006     /// It essentially is the driver for running `cargo test`.
1007     ///
1008     /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
1009     /// arguments, and those arguments are discovered from `cargo metadata`.
1010     fn run(self, builder: &Builder) {
1011         let build = builder.build;
1012         let compiler = self.compiler;
1013         let target = self.target;
1014         let mode = self.mode;
1015         let test_kind = self.test_kind;
1016         let krate = self.krate;
1017
1018         builder.ensure(compile::Test { compiler, target });
1019         builder.ensure(RemoteCopyLibs { compiler, target });
1020         let (name, path, features, root) = match mode {
1021             Mode::Libstd => {
1022                 ("libstd", "src/libstd", build.std_features(), "std")
1023             }
1024             Mode::Libtest => {
1025                 ("libtest", "src/libtest", String::new(), "test")
1026             }
1027             Mode::Librustc => {
1028                 builder.ensure(compile::Rustc { compiler, target });
1029                 ("librustc", "src/rustc", build.rustc_features(), "rustc-main")
1030             }
1031             _ => panic!("can only test libraries"),
1032         };
1033         let root = INTERNER.intern_string(String::from(root));
1034         let _folder = build.fold_output(|| {
1035             format!("{}_stage{}-{}", test_kind.subcommand(), compiler.stage, name)
1036         });
1037         println!("{} {} stage{} ({} -> {})", test_kind, name, compiler.stage,
1038                 &compiler.host, target);
1039
1040         // If we're not doing a full bootstrap but we're testing a stage2 version of
1041         // libstd, then what we're actually testing is the libstd produced in
1042         // stage1. Reflect that here by updating the compiler that we're working
1043         // with automatically.
1044         let compiler = if build.force_use_stage1(compiler, target) {
1045             builder.compiler(1, compiler.host)
1046         } else {
1047             compiler.clone()
1048         };
1049
1050         // Build up the base `cargo test` command.
1051         //
1052         // Pass in some standard flags then iterate over the graph we've discovered
1053         // in `cargo metadata` with the maps above and figure out what `-p`
1054         // arguments need to get passed.
1055         let mut cargo = builder.cargo(compiler, mode, target, test_kind.subcommand());
1056         cargo.arg("--manifest-path")
1057             .arg(build.src.join(path).join("Cargo.toml"))
1058             .arg("--features").arg(features);
1059         if test_kind.subcommand() == "test" && !build.fail_fast {
1060             cargo.arg("--no-fail-fast");
1061         }
1062
1063         match krate {
1064             Some(krate) => {
1065                 cargo.arg("-p").arg(krate);
1066             }
1067             None => {
1068                 let mut visited = HashSet::new();
1069                 let mut next = vec![root];
1070                 while let Some(name) = next.pop() {
1071                     // Right now jemalloc is our only target-specific crate in the
1072                     // sense that it's not present on all platforms. Custom skip it
1073                     // here for now, but if we add more this probably wants to get
1074                     // more generalized.
1075                     //
1076                     // Also skip `build_helper` as it's not compiled normally for
1077                     // target during the bootstrap and it's just meant to be a
1078                     // helper crate, not tested. If it leaks through then it ends up
1079                     // messing with various mtime calculations and such.
1080                     if !name.contains("jemalloc") && *name != *"build_helper" {
1081                         cargo.arg("-p").arg(&format!("{}:0.0.0", name));
1082                     }
1083                     for dep in build.crates[&name].deps.iter() {
1084                         if visited.insert(dep) {
1085                             next.push(*dep);
1086                         }
1087                     }
1088                 }
1089             }
1090         }
1091
1092         // The tests are going to run with the *target* libraries, so we need to
1093         // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
1094         //
1095         // Note that to run the compiler we need to run with the *host* libraries,
1096         // but our wrapper scripts arrange for that to be the case anyway.
1097         let mut dylib_path = dylib_path();
1098         dylib_path.insert(0, PathBuf::from(&*builder.sysroot_libdir(compiler, target)));
1099         cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
1100
1101         if target.contains("emscripten") || build.remote_tested(target) {
1102             cargo.arg("--no-run");
1103         }
1104
1105         cargo.arg("--");
1106
1107         if build.config.quiet_tests {
1108             cargo.arg("--quiet");
1109         }
1110
1111         let _time = util::timeit();
1112
1113         if target.contains("emscripten") {
1114             build.run(&mut cargo);
1115             krate_emscripten(build, compiler, target, mode);
1116         } else if build.remote_tested(target) {
1117             build.run(&mut cargo);
1118             krate_remote(builder, compiler, target, mode);
1119         } else {
1120             cargo.args(&build.flags.cmd.test_args());
1121             try_run(build, &mut cargo);
1122         }
1123     }
1124 }
1125
1126 fn krate_emscripten(build: &Build,
1127                     compiler: Compiler,
1128                     target: Interned<String>,
1129                     mode: Mode) {
1130     let out_dir = build.cargo_out(compiler, mode, target);
1131     let tests = find_tests(&out_dir.join("deps"), target);
1132
1133     let nodejs = build.config.nodejs.as_ref().expect("nodejs not configured");
1134     for test in tests {
1135         println!("running {}", test.display());
1136         let mut cmd = Command::new(nodejs);
1137         cmd.arg(&test);
1138         if build.config.quiet_tests {
1139             cmd.arg("--quiet");
1140         }
1141         try_run(build, &mut cmd);
1142     }
1143 }
1144
1145 fn krate_remote(builder: &Builder,
1146                 compiler: Compiler,
1147                 target: Interned<String>,
1148                 mode: Mode) {
1149     let build = builder.build;
1150     let out_dir = build.cargo_out(compiler, mode, target);
1151     let tests = find_tests(&out_dir.join("deps"), target);
1152
1153     let tool = builder.tool_exe(Tool::RemoteTestClient);
1154     for test in tests {
1155         let mut cmd = Command::new(&tool);
1156         cmd.arg("run")
1157            .arg(&test);
1158         if build.config.quiet_tests {
1159             cmd.arg("--quiet");
1160         }
1161         cmd.args(&build.flags.cmd.test_args());
1162         try_run(build, &mut cmd);
1163     }
1164 }
1165
1166 fn find_tests(dir: &Path, target: Interned<String>) -> Vec<PathBuf> {
1167     let mut dst = Vec::new();
1168     for e in t!(dir.read_dir()).map(|e| t!(e)) {
1169         let file_type = t!(e.file_type());
1170         if !file_type.is_file() {
1171             continue
1172         }
1173         let filename = e.file_name().into_string().unwrap();
1174         if (target.contains("windows") && filename.ends_with(".exe")) ||
1175            (!target.contains("windows") && !filename.contains(".")) ||
1176            (target.contains("emscripten") &&
1177             filename.ends_with(".js") &&
1178             !filename.ends_with(".asm.js")) {
1179             dst.push(e.path());
1180         }
1181     }
1182     dst
1183 }
1184
1185 /// Some test suites are run inside emulators or on remote devices, and most
1186 /// of our test binaries are linked dynamically which means we need to ship
1187 /// the standard library and such to the emulator ahead of time. This step
1188 /// represents this and is a dependency of all test suites.
1189 ///
1190 /// Most of the time this is a noop. For some steps such as shipping data to
1191 /// QEMU we have to build our own tools so we've got conditional dependencies
1192 /// on those programs as well. Note that the remote test client is built for
1193 /// the build target (us) and the server is built for the target.
1194 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1195 pub struct RemoteCopyLibs {
1196     compiler: Compiler,
1197     target: Interned<String>,
1198 }
1199
1200 impl Step for RemoteCopyLibs {
1201     type Output = ();
1202
1203     fn should_run(run: ShouldRun) -> ShouldRun {
1204         run.never()
1205     }
1206
1207     fn run(self, builder: &Builder) {
1208         let build = builder.build;
1209         let compiler = self.compiler;
1210         let target = self.target;
1211         if !build.remote_tested(target) {
1212             return
1213         }
1214
1215         builder.ensure(compile::Test { compiler, target });
1216
1217         println!("REMOTE copy libs to emulator ({})", target);
1218         t!(fs::create_dir_all(build.out.join("tmp")));
1219
1220         let server = builder.ensure(tool::RemoteTestServer { stage: compiler.stage, target });
1221
1222         // Spawn the emulator and wait for it to come online
1223         let tool = builder.tool_exe(Tool::RemoteTestClient);
1224         let mut cmd = Command::new(&tool);
1225         cmd.arg("spawn-emulator")
1226            .arg(target)
1227            .arg(&server)
1228            .arg(build.out.join("tmp"));
1229         if let Some(rootfs) = build.qemu_rootfs(target) {
1230             cmd.arg(rootfs);
1231         }
1232         build.run(&mut cmd);
1233
1234         // Push all our dylibs to the emulator
1235         for f in t!(builder.sysroot_libdir(compiler, target).read_dir()) {
1236             let f = t!(f);
1237             let name = f.file_name().into_string().unwrap();
1238             if util::is_dylib(&name) {
1239                 build.run(Command::new(&tool)
1240                                   .arg("push")
1241                                   .arg(f.path()));
1242             }
1243         }
1244     }
1245 }
1246
1247 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1248 pub struct Distcheck;
1249
1250 impl Step for Distcheck {
1251     type Output = ();
1252
1253     fn should_run(run: ShouldRun) -> ShouldRun {
1254         run.path("distcheck")
1255     }
1256
1257     /// Run "distcheck", a 'make check' from a tarball
1258     fn run(self, builder: &Builder) {
1259         let build = builder.build;
1260
1261         if *build.build != *"x86_64-unknown-linux-gnu" {
1262             return
1263         }
1264         if !build.config.host.iter().any(|s| s == "x86_64-unknown-linux-gnu") {
1265             return
1266         }
1267         if !build.config.target.iter().any(|s| s == "x86_64-unknown-linux-gnu") {
1268             return
1269         }
1270
1271         println!("Distcheck");
1272         let dir = build.out.join("tmp").join("distcheck");
1273         let _ = fs::remove_dir_all(&dir);
1274         t!(fs::create_dir_all(&dir));
1275
1276         let mut cmd = Command::new("tar");
1277         cmd.arg("-xzf")
1278            .arg(builder.ensure(dist::PlainSourceTarball))
1279            .arg("--strip-components=1")
1280            .current_dir(&dir);
1281         build.run(&mut cmd);
1282         build.run(Command::new("./configure")
1283                          .args(&build.config.configure_args)
1284                          .arg("--enable-vendor")
1285                          .current_dir(&dir));
1286         build.run(Command::new(build_helper::make(&build.build))
1287                          .arg("check")
1288                          .current_dir(&dir));
1289
1290         // Now make sure that rust-src has all of libstd's dependencies
1291         println!("Distcheck rust-src");
1292         let dir = build.out.join("tmp").join("distcheck-src");
1293         let _ = fs::remove_dir_all(&dir);
1294         t!(fs::create_dir_all(&dir));
1295
1296         let mut cmd = Command::new("tar");
1297         cmd.arg("-xzf")
1298            .arg(builder.ensure(dist::Src))
1299            .arg("--strip-components=1")
1300            .current_dir(&dir);
1301         build.run(&mut cmd);
1302
1303         let toml = dir.join("rust-src/lib/rustlib/src/rust/src/libstd/Cargo.toml");
1304         build.run(Command::new(&build.initial_cargo)
1305                          .arg("generate-lockfile")
1306                          .arg("--manifest-path")
1307                          .arg(&toml)
1308                          .current_dir(&dir));
1309     }
1310 }
1311
1312 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1313 pub struct Bootstrap;
1314
1315 impl Step for Bootstrap {
1316     type Output = ();
1317     const DEFAULT: bool = true;
1318     const ONLY_HOSTS: bool = true;
1319     const ONLY_BUILD: bool = true;
1320
1321     /// Test the build system itself
1322     fn run(self, builder: &Builder) {
1323         let build = builder.build;
1324         let mut cmd = Command::new(&build.initial_cargo);
1325         cmd.arg("test")
1326            .current_dir(build.src.join("src/bootstrap"))
1327            .env("CARGO_TARGET_DIR", build.out.join("bootstrap"))
1328            .env("RUSTC_BOOTSTRAP", "1")
1329            .env("RUSTC", &build.initial_rustc);
1330         if !build.fail_fast {
1331             cmd.arg("--no-fail-fast");
1332         }
1333         cmd.arg("--").args(&build.flags.cmd.test_args());
1334         try_run(build, &mut cmd);
1335     }
1336
1337     fn should_run(run: ShouldRun) -> ShouldRun {
1338         run.path("src/bootstrap")
1339     }
1340
1341     fn make_run(
1342         builder: &Builder,
1343         _path: Option<&Path>,
1344         _host: Interned<String>,
1345         _target: Interned<String>,
1346     ) {
1347         builder.ensure(Bootstrap);
1348     }
1349 }