]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/sanity.rs
c7f514da939a60639b7082ed5a8b7b64a2a80f0f
[rust.git] / src / bootstrap / sanity.rs
1 // Copyright 2015 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 //! Sanity checking performed by rustbuild before actually executing anything.
12 //!
13 //! This module contains the implementation of ensuring that the build
14 //! environment looks reasonable before progressing. This will verify that
15 //! various programs like git and python exist, along with ensuring that all C
16 //! compilers for cross-compiling are found.
17 //!
18 //! In theory if we get past this phase it's a bug if a build fails, but in
19 //! practice that's likely not true!
20
21 use std::collections::HashMap;
22 use std::env;
23 use std::ffi::{OsString, OsStr};
24 use std::fs::{self, File};
25 use std::io::Read;
26 use std::path::PathBuf;
27 use std::process::Command;
28
29 use build_helper::output;
30
31 use Build;
32
33 struct Finder {
34     cache: HashMap<OsString, Option<PathBuf>>,
35     path: OsString,
36 }
37
38 impl Finder {
39     fn new() -> Self {
40         Self {
41             cache: HashMap::new(),
42             path: env::var_os("PATH").unwrap_or_default()
43         }
44     }
45
46     fn maybe_have<S: AsRef<OsStr>>(&mut self, cmd: S) -> Option<PathBuf> {
47         let cmd: OsString = cmd.as_ref().into();
48         let path = self.path.clone();
49         self.cache.entry(cmd.clone()).or_insert_with(|| {
50             for path in env::split_paths(&path) {
51                 let target = path.join(&cmd);
52                 let mut cmd_alt = cmd.clone();
53                 cmd_alt.push(".exe");
54                 if target.is_file() || // some/path/git
55                 target.with_extension("exe").exists() || // some/path/git.exe
56                 target.join(&cmd_alt).exists() { // some/path/git/git.exe
57                     return Some(target);
58                 }
59             }
60             None
61         }).clone()
62     }
63
64     fn must_have<S: AsRef<OsStr>>(&mut self, cmd: S) -> PathBuf {
65         self.maybe_have(&cmd).unwrap_or_else(|| {
66             panic!("\n\ncouldn't find required command: {:?}\n\n", cmd.as_ref());
67         })
68     }
69 }
70
71 pub fn check(build: &mut Build) {
72     let path = env::var_os("PATH").unwrap_or_default();
73     // On Windows, quotes are invalid characters for filename paths, and if
74     // one is present as part of the PATH then that can lead to the system
75     // being unable to identify the files properly. See
76     // https://github.com/rust-lang/rust/issues/34959 for more details.
77     if cfg!(windows) && path.to_string_lossy().contains("\"") {
78         panic!("PATH contains invalid character '\"'");
79     }
80
81     let mut cmd_finder = Finder::new();
82     // If we've got a git directory we're gonna need git to update
83     // submodules and learn about various other aspects.
84     if build.rust_info.is_git() {
85         cmd_finder.must_have("git");
86     }
87
88     // We need cmake, but only if we're actually building LLVM or sanitizers.
89     let building_llvm = build.hosts.iter()
90         .filter_map(|host| build.config.target_config.get(host))
91         .any(|config| config.llvm_config.is_none());
92     if building_llvm || build.config.sanitizers {
93         cmd_finder.must_have("cmake");
94     }
95
96     // Ninja is currently only used for LLVM itself.
97     if building_llvm {
98         if build.config.ninja {
99             // Some Linux distros rename `ninja` to `ninja-build`.
100             // CMake can work with either binary name.
101             if cmd_finder.maybe_have("ninja-build").is_none() {
102                 cmd_finder.must_have("ninja");
103             }
104         }
105
106         // If ninja isn't enabled but we're building for MSVC then we try
107         // doubly hard to enable it. It was realized in #43767 that the msbuild
108         // CMake generator for MSVC doesn't respect configuration options like
109         // disabling LLVM assertions, which can often be quite important!
110         //
111         // In these cases we automatically enable Ninja if we find it in the
112         // environment.
113         if !build.config.ninja && build.config.build.contains("msvc") {
114             if cmd_finder.maybe_have("ninja").is_some() {
115                 build.config.ninja = true;
116             }
117         }
118     }
119
120     build.config.python = build.config.python.take().map(|p| cmd_finder.must_have(p))
121         .or_else(|| env::var_os("BOOTSTRAP_PYTHON").map(PathBuf::from)) // set by bootstrap.py
122         .or_else(|| cmd_finder.maybe_have("python2.7"))
123         .or_else(|| cmd_finder.maybe_have("python2"))
124         .or_else(|| Some(cmd_finder.must_have("python")));
125
126     build.config.nodejs = build.config.nodejs.take().map(|p| cmd_finder.must_have(p))
127         .or_else(|| cmd_finder.maybe_have("node"))
128         .or_else(|| cmd_finder.maybe_have("nodejs"));
129
130     build.config.gdb = build.config.gdb.take().map(|p| cmd_finder.must_have(p))
131         .or_else(|| cmd_finder.maybe_have("gdb"));
132
133     // We're gonna build some custom C code here and there, host triples
134     // also build some C++ shims for LLVM so we need a C++ compiler.
135     for target in &build.targets {
136         // On emscripten we don't actually need the C compiler to just
137         // build the target artifacts, only for testing. For the sake
138         // of easier bot configuration, just skip detection.
139         if target.contains("emscripten") {
140             continue;
141         }
142
143         if !build.config.dry_run {
144             cmd_finder.must_have(build.cc(*target));
145             if let Some(ar) = build.ar(*target) {
146                 cmd_finder.must_have(ar);
147             }
148         }
149     }
150
151     for host in &build.hosts {
152         if !build.config.dry_run {
153             cmd_finder.must_have(build.cxx(*host).unwrap());
154         }
155
156         // The msvc hosts don't use jemalloc, turn it off globally to
157         // avoid packaging the dummy liballoc_jemalloc on that platform.
158         if host.contains("msvc") {
159             build.config.use_jemalloc = false;
160         }
161     }
162
163     // Externally configured LLVM requires FileCheck to exist
164     let filecheck = build.llvm_filecheck(build.build);
165     if !filecheck.starts_with(&build.out) && !filecheck.exists() && build.config.codegen_tests {
166         panic!("FileCheck executable {:?} does not exist", filecheck);
167     }
168
169     for target in &build.targets {
170         // Can't compile for iOS unless we're on macOS
171         if target.contains("apple-ios") &&
172            !build.build.contains("apple-darwin") {
173             panic!("the iOS target is only supported on macOS");
174         }
175
176         if target.contains("-none-") {
177             if build.no_std(*target).is_none() {
178                 let target = build.config.target_config.entry(target.clone())
179                     .or_insert(Default::default());
180
181                 target.no_std = true;
182             }
183
184             if build.no_std(*target) == Some(false) {
185                 panic!("All the *-none-* targets are no-std targets")
186             }
187         }
188
189         // Make sure musl-root is valid
190         if target.contains("musl") {
191             // If this is a native target (host is also musl) and no musl-root is given,
192             // fall back to the system toolchain in /usr before giving up
193             if build.musl_root(*target).is_none() && build.config.build == *target {
194                 let target = build.config.target_config.entry(target.clone())
195                                  .or_insert(Default::default());
196                 target.musl_root = Some("/usr".into());
197             }
198             match build.musl_root(*target) {
199                 Some(root) => {
200                     if fs::metadata(root.join("lib/libc.a")).is_err() {
201                         panic!("couldn't find libc.a in musl dir: {}",
202                                root.join("lib").display());
203                     }
204                     if fs::metadata(root.join("lib/libunwind.a")).is_err() {
205                         panic!("couldn't find libunwind.a in musl dir: {}",
206                                root.join("lib").display());
207                     }
208                 }
209                 None => {
210                     panic!("when targeting MUSL either the rust.musl-root \
211                             option or the target.$TARGET.musl-root option must \
212                             be specified in config.toml")
213                 }
214             }
215         }
216
217         if target.contains("msvc") {
218             // There are three builds of cmake on windows: MSVC, MinGW, and
219             // Cygwin. The Cygwin build does not have generators for Visual
220             // Studio, so detect that here and error.
221             let out = output(Command::new("cmake").arg("--help"));
222             if !out.contains("Visual Studio") {
223                 panic!("
224 cmake does not support Visual Studio generators.
225
226 This is likely due to it being an msys/cygwin build of cmake,
227 rather than the required windows version, built using MinGW
228 or Visual Studio.
229
230 If you are building under msys2 try installing the mingw-w64-x86_64-cmake
231 package instead of cmake:
232
233 $ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake
234 ");
235             }
236         }
237     }
238
239     let run = |cmd: &mut Command| {
240         cmd.output().map(|output| {
241             String::from_utf8_lossy(&output.stdout)
242                    .lines().next().unwrap_or_else(|| {
243                        panic!("{:?} failed {:?}", cmd, output)
244                    }).to_string()
245         })
246     };
247     build.lldb_version = run(Command::new("lldb").arg("--version")).ok();
248     if build.lldb_version.is_some() {
249         build.lldb_python_dir = run(Command::new("lldb").arg("-P")).ok();
250     }
251
252     if let Some(ref s) = build.config.ccache {
253         cmd_finder.must_have(s);
254     }
255
256     if build.config.channel == "stable" {
257         let mut stage0 = String::new();
258         t!(t!(File::open(build.src.join("src/stage0.txt")))
259             .read_to_string(&mut stage0));
260         if stage0.contains("\ndev:") {
261             panic!("bootstrapping from a dev compiler in a stable release, but \
262                     should only be bootstrapping from a released compiler!");
263         }
264     }
265 }