tool.rs 21.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

M
Mark Simulacrum 已提交
11
use std::fs;
12
use std::env;
13
use std::path::PathBuf;
14
use std::process::{Command, exit};
15
use std::slice::SliceConcatExt;
16 17

use Mode;
M
Mark Simulacrum 已提交
18
use Compiler;
19
use builder::{Step, RunConfig, ShouldRun, Builder};
20
use util::{exe, add_lib_path};
21
use compile::{self, libtest_stamp, libstd_stamp, librustc_stamp};
22 23
use native;
use channel::GitInfo;
24
use cache::Interned;
25
use toolstate::ToolState;
26

27
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
28 29 30 31
pub struct CleanTools {
    pub compiler: Compiler,
    pub target: Interned<String>,
    pub mode: Mode,
32 33
}

34
impl Step for CleanTools {
35 36
    type Output = ();

37 38
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.never()
39 40
    }

41 42
    fn run(self, builder: &Builder) {
        let build = builder.build;
43
        let compiler = self.compiler;
44 45 46
        let target = self.target;
        let mode = self.mode;

47 48 49 50 51 52 53 54
        // This is for the original compiler, but if we're forced to use stage 1, then
        // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
        // we copy the libs forward.
        let tools_dir = build.stage_out(compiler, Mode::Tool);
        let compiler = if builder.force_use_stage1(compiler, target) {
            builder.compiler(1, compiler.host)
        } else {
            compiler
55
        };
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

        for &cur_mode in &[Mode::Libstd, Mode::Libtest, Mode::Librustc] {
            let stamp = match cur_mode {
                Mode::Libstd => libstd_stamp(build, compiler, target),
                Mode::Libtest => libtest_stamp(build, compiler, target),
                Mode::Librustc => librustc_stamp(build, compiler, target),
                _ => panic!(),
            };

            if build.clear_if_dirty(&tools_dir, &stamp) {
                break;
            }

            // If we are a rustc tool, and std changed, we also need to clear ourselves out -- our
            // dependencies depend on std. Therefore, we iterate up until our own mode.
            if mode == cur_mode {
                break;
            }
        }
75 76 77
    }
}

78
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
79 80 81 82
struct ToolBuild {
    compiler: Compiler,
    target: Interned<String>,
    tool: &'static str,
83
    path: &'static str,
84
    mode: Mode,
85
    is_ext_tool: bool,
86
    extra_features: Vec<String>,
87 88
}

89
impl Step for ToolBuild {
90
    type Output = Option<PathBuf>;
91

92 93
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.never()
94 95
    }

96 97 98 99
    /// Build a tool in `src/tools`
    ///
    /// This will build the specified tool with the specified `host` compiler in
    /// `stage` into the normal cargo output directory.
100
    fn run(self, builder: &Builder) -> Option<PathBuf> {
101
        let build = builder.build;
102
        let compiler = self.compiler;
103 104
        let target = self.target;
        let tool = self.tool;
105
        let path = self.path;
106
        let is_ext_tool = self.is_ext_tool;
107

108 109 110 111 112 113 114
        match self.mode {
            Mode::Libstd => builder.ensure(compile::Std { compiler, target }),
            Mode::Libtest => builder.ensure(compile::Test { compiler, target }),
            Mode::Librustc => builder.ensure(compile::Rustc { compiler, target }),
            Mode::Tool => panic!("unexpected Mode::Tool for tool build")
        }

115
        let mut cargo = prepare_tool_cargo(builder, compiler, target, "build", path);
116
        cargo.arg("--features").arg(self.extra_features.join(" "));
117 118 119

        let _folder = build.fold_output(|| format!("stage{}-{}", compiler.stage, tool));
        println!("Building stage{} tool {} ({})", compiler.stage, tool, target);
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
        let mut duplicates = Vec::new();
        let is_expected = compile::stream_cargo(build, &mut cargo, &mut |msg| {
            // Only care about big things like the RLS/Cargo for now
            if tool != "rls" && tool != "cargo" {
                return
            }
            let (id, features, filenames) = match msg {
                compile::CargoMessage::CompilerArtifact {
                    package_id,
                    features,
                    filenames
                } => {
                    (package_id, features, filenames)
                }
                _ => return,
            };
            let features = features.iter().map(|s| s.to_string()).collect::<Vec<_>>();

            for path in filenames {
                let val = (tool, PathBuf::from(&*path), features.clone());
                // we're only interested in deduplicating rlibs for now
                if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") {
                    continue
                }

                // Don't worry about libs that turn out to be host dependencies
                // or build scripts, we only care about target dependencies that
                // are in `deps`.
                if let Some(maybe_target) = val.1
                    .parent()                   // chop off file name
                    .and_then(|p| p.parent())   // chop off `deps`
                    .and_then(|p| p.parent())   // chop off `release`
                    .and_then(|p| p.file_name())
                    .and_then(|p| p.to_str())
                {
                    if maybe_target != &*target {
                        continue
                    }
                }

                let mut artifacts = build.tool_artifacts.borrow_mut();
                let prev_artifacts = artifacts
                    .entry(target)
                    .or_insert_with(Default::default);
                if let Some(prev) = prev_artifacts.get(&*id) {
                    if prev.1 != val.1 {
                        duplicates.push((
                            id.to_string(),
                            val,
                            prev.clone(),
                        ));
                    }
                    return
                }
                prev_artifacts.insert(id.to_string(), val);
            }
        });

        if is_expected && duplicates.len() != 0 {
            println!("duplicate artfacts found when compiling a tool, this \
                      typically means that something was recompiled because \
                      a transitive dependency has different features activated \
                      than in a previous build:\n");
            for (id, cur, prev) in duplicates {
                println!("  {}", id);
                println!("    `{}` enabled features {:?} at {:?}",
                         cur.0, cur.2, cur.1);
                println!("    `{}` enabled features {:?} at {:?}",
                         prev.0, prev.2, prev.1);
            }
            println!("");
            panic!("tools should not compile multiple copies of the same crate");
        }

