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_ENABLE_LIBXML2", "OFF")
153 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
154 .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
155 .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
157 // By default, LLVM will automatically find OCaml and, if it finds it,
158 // install the LLVM bindings in LLVM_OCAML_INSTALL_PATH, which defaults
159 // to /usr/bin/ocaml.
160 // This causes problem for non-root builds of Rust. Side-step the issue
161 // by setting LLVM_OCAML_INSTALL_PATH to a relative path, so it installs
163 cfg.define("LLVM_OCAML_INSTALL_PATH",
164 env::var_os("LLVM_OCAML_INSTALL_PATH").unwrap_or_else(|| "usr/lib/ocaml".into()));
166 // This setting makes the LLVM tools link to the dynamic LLVM library,
167 // which saves both memory during parallel links and overall disk space
168 // for the tools. We don't distribute any of those tools, so this is
169 // just a local concern. However, it doesn't work well everywhere.
170 if target.contains("linux-gnu") || target.contains("apple-darwin") {
171 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
174 if target.contains("msvc") {
175 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
176 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
177 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
178 cfg.static_crt(true);
181 if target.starts_with("i686") {
182 cfg.define("LLVM_BUILD_32_BITS", "ON");
185 if let Some(num_linkers) = builder.config.llvm_link_jobs {
187 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
191 // http://llvm.org/docs/HowToCrossCompileLLVM.html
192 if target != builder.config.build && !emscripten {
193 builder.ensure(Llvm {
194 target: builder.config.build,
197 // FIXME: if the llvm root for the build triple is overridden then we
198 // should use llvm-tblgen from there, also should verify that it
199 // actually exists most of the time in normal installs of LLVM.
200 let host = builder.llvm_out(builder.config.build).join("bin/llvm-tblgen");
201 cfg.define("CMAKE_CROSSCOMPILING", "True")
202 .define("LLVM_TABLEGEN", &host);
204 if target.contains("netbsd") {
205 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
206 } else if target.contains("freebsd") {
207 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
210 cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
213 configure_cmake(builder, target, &mut cfg, false);
215 // FIXME: we don't actually need to build all LLVM tools and all LLVM
216 // libraries here, e.g. we just want a few components and a few
217 // tools. Figure out how to filter them down and only build the right
218 // tools and libs on all platforms.
220 if builder.config.dry_run {
221 return build_llvm_config;
226 t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
232 fn check_llvm_version(builder: &Builder, llvm_config: &Path) {
233 if !builder.config.llvm_version_check {
237 if builder.config.dry_run {
241 let mut cmd = Command::new(llvm_config);
242 let version = output(cmd.arg("--version"));
243 let mut parts = version.split('.').take(2)
244 .filter_map(|s| s.parse::<u32>().ok());
245 if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
246 if major > 3 || (major == 3 && minor >= 9) {
250 panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version)
253 fn configure_cmake(builder: &Builder,
254 target: Interned<String>,
255 cfg: &mut cmake::Config,
256 building_dist_binaries: bool) {
257 if builder.config.ninja {
258 cfg.generator("Ninja");
261 .host(&builder.config.build);
263 let sanitize_cc = |cc: &Path| {
264 if target.contains("msvc") {
265 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
267 cc.as_os_str().to_owned()
271 // MSVC with CMake uses msbuild by default which doesn't respect these
272 // vars that we'd otherwise configure. In that case we just skip this
274 if target.contains("msvc") && !builder.config.ninja {
278 let cc = builder.cc(target);
279 let cxx = builder.cxx(target).unwrap();
281 // Handle msvc + ninja + ccache specially (this is what the bots use)
282 if target.contains("msvc") &&
283 builder.config.ninja &&
284 builder.config.ccache.is_some() {
285 let mut cc = env::current_exe().expect("failed to get cwd");
286 cc.set_file_name("sccache-plus-cl.exe");
288 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
289 .define("CMAKE_CXX_COMPILER", sanitize_cc(&cc));
290 cfg.env("SCCACHE_PATH",
291 builder.config.ccache.as_ref().unwrap())
292 .env("SCCACHE_TARGET", target);
294 // If ccache is configured we inform the build a little differently hwo
295 // to invoke ccache while also invoking our compilers.
296 } else if let Some(ref ccache) = builder.config.ccache {
297 cfg.define("CMAKE_C_COMPILER", ccache)
298 .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
299 .define("CMAKE_CXX_COMPILER", ccache)
300 .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
302 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
303 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
306 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
307 cfg.define("CMAKE_C_FLAGS", builder.cflags(target).join(" "));
308 let mut cxxflags = builder.cflags(target).join(" ");
309 if building_dist_binaries {
310 if builder.config.llvm_static_stdcpp && !target.contains("windows") {
311 cxxflags.push_str(" -static-libstdc++");
314 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
315 if let Some(ar) = builder.ar(target) {
316 if ar.is_absolute() {
317 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
318 // tries to resolve this path in the LLVM build directory.
319 cfg.define("CMAKE_AR", sanitize_cc(ar));
323 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
324 cfg.env("RUST_LOG", "sccache=warn");
328 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
330 pub target: Interned<String>,
334 type Output = PathBuf;
335 const ONLY_HOSTS: bool = true;
337 fn should_run(run: ShouldRun) -> ShouldRun {
338 run.path("src/tools/lld")
341 fn make_run(run: RunConfig) {
342 run.builder.ensure(Lld { target: run.target });
345 /// Compile LLVM for `target`.
346 fn run(self, builder: &Builder) -> PathBuf {
347 if builder.config.dry_run {
348 return PathBuf::from("lld-out-dir-test-gen");
350 let target = self.target;
352 let llvm_config = builder.ensure(Llvm {
357 let out_dir = builder.lld_out(target);
358 let done_stamp = out_dir.join("lld-finished-building");
359 if done_stamp.exists() {
363 let _folder = builder.fold_output(|| "lld");
364 builder.info(&format!("Building LLD for {}", target));
365 let _time = util::timeit(&builder);
366 t!(fs::create_dir_all(&out_dir));
368 let mut cfg = cmake::Config::new(builder.src.join("src/tools/lld"));
369 configure_cmake(builder, target, &mut cfg, true);
371 cfg.out_dir(&out_dir)
373 .define("LLVM_CONFIG_PATH", llvm_config)
374 .define("LLVM_INCLUDE_TESTS", "OFF");
378 t!(File::create(&done_stamp));
383 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
384 pub struct TestHelpers {
385 pub target: Interned<String>,
388 impl Step for TestHelpers {
391 fn should_run(run: ShouldRun) -> ShouldRun {
392 run.path("src/test/auxiliary/rust_test_helpers.c")
395 fn make_run(run: RunConfig) {
396 run.builder.ensure(TestHelpers { target: run.target })
399 /// Compiles the `rust_test_helpers.c` library which we used in various
400 /// `run-pass` test suites for ABI testing.
401 fn run(self, builder: &Builder) {
402 if builder.config.dry_run {
405 let target = self.target;
406 let dst = builder.test_helpers_out(target);
407 let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
408 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
412 let _folder = builder.fold_output(|| "build_test_helpers");
413 builder.info(&format!("Building test helpers"));
414 t!(fs::create_dir_all(&dst));
415 let mut cfg = cc::Build::new();
417 // We may have found various cross-compilers a little differently due to our
418 // extra configuration, so inform gcc of these compilers. Note, though, that
419 // on MSVC we still need gcc's detection of env vars (ugh).
420 if !target.contains("msvc") {
421 if let Some(ar) = builder.ar(target) {
424 cfg.compiler(builder.cc(target));
427 cfg.cargo_metadata(false)
430 .host(&builder.config.build)
434 .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
435 .compile("rust_test_helpers");
439 const OPENSSL_VERS: &'static str = "1.0.2n";
440 const OPENSSL_SHA256: &'static str =
441 "370babb75f278c39e0c50e8c4e7493bc0f18db6867478341a832a982fd15a8fe";
443 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
445 pub target: Interned<String>,
448 impl Step for Openssl {
451 fn should_run(run: ShouldRun) -> ShouldRun {
455 fn run(self, builder: &Builder) {
456 if builder.config.dry_run {
459 let target = self.target;
460 let out = match builder.openssl_dir(target) {
465 let stamp = out.join(".stamp");
466 let mut contents = String::new();
467 drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
468 if contents == OPENSSL_VERS {
471 t!(fs::create_dir_all(&out));
473 let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
474 let tarball = out.join(&name);
475 if !tarball.exists() {
476 let tmp = tarball.with_extension("tmp");
477 // originally from https://www.openssl.org/source/...
478 let url = format!("https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/{}",
480 let mut last_error = None;
482 let status = Command::new("curl")
484 .arg("-f") // make curl fail if the URL does not return HTTP 200
487 .expect("failed to spawn curl");
489 // Retry if download failed.
490 if !status.success() {
491 last_error = Some(status.to_string());
495 // Ensure the hash is correct.
496 let mut shasum = if target.contains("apple") ||
497 builder.config.build.contains("netbsd") {
498 let mut cmd = Command::new("shasum");
499 cmd.arg("-a").arg("256");
502 Command::new("sha256sum")
504 let output = output(&mut shasum.arg(&tmp));
505 let found = output.split_whitespace().next().unwrap();
507 // If the hash is wrong, probably the download is incomplete or S3 served an error
508 // page. In any case, retry.
509 if found != OPENSSL_SHA256 {
510 last_error = Some(format!(
511 "downloaded openssl sha256 different\n\
520 // Everything is fine, so exit the retry loop.
524 if let Some(error) = last_error {
525 panic!("failed to download openssl source: {}", error);
527 t!(fs::rename(&tmp, &tarball));
529 let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
530 let dst = builder.openssl_install_dir(target).unwrap();
531 drop(fs::remove_dir_all(&obj));
532 drop(fs::remove_dir_all(&dst));
533 builder.run(Command::new("tar").arg("zxf").arg(&tarball).current_dir(&out));
535 let mut configure = Command::new("perl");
536 configure.arg(obj.join("Configure"));
537 configure.arg(format!("--prefix={}", dst.display()));
538 configure.arg("no-dso");
539 configure.arg("no-ssl2");
540 configure.arg("no-ssl3");
542 let os = match &*target {
543 "aarch64-linux-android" => "linux-aarch64",
544 "aarch64-unknown-linux-gnu" => "linux-aarch64",
545 "aarch64-unknown-linux-musl" => "linux-aarch64",
546 "arm-linux-androideabi" => "android",
547 "arm-unknown-linux-gnueabi" => "linux-armv4",
548 "arm-unknown-linux-gnueabihf" => "linux-armv4",
549 "armv7-linux-androideabi" => "android-armv7",
550 "armv7-unknown-linux-gnueabihf" => "linux-armv4",
551 "i586-unknown-linux-gnu" => "linux-elf",
552 "i586-unknown-linux-musl" => "linux-elf",
553 "i686-apple-darwin" => "darwin-i386-cc",
554 "i686-linux-android" => "android-x86",
555 "i686-unknown-freebsd" => "BSD-x86-elf",
556 "i686-unknown-linux-gnu" => "linux-elf",
557 "i686-unknown-linux-musl" => "linux-elf",
558 "i686-unknown-netbsd" => "BSD-x86-elf",
559 "mips-unknown-linux-gnu" => "linux-mips32",
560 "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
561 "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
562 "mipsel-unknown-linux-gnu" => "linux-mips32",
563 "powerpc-unknown-linux-gnu" => "linux-ppc",
564 "powerpc-unknown-linux-gnuspe" => "linux-ppc",
565 "powerpc-unknown-netbsd" => "BSD-generic32",
566 "powerpc64-unknown-linux-gnu" => "linux-ppc64",
567 "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
568 "s390x-unknown-linux-gnu" => "linux64-s390x",
569 "sparc-unknown-linux-gnu" => "linux-sparcv9",
570 "sparc64-unknown-linux-gnu" => "linux64-sparcv9",
571 "sparc64-unknown-netbsd" => "BSD-sparc64",
572 "x86_64-apple-darwin" => "darwin64-x86_64-cc",
573 "x86_64-linux-android" => "linux-x86_64",
574 "x86_64-unknown-freebsd" => "BSD-x86_64",
575 "x86_64-unknown-dragonfly" => "BSD-x86_64",
576 "x86_64-unknown-linux-gnu" => "linux-x86_64",
577 "x86_64-unknown-linux-gnux32" => "linux-x32",
578 "x86_64-unknown-linux-musl" => "linux-x86_64",
579 "x86_64-unknown-netbsd" => "BSD-x86_64",
580 _ => panic!("don't know how to configure OpenSSL for {}", target),
583 configure.env("CC", builder.cc(target));
584 for flag in builder.cflags(target) {
587 // There is no specific os target for android aarch64 or x86_64,
588 // so we need to pass some extra cflags
589 if target == "aarch64-linux-android" || target == "x86_64-linux-android" {
590 configure.arg("-mandroid");
591 configure.arg("-fomit-frame-pointer");
593 if target == "sparc64-unknown-netbsd" {
594 // Need -m64 to get assembly generated correctly for sparc64.
595 configure.arg("-m64");
596 if builder.config.build.contains("netbsd") {
597 // Disable sparc64 asm on NetBSD builders, it uses
598 // m4(1)'s -B flag, which NetBSD m4 does not support.
599 configure.arg("no-asm");
603 // Non-PIE linker support was removed in Lollipop
604 // https://source.android.com/security/enhancements/enhancements50
605 if target == "i686-linux-android" {
606 configure.arg("no-asm");
608 configure.current_dir(&obj);
609 builder.info(&format!("Configuring openssl for {}", target));
610 builder.run_quiet(&mut configure);
611 builder.info(&format!("Building openssl for {}", target));
612 builder.run_quiet(Command::new("make").arg("-j1").current_dir(&obj));
613 builder.info(&format!("Installing openssl for {}", target));
614 builder.run_quiet(Command::new("make").arg("install").arg("-j1").current_dir(&obj));
616 let mut f = t!(File::create(&stamp));
617 t!(f.write_all(OPENSSL_VERS.as_bytes()));