]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Rollup merge of #47277 - tspiteri:log-correctness, r=frewsxcv
[rust.git] / src / bootstrap / native.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 //! Compilation of native dependencies like LLVM.
12 //!
13 //! Native projects like LLVM unfortunately aren't suited just yet for
14 //! compilation in build scripts that Cargo has. This is because the
15 //! compilation takes a *very* long time but also because we don't want to
16 //! compile LLVM 3 times as part of a normal bootstrap (we want it cached).
17 //!
18 //! LLVM and compiler-rt are essentially just wired up to everything else to
19 //! ensure that they're always in place if needed.
20
21 use std::env;
22 use std::ffi::OsString;
23 use std::fs::{self, File};
24 use std::io::{Read, Write};
25 use std::path::Path;
26 use std::process::Command;
27
28 use build_helper::output;
29 use cmake;
30 use cc;
31
32 use Build;
33 use util;
34 use build_helper::up_to_date;
35 use builder::{Builder, RunConfig, ShouldRun, Step};
36 use cache::Interned;
37
38 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
39 pub struct Llvm {
40     pub target: Interned<String>,
41 }
42
43 impl Step for Llvm {
44     type Output = ();
45     const ONLY_HOSTS: bool = true;
46
47     fn should_run(run: ShouldRun) -> ShouldRun {
48         run.path("src/llvm")
49     }
50
51     fn make_run(run: RunConfig) {
52         run.builder.ensure(Llvm { target: run.target })
53     }
54
55     /// Compile LLVM for `target`.
56     fn run(self, builder: &Builder) {
57         let build = builder.build;
58         let target = self.target;
59
60         // If we're not compiling for LLVM bail out here.
61         if !build.config.llvm_enabled {
62             return;
63         }
64
65         // If we're using a custom LLVM bail out here, but we can only use a
66         // custom LLVM for the build triple.
67         if let Some(config) = build.config.target_config.get(&target) {
68             if let Some(ref s) = config.llvm_config {
69                 return check_llvm_version(build, s);
70             }
71         }
72
73         let rebuild_trigger = build.src.join("src/rustllvm/llvm-rebuild-trigger");
74         let mut rebuild_trigger_contents = String::new();
75         t!(t!(File::open(&rebuild_trigger)).read_to_string(&mut rebuild_trigger_contents));
76
77         let out_dir = build.llvm_out(target);
78         let done_stamp = out_dir.join("llvm-finished-building");
79         if done_stamp.exists() {
80             let mut done_contents = String::new();
81             t!(t!(File::open(&done_stamp)).read_to_string(&mut done_contents));
82
83             // If LLVM was already built previously and contents of the rebuild-trigger file
84             // didn't change from the previous build, then no action is required.
85             if done_contents == rebuild_trigger_contents {
86                 return
87             }
88         }
89
90         let _folder = build.fold_output(|| "llvm");
91         println!("Building LLVM for {}", target);
92         let _time = util::timeit();
93         t!(fs::create_dir_all(&out_dir));
94
95         // http://llvm.org/docs/CMake.html
96         let mut cfg = cmake::Config::new(build.src.join("src/llvm"));
97         if build.config.ninja {
98             cfg.generator("Ninja");
99         }
100
101         let profile = match (build.config.llvm_optimize, build.config.llvm_release_debuginfo) {
102             (false, _) => "Debug",
103             (true, false) => "Release",
104             (true, true) => "RelWithDebInfo",
105         };
106
107         // NOTE: remember to also update `config.toml.example` when changing the defaults!
108         let llvm_targets = match build.config.llvm_targets {
109             Some(ref s) => s,
110             None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;JSBackend;MSP430;Sparc;NVPTX;Hexagon",
111         };
112
113         let llvm_exp_targets = &build.config.llvm_experimental_targets;
114
115         let assertions = if build.config.llvm_assertions {"ON"} else {"OFF"};
116
117         cfg.target(&target)
118            .host(&build.build)
119            .out_dir(&out_dir)
120            .profile(profile)
121            .define("LLVM_ENABLE_ASSERTIONS", assertions)
122            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
123            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
124            .define("LLVM_INCLUDE_EXAMPLES", "OFF")
125            .define("LLVM_INCLUDE_TESTS", "OFF")
126            .define("LLVM_INCLUDE_DOCS", "OFF")
127            .define("LLVM_ENABLE_ZLIB", "OFF")
128            .define("WITH_POLLY", "OFF")
129            .define("LLVM_ENABLE_TERMINFO", "OFF")
130            .define("LLVM_ENABLE_LIBEDIT", "OFF")
131            .define("LLVM_PARALLEL_COMPILE_JOBS", build.jobs().to_string())
132            .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
133            .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
134
135
136         // This setting makes the LLVM tools link to the dynamic LLVM library,
137         // which saves both memory during parallel links and overall disk space
138         // for the tools.  We don't distribute any of those tools, so this is
139         // just a local concern.  However, it doesn't work well everywhere.
140         if target.contains("linux-gnu") || target.contains("apple-darwin") {
141            cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
142         }
143
144         if target.contains("msvc") {
145             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
146             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
147             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
148             cfg.static_crt(true);
149         }
150
151         if target.starts_with("i686") {
152             cfg.define("LLVM_BUILD_32_BITS", "ON");
153         }
154
155         if let Some(num_linkers) = build.config.llvm_link_jobs {
156             if num_linkers > 0 {
157                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
158             }
159         }
160
161         // http://llvm.org/docs/HowToCrossCompileLLVM.html
162         if target != build.build {
163             builder.ensure(Llvm { target: build.build });
164             // FIXME: if the llvm root for the build triple is overridden then we
165             //        should use llvm-tblgen from there, also should verify that it
166             //        actually exists most of the time in normal installs of LLVM.
167             let host = build.llvm_out(build.build).join("bin/llvm-tblgen");
168             cfg.define("CMAKE_CROSSCOMPILING", "True")
169                .define("LLVM_TABLEGEN", &host);
170
171             if target.contains("netbsd") {
172                cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
173             } else if target.contains("freebsd") {
174                cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
175             }
176
177             cfg.define("LLVM_NATIVE_BUILD", build.llvm_out(build.build).join("build"));
178         }
179
180         let sanitize_cc = |cc: &Path| {
181             if target.contains("msvc") {
182                 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
183             } else {
184                 cc.as_os_str().to_owned()
185             }
186         };
187
188         let configure_compilers = |cfg: &mut cmake::Config| {
189             // MSVC with CMake uses msbuild by default which doesn't respect these
190             // vars that we'd otherwise configure. In that case we just skip this
191             // entirely.
192             if target.contains("msvc") && !build.config.ninja {
193                 return
194             }
195
196             let cc = build.cc(target);
197             let cxx = build.cxx(target).unwrap();
198
199             // Handle msvc + ninja + ccache specially (this is what the bots use)
200             if target.contains("msvc") &&
201                build.config.ninja &&
202                build.config.ccache.is_some() {
203                 let mut cc = env::current_exe().expect("failed to get cwd");
204                 cc.set_file_name("sccache-plus-cl.exe");
205
206                cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
207                   .define("CMAKE_CXX_COMPILER", sanitize_cc(&cc));
208                cfg.env("SCCACHE_PATH",
209                        build.config.ccache.as_ref().unwrap())
210                   .env("SCCACHE_TARGET", target);
211
212             // If ccache is configured we inform the build a little differently hwo
213             // to invoke ccache while also invoking our compilers.
214             } else if let Some(ref ccache) = build.config.ccache {
215                cfg.define("CMAKE_C_COMPILER", ccache)
216                   .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
217                   .define("CMAKE_CXX_COMPILER", ccache)
218                   .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
219             } else {
220                cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
221                   .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
222             }
223
224             cfg.build_arg("-j").build_arg(build.jobs().to_string());
225             cfg.define("CMAKE_C_FLAGS", build.cflags(target).join(" "));
226             cfg.define("CMAKE_CXX_FLAGS", build.cflags(target).join(" "));
227             if let Some(ar) = build.ar(target) {
228                 if ar.is_absolute() {
229                     // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
230                     // tries to resolve this path in the LLVM build directory.
231                     cfg.define("CMAKE_AR", sanitize_cc(ar));
232                 }
233             }
234         };
235
236         configure_compilers(&mut cfg);
237
238         if env::var_os("SCCACHE_ERROR_LOG").is_some() {
239             cfg.env("RUST_LOG", "sccache=warn");
240         }
241
242         // FIXME: we don't actually need to build all LLVM tools and all LLVM
243         //        libraries here, e.g. we just want a few components and a few
244         //        tools. Figure out how to filter them down and only build the right
245         //        tools and libs on all platforms.
246         cfg.build();
247
248         t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
249     }
250 }
251
252 fn check_llvm_version(build: &Build, llvm_config: &Path) {
253     if !build.config.llvm_version_check {
254         return
255     }
256
257     let mut cmd = Command::new(llvm_config);
258     let version = output(cmd.arg("--version"));
259     let mut parts = version.split('.').take(2)
260         .filter_map(|s| s.parse::<u32>().ok());
261     if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
262         if major > 3 || (major == 3 && minor >= 9) {
263             return
264         }
265     }
266     panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version)
267 }
268
269 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
270 pub struct TestHelpers {
271     pub target: Interned<String>,
272 }
273
274 impl Step for TestHelpers {
275     type Output = ();
276
277     fn should_run(run: ShouldRun) -> ShouldRun {
278         run.path("src/rt/rust_test_helpers.c")
279     }
280
281     fn make_run(run: RunConfig) {
282         run.builder.ensure(TestHelpers { target: run.target })
283     }
284
285     /// Compiles the `rust_test_helpers.c` library which we used in various
286     /// `run-pass` test suites for ABI testing.
287     fn run(self, builder: &Builder) {
288         let build = builder.build;
289         let target = self.target;
290         let dst = build.test_helpers_out(target);
291         let src = build.src.join("src/rt/rust_test_helpers.c");
292         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
293             return
294         }
295
296         let _folder = build.fold_output(|| "build_test_helpers");
297         println!("Building test helpers");
298         t!(fs::create_dir_all(&dst));
299         let mut cfg = cc::Build::new();
300
301         // We may have found various cross-compilers a little differently due to our
302         // extra configuration, so inform gcc of these compilers. Note, though, that
303         // on MSVC we still need gcc's detection of env vars (ugh).
304         if !target.contains("msvc") {
305             if let Some(ar) = build.ar(target) {
306                 cfg.archiver(ar);
307             }
308             cfg.compiler(build.cc(target));
309         }
310
311         cfg.cargo_metadata(false)
312            .out_dir(&dst)
313            .target(&target)
314            .host(&build.build)
315            .opt_level(0)
316            .warnings(false)
317            .debug(false)
318            .file(build.src.join("src/rt/rust_test_helpers.c"))
319            .compile("rust_test_helpers");
320     }
321 }
322
323 const OPENSSL_VERS: &'static str = "1.0.2m";
324 const OPENSSL_SHA256: &'static str =
325     "8c6ff15ec6b319b50788f42c7abc2890c08ba5a1cdcd3810eb9092deada37b0f";
326
327 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
328 pub struct Openssl {
329     pub target: Interned<String>,
330 }
331
332 impl Step for Openssl {
333     type Output = ();
334
335     fn should_run(run: ShouldRun) -> ShouldRun {
336         run.never()
337     }
338
339     fn run(self, builder: &Builder) {
340         let build = builder.build;
341         let target = self.target;
342         let out = match build.openssl_dir(target) {
343             Some(dir) => dir,
344             None => return,
345         };
346
347         let stamp = out.join(".stamp");
348         let mut contents = String::new();
349         drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
350         if contents == OPENSSL_VERS {
351             return
352         }
353         t!(fs::create_dir_all(&out));
354
355         let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
356         let tarball = out.join(&name);
357         if !tarball.exists() {
358             let tmp = tarball.with_extension("tmp");
359             // originally from https://www.openssl.org/source/...
360             let url = format!("https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/{}",
361                               name);
362             let mut last_error = None;
363             for _ in 0..3 {
364                 let status = Command::new("curl")
365                                 .arg("-o").arg(&tmp)
366                                 .arg("-f")  // make curl fail if the URL does not return HTTP 200
367                                 .arg(&url)
368                                 .status()
369                                 .expect("failed to spawn curl");
370
371                 // Retry if download failed.
372                 if !status.success() {
373                     last_error = Some(status.to_string());
374                     continue;
375                 }
376
377                 // Ensure the hash is correct.
378                 let mut shasum = if target.contains("apple") || build.build.contains("netbsd") {
379                     let mut cmd = Command::new("shasum");
380                     cmd.arg("-a").arg("256");
381                     cmd
382                 } else {
383                     Command::new("sha256sum")
384                 };
385                 let output = output(&mut shasum.arg(&tmp));
386                 let found = output.split_whitespace().next().unwrap();
387
388                 // If the hash is wrong, probably the download is incomplete or S3 served an error
389                 // page. In any case, retry.
390                 if found != OPENSSL_SHA256 {
391                     last_error = Some(format!(
392                         "downloaded openssl sha256 different\n\
393                          expected: {}\n\
394                          found:    {}\n",
395                         OPENSSL_SHA256,
396                         found
397                     ));
398                     continue;
399                 }
400
401                 // Everything is fine, so exit the retry loop.
402                 last_error = None;
403                 break;
404             }
405             if let Some(error) = last_error {
406                 panic!("failed to download openssl source: {}", error);
407             }
408             t!(fs::rename(&tmp, &tarball));
409         }
410         let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
411         let dst = build.openssl_install_dir(target).unwrap();
412         drop(fs::remove_dir_all(&obj));
413         drop(fs::remove_dir_all(&dst));
414         build.run(Command::new("tar").arg("zxf").arg(&tarball).current_dir(&out));
415
416         let mut configure = Command::new("perl");
417         configure.arg(obj.join("Configure"));
418         configure.arg(format!("--prefix={}", dst.display()));
419         configure.arg("no-dso");
420         configure.arg("no-ssl2");
421         configure.arg("no-ssl3");
422
423         let os = match &*target {
424             "aarch64-linux-android" => "linux-aarch64",
425             "aarch64-unknown-linux-gnu" => "linux-aarch64",
426             "aarch64-unknown-linux-musl" => "linux-aarch64",
427             "arm-linux-androideabi" => "android",
428             "arm-unknown-linux-gnueabi" => "linux-armv4",
429             "arm-unknown-linux-gnueabihf" => "linux-armv4",
430             "armv7-linux-androideabi" => "android-armv7",
431             "armv7-unknown-linux-gnueabihf" => "linux-armv4",
432             "i586-unknown-linux-gnu" => "linux-elf",
433             "i586-unknown-linux-musl" => "linux-elf",
434             "i686-apple-darwin" => "darwin-i386-cc",
435             "i686-linux-android" => "android-x86",
436             "i686-unknown-freebsd" => "BSD-x86-elf",
437             "i686-unknown-linux-gnu" => "linux-elf",
438             "i686-unknown-linux-musl" => "linux-elf",
439             "i686-unknown-netbsd" => "BSD-x86-elf",
440             "mips-unknown-linux-gnu" => "linux-mips32",
441             "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
442             "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
443             "mipsel-unknown-linux-gnu" => "linux-mips32",
444             "powerpc-unknown-linux-gnu" => "linux-ppc",
445             "powerpc64-unknown-linux-gnu" => "linux-ppc64",
446             "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
447             "s390x-unknown-linux-gnu" => "linux64-s390x",
448             "sparc64-unknown-linux-gnu" => "linux64-sparcv9",
449             "sparc64-unknown-netbsd" => "BSD-sparc64",
450             "x86_64-apple-darwin" => "darwin64-x86_64-cc",
451             "x86_64-linux-android" => "linux-x86_64",
452             "x86_64-unknown-freebsd" => "BSD-x86_64",
453             "x86_64-unknown-dragonfly" => "BSD-x86_64",
454             "x86_64-unknown-linux-gnu" => "linux-x86_64",
455             "x86_64-unknown-linux-musl" => "linux-x86_64",
456             "x86_64-unknown-netbsd" => "BSD-x86_64",
457             _ => panic!("don't know how to configure OpenSSL for {}", target),
458         };
459         configure.arg(os);
460         configure.env("CC", build.cc(target));
461         for flag in build.cflags(target) {
462             configure.arg(flag);
463         }
464         // There is no specific os target for android aarch64 or x86_64,
465         // so we need to pass some extra cflags
466         if target == "aarch64-linux-android" || target == "x86_64-linux-android" {
467             configure.arg("-mandroid");
468             configure.arg("-fomit-frame-pointer");
469         }
470         if target == "sparc64-unknown-netbsd" {
471             // Need -m64 to get assembly generated correctly for sparc64.
472             configure.arg("-m64");
473             if build.build.contains("netbsd") {
474                 // Disable sparc64 asm on NetBSD builders, it uses
475                 // m4(1)'s -B flag, which NetBSD m4 does not support.
476                 configure.arg("no-asm");
477             }
478         }
479         // Make PIE binaries
480         // Non-PIE linker support was removed in Lollipop
481         // https://source.android.com/security/enhancements/enhancements50
482         if target == "i686-linux-android" {
483             configure.arg("no-asm");
484         }
485         configure.current_dir(&obj);
486         println!("Configuring openssl for {}", target);
487         build.run_quiet(&mut configure);
488         println!("Building openssl for {}", target);
489         build.run_quiet(Command::new("make").arg("-j1").current_dir(&obj));
490         println!("Installing openssl for {}", target);
491         build.run_quiet(Command::new("make").arg("install").current_dir(&obj));
492
493         let mut f = t!(File::create(&stamp));
494         t!(f.write_all(OPENSSL_VERS.as_bytes()));
495     }
496 }