194
        build.save_toolstate(tool, if is_expected {
195
            ToolState::TestFail
196
        } else {
197
            ToolState::BuildFail
198 199 200
        });

        if !is_expected {
201
            if !is_ext_tool {
M
Mark Simulacrum 已提交
202
                exit(1);
203 204 205
            } else {
                return None;
            }
206
        } else {
207 208 209
            let cargo_out = build.cargo_out(compiler, Mode::Tool, target)
                .join(exe(tool, &compiler.host));
            let bin = build.tools_dir(compiler).join(exe(tool, &compiler.host));
210
            build.copy(&cargo_out, &bin);
211 212
            Some(bin)
        }
213 214
    }
}
215

216
pub fn prepare_tool_cargo(
217 218 219
    builder: &Builder,
    compiler: Compiler,
    target: Interned<String>,
220
    command: &'static str,
221
    path: &'static str,
222 223
) -> Command {
    let build = builder.build;
224
    let mut cargo = builder.cargo(compiler, Mode::Tool, target, command);
225
    let dir = build.src.join(path);
226 227 228 229 230 231 232 233 234 235 236
    cargo.arg("--manifest-path").arg(dir.join("Cargo.toml"));

    // We don't want to build tools dynamically as they'll be running across
    // stages and such and it's just easier if they're not dynamically linked.
    cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");

    if let Some(dir) = build.openssl_install_dir(target) {
        cargo.env("OPENSSL_STATIC", "1");
        cargo.env("OPENSSL_DIR", dir);
        cargo.env("LIBZ_SYS_STATIC", "1");
    }
237

A
Alex Crichton 已提交
238 239 240 241
    // if tools are using lzma we want to force the build script to build its
    // own copy
    cargo.env("LZMA_API_STATIC", "1");

242
    cargo.env("CFG_RELEASE_CHANNEL", &build.config.channel);
243
    cargo.env("CFG_VERSION", build.rust_version());
244

245 246 247 248 249 250 251 252 253
    let info = GitInfo::new(&build.config, &dir);
    if let Some(sha) = info.sha() {
        cargo.env("CFG_COMMIT_HASH", sha);
    }
    if let Some(sha_short) = info.sha_short() {
        cargo.env("CFG_SHORT_COMMIT_HASH", sha_short);
    }
    if let Some(date) = info.commit_date() {
        cargo.env("CFG_COMMIT_DATE", date);
254
    }
255
    cargo
256 257 258 259 260 261 262 263 264 265 266 267 268
}

