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 using a custom LLVM bail out here, but we can only use a
61 // custom LLVM for the build triple.
62 if let Some(config) = build.config.target_config.get(&target) {
63 if let Some(ref s) = config.llvm_config {
64 return check_llvm_version(build, s);
68 let rebuild_trigger = build.src.join("src/rustllvm/llvm-rebuild-trigger");
69 let mut rebuild_trigger_contents = String::new();
70 t!(t!(File::open(&rebuild_trigger)).read_to_string(&mut rebuild_trigger_contents));
72 let out_dir = build.llvm_out(target);
73 let done_stamp = out_dir.join("llvm-finished-building");
74 if done_stamp.exists() {
75 let mut done_contents = String::new();
76 t!(t!(File::open(&done_stamp)).read_to_string(&mut done_contents));
78 // If LLVM was already built previously and contents of the rebuild-trigger file
79 // didn't change from the previous build, then no action is required.
80 if done_contents == rebuild_trigger_contents {
85 let _folder = build.fold_output(|| "llvm");
86 println!("Building LLVM for {}", target);
87 let _time = util::timeit();
88 t!(fs::create_dir_all(&out_dir));
90 // http://llvm.org/docs/CMake.html
91 let mut cfg = cmake::Config::new(build.src.join("src/llvm"));
92 if build.config.ninja {
93 cfg.generator("Ninja");
96 let profile = match (build.config.llvm_optimize, build.config.llvm_release_debuginfo) {
97 (false, _) => "Debug",
98 (true, false) => "Release",
99 (true, true) => "RelWithDebInfo",
102 // NOTE: remember to also update `config.toml.example` when changing the defaults!
103 let llvm_targets = match build.config.llvm_targets {
105 None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;JSBackend;MSP430;Sparc;NVPTX;Hexagon",
108 let llvm_exp_targets = &build.config.llvm_experimental_targets;
110 let assertions = if build.config.llvm_assertions {"ON"} else {"OFF"};
116 .define("LLVM_ENABLE_ASSERTIONS", assertions)
117 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
118 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
119 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
120 .define("LLVM_INCLUDE_TESTS", "OFF")
121 .define("LLVM_INCLUDE_DOCS", "OFF")
122 .define("LLVM_ENABLE_ZLIB", "OFF")
123 .define("WITH_POLLY", "OFF")
124 .define("LLVM_ENABLE_TERMINFO", "OFF")
125 .define("LLVM_ENABLE_LIBEDIT", "OFF")
126 .define("LLVM_PARALLEL_COMPILE_JOBS", build.jobs().to_string())
127 .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
128 .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
131 // This setting makes the LLVM tools link to the dynamic LLVM library,
132 // which saves both memory during parallel links and overall disk space
133 // for the tools. We don't distribute any of those tools, so this is
134 // just a local concern. However, it doesn't work well everywhere.
135 if target.contains("linux-gnu") || target.contains("apple-darwin") {
136 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
139 if target.contains("msvc") {
140 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
141 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
142 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
143 cfg.static_crt(true);
146 if target.starts_with("i686") {
147 cfg.define("LLVM_BUILD_32_BITS", "ON");
150 if let Some(num_linkers) = build.config.llvm_link_jobs {
152 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
156 // http://llvm.org/docs/HowToCrossCompileLLVM.html
157 if target != build.build {
158 builder.ensure(Llvm { target: build.build });
159 // FIXME: if the llvm root for the build triple is overridden then we
160 // should use llvm-tblgen from there, also should verify that it
161 // actually exists most of the time in normal installs of LLVM.
162 let host = build.llvm_out(build.build).join("bin/llvm-tblgen");
163 cfg.define("CMAKE_CROSSCOMPILING", "True")
164 .define("LLVM_TABLEGEN", &host);
166 if target.contains("netbsd") {
167 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
168 } else if target.contains("freebsd") {
169 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
172 cfg.define("LLVM_NATIVE_BUILD", build.llvm_out(build.build).join("build"));
175 let sanitize_cc = |cc: &Path| {
176 if target.contains("msvc") {
177 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
179 cc.as_os_str().to_owned()
183 let configure_compilers = |cfg: &mut cmake::Config| {
184 // MSVC with CMake uses msbuild by default which doesn't respect these
185 // vars that we'd otherwise configure. In that case we just skip this
187 if target.contains("msvc") && !build.config.ninja {
191 let cc = build.cc(target);
192 let cxx = build.cxx(target).unwrap();
194 // Handle msvc + ninja + ccache specially (this is what the bots use)
195 if target.contains("msvc") &&
196 build.config.ninja &&
197 build.config.ccache.is_some() {
198 let mut cc = env::current_exe().expect("failed to get cwd");
199 cc.set_file_name("sccache-plus-cl.exe");
201 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
202 .define("CMAKE_CXX_COMPILER", sanitize_cc(&cc));
203 cfg.env("SCCACHE_PATH",
204 build.config.ccache.as_ref().unwrap())
205 .env("SCCACHE_TARGET", target);
207 // If ccache is configured we inform the build a little differently hwo
208 // to invoke ccache while also invoking our compilers.
209 } else if let Some(ref ccache) = build.config.ccache {
210 cfg.define("CMAKE_C_COMPILER", ccache)
211 .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
212 .define("CMAKE_CXX_COMPILER", ccache)
213 .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
215 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
216 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
219 cfg.build_arg("-j").build_arg(build.jobs().to_string());
220 cfg.define("CMAKE_C_FLAGS", build.cflags(target).join(" "));
221 cfg.define("CMAKE_CXX_FLAGS", build.cflags(target).join(" "));
222 if let Some(ar) = build.ar(target) {
223 if ar.is_absolute() {
224 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
225 // tries to resolve this path in the LLVM build directory.
226 cfg.define("CMAKE_AR", sanitize_cc(ar));
231 configure_compilers(&mut cfg);
233 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
234 cfg.env("RUST_LOG", "sccache=warn");
237 // FIXME: we don't actually need to build all LLVM tools and all LLVM
238 // libraries here, e.g. we just want a few components and a few
239 // tools. Figure out how to filter them down and only build the right
240 // tools and libs on all platforms.
243 t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
247 fn check_llvm_version(build: &Build, llvm_config: &Path) {
248 if !build.config.llvm_version_check {
252 let mut cmd = Command::new(llvm_config);
253 let version = output(cmd.arg("--version"));
254 let mut parts = version.split('.').take(2)
255 .filter_map(|s| s.parse::<u32>().ok());
256 if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
257 if major > 3 || (major == 3 && minor >= 9) {
261 panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version)
264 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
265 pub struct TestHelpers {
266 pub target: Interned<String>,
269 impl Step for TestHelpers {
272 fn should_run(run: ShouldRun) -> ShouldRun {
273 run.path("src/rt/rust_test_helpers.c")
276 fn make_run(run: RunConfig) {
277 run.builder.ensure(TestHelpers { target: run.target })
280 /// Compiles the `rust_test_helpers.c` library which we used in various
281 /// `run-pass` test suites for ABI testing.
282 fn run(self, builder: &Builder) {
283 let build = builder.build;
284 let target = self.target;
285 let dst = build.test_helpers_out(target);
286 let src = build.src.join("src/rt/rust_test_helpers.c");
287 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
291 let _folder = build.fold_output(|| "build_test_helpers");
292 println!("Building test helpers");
293 t!(fs::create_dir_all(&dst));
294 let mut cfg = cc::Build::new();
296 // We may have found various cross-compilers a little differently due to our
297 // extra configuration, so inform gcc of these compilers. Note, though, that
298 // on MSVC we still need gcc's detection of env vars (ugh).
299 if !target.contains("msvc") {
300 if let Some(ar) = build.ar(target) {
303 cfg.compiler(build.cc(target));
306 cfg.cargo_metadata(false)
313 .file(build.src.join("src/rt/rust_test_helpers.c"))
314 .compile("rust_test_helpers");
318 const OPENSSL_VERS: &'static str = "1.0.2m";
319 const OPENSSL_SHA256: &'static str =
320 "8c6ff15ec6b319b50788f42c7abc2890c08ba5a1cdcd3810eb9092deada37b0f";
322 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
324 pub target: Interned<String>,
327 impl Step for Openssl {
330 fn should_run(run: ShouldRun) -> ShouldRun {
334 fn run(self, builder: &Builder) {
335 let build = builder.build;
336 let target = self.target;
337 let out = match build.openssl_dir(target) {
342 let stamp = out.join(".stamp");
343 let mut contents = String::new();
344 drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
345 if contents == OPENSSL_VERS {
348 t!(fs::create_dir_all(&out));
350 let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
351 let tarball = out.join(&name);
352 if !tarball.exists() {
353 let tmp = tarball.with_extension("tmp");
354 // originally from https://www.openssl.org/source/...
355 let url = format!("https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/{}",
357 let mut last_error = None;
359 let status = Command::new("curl")
361 .arg("-f") // make curl fail if the URL does not return HTTP 200
364 .expect("failed to spawn curl");
366 // Retry if download failed.
367 if !status.success() {
368 last_error = Some(status.to_string());
372 // Ensure the hash is correct.
373 let mut shasum = if target.contains("apple") || build.build.contains("netbsd") {
374 let mut cmd = Command::new("shasum");
375 cmd.arg("-a").arg("256");
378 Command::new("sha256sum")
380 let output = output(&mut shasum.arg(&tmp));
381 let found = output.split_whitespace().next().unwrap();
383 // If the hash is wrong, probably the download is incomplete or S3 served an error
384 // page. In any case, retry.
385 if found != OPENSSL_SHA256 {
386 last_error = Some(format!(
387 "downloaded openssl sha256 different\n\
396 // Everything is fine, so exit the retry loop.
400 if let Some(error) = last_error {
401 panic!("failed to download openssl source: {}", error);
403 t!(fs::rename(&tmp, &tarball));
405 let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
406 let dst = build.openssl_install_dir(target).unwrap();
407 drop(fs::remove_dir_all(&obj));
408 drop(fs::remove_dir_all(&dst));
409 build.run(Command::new("tar").arg("zxf").arg(&tarball).current_dir(&out));
411 let mut configure = Command::new("perl");
412 configure.arg(obj.join("Configure"));
413 configure.arg(format!("--prefix={}", dst.display()));
414 configure.arg("no-dso");
415 configure.arg("no-ssl2");
416 configure.arg("no-ssl3");
418 let os = match &*target {
419 "aarch64-linux-android" => "linux-aarch64",
420 "aarch64-unknown-linux-gnu" => "linux-aarch64",
421 "aarch64-unknown-linux-musl" => "linux-aarch64",
422 "arm-linux-androideabi" => "android",
423 "arm-unknown-linux-gnueabi" => "linux-armv4",
424 "arm-unknown-linux-gnueabihf" => "linux-armv4",
425 "armv7-linux-androideabi" => "android-armv7",
426 "armv7-unknown-linux-gnueabihf" => "linux-armv4",
427 "i586-unknown-linux-gnu" => "linux-elf",
428 "i586-unknown-linux-musl" => "linux-elf",
429 "i686-apple-darwin" => "darwin-i386-cc",
430 "i686-linux-android" => "android-x86",
431 "i686-unknown-freebsd" => "BSD-x86-elf",
432 "i686-unknown-linux-gnu" => "linux-elf",
433 "i686-unknown-linux-musl" => "linux-elf",
434 "i686-unknown-netbsd" => "BSD-x86-elf",
435 "mips-unknown-linux-gnu" => "linux-mips32",
436 "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
437 "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
438 "mipsel-unknown-linux-gnu" => "linux-mips32",
439 "powerpc-unknown-linux-gnu" => "linux-ppc",
440 "powerpc64-unknown-linux-gnu" => "linux-ppc64",
441 "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
442 "s390x-unknown-linux-gnu" => "linux64-s390x",
443 "sparc64-unknown-linux-gnu" => "linux64-sparcv9",
444 "sparc64-unknown-netbsd" => "BSD-sparc64",
445 "x86_64-apple-darwin" => "darwin64-x86_64-cc",
446 "x86_64-linux-android" => "linux-x86_64",
447 "x86_64-unknown-freebsd" => "BSD-x86_64",
448 "x86_64-unknown-dragonfly" => "BSD-x86_64",
449 "x86_64-unknown-linux-gnu" => "linux-x86_64",
450 "x86_64-unknown-linux-musl" => "linux-x86_64",
451 "x86_64-unknown-netbsd" => "BSD-x86_64",
452 _ => panic!("don't know how to configure OpenSSL for {}", target),
455 configure.env("CC", build.cc(target));
456 for flag in build.cflags(target) {
459 // There is no specific os target for android aarch64 or x86_64,
460 // so we need to pass some extra cflags
461 if target == "aarch64-linux-android" || target == "x86_64-linux-android" {
462 configure.arg("-mandroid");
463 configure.arg("-fomit-frame-pointer");
465 if target == "sparc64-unknown-netbsd" {
466 // Need -m64 to get assembly generated correctly for sparc64.
467 configure.arg("-m64");
468 if build.build.contains("netbsd") {
469 // Disable sparc64 asm on NetBSD builders, it uses
470 // m4(1)'s -B flag, which NetBSD m4 does not support.
471 configure.arg("no-asm");
475 // Non-PIE linker support was removed in Lollipop
476 // https://source.android.com/security/enhancements/enhancements50
477 if target == "i686-linux-android" {
478 configure.arg("no-asm");
480 configure.current_dir(&obj);
481 println!("Configuring openssl for {}", target);
482 build.run_quiet(&mut configure);
483 println!("Building openssl for {}", target);
484 build.run_quiet(Command::new("make").arg("-j1").current_dir(&obj));
485 println!("Installing openssl for {}", target);
486 build.run_quiet(Command::new("make").arg("install").current_dir(&obj));
488 let mut f = t!(File::create(&stamp));
489 t!(f.write_all(OPENSSL_VERS.as_bytes()));