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.
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.
11 //! Compilation of native dependencies like LLVM.
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).
18 //! LLVM and compiler-rt are essentially just wired up to everything else to
19 //! ensure that they're always in place if needed.
22 use std::ffi::OsString;
23 use std::fs::{self, File};
24 use std::io::{Read, Write};
26 use std::process::Command;
28 use build_helper::output;
34 use build_helper::up_to_date;
35 use builder::{Builder, RunConfig, ShouldRun, Step};
38 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
40 pub target: Interned<String>,
45 const ONLY_HOSTS: bool = true;
47 fn should_run(run: ShouldRun) -> ShouldRun {
51 fn make_run(run: RunConfig) {
52 run.builder.ensure(Llvm { target: run.target })
55 /// Compile LLVM for `target`.
56 fn run(self, builder: &Builder) {
57 let build = builder.build;
58 let target = self.target;
60 // If we're not compiling for LLVM bail out here.
61 if !build.config.llvm_enabled {
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);
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));
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));
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 {
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));
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");
101 let profile = match (build.config.llvm_optimize, build.config.llvm_release_debuginfo) {
102 (false, _) => "Debug",
103 (true, false) => "Release",
104 (true, true) => "RelWithDebInfo",
107 // NOTE: remember to also update `config.toml.example` when changing the defaults!
108 let llvm_targets = match build.config.llvm_targets {
110 None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;JSBackend;MSP430;Sparc;NVPTX;Hexagon",
113 let llvm_exp_targets = match build.config.llvm_experimental_targets {
118 let assertions = if build.config.llvm_assertions {"ON"} else {"OFF"};
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);
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");
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);
154 if target.starts_with("i686") {
155 cfg.define("LLVM_BUILD_32_BITS", "ON");
158 if let Some(num_linkers) = build.config.llvm_link_jobs {
160 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
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);
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");
180 cfg.define("LLVM_NATIVE_BUILD", build.llvm_out(build.build).join("build"));
183 let sanitize_cc = |cc: &Path| {
184 if target.contains("msvc") {
185 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
187 cc.as_os_str().to_owned()
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
195 if target.contains("msvc") && !build.config.ninja {
199 let cc = build.cc(target);
200 let cxx = build.cxx(target).unwrap();
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");
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);
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));
223 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
224 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
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));
239 configure_compilers(&mut cfg);
241 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
242 cfg.env("RUST_LOG", "sccache=warn");
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.
251 t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
255 fn check_llvm_version(build: &Build, llvm_config: &Path) {
256 if !build.config.llvm_version_check {
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) {
269 panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version)
272 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
273 pub struct TestHelpers {
274 pub target: Interned<String>,
277 impl Step for TestHelpers {
280 fn should_run(run: ShouldRun) -> ShouldRun {
281 run.path("src/rt/rust_test_helpers.c")
284 fn make_run(run: RunConfig) {
285 run.builder.ensure(TestHelpers { target: run.target })
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")) {
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();
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) {
311 cfg.compiler(build.cc(target));
314 cfg.cargo_metadata(false)
321 .file(build.src.join("src/rt/rust_test_helpers.c"))
322 .compile("librust_test_helpers.a");
326 const OPENSSL_VERS: &'static str = "1.0.2k";
327 const OPENSSL_SHA256: &'static str =
328 "6b3977c61f2aedf0f96367dcfb5c6e578cf37e7b8d913b4ecb6643c3cb88d8c0";
330 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
332 pub target: Interned<String>,
335 impl Step for Openssl {
338 fn should_run(run: ShouldRun) -> ShouldRun {
342 fn run(self, builder: &Builder) {
343 let build = builder.build;
344 let target = self.target;
345 let out = match build.openssl_dir(target) {
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 {
356 t!(fs::create_dir_all(&out));
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/{}",
365 let mut last_error = None;
367 let status = Command::new("curl")
369 .arg("-f") // make curl fail if the URL does not return HTTP 200
372 .expect("failed to spawn curl");
374 // Retry if download failed.
375 if !status.success() {
376 last_error = Some(status.to_string());
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");
386 Command::new("sha256sum")
388 let output = output(&mut shasum.arg(&tmp));
389 let found = output.split_whitespace().next().unwrap();
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\
404 // Everything is fine, so exit the retry loop.
408 if let Some(error) = last_error {
409 panic!("failed to download openssl source: {}", error);
411 t!(fs::rename(&tmp, &tarball));
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));
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");
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),
460 configure.env("CC", build.cc(target));
461 for flag in build.cflags(target) {
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");
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");
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");
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));
493 let mut f = t!(File::create(&stamp));
494 t!(f.write_all(OPENSSL_VERS.as_bytes()));