macro_rules! tool {
    ($($name:ident, $path:expr, $tool_name:expr, $mode:expr;)+) => {
        #[derive(Copy, Clone)]
        pub enum Tool {
            $(
                $name,
            )+
        }

        impl<'a> Builder<'a> {
            pub fn tool_exe(&self, tool: Tool) -> PathBuf {
269
                let stage = self.tool_default_stage(tool);
270 271 272
                match tool {
                    $(Tool::$name =>
                        self.ensure($name {
273
                            compiler: self.compiler(stage, self.build.build),
274
                            target: self.build.build,
275 276 277 278
                        }),
                    )+
                }
            }
279 280

            pub fn tool_default_stage(&self, tool: Tool) -> u32 {
281 282 283 284
                // Compile the error-index in the same stage as rustdoc to avoid
                // recompiling rustdoc twice if we can. Otherwise compile
                // everything else in stage0 as there's no need to rebootstrap
                // everything.
285
                match tool {
286
                    Tool::ErrorIndex if self.top_stage >= 2 => self.top_stage,
287 288 289
                    _ => 0,
                }
            }
290 291 292
        }

        $(
293 294
            #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
        pub struct $name {
295
            pub compiler: Compiler,
296
            pub target: Interned<String>,
297 298
        }

299
        impl Step for $name {
300 301
            type Output = PathBuf;

302 303
            fn should_run(run: ShouldRun) -> ShouldRun {
                run.path($path)
304 305
            }

306 307
            fn make_run(run: RunConfig) {
                run.builder.ensure($name {
308
                    compiler: run.builder.compiler(run.builder.top_stage, run.builder.build.build),
309
                    target: run.target,
310 311 312 313 314
                });
            }

            fn run(self, builder: &Builder) -> PathBuf {
                builder.ensure(ToolBuild {
315
                    compiler: self.compiler,
316 317 318
                    target: self.target,
                    tool: $tool_name,
                    mode: $mode,
319
                    path: $path,
320
                    is_ext_tool: false,
321
                    extra_features: Vec::new(),
322
                }).expect("expected to build -- essential tool")
323 324 325 326 327 328 329 330 331
            }
        }
        )+
    }
}

tool!(
    Rustbook, "src/tools/rustbook", "rustbook", Mode::Librustc;
    ErrorIndex, "src/tools/error_index_generator", "error_index_generator", Mode::Librustc;
332
    UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen", Mode::Libstd;
333 334 335 336
    Tidy, "src/tools/tidy", "tidy", Mode::Libstd;
    Linkchecker, "src/tools/linkchecker", "linkchecker", Mode::Libstd;
    CargoTest, "src/tools/cargotest", "cargotest", Mode::Libstd;
    Compiletest, "src/tools/compiletest", "compiletest", Mode::Libtest;
337
    BuildManifest, "src/tools/build-manifest", "build-manifest", Mode::Libstd;
338
    RemoteTestClient, "src/tools/remote-test-client", "remote-test-client", Mode::Libstd;
339
    RustInstaller, "src/tools/rust-installer", "fabricate", Mode::Libstd;
G
Guillaume Gomez 已提交
340
    RustdocTheme, "src/tools/rustdoc-themes", "rustdoc-themes", Mode::Libstd;
341 342
);

343 344
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct RemoteTestServer {
345
    pub compiler: Compiler,
346
    pub target: Interned<String>,
347 348
}

349
impl Step for RemoteTestServer {
350 351
    type Output = PathBuf;

352 353
    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/remote-test-server")
354 355
    }

356 357
    fn make_run(run: RunConfig) {
        run.builder.ensure(RemoteTestServer {
358
            compiler: run.builder.compiler(run.builder.top_stage, run.builder.build.build),
359
            target: run.target,
360 361 362 363 364
        });
    }

    fn run(self, builder: &Builder) -> PathBuf {
        builder.ensure(ToolBuild {
365
            compiler: self.compiler,
366 367 368
            target: self.target,
            tool: "remote-test-server",
            mode: Mode::Libstd,
369
            path: "src/tools/remote-test-server",
370
            is_ext_tool: false,
371
            extra_features: Vec::new(),
372
        }).expect("expected to build -- essential tool")
373 374 375
    }
}

M
Mark Simulacrum 已提交
376 377
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Rustdoc {
378
    pub host: Interned<String>,
M
Mark Simulacrum 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391
}

impl Step for Rustdoc {
    type Output = PathBuf;
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

    fn should_run(run: ShouldRun) -> ShouldRun {
        run.path("src/tools/rustdoc")
    }

    fn make_run(run: RunConfig) {
        run.builder.ensure(Rustdoc {
392
            host: run.host,
M
Mark Simulacrum 已提交
393 394 395 396
        });
    }

