]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
bb482813a23fe5791ad71e40c05e353d372799bc
[rust.git] / src / bootstrap / native.rs
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.
4 //
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.
10
11 //! Compilation of native dependencies like LLVM.
12 //!
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).
17 //!
18 //! LLVM and compiler-rt are essentially just wired up to everything else to
19 //! ensure that they're always in place if needed.
20
21 use std::env;
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;
27
28 use build_helper::output;
29 use cmake;
30 use cc;
31
32 use Build;
33 use util::{self, exe};
34 use build_helper::up_to_date;
35 use builder::{Builder, RunConfig, ShouldRun, Step};
36 use cache::Interned;
37
38 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
39 pub struct Llvm {
40     pub target: Interned<String>,
41     pub emscripten: bool,
42 }
43
44 impl Step for Llvm {
45     type Output = PathBuf; // path to llvm-config
46
47     const ONLY_HOSTS: bool = true;
48
49     fn should_run(run: ShouldRun) -> ShouldRun {
50         run.path("src/llvm").path("src/llvm-emscripten")
51     }
52
53     fn make_run(run: RunConfig) {
54         let emscripten = run.path.map(|p| {
55             p.ends_with("llvm-emscripten")
56         }).unwrap_or(false);
57         run.builder.ensure(Llvm {
58             target: run.target,
59             emscripten,
60         });
61     }
62
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;
68
69         // If we're using a custom LLVM bail out here, but we can only use a
70         // custom LLVM for the build triple.
71         if !self.emscripten {
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()
76                 }
77             }
78         }
79
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));
83
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");
87             (dir, config_dir)
88         } else {
89             (build.llvm_out(target),
90                 build.llvm_out(build.config.build).join("bin"))
91         };
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));
98
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
103             }
104         }
105
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));
111
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");
117         }
118
119         let profile = match (build.config.llvm_optimize, build.config.llvm_release_debuginfo) {
120             (false, _) => "Debug",
121             (true, false) => "Release",
122             (true, true) => "RelWithDebInfo",
123         };
124
125         // NOTE: remember to also update `config.toml.example` when changing the
126         // defaults!
127         let llvm_targets = if self.emscripten {
128             "JSBackend"
129         } else {
130             match build.config.llvm_targets {
131                 Some(ref s) => s,
132                 None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;MSP430;Sparc;NVPTX;Hexagon",
133             }
134         };
135
136         let llvm_exp_targets = if self.emscripten {
137             ""
138         } else {
139             &build.config.llvm_experimental_targets[..]
140         };
141
142         let assertions = if build.config.llvm_assertions {"ON"} else {"OFF"};
143
144         cfg.target(&target)
145            .host(&build.build)
146            .out_dir(&out_dir)
147            .profile(profile)
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_OCAML_INSTALL_PATH", "usr/lib/ocaml")
159            .define("LLVM_PARALLEL_COMPILE_JOBS", build.jobs().to_string())
160            .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
161            .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
162
163
164         // This setting makes the LLVM tools link to the dynamic LLVM library,
165         // which saves both memory during parallel links and overall disk space
166         // for the tools.  We don't distribute any of those tools, so this is
167         // just a local concern.  However, it doesn't work well everywhere.
168         if target.contains("linux-gnu") || target.contains("apple-darwin") {
169            cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
170         }
171
172         if target.contains("msvc") {
173             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
174             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
175             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
176             cfg.static_crt(true);
177         }
178
179         if target.starts_with("i686") {
180             cfg.define("LLVM_BUILD_32_BITS", "ON");
181         }
182
183         if let Some(num_linkers) = build.config.llvm_link_jobs {
184             if num_linkers > 0 {
185                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
186             }
187         }
188
189         // http://llvm.org/docs/HowToCrossCompileLLVM.html
190         if target != build.build {
191             builder.ensure(Llvm {
192                 target: build.build,
193                 emscripten: false,
194             });
195             // FIXME: if the llvm root for the build triple is overridden then we
196             //        should use llvm-tblgen from there, also should verify that it
197             //        actually exists most of the time in normal installs of LLVM.
198             let host = build.llvm_out(build.build).join("bin/llvm-tblgen");
199             cfg.define("CMAKE_CROSSCOMPILING", "True")
200                .define("LLVM_TABLEGEN", &host);
201
202             if target.contains("netbsd") {
203                cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
204             } else if target.contains("freebsd") {
205                cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
206             }
207
208             cfg.define("LLVM_NATIVE_BUILD", build.llvm_out(build.build).join("build"));
209         }
210
211         let sanitize_cc = |cc: &Path| {
212             if target.contains("msvc") {
213                 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
214             } else {
215                 cc.as_os_str().to_owned()
216             }
217         };
218
219         let configure_compilers = |cfg: &mut cmake::Config| {
220             // MSVC with CMake uses msbuild by default which doesn't respect these
221             // vars that we'd otherwise configure. In that case we just skip this
222             // entirely.
223             if target.contains("msvc") && !build.config.ninja {
224                 return
225             }
226
227             let cc = build.cc(target);
228             let cxx = build.cxx(target).unwrap();
229
230             // Handle msvc + ninja + ccache specially (this is what the bots use)
231             if target.contains("msvc") &&
232                build.config.ninja &&
233                build.config.ccache.is_some() {
234                 let mut cc = env::current_exe().expect("failed to get cwd");
235                 cc.set_file_name("sccache-plus-cl.exe");
236
237                cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
238                   .define("CMAKE_CXX_COMPILER", sanitize_cc(&cc));
239                cfg.env("SCCACHE_PATH",
240                        build.config.ccache.as_ref().unwrap())
241                   .env("SCCACHE_TARGET", target);
242
243             // If ccache is configured we inform the build a little differently hwo
244             // to invoke ccache while also invoking our compilers.
245             } else if let Some(ref ccache) = build.config.ccache {
246                cfg.define("CMAKE_C_COMPILER", ccache)
247                   .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
248                   .define("CMAKE_CXX_COMPILER", ccache)
249                   .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
250             } else {
251                cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
252                   .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
253             }
254
255             cfg.build_arg("-j").build_arg(build.jobs().to_string());
256             cfg.define("CMAKE_C_FLAGS", build.cflags(target).join(" "));
257             cfg.define("CMAKE_CXX_FLAGS", build.cflags(target).join(" "));
258             if let Some(ar) = build.ar(target) {
259                 if ar.is_absolute() {
260                     // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
261                     // tries to resolve this path in the LLVM build directory.
262                     cfg.define("CMAKE_AR", sanitize_cc(ar));
263                 }
264             }
265         };
266
267         configure_compilers(&mut cfg);
268
269         if env::var_os("SCCACHE_ERROR_LOG").is_some() {
270             cfg.env("RUST_LOG", "sccache=warn");
271         }
272
273         // FIXME: we don't actually need to build all LLVM tools and all LLVM
274         //        libraries here, e.g. we just want a few components and a few
275         //        tools. Figure out how to filter them down and only build the right
276         //        tools and libs on all platforms.
277         cfg.build();
278
279         t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
280
281         build_llvm_config
282     }
283 }
284
285 fn check_llvm_version(build: &Build, llvm_config: &Path) {
286     if !build.config.llvm_version_check {
287         return
288     }
289
290     let mut cmd = Command::new(llvm_config);
291     let version = output(cmd.arg("--version"));
292     let mut parts = version.split('.').take(2)
293         .filter_map(|s| s.parse::<u32>().ok());
294     if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
295         if major > 3 || (major == 3 && minor >= 9) {
296             return
297         }
298     }
299     panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version)
300 }
301
302 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
303 pub struct TestHelpers {
304     pub target: Interned<String>,
305 }
306
307 impl Step for TestHelpers {
308     type Output = ();
309
310     fn should_run(run: ShouldRun) -> ShouldRun {
311         run.path("src/rt/rust_test_helpers.c")
312     }
313
314     fn make_run(run: RunConfig) {
315         run.builder.ensure(TestHelpers { target: run.target })
316     }
317
318     /// Compiles the `rust_test_helpers.c` library which we used in various
319     /// `run-pass` test suites for ABI testing.
320     fn run(self, builder: &Builder) {
321         let build = builder.build;
322         let target = self.target;
323         let dst = build.test_helpers_out(target);
324         let src = build.src.join("src/rt/rust_test_helpers.c");
325         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
326             return
327         }
328
329         let _folder = build.fold_output(|| "build_test_helpers");
330         println!("Building test helpers");
331         t!(fs::create_dir_all(&dst));
332         let mut cfg = cc::Build::new();
333
334         // We may have found various cross-compilers a little differently due to our
335         // extra configuration, so inform gcc of these compilers. Note, though, that
336         // on MSVC we still need gcc's detection of env vars (ugh).
337         if !target.contains("msvc") {
338             if let Some(ar) = build.ar(target) {
339                 cfg.archiver(ar);
340             }
341             cfg.compiler(build.cc(target));
342         }
343
344         cfg.cargo_metadata(false)
345            .out_dir(&dst)
346            .target(&target)
347            .host(&build.build)
348            .opt_level(0)
349            .warnings(false)
350            .debug(false)
351            .file(build.src.join("src/rt/rust_test_helpers.c"))
352            .compile("rust_test_helpers");
353     }
354 }
355
356 const OPENSSL_VERS: &'static str = "1.0.2m";
357 const OPENSSL_SHA256: &'static str =
358     "8c6ff15ec6b319b50788f42c7abc2890c08ba5a1cdcd3810eb9092deada37b0f";
359
360 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
361 pub struct Openssl {
362     pub target: Interned<String>,
363 }
364
365 impl Step for Openssl {
366     type Output = ();
367
368     fn should_run(run: ShouldRun) -> ShouldRun {
369         run.never()
370     }
371
372     fn run(self, builder: &Builder) {
373         let build = builder.build;
374         let target = self.target;
375         let out = match build.openssl_dir(target) {
376             Some(dir) => dir,
377             None => return,
378         };
379
380         let stamp = out.join(".stamp");
381         let mut contents = String::new();
382         drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
383         if contents == OPENSSL_VERS {
384             return
385         }
386         t!(fs::create_dir_all(&out));
387
388         let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
389         let tarball = out.join(&name);
390         if !tarball.exists() {
391             let tmp = tarball.with_extension("tmp");
392             // originally from https://www.openssl.org/source/...
393             let url = format!("https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/{}",
394                               name);
395             let mut last_error = None;
396             for _ in 0..3 {
397                 let status = Command::new("curl")
398                                 .arg("-o").arg(&tmp)
399                                 .arg("-f")  // make curl fail if the URL does not return HTTP 200
400                                 .arg(&url)
401                                 .status()
402                                 .expect("failed to spawn curl");
403
404                 // Retry if download failed.
405                 if !status.success() {
406                     last_error = Some(status.to_string());
407                     continue;
408                 }
409
410                 // Ensure the hash is correct.
411                 let mut shasum = if target.contains("apple") || build.build.contains("netbsd") {
412                     let mut cmd = Command::new("shasum");
413                     cmd.arg("-a").arg("256");
414                     cmd
415                 } else {
416                     Command::new("sha256sum")
417                 };
418                 let output = output(&mut shasum.arg(&tmp));
419                 let found = output.split_whitespace().next().unwrap();
420
421                 // If the hash is wrong, probably the download is incomplete or S3 served an error
422                 // page. In any case, retry.
423                 if found != OPENSSL_SHA256 {
424                     last_error = Some(format!(
425                         "downloaded openssl sha256 different\n\
426                          expected: {}\n\
427                          found:    {}\n",
428                         OPENSSL_SHA256,
429                         found
430                     ));
431                     continue;
432                 }
433
434                 // Everything is fine, so exit the retry loop.
435                 last_error = None;
436                 break;
437             }
438             if let Some(error) = last_error {
439                 panic!("failed to download openssl source: {}", error);
440             }
441             t!(fs::rename(&tmp, &tarball));
442         }
443         let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
444         let dst = build.openssl_install_dir(target).unwrap();
445         drop(fs::remove_dir_all(&obj));
446         drop(fs::remove_dir_all(&dst));
447         build.run(Command::new("tar").arg("zxf").arg(&tarball).current_dir(&out));
448
449         let mut configure = Command::new("perl");
450         configure.arg(obj.join("Configure"));
451         configure.arg(format!("--prefix={}", dst.display()));
452         configure.arg("no-dso");
453         configure.arg("no-ssl2");
454         configure.arg("no-ssl3");
455
456         let os = match &*target {
457             "aarch64-linux-android" => "linux-aarch64",
458             "aarch64-unknown-linux-gnu" => "linux-aarch64",
459             "aarch64-unknown-linux-musl" => "linux-aarch64",
460             "arm-linux-androideabi" => "android",
461             "arm-unknown-linux-gnueabi" => "linux-armv4",
462             "arm-unknown-linux-gnueabihf" => "linux-armv4",
463             "armv7-linux-androideabi" => "android-armv7",
464             "armv7-unknown-linux-gnueabihf" => "linux-armv4",
465             "i586-unknown-linux-gnu" => "linux-elf",
466             "i586-unknown-linux-musl" => "linux-elf",
467             "i686-apple-darwin" => "darwin-i386-cc",
468             "i686-linux-android" => "android-x86",
469             "i686-unknown-freebsd" => "BSD-x86-elf",
470             "i686-unknown-linux-gnu" => "linux-elf",
471             "i686-unknown-linux-musl" => "linux-elf",
472             "i686-unknown-netbsd" => "BSD-x86-elf",
473             "mips-unknown-linux-gnu" => "linux-mips32",
474             "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
475             "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
476             "mipsel-unknown-linux-gnu" => "linux-mips32",
477             "powerpc-unknown-linux-gnu" => "linux-ppc",
478             "powerpc64-unknown-linux-gnu" => "linux-ppc64",
479             "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
480             "s390x-unknown-linux-gnu" => "linux64-s390x",
481             "sparc64-unknown-linux-gnu" => "linux64-sparcv9",
482             "sparc64-unknown-netbsd" => "BSD-sparc64",
483             "x86_64-apple-darwin" => "darwin64-x86_64-cc",
484             "x86_64-linux-android" => "linux-x86_64",
485             "x86_64-unknown-freebsd" => "BSD-x86_64",
486             "x86_64-unknown-dragonfly" => "BSD-x86_64",
487             "x86_64-unknown-linux-gnu" => "linux-x86_64",
488             "x86_64-unknown-linux-musl" => "linux-x86_64",
489             "x86_64-unknown-netbsd" => "BSD-x86_64",
490             _ => panic!("don't know how to configure OpenSSL for {}", target),
491         };
492         configure.arg(os);
493         configure.env("CC", build.cc(target));
494         for flag in build.cflags(target) {
495             configure.arg(flag);
496         }
497         // There is no specific os target for android aarch64 or x86_64,
498         // so we need to pass some extra cflags
499         if target == "aarch64-linux-android" || target == "x86_64-linux-android" {
500             configure.arg("-mandroid");
501             configure.arg("-fomit-frame-pointer");
502         }
503         if target == "sparc64-unknown-netbsd" {
504             // Need -m64 to get assembly generated correctly for sparc64.
505             configure.arg("-m64");
506             if build.build.contains("netbsd") {
507                 // Disable sparc64 asm on NetBSD builders, it uses
508                 // m4(1)'s -B flag, which NetBSD m4 does not support.
509                 configure.arg("no-asm");
510             }
511         }
512         // Make PIE binaries
513         // Non-PIE linker support was removed in Lollipop
514         // https://source.android.com/security/enhancements/enhancements50
515         if target == "i686-linux-android" {
516             configure.arg("no-asm");
517         }
518         configure.current_dir(&obj);
519         println!("Configuring openssl for {}", target);
520         build.run_quiet(&mut configure);
521         println!("Building openssl for {}", target);
522         build.run_quiet(Command::new("make").arg("-j1").current_dir(&obj));
523         println!("Installing openssl for {}", target);
524         build.run_quiet(Command::new("make").arg("install").current_dir(&obj));
525
526         let mut f = t!(File::create(&stamp));
527         t!(f.write_all(OPENSSL_VERS.as_bytes()));
528     }
529 }