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;
32 use util::{self, exe};
33 use build_helper::up_to_date;
34 use builder::{Builder, RunConfig, ShouldRun, Step};
37 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
39 pub target: Interned<String>,
44 type Output = PathBuf; // path to llvm-config
46 const ONLY_HOSTS: bool = true;
48 fn should_run(run: ShouldRun) -> ShouldRun {
49 run.path("src/llvm").path("src/llvm-emscripten")
52 fn make_run(run: RunConfig) {
53 let emscripten = run.path.ends_with("llvm-emscripten");
54 run.builder.ensure(Llvm {
60 /// Compile LLVM for `target`.
61 fn run(self, builder: &Builder) -> PathBuf {
62 let target = self.target;
63 let emscripten = self.emscripten;
65 // If we're using a custom LLVM bail out here, but we can only use a
66 // custom LLVM for the build triple.
68 if let Some(config) = builder.config.target_config.get(&target) {
69 if let Some(ref s) = config.llvm_config {
70 check_llvm_version(builder, s);
71 return s.to_path_buf()
76 let rebuild_trigger = builder.src.join("src/rustllvm/llvm-rebuild-trigger");
77 let mut rebuild_trigger_contents = String::new();
78 t!(t!(File::open(&rebuild_trigger)).read_to_string(&mut rebuild_trigger_contents));
80 let (out_dir, llvm_config_ret_dir) = if emscripten {
81 let dir = builder.emscripten_llvm_out(target);
82 let config_dir = dir.join("bin");
85 let mut dir = builder.llvm_out(builder.config.build);
86 if !builder.config.build.contains("msvc") || builder.config.ninja {
89 (builder.llvm_out(target), dir.join("bin"))
91 let done_stamp = out_dir.join("llvm-finished-building");
92 let build_llvm_config = llvm_config_ret_dir
93 .join(exe("llvm-config", &*builder.config.build));
94 if done_stamp.exists() {
95 let mut done_contents = String::new();
96 t!(t!(File::open(&done_stamp)).read_to_string(&mut done_contents));
98 // If LLVM was already built previously and contents of the rebuild-trigger file
99 // didn't change from the previous build, then no action is required.
100 if done_contents == rebuild_trigger_contents {
101 return build_llvm_config
105 let _folder = builder.fold_output(|| "llvm");
106 let descriptor = if emscripten { "Emscripten " } else { "" };
107 builder.info(&format!("Building {}LLVM for {}", descriptor, target));
108 let _time = util::timeit(&builder);
109 t!(fs::create_dir_all(&out_dir));
111 // http://llvm.org/docs/CMake.html
112 let root = if self.emscripten { "src/llvm-emscripten" } else { "src/llvm" };
113 let mut cfg = cmake::Config::new(builder.src.join(root));
115 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
116 (false, _) => "Debug",
117 (true, false) => "Release",
118 (true, true) => "RelWithDebInfo",
121 // NOTE: remember to also update `config.toml.example` when changing the
123 let llvm_targets = if self.emscripten {
126 match builder.config.llvm_targets {
128 None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;MSP430;Sparc;NVPTX;Hexagon",
132 let llvm_exp_targets = if self.emscripten {
135 &builder.config.llvm_experimental_targets[..]
138 let assertions = if builder.config.llvm_assertions {"ON"} else {"OFF"};
140 cfg.out_dir(&out_dir)
142 .define("LLVM_ENABLE_ASSERTIONS", assertions)
143 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
144 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
145 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
146 .define("LLVM_INCLUDE_TESTS", "OFF")
147 .define("LLVM_INCLUDE_DOCS", "OFF")
148 .define("LLVM_ENABLE_ZLIB", "OFF")
149 .define("WITH_POLLY", "OFF")
150 .define("LLVM_ENABLE_TERMINFO", "OFF")
151 .define("LLVM_ENABLE_LIBEDIT", "OFF")
152 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
153 .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
154 .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
156 // By default, LLVM will automatically find OCaml and, if it finds it,
157 // install the LLVM bindings in LLVM_OCAML_INSTALL_PATH, which defaults
158 // to /usr/bin/ocaml.
159 // This causes problem for non-root builds of Rust. Side-step the issue
160 // by setting LLVM_OCAML_INSTALL_PATH to a relative path, so it installs
162 cfg.define("LLVM_OCAML_INSTALL_PATH",
163 env::var_os("LLVM_OCAML_INSTALL_PATH").unwrap_or_else(|| "usr/lib/ocaml".into()));
165 // This setting makes the LLVM tools link to the dynamic LLVM library,
166 // which saves both memory during parallel links and overall disk space
167 // for the tools. We don't distribute any of those tools, so this is
168 // just a local concern. However, it doesn't work well everywhere.
169 if target.contains("linux-gnu") || target.contains("apple-darwin") {
170 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
173 if target.contains("msvc") {
174 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
175 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
176 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
177 cfg.static_crt(true);
180 if target.starts_with("i686") {
181 cfg.define("LLVM_BUILD_32_BITS", "ON");
184 if let Some(num_linkers) = builder.config.llvm_link_jobs {
186 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
190 // http://llvm.org/docs/HowToCrossCompileLLVM.html
191 if target != builder.config.build && !emscripten {
192 builder.ensure(Llvm {
193 target: builder.config.build,
196 // FIXME: if the llvm root for the build triple is overridden then we
197 // should use llvm-tblgen from there, also should verify that it
198 // actually exists most of the time in normal installs of LLVM.
199 let host = builder.llvm_out(builder.config.build).join("bin/llvm-tblgen");
200 cfg.define("CMAKE_CROSSCOMPILING", "True")
201 .define("LLVM_TABLEGEN", &host);
203 if target.contains("netbsd") {
204 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
205 } else if target.contains("freebsd") {
206 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
209 cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
212 configure_cmake(builder, target, &mut cfg, false);
214 // FIXME: we don't actually need to build all LLVM tools and all LLVM
215 // libraries here, e.g. we just want a few components and a few
216 // tools. Figure out how to filter them down and only build the right
217 // tools and libs on all platforms.
219 if builder.config.dry_run {
220 return build_llvm_config;
225 t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
231 fn check_llvm_version(builder: &Builder, llvm_config: &Path) {
232 if !builder.config.llvm_version_check {
236 if builder.config.dry_run {
240 let mut cmd = Command::new(llvm_config);
241 let version = output(cmd.arg("--version"));
242 let mut parts = version.split('.').take(2)
243 .filter_map(|s| s.parse::<u32>().ok());
244 if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
245 if major > 3 || (major == 3 && minor >= 9) {
249 panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version)
252 fn configure_cmake(builder: &Builder,
253 target: Interned<String>,
254 cfg: &mut cmake::Config,
255 building_dist_binaries: bool) {
256 if builder.config.ninja {
257 cfg.generator("Ninja");
260 .host(&builder.config.build);
262 let sanitize_cc = |cc: &Path| {
263 if target.contains("msvc") {
264 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
266 cc.as_os_str().to_owned()
270 // MSVC with CMake uses msbuild by default which doesn't respect these
271 // vars that we'd otherwise configure. In that case we just skip this
273 if target.contains("msvc") && !builder.config.ninja {
277 let cc = builder.cc(target);
278 let cxx = builder.cxx(target).unwrap();
280 // Handle msvc + ninja + ccache specially (this is what the bots use)
281 if target.contains("msvc") &&
282 builder.config.ninja &&
283 builder.config.ccache.is_some() {
284 let mut cc = env::current_exe().expect("failed to get cwd");
285 cc.set_file_name("sccache-plus-cl.exe");
287 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
288 .define("CMAKE_CXX_COMPILER", sanitize_cc(&cc));
289 cfg.env("SCCACHE_PATH",
290 builder.config.ccache.as_ref().unwrap())
291 .env("SCCACHE_TARGET", target);
293 // If ccache is configured we inform the build a little differently hwo
294 // to invoke ccache while also invoking our compilers.
295 } else if let Some(ref ccache) = builder.config.ccache {
296 cfg.define("CMAKE_C_COMPILER", ccache)
297 .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
298 .define("CMAKE_CXX_COMPILER", ccache)
299 .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
301 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
302 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
305 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
306 cfg.define("CMAKE_C_FLAGS", builder.cflags(target).join(" "));
307 let mut cxxflags = builder.cflags(target).join(" ");
308 if building_dist_binaries {
309 if builder.config.llvm_static_stdcpp && !target.contains("windows") {
310 cxxflags.push_str(" -static-libstdc++");
313 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
314 if let Some(ar) = builder.ar(target) {
315 if ar.is_absolute() {
316 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
317 // tries to resolve this path in the LLVM build directory.
318 cfg.define("CMAKE_AR", sanitize_cc(ar));
322 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
323 cfg.env("RUST_LOG", "sccache=warn");
327 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
329 pub target: Interned<String>,
333 type Output = PathBuf;
334 const ONLY_HOSTS: bool = true;
336 fn should_run(run: ShouldRun) -> ShouldRun {
337 run.path("src/tools/lld")
340 fn make_run(run: RunConfig) {
341 run.builder.ensure(Lld { target: run.target });
344 /// Compile LLVM for `target`.
345 fn run(self, builder: &Builder) -> PathBuf {
346 if builder.config.dry_run {
347 return PathBuf::from("lld-out-dir-test-gen");
349 let target = self.target;
351 let llvm_config = builder.ensure(Llvm {
356 let out_dir = builder.lld_out(target);
357 let done_stamp = out_dir.join("lld-finished-building");
358 if done_stamp.exists() {
362 let _folder = builder.fold_output(|| "lld");
363 builder.info(&format!("Building LLD for {}", target));
364 let _time = util::timeit(&builder);
365 t!(fs::create_dir_all(&out_dir));
367 let mut cfg = cmake::Config::new(builder.src.join("src/tools/lld"));
368 configure_cmake(builder, target, &mut cfg, true);
370 cfg.out_dir(&out_dir)
372 .define("LLVM_CONFIG_PATH", llvm_config)
373 .define("LLVM_INCLUDE_TESTS", "OFF");
377 t!(File::create(&done_stamp));
382 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
383 pub struct TestHelpers {
384 pub target: Interned<String>,
387 impl Step for TestHelpers {
390 fn should_run(run: ShouldRun) -> ShouldRun {
391 run.path("src/test/auxiliary/rust_test_helpers.c")
394 fn make_run(run: RunConfig) {
395 run.builder.ensure(TestHelpers { target: run.target })
398 /// Compiles the `rust_test_helpers.c` library which we used in various
399 /// `run-pass` test suites for ABI testing.
400 fn run(self, builder: &Builder) {
401 if builder.config.dry_run {
404 let target = self.target;
405 let dst = builder.test_helpers_out(target);
406 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
407 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
411 let _folder = builder.fold_output(|| "build_test_helpers");
412 builder.info(&format!("Building test helpers"));
413 t!(fs::create_dir_all(&dst));
414 let mut cfg = cc::Build::new();
416 // We may have found various cross-compilers a little differently due to our
417 // extra configuration, so inform gcc of these compilers. Note, though, that
418 // on MSVC we still need gcc's detection of env vars (ugh).
419 if !target.contains("msvc") {
420 if let Some(ar) = builder.ar(target) {
423 cfg.compiler(builder.cc(target));
426 cfg.cargo_metadata(false)
429 .host(&builder.config.build)
433 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
434 .compile("rust_test_helpers");
438 const OPENSSL_VERS: &'static str = "1.0.2n";
439 const OPENSSL_SHA256: &'static str =
440 "370babb75f278c39e0c50e8c4e7493bc0f18db6867478341a832a982fd15a8fe";
442 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
444 pub target: Interned<String>,
447 impl Step for Openssl {
450 fn should_run(run: ShouldRun) -> ShouldRun {
454 fn run(self, builder: &Builder) {
455 if builder.config.dry_run {
458 let target = self.target;
459 let out = match builder.openssl_dir(target) {
464 let stamp = out.join(".stamp");
465 let mut contents = String::new();
466 drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
467 if contents == OPENSSL_VERS {
470 t!(fs::create_dir_all(&out));
472 let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
473 let tarball = out.join(&name);
474 if !tarball.exists() {
475 let tmp = tarball.with_extension("tmp");
476 // originally from https://www.openssl.org/source/...
477 let url = format!("https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/{}",
479 let mut last_error = None;
481 let status = Command::new("curl")
483 .arg("-f") // make curl fail if the URL does not return HTTP 200
486 .expect("failed to spawn curl");
488 // Retry if download failed.
489 if !status.success() {
490 last_error = Some(status.to_string());
494 // Ensure the hash is correct.
495 let mut shasum = if target.contains("apple") ||
496 builder.config.build.contains("netbsd") {
497 let mut cmd = Command::new("shasum");
498 cmd.arg("-a").arg("256");
501 Command::new("sha256sum")
503 let output = output(&mut shasum.arg(&tmp));
504 let found = output.split_whitespace().next().unwrap();
506 // If the hash is wrong, probably the download is incomplete or S3 served an error
507 // page. In any case, retry.
508 if found != OPENSSL_SHA256 {
509 last_error = Some(format!(
510 "downloaded openssl sha256 different\n\
519 // Everything is fine, so exit the retry loop.
523 if let Some(error) = last_error {
524 panic!("failed to download openssl source: {}", error);
526 t!(fs::rename(&tmp, &tarball));
528 let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
529 let dst = builder.openssl_install_dir(target).unwrap();
530 drop(fs::remove_dir_all(&obj));
531 drop(fs::remove_dir_all(&dst));
532 builder.run(Command::new("tar").arg("zxf").arg(&tarball).current_dir(&out));
534 let mut configure = Command::new("perl");
535 configure.arg(obj.join("Configure"));
536 configure.arg(format!("--prefix={}", dst.display()));
537 configure.arg("no-dso");
538 configure.arg("no-ssl2");
539 configure.arg("no-ssl3");
541 let os = match &*target {
542 "aarch64-linux-android" => "linux-aarch64",
543 "aarch64-unknown-linux-gnu" => "linux-aarch64",
544 "aarch64-unknown-linux-musl" => "linux-aarch64",
545 "arm-linux-androideabi" => "android",
546 "arm-unknown-linux-gnueabi" => "linux-armv4",
547 "arm-unknown-linux-gnueabihf" => "linux-armv4",
548 "armv7-linux-androideabi" => "android-armv7",
549 "armv7-unknown-linux-gnueabihf" => "linux-armv4",
550 "i586-unknown-linux-gnu" => "linux-elf",
551 "i586-unknown-linux-musl" => "linux-elf",
552 "i686-apple-darwin" => "darwin-i386-cc",
553 "i686-linux-android" => "android-x86",
554 "i686-unknown-freebsd" => "BSD-x86-elf",
555 "i686-unknown-linux-gnu" => "linux-elf",
556 "i686-unknown-linux-musl" => "linux-elf",
557 "i686-unknown-netbsd" => "BSD-x86-elf",
558 "mips-unknown-linux-gnu" => "linux-mips32",
559 "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
560 "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
561 "mipsel-unknown-linux-gnu" => "linux-mips32",
562 "powerpc-unknown-linux-gnu" => "linux-ppc",
563 "powerpc-unknown-linux-gnuspe" => "linux-ppc",
564 "powerpc-unknown-netbsd" => "BSD-generic32",
565 "powerpc64-unknown-linux-gnu" => "linux-ppc64",
566 "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
567 "s390x-unknown-linux-gnu" => "linux64-s390x",
568 "sparc-unknown-linux-gnu" => "linux-sparcv9",
569 "sparc64-unknown-linux-gnu" => "linux64-sparcv9",
570 "sparc64-unknown-netbsd" => "BSD-sparc64",
571 "x86_64-apple-darwin" => "darwin64-x86_64-cc",
572 "x86_64-linux-android" => "linux-x86_64",
573 "x86_64-unknown-freebsd" => "BSD-x86_64",
574 "x86_64-unknown-dragonfly" => "BSD-x86_64",
575 "x86_64-unknown-linux-gnu" => "linux-x86_64",
576 "x86_64-unknown-linux-gnux32" => "linux-x32",
577 "x86_64-unknown-linux-musl" => "linux-x86_64",
578 "x86_64-unknown-netbsd" => "BSD-x86_64",
579 _ => panic!("don't know how to configure OpenSSL for {}", target),
582 configure.env("CC", builder.cc(target));
583 for flag in builder.cflags(target) {
586 // There is no specific os target for android aarch64 or x86_64,
587 // so we need to pass some extra cflags
588 if target == "aarch64-linux-android" || target == "x86_64-linux-android" {
589 configure.arg("-mandroid");
590 configure.arg("-fomit-frame-pointer");
592 if target == "sparc64-unknown-netbsd" {
593 // Need -m64 to get assembly generated correctly for sparc64.
594 configure.arg("-m64");
595 if builder.config.build.contains("netbsd") {
596 // Disable sparc64 asm on NetBSD builders, it uses
597 // m4(1)'s -B flag, which NetBSD m4 does not support.
598 configure.arg("no-asm");
602 // Non-PIE linker support was removed in Lollipop
603 // https://source.android.com/security/enhancements/enhancements50
604 if target == "i686-linux-android" {
605 configure.arg("no-asm");
607 configure.current_dir(&obj);
608 builder.info(&format!("Configuring openssl for {}", target));
609 builder.run_quiet(&mut configure);
610 builder.info(&format!("Building openssl for {}", target));
611 builder.run_quiet(Command::new("make").arg("-j1").current_dir(&obj));
612 builder.info(&format!("Installing openssl for {}", target));
613 builder.run_quiet(Command::new("make").arg("install").arg("-j1").current_dir(&obj));
615 let mut f = t!(File::create(&stamp));
616 t!(f.write_all(OPENSSL_VERS.as_bytes()));