    fn run(self, builder: &Builder) -> PathBuf {
397
        let build = builder.build;
398
        let target_compiler = builder.compiler(builder.top_stage, self.host);
399
        let target = target_compiler.host;
M
Mark Simulacrum 已提交
400
        let build_compiler = if target_compiler.stage == 0 {
401
            builder.compiler(0, builder.build.build)
402 403 404
        } else if target_compiler.stage >= 2 {
            // Past stage 2, we consider the compiler to be ABI-compatible and hence capable of
            // building rustdoc itself.
405
            builder.compiler(target_compiler.stage, builder.build.build)
M
Mark Simulacrum 已提交
406
        } else {
407 408 409
            // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise
            // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage
            // compilers, which isn't what we want.
410
            builder.compiler(target_compiler.stage - 1, builder.build.build)
M
Mark Simulacrum 已提交
411 412
        };

413
        builder.ensure(compile::Rustc { compiler: build_compiler, target });
414 415 416 417
        builder.ensure(compile::Rustc {
            compiler: build_compiler,
            target: builder.build.build,
        });
418

419 420 421
        let mut cargo = prepare_tool_cargo(builder,
                                           build_compiler,
                                           target,
422
                                           "build",
423
                                           "src/tools/rustdoc");
424 425 426 427 428

        // Most tools don't get debuginfo, but rustdoc should.
        cargo.env("RUSTC_DEBUGINFO", builder.config.rust_debuginfo.to_string())
             .env("RUSTC_DEBUGINFO_LINES", builder.config.rust_debuginfo_lines.to_string());

429 430
        let _folder = build.fold_output(|| format!("stage{}-rustdoc", target_compiler.stage));
        println!("Building rustdoc for stage{} ({})", target_compiler.stage, target_compiler.host);
431
        build.run(&mut cargo);
432

433 434 435
        // Cargo adds a number of paths to the dylib search path on windows, which results in
        // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
        // rustdoc a different name.
436
        let tool_rustdoc = build.cargo_out(build_compiler, Mode::Tool, target)
437
            .join(exe("rustdoc-tool-binary", &target_compiler.host));
M
Mark Simulacrum 已提交
438 439 440 441 442 443 444 445

        // don't create a stage0-sysroot/bin directory.
        if target_compiler.stage > 0 {
            let sysroot = builder.sysroot(target_compiler);
            let bindir = sysroot.join("bin");
            t!(fs::create_dir_all(&bindir));
            let bin_rustdoc = bindir.join(exe("rustdoc", &*target_compiler.host));
            let _ = fs::remove_file(&bin_rustdoc);
446
            build.copy(&tool_rustdoc, &bin_rustdoc);
M
Mark Simulacrum 已提交
447 448 449 450 451 452 453
            bin_rustdoc
        } else {
            tool_rustdoc
        }
    }
}

454 455
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Cargo {
456
    pub compiler: Compiler,
457
    pub target: Interned<String>,
458 459
}

460
impl Step for Cargo {
461 462 463 464
    type Output = PathBuf;
    const DEFAULT: bool = true;
    const ONLY_HOSTS: bool = true;

465
    fn should_run(run: ShouldRun) -> ShouldRun {
466 467
        let builder = run.builder;
        run.path("src/tools/cargo").default_condition(builder.build.config.extended)
468 469
    }

470 471
    fn make_run(run: RunConfig) {
        run.builder.ensure(Cargo {
472
            compiler: run.builder.compiler(run.builder.top_stage, run.builder.build.build),
473
            target: run.target,
474 475 476 477 478 479 480 481 482
        });
    }

    fn run(self, builder: &Builder) -> PathBuf {
        builder.ensure(native::Openssl {
            target: self.target,
        });
        // Cargo depends on procedural macros, which requires a full host
        // compiler to be available, so we need to depend on that.
483
        builder.ensure(compile::Rustc {
484
            compiler: self.compiler,
485
            target: builder.build.build,
486 487
        });
        builder.ensure(ToolBuild {
488
            compiler: self.compiler,
489 490
            target: self.target,
            tool: "cargo",
A
Alex Crichton 已提交
491
            mode: Mode::Librustc,
492
            path: "src/tools/cargo",
493
            is_ext_tool: false,
494
            extra_features: Vec::new(),
495
        }).expect("expected to build -- essential tool")
496 497 498
    }
}

