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};
25 use std::path::{Path, PathBuf};
26 use std::process::Command;
28 use build_helper::output;
33 use util::{self, exe};
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 type Output = PathBuf; // path to llvm-config
47 const ONLY_HOSTS: bool = true;
49 fn should_run(run: ShouldRun) -> ShouldRun {
50 run.path("src/llvm").path("src/llvm-emscripten")
53 fn make_run(run: RunConfig) {
54 let emscripten = run.path.map(|p| {
55 p.ends_with("llvm-emscripten")
57 run.builder.ensure(Llvm {
63 /// Compile LLVM for `target`.
64 fn run(self, builder: &Builder) -> PathBuf {
65 let build = builder.build;
66 let target = self.target;
67 let emscripten = self.emscripten;
69 // If we're using a custom LLVM bail out here, but we can only use a
70 // custom LLVM for the build triple.
72 if let Some(config) = build.config.target_config.get(&target) {
73 if let Some(ref s) = config.llvm_config {
74 check_llvm_version(build, s);
75 return s.to_path_buf()
80 let rebuild_trigger = build.src.join("src/rustllvm/llvm-rebuild-trigger");
81 let mut rebuild_trigger_contents = String::new();
82 t!(t!(File::open(&rebuild_trigger)).read_to_string(&mut rebuild_trigger_contents));
84 let (out_dir, llvm_config_ret_dir) = if emscripten {
85 let dir = build.emscripten_llvm_out(target);
86 let config_dir = dir.join("bin");
89 (build.llvm_out(target),
90 build.llvm_out(build.config.build).join("bin"))
92 let done_stamp = out_dir.join("llvm-finished-building");
93 let build_llvm_config = llvm_config_ret_dir
94 .join(exe("llvm-config", &*build.config.build));
95 if done_stamp.exists() {
96 let mut done_contents = String::new();
97 t!(t!(File::open(&done_stamp)).read_to_string(&mut done_contents));
99 // If LLVM was already built previously and contents of the rebuild-trigger file
100 // didn't change from the previous build, then no action is required.
101 if done_contents == rebuild_trigger_contents {
102 return build_llvm_config
106 let _folder = build.fold_output(|| "llvm");
107 let descriptor = if emscripten { "Emscripten " } else { "" };
108 println!("Building {}LLVM for {}", descriptor, target);
109 let _time = util::timeit();
110 t!(fs::create_dir_all(&out_dir));
112 // http://llvm.org/docs/CMake.html
113 let root = if self.emscripten { "src/llvm-emscripten" } else { "src/llvm" };
114 let mut cfg = cmake::Config::new(build.src.join(root));
115 if build.config.ninja {
116 cfg.generator("Ninja");
119 let profile = match (build.config.llvm_optimize, build.config.llvm_release_debuginfo) {
120 (false, _) => "Debug",
121 (true, false) => "Release",
122 (true, true) => "RelWithDebInfo",
125 // NOTE: remember to also update `config.toml.example` when changing the
127 let llvm_targets = if self.emscripten {
130 match build.config.llvm_targets {
132 None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;MSP430;Sparc;NVPTX;Hexagon",
136 let llvm_exp_targets = if self.emscripten {
139 &build.config.llvm_experimental_targets[..]
142 let assertions = if build.config.llvm_assertions {"ON"} else {"OFF"};
148 .define("LLVM_ENABLE_ASSERTIONS", assertions)
149 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
150 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
151 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
152 .define("LLVM_INCLUDE_TESTS", "OFF")
153 .define("LLVM_INCLUDE_DOCS", "OFF")
154 .define("LLVM_ENABLE_ZLIB", "OFF")
155 .define("WITH_POLLY", "OFF")
156 .define("LLVM_ENABLE_TERMINFO", "OFF")
157 .define("LLVM_ENABLE_LIBEDIT", "OFF")
158 .define("LLVM_PARALLEL_COMPILE_JOBS", build.jobs().to_string())
159 .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
160 .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
163 // This setting makes the LLVM tools link to the dynamic LLVM library,
164 // which saves both memory during parallel links and overall disk space
165 // for the tools. We don't distribute any of those tools, so this is
166 // just a local concern. However, it doesn't work well everywhere.
167 if target.contains("linux-gnu") || target.contains("apple-darwin") {
168 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
171 if target.contains("msvc") {
172 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
173 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
174 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
175 cfg.static_crt(true);
178 if target.starts_with("i686") {
179 cfg.define("LLVM_BUILD_32_BITS", "ON");
182 if let Some(num_linkers) = build.config.llvm_link_jobs {
184 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
188 // http://llvm.org/docs/HowToCrossCompileLLVM.html
189 if target != build.build && !emscripten {
190 builder.ensure(Llvm {
194 // FIXME: if the llvm root for the build triple is overridden then we
195 // should use llvm-tblgen from there, also should verify that it
196 // actually exists most of the time in normal installs of LLVM.
197 let host = build.llvm_out(build.build).join("bin/llvm-tblgen");
198 cfg.define("CMAKE_CROSSCOMPILING", "True")
199 .define("LLVM_TABLEGEN", &host);
201 if target.contains("netbsd") {
202 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
203 } else if target.contains("freebsd") {
204 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
207 cfg.define("LLVM_NATIVE_BUILD", build.llvm_out(build.build).join("build"));
210 let sanitize_cc = |cc: &Path| {
211 if target.contains("msvc") {
212 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
214 cc.as_os_str().to_owned()
218 let configure_compilers = |cfg: &mut cmake::Config| {
219 // MSVC with CMake uses msbuild by default which doesn't respect these
220 // vars that we'd otherwise configure. In that case we just skip this
222 if target.contains("msvc") && !build.config.ninja {
226 let cc = build.cc(target);
227 let cxx = build.cxx(target).unwrap();
229 // Handle msvc + ninja + ccache specially (this is what the bots use)
230 if target.contains("msvc") &&
231 build.config.ninja &&
232 build.config.ccache.is_some() {
233 let mut cc = env::current_exe().expect("failed to get cwd");
234 cc.set_file_name("sccache-plus-cl.exe");
236 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
237 .define("CMAKE_CXX_COMPILER", sanitize_cc(&cc));
238 cfg.env("SCCACHE_PATH",
239 build.config.ccache.as_ref().unwrap())
240 .env("SCCACHE_TARGET", target);
242 // If ccache is configured we inform the build a little differently hwo
243 // to invoke ccache while also invoking our compilers.
244 } else if let Some(ref ccache) = build.config.ccache {
245 cfg.define("CMAKE_C_COMPILER", ccache)
246 .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
247 .define("CMAKE_CXX_COMPILER", ccache)
248 .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
250 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
251 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
254 cfg.build_arg("-j").build_arg(build.jobs().to_string());
255 cfg.define("CMAKE_C_FLAGS", build.cflags(target).join(" "));
256 cfg.define("CMAKE_CXX_FLAGS", build.cflags(target).join(" "));
257 if let Some(ar) = build.ar(target) {
258 if ar.is_absolute() {
259 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
260 // tries to resolve this path in the LLVM build directory.
261 cfg.define("CMAKE_AR", sanitize_cc(ar));
266 configure_compilers(&mut cfg);
268 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
269 cfg.env("RUST_LOG", "sccache=warn");
272 // FIXME: we don't actually need to build all LLVM tools and all LLVM
273 // libraries here, e.g. we just want a few components and a few
274 // tools. Figure out how to filter them down and only build the right
275 // tools and libs on all platforms.
278 t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
284 fn check_llvm_version(build: &Build, llvm_config: &Path) {
285 if !build.config.llvm_version_check {
289 let mut cmd = Command::new(llvm_config);
290 let version = output(cmd.arg("--version"));
291 let mut parts = version.split('.').take(2)
292 .filter_map(|s| s.parse::<u32>().ok());
293 if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
294 if major > 3 || (major == 3 && minor >= 9) {
298 panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version)
301 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
302 pub struct TestHelpers {
303 pub target: Interned<String>,
306 impl Step for TestHelpers {
309 fn should_run(run: ShouldRun) -> ShouldRun {
310 run.path("src/rt/rust_test_helpers.c")
313 fn make_run(run: RunConfig) {
314 run.builder.ensure(TestHelpers { target: run.target })
317 /// Compiles the `rust_test_helpers.c` library which we used in various
318 /// `run-pass` test suites for ABI testing.
319 fn run(self, builder: &Builder) {
320 let build = builder.build;
321 let target = self.target;
322 let dst = build.test_helpers_out(target);
323 let src = build.src.join("src/rt/rust_test_helpers.c");
324 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
328 let _folder = build.fold_output(|| "build_test_helpers");
329 println!("Building test helpers");
330 t!(fs::create_dir_all(&dst));
331 let mut cfg = cc::Build::new();
333 // We may have found various cross-compilers a little differently due to our
334 // extra configuration, so inform gcc of these compilers. Note, though, that
335 // on MSVC we still need gcc's detection of env vars (ugh).
336 if !target.contains("msvc") {
337 if let Some(ar) = build.ar(target) {
340 cfg.compiler(build.cc(target));
343 cfg.cargo_metadata(false)
350 .file(build.src.join("src/rt/rust_test_helpers.c"))
351 .compile("rust_test_helpers");
355 const OPENSSL_VERS: &'static str = "1.0.2m";
356 const OPENSSL_SHA256: &'static str =
357 "8c6ff15ec6b319b50788f42c7abc2890c08ba5a1cdcd3810eb9092deada37b0f";
359 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
361 pub target: Interned<String>,
364 impl Step for Openssl {
367 fn should_run(run: ShouldRun) -> ShouldRun {
371 fn run(self, builder: &Builder) {
372 let build = builder.build;
373 let target = self.target;
374 let out = match build.openssl_dir(target) {
379 let stamp = out.join(".stamp");
380 let mut contents = String::new();
381 drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
382 if contents == OPENSSL_VERS {
385 t!(fs::create_dir_all(&out));
387 let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
388 let tarball = out.join(&name);
389 if !tarball.exists() {
390 let tmp = tarball.with_extension("tmp");
391 // originally from https://www.openssl.org/source/...
392 let url = format!("https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/{}",
394 let mut last_error = None;
396 let status = Command::new("curl")
398 .arg("-f") // make curl fail if the URL does not return HTTP 200
401 .expect("failed to spawn curl");
403 // Retry if download failed.
404 if !status.success() {
405 last_error = Some(status.to_string());
409 // Ensure the hash is correct.
410 let mut shasum = if target.contains("apple") || build.build.contains("netbsd") {
411 let mut cmd = Command::new("shasum");
412 cmd.arg("-a").arg("256");
415 Command::new("sha256sum")
417 let output = output(&mut shasum.arg(&tmp));
418 let found = output.split_whitespace().next().unwrap();
420 // If the hash is wrong, probably the download is incomplete or S3 served an error
421 // page. In any case, retry.
422 if found != OPENSSL_SHA256 {
423 last_error = Some(format!(
424 "downloaded openssl sha256 different\n\
433 // Everything is fine, so exit the retry loop.
437 if let Some(error) = last_error {
438 panic!("failed to download openssl source: {}", error);
440 t!(fs::rename(&tmp, &tarball));
442 let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
443 let dst = build.openssl_install_dir(target).unwrap();
444 drop(fs::remove_dir_all(&obj));
445 drop(fs::remove_dir_all(&dst));
446 build.run(Command::new("tar").arg("zxf").arg(&tarball).current_dir(&out));
448 let mut configure = Command::new("perl");
449 configure.arg(obj.join("Configure"));
450 configure.arg(format!("--prefix={}", dst.display()));
451 configure.arg("no-dso");
452 configure.arg("no-ssl2");
453 configure.arg("no-ssl3");
455 let os = match &*target {
456 "aarch64-linux-android" => "linux-aarch64",
457 "aarch64-unknown-linux-gnu" => "linux-aarch64",
458 "aarch64-unknown-linux-musl" => "linux-aarch64",
459 "arm-linux-androideabi" => "android",
460 "arm-unknown-linux-gnueabi" => "linux-armv4",
461 "arm-unknown-linux-gnueabihf" => "linux-armv4",
462 "armv7-linux-androideabi" => "android-armv7",
463 "armv7-unknown-linux-gnueabihf" => "linux-armv4",
464 "i586-unknown-linux-gnu" => "linux-elf",
465 "i586-unknown-linux-musl" => "linux-elf",
466 "i686-apple-darwin" => "darwin-i386-cc",
467 "i686-linux-android" => "android-x86",
468 "i686-unknown-freebsd" => "BSD-x86-elf",
469 "i686-unknown-linux-gnu" => "linux-elf",
470 "i686-unknown-linux-musl" => "linux-elf",
471 "i686-unknown-netbsd" => "BSD-x86-elf",
472 "mips-unknown-linux-gnu" => "linux-mips32",
473 "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
474 "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
475 "mipsel-unknown-linux-gnu" => "linux-mips32",
476 "powerpc-unknown-linux-gnu" => "linux-ppc",
477 "powerpc64-unknown-linux-gnu" => "linux-ppc64",
478 "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
479 "s390x-unknown-linux-gnu" => "linux64-s390x",
480 "sparc64-unknown-linux-gnu" => "linux64-sparcv9",
481 "sparc64-unknown-netbsd" => "BSD-sparc64",
482 "x86_64-apple-darwin" => "darwin64-x86_64-cc",
483 "x86_64-linux-android" => "linux-x86_64",
484 "x86_64-unknown-freebsd" => "BSD-x86_64",
485 "x86_64-unknown-dragonfly" => "BSD-x86_64",
486 "x86_64-unknown-linux-gnu" => "linux-x86_64",
487 "x86_64-unknown-linux-musl" => "linux-x86_64",
488 "x86_64-unknown-netbsd" => "BSD-x86_64",
489 _ => panic!("don't know how to configure OpenSSL for {}", target),
492 configure.env("CC", build.cc(target));
493 for flag in build.cflags(target) {
496 // There is no specific os target for android aarch64 or x86_64,
497 // so we need to pass some extra cflags
498 if target == "aarch64-linux-android" || target == "x86_64-linux-android" {
499 configure.arg("-mandroid");
500 configure.arg("-fomit-frame-pointer");
502 if target == "sparc64-unknown-netbsd" {
503 // Need -m64 to get assembly generated correctly for sparc64.
504 configure.arg("-m64");
505 if build.build.contains("netbsd") {
506 // Disable sparc64 asm on NetBSD builders, it uses
507 // m4(1)'s -B flag, which NetBSD m4 does not support.
508 configure.arg("no-asm");
512 // Non-PIE linker support was removed in Lollipop
513 // https://source.android.com/security/enhancements/enhancements50
514 if target == "i686-linux-android" {
515 configure.arg("no-asm");
517 configure.current_dir(&obj);
518 println!("Configuring openssl for {}", target);
519 build.run_quiet(&mut configure);
520 println!("Building openssl for {}", target);
521 build.run_quiet(Command::new("make").arg("-j1").current_dir(&obj));
522 println!("Installing openssl for {}", target);
523 build.run_quiet(Command::new("make").arg("install").current_dir(&obj));
525 let mut f = t!(File::create(&stamp));
526 t!(f.write_all(OPENSSL_VERS.as_bytes()));