]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Rollup merge of #45465 - glaubitz:sparc64, r=alexcrichton
[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 = match build.config.llvm_experimental_targets {
114             Some(ref s) => s,
115             None => "",
116         };
117
118         let assertions = if build.config.llvm_assertions {"ON"} else {"OFF"};
119
120         cfg.target(&target)
121            .host(&build.build)
122            .out_dir(&out_dir)
123            .profile(profile)
124            .define("LLVM_ENABLE_ASSERTIONS", assertions)
125            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
126            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
127            .define("LLVM_INCLUDE_EXAMPLES", "OFF")
128            .define("LLVM_INCLUDE_TESTS", "OFF")
129            .define("LLVM_INCLUDE_DOCS", "OFF")
130            .define("LLVM_ENABLE_ZLIB", "OFF")
131            .define("WITH_POLLY", "OFF")
132            .define("LLVM_ENABLE_TERMINFO", "OFF")
133            .define("LLVM_ENABLE_LIBEDIT", "OFF")
134            .define("LLVM_PARALLEL_COMPILE_JOBS", build.jobs().to_string())
135            .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
136            .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
137
138
139         // This setting makes the LLVM tools link to the dynamic LLVM library,
140         // which saves both memory during parallel links and overall disk space
141         // for the tools.  We don't distribute any of those tools, so this is
142         // just a local concern.  However, it doesn't work well everywhere.
143         if target.contains("linux-gnu") || target.contains("apple-darwin") {
144            cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
145         }
146
147         if target.contains("msvc") {
148             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
149             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
150             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
151             cfg.static_crt(true);
152         }
153
154         if target.starts_with("i686") {
155             cfg.define("LLVM_BUILD_32_BITS", "ON");
156         }
157
158         if let Some(num_linkers) = build.config.llvm_link_jobs {
159             if num_linkers > 0 {
160                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
161             }
162         }
163
164         // http://llvm.org/docs/HowToCrossCompileLLVM.html
165         if target != build.build {
166             builder.ensure(Llvm { target: build.build });
167             // FIXME: if the llvm root for the build triple is overridden then we
168             //        should use llvm-tblgen from there, also should verify that it
169             //        actually exists most of the time in normal installs of LLVM.
170             let host = build.llvm_out(build.build).join("bin/llvm-tblgen");
171             cfg.define("CMAKE_CROSSCOMPILING", "True")
172                .define("LLVM_TABLEGEN", &host);
173
174             if target.contains("netbsd") {
175                cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
176             } else if target.contains("freebsd") {
177                cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
178             }
179
180             cfg.define("LLVM_NATIVE_BUILD", build.llvm_out(build.build).join("build"));
181         }
182
183         let sanitize_cc = |cc: &Path| {
184             if target.contains("msvc") {
185                 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
186             } else {
187                 cc.as_os_str().to_owned()
188             }
189         };
190
191         let configure_compilers = |cfg: &mut cmake::Config| {
192             // MSVC with CMake uses msbuild by default which doesn't respect these
193             // vars that we'd otherwise configure. In that case we just skip this
194             // entirely.
195             if target.contains("msvc") && !build.config.ninja {
196                 return
197             }
198
199             let cc = build.cc(target);
200             let cxx = build.cxx(target).unwrap();
201
202             // Handle msvc + ninja + ccache specially (this is what the bots use)
203             if target.contains("msvc") &&
204                build.config.ninja &&
205                build.config.ccache.is_some() {
206                 let mut cc = env::current_exe().expect("failed to get cwd");
207                 cc.set_file_name("sccache-plus-cl.exe");
208
209                cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
210                   .define("CMAKE_CXX_COMPILER", sanitize_cc(&cc));
211                cfg.env("SCCACHE_PATH",
212                        build.config.ccache.as_ref().unwrap())
213                   .env("SCCACHE_TARGET", target);
214
215             // If ccache is configured we inform the build a little differently hwo
216             // to invoke ccache while also invoking our compilers.
217             } else if let Some(ref ccache) = build.config.ccache {
218                cfg.define("CMAKE_C_COMPILER", ccache)
219                   .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
220                   .define("CMAKE_CXX_COMPILER", ccache)
221                   .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
222             } else {
223                cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
224                   .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
225             }
226
227             cfg.build_arg("-j").build_arg(build.jobs().to_string());
228             cfg.define("CMAKE_C_FLAGS", build.cflags(target).join(" "));
229             cfg.define("CMAKE_CXX_FLAGS", build.cflags(target).join(" "));
230             if let Some(ar) = build.ar(target) {
231                 if ar.is_absolute() {
232                     // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
233                     // tries to resolve this path in the LLVM build directory.
234                     cfg.define("CMAKE_AR", sanitize_cc(ar));
235                 }
236             }
237         };
238
239         configure_compilers(&mut cfg);
240
241         if env::var_os("SCCACHE_ERROR_LOG").is_some() {
242             cfg.env("RUST_LOG", "sccache=warn");
243         }
244
245         // FIXME: we don't actually need to build all LLVM tools and all LLVM
246         //        libraries here, e.g. we just want a few components and a few
247         //        tools. Figure out how to filter them down and only build the right
248         //        tools and libs on all platforms.
249         cfg.build();
250
251         t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
252     }
253 }
254
255 fn check_llvm_version(build: &Build, llvm_config: &Path) {
256     if !build.config.llvm_version_check {
257         return
258     }
259
260     let mut cmd = Command::new(llvm_config);
261     let version = output(cmd.arg("--version"));
262     let mut parts = version.split('.').take(2)
263         .filter_map(|s| s.parse::<u32>().ok());
264     if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
265         if major > 3 || (major == 3 && minor >= 9) {
266             return
267         }
268     }
269     panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version)
270 }
271
272 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
273 pub struct TestHelpers {
274     pub target: Interned<String>,
275 }
276
277 impl Step for TestHelpers {
278     type Output = ();
279
280     fn should_run(run: ShouldRun) -> ShouldRun {
281         run.path("src/rt/rust_test_helpers.c")
282     }
283
284     fn make_run(run: RunConfig) {
285         run.builder.ensure(TestHelpers { target: run.target })
286     }
287
288     /// Compiles the `rust_test_helpers.c` library which we used in various
289     /// `run-pass` test suites for ABI testing.
290     fn run(self, builder: &Builder) {
291         let build = builder.build;
292         let target = self.target;
293         let dst = build.test_helpers_out(target);
294         let src = build.src.join("src/rt/rust_test_helpers.c");
295         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
296             return
297         }
298
299         let _folder = build.fold_output(|| "build_test_helpers");
300         println!("Building test helpers");
301         t!(fs::create_dir_all(&dst));
302         let mut cfg = cc::Build::new();
303
304         // We may have found various cross-compilers a little differently due to our
305         // extra configuration, so inform gcc of these compilers. Note, though, that
306         // on MSVC we still need gcc's detection of env vars (ugh).
307         if !target.contains("msvc") {
308             if let Some(ar) = build.ar(target) {
309                 cfg.archiver(ar);
310             }
311             cfg.compiler(build.cc(target));
312         }
313
314         cfg.cargo_metadata(false)
315            .out_dir(&dst)
316            .target(&target)
317            .host(&build.build)
318            .opt_level(0)
319            .warnings(false)
320            .debug(false)
321            .file(build.src.join("src/rt/rust_test_helpers.c"))
322            .compile("librust_test_helpers.a");
323     }
324 }
325
326 const OPENSSL_VERS: &'static str = "1.0.2k";
327 const OPENSSL_SHA256: &'static str =
328     "6b3977c61f2aedf0f96367dcfb5c6e578cf37e7b8d913b4ecb6643c3cb88d8c0";
329
330 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
331 pub struct Openssl {
332     pub target: Interned<String>,
333 }
334
335 impl Step for Openssl {
336     type Output = ();
337
338     fn should_run(run: ShouldRun) -> ShouldRun {
339         run.never()
340     }
341
342     fn run(self, builder: &Builder) {
343         let build = builder.build;
344         let target = self.target;
345         let out = match build.openssl_dir(target) {
346             Some(dir) => dir,
347             None => return,
348         };
349
350         let stamp = out.join(".stamp");
351         let mut contents = String::new();
352         drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
353         if contents == OPENSSL_VERS {
354             return
355         }
356         t!(fs::create_dir_all(&out));
357
358         let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
359         let tarball = out.join(&name);
360         if !tarball.exists() {
361             let tmp = tarball.with_extension("tmp");
362             // originally from https://www.openssl.org/source/...
363             let url = format!("https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/{}",
364                               name);
365             let mut last_error = None;
366             for _ in 0..3 {
367                 let status = Command::new("curl")
368                                 .arg("-o").arg(&tmp)
369                                 .arg("-f")  // make curl fail if the URL does not return HTTP 200
370                                 .arg(&url)
371                                 .status()
372                                 .expect("failed to spawn curl");
373
374                 // Retry if download failed.
375                 if !status.success() {
376                     last_error = Some(status.to_string());
377                     continue;
378                 }
379
380                 // Ensure the hash is correct.
381                 let mut shasum = if target.contains("apple") || build.build.contains("netbsd") {
382                     let mut cmd = Command::new("shasum");
383                     cmd.arg("-a").arg("256");
384                     cmd
385                 } else {
386                     Command::new("sha256sum")
387                 };
388                 let output = output(&mut shasum.arg(&tmp));
389                 let found = output.split_whitespace().next().unwrap();
390
391                 // If the hash is wrong, probably the download is incomplete or S3 served an error
392                 // page. In any case, retry.
393                 if found != OPENSSL_SHA256 {
394                     last_error = Some(format!(
395                         "downloaded openssl sha256 different\n\
396                          expected: {}\n\
397                          found:    {}\n",
398                         OPENSSL_SHA256,
399                         found
400                     ));
401                     continue;
402                 }
403
404                 // Everything is fine, so exit the retry loop.
405                 last_error = None;
406                 break;
407             }
408             if let Some(error) = last_error {
409                 panic!("failed to download openssl source: {}", error);
410             }
411             t!(fs::rename(&tmp, &tarball));
412         }
413         let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
414         let dst = build.openssl_install_dir(target).unwrap();
415         drop(fs::remove_dir_all(&obj));
416         drop(fs::remove_dir_all(&dst));
417         build.run(Command::new("tar").arg("zxf").arg(&tarball).current_dir(&out));
418
419         let mut configure = Command::new("perl");
420         configure.arg(obj.join("Configure"));
421         configure.arg(format!("--prefix={}", dst.display()));
422         configure.arg("no-dso");
423         configure.arg("no-ssl2");
424         configure.arg("no-ssl3");
425
426         let os = match &*target {
427             "aarch64-linux-android" => "linux-aarch64",
428             "aarch64-unknown-linux-gnu" => "linux-aarch64",
429             "aarch64-unknown-linux-musl" => "linux-aarch64",
430             "arm-linux-androideabi" => "android",
431             "arm-unknown-linux-gnueabi" => "linux-armv4",
432             "arm-unknown-linux-gnueabihf" => "linux-armv4",
433             "armv7-linux-androideabi" => "android-armv7",
434             "armv7-unknown-linux-gnueabihf" => "linux-armv4",
435             "i686-apple-darwin" => "darwin-i386-cc",
436             "i686-linux-android" => "android-x86",
437             "i686-unknown-freebsd" => "BSD-x86-elf",
438             "i686-unknown-linux-gnu" => "linux-elf",
439             "i686-unknown-linux-musl" => "linux-elf",
440             "i686-unknown-netbsd" => "BSD-x86-elf",
441             "mips-unknown-linux-gnu" => "linux-mips32",
442             "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
443             "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
444             "mipsel-unknown-linux-gnu" => "linux-mips32",
445             "powerpc-unknown-linux-gnu" => "linux-ppc",
446             "powerpc64-unknown-linux-gnu" => "linux-ppc64",
447             "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
448             "s390x-unknown-linux-gnu" => "linux64-s390x",
449             "sparc64-unknown-linux-gnu" => "linux64-sparcv9",
450             "sparc64-unknown-netbsd" => "BSD-sparc64",
451             "x86_64-apple-darwin" => "darwin64-x86_64-cc",
452             "x86_64-linux-android" => "linux-x86_64",
453             "x86_64-unknown-freebsd" => "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 }