499 500 501 502 503 504 505 506
macro_rules! tool_extended {
    (($sel:ident, $builder:ident),
       $($name:ident,
       $toolstate:ident,
       $path:expr,
       $tool_name:expr,
       $extra_deps:block;)+) => {
        $(
507
            #[derive(Debug, Clone, Hash, PartialEq, Eq)]
508 509 510
        pub struct $name {
            pub compiler: Compiler,
            pub target: Interned<String>,
511
            pub extra_features: Vec<String>,
512
        }
O
Oliver Schneider 已提交
513

514 515 516 517
        impl Step for $name {
            type Output = Option<PathBuf>;
            const DEFAULT: bool = true;
            const ONLY_HOSTS: bool = true;
O
Oliver Schneider 已提交
518

519 520 521 522
            fn should_run(run: ShouldRun) -> ShouldRun {
                let builder = run.builder;
                run.path($path).default_condition(builder.build.config.extended)
            }
O
Oliver Schneider 已提交
523

524 525 526 527
            fn make_run(run: RunConfig) {
                run.builder.ensure($name {
                    compiler: run.builder.compiler(run.builder.top_stage, run.builder.build.build),
                    target: run.target,
528
                    extra_features: Vec::new(),
529 530 531
                });
            }

532 533
            #[allow(unused_mut)]
            fn run(mut $sel, $builder: &Builder) -> Option<PathBuf> {
534 535 536 537 538 539 540
                $extra_deps
                $builder.ensure(ToolBuild {
                    compiler: $sel.compiler,
                    target: $sel.target,
                    tool: $tool_name,
                    mode: Mode::Librustc,
                    path: $path,
541
                    extra_features: $sel.extra_features,
542
                    is_ext_tool: true,
543 544 545 546
                })
            }
        }
        )+
O
Oliver Schneider 已提交
547
    }
548
}
O
Oliver Schneider 已提交
549

550
tool_extended!((self, builder),
551
    Cargofmt, rustfmt, "src/tools/rustfmt", "cargo-fmt", {};
552
    Clippy, clippy, "src/tools/clippy", "clippy-driver", {
O
Oliver Schneider 已提交
553 554 555 556 557 558
        // Clippy depends on procedural macros (serde), which requires a full host
        // compiler to be available, so we need to depend on that.
        builder.ensure(compile::Rustc {
            compiler: self.compiler,
            target: builder.build.build,
        });
559 560 561
    };
    Miri, miri, "src/tools/miri", "miri", {};
    Rls, rls, "src/tools/rls", "rls", {
562 563 564 565 566 567 568 569
        let clippy = builder.ensure(Clippy {
            compiler: self.compiler,
            target: self.target,
            extra_features: Vec::new(),
        });
        if clippy.is_some() {
            self.extra_features.push("clippy".to_owned());
        }
570 571 572 573 574
        builder.ensure(native::Openssl {
            target: self.target,
        });
        // RLS depends on procedural macros, which requires a full host
        // compiler to be available, so we need to depend on that.
575
        builder.ensure(compile::Rustc {
576
            compiler: self.compiler,
577
            target: builder.build.build,
578
        });
579 580 581
    };
    Rustfmt, rustfmt, "src/tools/rustfmt", "rustfmt", {};
);
582

M
Mark Simulacrum 已提交
583 584 585
impl<'a> Builder<'a> {
    /// Get a `Command` which is ready to run `tool` in `stage` built for
    /// `host`.
M
Mark Simulacrum 已提交
586 587
    pub fn tool_cmd(&self, tool: Tool) -> Command {
        let mut cmd = Command::new(self.tool_exe(tool));
588
        let compiler = self.compiler(self.tool_default_stage(tool), self.build.build);
M
Mark Simulacrum 已提交
589 590 591 592 593 594 595 596 597
        self.prepare_tool_cmd(compiler, &mut cmd);
        cmd
    }

    /// Prepares the `cmd` provided to be able to run the `compiler` provided.
    ///
    /// Notably this munges the dynamic library lookup path to point to the
    /// right location to run `compiler`.
    fn prepare_tool_cmd(&self, compiler: Compiler, cmd: &mut Command) {
598 599 600 601
        let host = &compiler.host;
        let mut paths: Vec<PathBuf> = vec![
            PathBuf::from(&self.sysroot_libdir(compiler, compiler.host)),
            self.cargo_out(compiler, Mode::Tool, *host).join("deps"),
M
Mark Simulacrum 已提交
602 603 604 605 606 607
        ];

        // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make
        // mode) and that C compiler may need some extra PATH modification. Do
        // so here.
        if compiler.host.contains("msvc") {
M
Mark Simulacrum 已提交
608
            let curpaths = env::var_os("PATH").unwrap_or_default();
M
Mark Simulacrum 已提交
609
            let curpaths = env::split_paths(&curpaths).collect::<Vec<_>>();
610
            for &(ref k, ref v) in self.cc[&compiler.host].env() {
M
Mark Simulacrum 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623
                if k != "PATH" {
                    continue
                }
                for path in env::split_paths(v) {
                    if !curpaths.contains(&path) {
                        paths.push(path);
                    }
                }
            }
        }
        add_lib_path(paths, cmd);
    }
}