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);
162 // By default, LLVM will automatically find OCaml and, if it finds it,
163 // install the LLVM bindings in LLVM_OCAML_INSTALL_PATH, which defaults
164 // to /usr/bin/ocaml.
165 // This causes problem for non-root builds of Rust. Side-step the issue
166 // by setting LLVM_OCAML_INSTALL_PATH to a relative path, so it installs
168 cfg.define("LLVM_OCAML_INSTALL_PATH",
169 env::var_os("LLVM_OCAML_INSTALL_PATH").unwrap_or_else(|| "usr/lib/ocaml".into()));
171 // This setting makes the LLVM tools link to the dynamic LLVM library,
172 // which saves both memory during parallel links and overall disk space
173 // for the tools. We don't distribute any of those tools, so this is
174 // just a local concern. However, it doesn't work well everywhere.
175 if target.contains("linux-gnu") || target.contains("apple-darwin") {
176 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
179 if target.contains("msvc") {
180 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
181 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
182 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
183 cfg.static_crt(true);
186 if target.starts_with("i686") {
187 cfg.define("LLVM_BUILD_32_BITS", "ON");
190 if let Some(num_linkers) = build.config.llvm_link_jobs {
192 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
196 // http://llvm.org/docs/HowToCrossCompileLLVM.html
197 if target != build.build && !emscripten {
198 builder.ensure(Llvm {
202 // FIXME: if the llvm root for the build triple is overridden then we
203 // should use llvm-tblgen from there, also should verify that it
204 // actually exists most of the time in normal installs of LLVM.
205 let host = build.llvm_out(build.build).join("bin/llvm-tblgen");
206 cfg.define("CMAKE_CROSSCOMPILING", "True")
207 .define("LLVM_TABLEGEN", &host);
209 if target.contains("netbsd") {
210 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
211 } else if target.contains("freebsd") {
212 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
215 cfg.define("LLVM_NATIVE_BUILD", build.llvm_out(build.build).join("build"));
218 let sanitize_cc = |cc: &Path| {
219 if target.contains("msvc") {
220 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
222 cc.as_os_str().to_owned()
226 let configure_compilers = |cfg: &mut cmake::Config| {
227 // MSVC with CMake uses msbuild by default which doesn't respect these
228 // vars that we'd otherwise configure. In that case we just skip this
230 if target.contains("msvc") && !build.config.ninja {
234 let cc = build.cc(target);
235 let cxx = build.cxx(target).unwrap();
237 // Handle msvc + ninja + ccache specially (this is what the bots use)
238 if target.contains("msvc") &&
239 build.config.ninja &&
240 build.config.ccache.is_some() {
241 let mut cc = env::current_exe().expect("failed to get cwd");
242 cc.set_file_name("sccache-plus-cl.exe");
244 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
245 .define("CMAKE_CXX_COMPILER", sanitize_cc(&cc));
246 cfg.env("SCCACHE_PATH",
247 build.config.ccache.as_ref().unwrap())
248 .env("SCCACHE_TARGET", target);
250 // If ccache is configured we inform the build a little differently hwo
251 // to invoke ccache while also invoking our compilers.
252 } else if let Some(ref ccache) = build.config.ccache {
253 cfg.define("CMAKE_C_COMPILER", ccache)
254 .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
255 .define("CMAKE_CXX_COMPILER", ccache)
256 .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
258 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
259 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
262 cfg.build_arg("-j").build_arg(build.jobs().to_string());
263 cfg.define("CMAKE_C_FLAGS", build.cflags(target).join(" "));
264 cfg.define("CMAKE_CXX_FLAGS", build.cflags(target).join(" "));
265 if let Some(ar) = build.ar(target) {
266 if ar.is_absolute() {
267 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
268 // tries to resolve this path in the LLVM build directory.
269 cfg.define("CMAKE_AR", sanitize_cc(ar));
274 configure_compilers(&mut cfg);
276 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
277 cfg.env("RUST_LOG", "sccache=warn");
280 // FIXME: we don't actually need to build all LLVM tools and all LLVM
281 // libraries here, e.g. we just want a few components and a few
282 // tools. Figure out how to filter them down and only build the right
283 // tools and libs on all platforms.
286 t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
292 fn check_llvm_version(build: &Build, llvm_config: &Path) {
293 if !build.config.llvm_version_check {
297 let mut cmd = Command::new(llvm_config);
298 let version = output(cmd.arg("--version"));
299 let mut parts = version.split('.').take(2)
300 .filter_map(|s| s.parse::<u32>().ok());
301 if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
302 if major > 3 || (major == 3 && minor >= 9) {
306 panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version)
309 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
310 pub struct TestHelpers {
311 pub target: Interned<String>,
314 impl Step for TestHelpers {
317 fn should_run(run: ShouldRun) -> ShouldRun {
318 run.path("src/rt/rust_test_helpers.c")
321 fn make_run(run: RunConfig) {
322 run.builder.ensure(TestHelpers { target: run.target })
325 /// Compiles the `rust_test_helpers.c` library which we used in various
326 /// `run-pass` test suites for ABI testing.
327 fn run(self, builder: &Builder) {
328 let build = builder.build;
329 let target = self.target;
330 let dst = build.test_helpers_out(target);
331 let src = build.src.join("src/rt/rust_test_helpers.c");
332 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
336 let _folder = build.fold_output(|| "build_test_helpers");
337 println!("Building test helpers");
338 t!(fs::create_dir_all(&dst));
339 let mut cfg = cc::Build::new();
341 // We may have found various cross-compilers a little differently due to our
342 // extra configuration, so inform gcc of these compilers. Note, though, that
343 // on MSVC we still need gcc's detection of env vars (ugh).
344 if !target.contains("msvc") {
345 if let Some(ar) = build.ar(target) {
348 cfg.compiler(build.cc(target));
351 cfg.cargo_metadata(false)
358 .file(build.src.join("src/rt/rust_test_helpers.c"))
359 .compile("rust_test_helpers");
363 const OPENSSL_VERS: &'static str = "1.0.2m";
364 const OPENSSL_SHA256: &'static str =
365 "8c6ff15ec6b319b50788f42c7abc2890c08ba5a1cdcd3810eb9092deada37b0f";
367 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
369 pub target: Interned<String>,
372 impl Step for Openssl {
375 fn should_run(run: ShouldRun) -> ShouldRun {
379 fn run(self, builder: &Builder) {
380 let build = builder.build;
381 let target = self.target;
382 let out = match build.openssl_dir(target) {
387 let stamp = out.join(".stamp");
388 let mut contents = String::new();
389 drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
390 if contents == OPENSSL_VERS {
393 t!(fs::create_dir_all(&out));
395 let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
396 let tarball = out.join(&name);
397 if !tarball.exists() {
398 let tmp = tarball.with_extension("tmp");
399 // originally from https://www.openssl.org/source/...
400 let url = format!("https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/{}",
402 let mut last_error = None;
404 let status = Command::new("curl")
406 .arg("-f") // make curl fail if the URL does not return HTTP 200
409 .expect("failed to spawn curl");
411 // Retry if download failed.
412 if !status.success() {
413 last_error = Some(status.to_string());
417 // Ensure the hash is correct.
418 let mut shasum = if target.contains("apple") || build.build.contains("netbsd") {
419 let mut cmd = Command::new("shasum");
420 cmd.arg("-a").arg("256");
423 Command::new("sha256sum")
425 let output = output(&mut shasum.arg(&tmp));
426 let found = output.split_whitespace().next().unwrap();
428 // If the hash is wrong, probably the download is incomplete or S3 served an error
429 // page. In any case, retry.
430 if found != OPENSSL_SHA256 {
431 last_error = Some(format!(
432 "downloaded openssl sha256 different\n\
441 // Everything is fine, so exit the retry loop.
445 if let Some(error) = last_error {
446 panic!("failed to download openssl source: {}", error);
448 t!(fs::rename(&tmp, &tarball));
450 let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
451 let dst = build.openssl_install_dir(target).unwrap();
452 drop(fs::remove_dir_all(&obj));
453 drop(fs::remove_dir_all(&dst));
454 build.run(Command::new("tar").arg("zxf").arg(&tarball).current_dir(&out));
456 let mut configure = Command::new("perl");
457 configure.arg(obj.join("Configure"));
458 configure.arg(format!("--prefix={}", dst.display()));
459 configure.arg("no-dso");
460 configure.arg("no-ssl2");
461 configure.arg("no-ssl3");
463 let os = match &*target {
464 "aarch64-linux-android" => "linux-aarch64",
465 "aarch64-unknown-linux-gnu" => "linux-aarch64",
466 "aarch64-unknown-linux-musl" => "linux-aarch64",
467 "arm-linux-androideabi" => "android",
468 "arm-unknown-linux-gnueabi" => "linux-armv4",
469 "arm-unknown-linux-gnueabihf" => "linux-armv4",
470 "armv7-linux-androideabi" => "android-armv7",
471 "armv7-unknown-linux-gnueabihf" => "linux-armv4",
472 "i586-unknown-linux-gnu" => "linux-elf",
473 "i586-unknown-linux-musl" => "linux-elf",
474 "i686-apple-darwin" => "darwin-i386-cc",
475 "i686-linux-android" => "android-x86",
476 "i686-unknown-freebsd" => "BSD-x86-elf",
477 "i686-unknown-linux-gnu" => "linux-elf",
478 "i686-unknown-linux-musl" => "linux-elf",
479 "i686-unknown-netbsd" => "BSD-x86-elf",
480 "mips-unknown-linux-gnu" => "linux-mips32",
481 "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
482 "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
483 "mipsel-unknown-linux-gnu" => "linux-mips32",
484 "powerpc-unknown-linux-gnu" => "linux-ppc",
485 "powerpc64-unknown-linux-gnu" => "linux-ppc64",
486 "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
487 "s390x-unknown-linux-gnu" => "linux64-s390x",
488 "sparc64-unknown-linux-gnu" => "linux64-sparcv9",
489 "sparc64-unknown-netbsd" => "BSD-sparc64",
490 "x86_64-apple-darwin" => "darwin64-x86_64-cc",
491 "x86_64-linux-android" => "linux-x86_64",
492 "x86_64-unknown-freebsd" => "BSD-x86_64",
493 "x86_64-unknown-dragonfly" => "BSD-x86_64",
494 "x86_64-unknown-linux-gnu" => "linux-x86_64",
495 "x86_64-unknown-linux-musl" => "linux-x86_64",
496 "x86_64-unknown-netbsd" => "BSD-x86_64",
497 _ => panic!("don't know how to configure OpenSSL for {}", target),
500 configure.env("CC", build.cc(target));
501 for flag in build.cflags(target) {
504 // There is no specific os target for android aarch64 or x86_64,
505 // so we need to pass some extra cflags
506 if target == "aarch64-linux-android" || target == "x86_64-linux-android" {
507 configure.arg("-mandroid");
508 configure.arg("-fomit-frame-pointer");
510 if target == "sparc64-unknown-netbsd" {
511 // Need -m64 to get assembly generated correctly for sparc64.
512 configure.arg("-m64");
513 if build.build.contains("netbsd") {
514 // Disable sparc64 asm on NetBSD builders, it uses
515 // m4(1)'s -B flag, which NetBSD m4 does not support.
516 configure.arg("no-asm");
520 // Non-PIE linker support was removed in Lollipop
521 // https://source.android.com/security/enhancements/enhancements50
522 if target == "i686-linux-android" {
523 configure.arg("no-asm");
525 configure.current_dir(&obj);
526 println!("Configuring openssl for {}", target);
527 build.run_quiet(&mut configure);
528 println!("Building openssl for {}", target);
529 build.run_quiet(Command::new("make").arg("-j1").current_dir(&obj));
530 println!("Installing openssl for {}", target);
531 build.run_quiet(Command::new("make").arg("install").current_dir(&obj));
533 let mut f = t!(File::create(&stamp));
534 t!(f.write_all(OPENSSL_VERS.as_bytes()));