]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Change code to work with the new system
[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 thie
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;
26 use std::process::Command;
27
28 use build_helper::output;
29 use cmake;
30 use gcc;
31
32 use Build;
33 use util;
34 use build_helper::up_to_date;
35
36 // rules.build("llvm", "src/llvm")
37 //      .host(true)
38 //      .dep(move |s| {
39 //          if s.target == build.build {
40 //              Step::noop()
41 //          } else {
42 //              s.target(&build.build)
43 //          }
44 //      })
45 //      .run(move |s| native::llvm(build, s.target));
46
47 #[derive(Serialize)]
48 pub struct Llvm<'a> {
49     pub target: &'a str,
50 }
51
52 impl<'a> Step<'a> for Llvm<'a> {
53     type Output = ();
54     const ONLY_HOSTS: bool = true;
55
56     /// Compile LLVM for `target`.
57     fn run(self, builder: &Builder) {
58         let build = builder.build;
59         let target = self.target;
60         // If we're using a custom LLVM bail out here, but we can only use a
61         // custom LLVM for the build triple.
62         if let Some(config) = build.config.target_config.get(target) {
63             if let Some(ref s) = config.llvm_config {
64                 return check_llvm_version(build, s);
65             }
66         }
67
68         let rebuild_trigger = build.src.join("src/rustllvm/llvm-rebuild-trigger");
69         let mut rebuild_trigger_contents = String::new();
70         t!(t!(File::open(&rebuild_trigger)).read_to_string(&mut rebuild_trigger_contents));
71
72         let out_dir = build.llvm_out(target);
73         let done_stamp = out_dir.join("llvm-finished-building");
74         if done_stamp.exists() {
75             let mut done_contents = String::new();
76             t!(t!(File::open(&done_stamp)).read_to_string(&mut done_contents));
77
78             // If LLVM was already built previously and contents of the rebuild-trigger file
79             // didn't change from the previous build, then no action is required.
80             if done_contents == rebuild_trigger_contents {
81                 return
82             }
83         }
84         if build.config.llvm_clean_rebuild {
85             drop(fs::remove_dir_all(&out_dir));
86         }
87
88         let _folder = build.fold_output(|| "llvm");
89         println!("Building LLVM for {}", target);
90         let _time = util::timeit();
91         t!(fs::create_dir_all(&out_dir));
92
93         // http://llvm.org/docs/CMake.html
94         let mut cfg = cmake::Config::new(build.src.join("src/llvm"));
95         if build.config.ninja {
96             cfg.generator("Ninja");
97         }
98
99         let profile = match (build.config.llvm_optimize, build.config.llvm_release_debuginfo) {
100             (false, _) => "Debug",
101             (true, false) => "Release",
102             (true, true) => "RelWithDebInfo",
103         };
104
105         // NOTE: remember to also update `config.toml.example` when changing the defaults!
106         let llvm_targets = match build.config.llvm_targets {
107             Some(ref s) => s,
108             None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;JSBackend;MSP430;Sparc;NVPTX;Hexagon",
109         };
110
111         let llvm_exp_targets = match build.config.llvm_experimental_targets {
112             Some(ref s) => s,
113             None => "",
114         };
115
116         let assertions = if build.config.llvm_assertions {"ON"} else {"OFF"};
117
118         cfg.target(target)
119            .host(&build.build)
120            .out_dir(&out_dir)
121            .profile(profile)
122            .define("LLVM_ENABLE_ASSERTIONS", assertions)
123            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
124            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
125            .define("LLVM_INCLUDE_EXAMPLES", "OFF")
126            .define("LLVM_INCLUDE_TESTS", "OFF")
127            .define("LLVM_INCLUDE_DOCS", "OFF")
128            .define("LLVM_ENABLE_ZLIB", "OFF")
129            .define("WITH_POLLY", "OFF")
130            .define("LLVM_ENABLE_TERMINFO", "OFF")
131            .define("LLVM_ENABLE_LIBEDIT", "OFF")
132            .define("LLVM_PARALLEL_COMPILE_JOBS", build.jobs().to_string())
133            .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
134            .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
135
136         if target.contains("msvc") {
137             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
138             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
139             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
140             cfg.static_crt(true);
141         }
142
143         if target.starts_with("i686") {
144             cfg.define("LLVM_BUILD_32_BITS", "ON");
145         }
146
147         if let Some(num_linkers) = build.config.llvm_link_jobs {
148             if num_linkers > 0 {
149                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
150             }
151         }
152
153         // http://llvm.org/docs/HowToCrossCompileLLVM.html
154         if target != build.build {
155             builder.ensure(Llvm { target: &build.build });
156             // FIXME: if the llvm root for the build triple is overridden then we
157             //        should use llvm-tblgen from there, also should verify that it
158             //        actually exists most of the time in normal installs of LLVM.
159             let host = build.llvm_out(&build.build).join("bin/llvm-tblgen");
160             cfg.define("CMAKE_CROSSCOMPILING", "True")
161                .define("LLVM_TABLEGEN", &host);
162         }
163
164         let sanitize_cc = |cc: &Path| {
165             if target.contains("msvc") {
166                 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
167             } else {
168                 cc.as_os_str().to_owned()
169             }
170         };
171
172         let configure_compilers = |cfg: &mut cmake::Config| {
173             // MSVC with CMake uses msbuild by default which doesn't respect these
174             // vars that we'd otherwise configure. In that case we just skip this
175             // entirely.
176             if target.contains("msvc") && !build.config.ninja {
177                 return
178             }
179
180             let cc = build.cc(target);
181             let cxx = build.cxx(target).unwrap();
182
183             // Handle msvc + ninja + ccache specially (this is what the bots use)
184             if target.contains("msvc") &&
185                build.config.ninja &&
186                build.config.ccache.is_some() {
187                 let mut cc = env::current_exe().expect("failed to get cwd");
188                 cc.set_file_name("sccache-plus-cl.exe");
189
190                cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc))
191                   .define("CMAKE_CXX_COMPILER", sanitize_cc(&cc));
192                cfg.env("SCCACHE_PATH",
193                        build.config.ccache.as_ref().unwrap())
194                   .env("SCCACHE_TARGET", target);
195
196             // If ccache is configured we inform the build a little differently hwo
197             // to invoke ccache while also invoking our compilers.
198             } else if let Some(ref ccache) = build.config.ccache {
199                cfg.define("CMAKE_C_COMPILER", ccache)
200                   .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
201                   .define("CMAKE_CXX_COMPILER", ccache)
202                   .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
203             } else {
204                cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
205                   .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
206             }
207
208             cfg.build_arg("-j").build_arg(build.jobs().to_string());
209             cfg.define("CMAKE_C_FLAGS", build.cflags(target).join(" "));
210             cfg.define("CMAKE_CXX_FLAGS", build.cflags(target).join(" "));
211         };
212
213         configure_compilers(&mut cfg);
214
215         if env::var_os("SCCACHE_ERROR_LOG").is_some() {
216             cfg.env("RUST_LOG", "sccache=warn");
217         }
218
219         // FIXME: we don't actually need to build all LLVM tools and all LLVM
220         //        libraries here, e.g. we just want a few components and a few
221         //        tools. Figure out how to filter them down and only build the right
222         //        tools and libs on all platforms.
223         cfg.build();
224
225         t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
226     }
227 }
228
229 fn check_llvm_version(build: &Build, llvm_config: &Path) {
230     if !build.config.llvm_version_check {
231         return
232     }
233
234     let mut cmd = Command::new(llvm_config);
235     let version = output(cmd.arg("--version"));
236     if version.starts_with("3.5") || version.starts_with("3.6") ||
237        version.starts_with("3.7") {
238         return
239     }
240     panic!("\n\nbad LLVM version: {}, need >=3.5\n\n", version)
241 }
242
243 //rules.build("test-helpers", "src/rt/rust_test_helpers.c")
244 //     .run(move |s| native::test_helpers(build, s.target));
245
246 #[derive(Serialize)]
247 pub struct TestHelpers<'a> {
248     target: &'a str,
249 }
250
251 impl<'a> Step<'a> for TestHelpers<'a> {
252     type Output = ();
253
254     fn should_run(_builder: &Builder, path: &Path) -> bool {
255         path.ends_with("src/rt/rust_test_helpers.c")
256     }
257
258     fn make_run(builder: &Builder, _path: Option<&Path>, _host: &str, target: &str) {
259         builder.ensure(TestHelpers { target })
260     }
261
262     /// Compiles the `rust_test_helpers.c` library which we used in various
263     /// `run-pass` test suites for ABI testing.
264     fn run(self, builder: &Builder) {
265         let build = builder.build;
266         let target = self.target;
267         let dst = build.test_helpers_out(target);
268         let src = build.src.join("src/rt/rust_test_helpers.c");
269         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
270             return
271         }
272
273         let _folder = build.fold_output(|| "build_test_helpers");
274         println!("Building test helpers");
275         t!(fs::create_dir_all(&dst));
276         let mut cfg = gcc::Config::new();
277
278         // We may have found various cross-compilers a little differently due to our
279         // extra configuration, so inform gcc of these compilers. Note, though, that
280         // on MSVC we still need gcc's detection of env vars (ugh).
281         if !target.contains("msvc") {
282             if let Some(ar) = build.ar(target) {
283                 cfg.archiver(ar);
284             }
285             cfg.compiler(build.cc(target));
286         }
287
288         cfg.cargo_metadata(false)
289            .out_dir(&dst)
290            .target(target)
291            .host(&build.build)
292            .opt_level(0)
293            .debug(false)
294            .file(build.src.join("src/rt/rust_test_helpers.c"))
295            .compile("librust_test_helpers.a");
296     }
297 }
298
299 const OPENSSL_VERS: &'static str = "1.0.2k";
300 const OPENSSL_SHA256: &'static str =
301     "6b3977c61f2aedf0f96367dcfb5c6e578cf37e7b8d913b4ecb6643c3cb88d8c0";
302
303 //rules.build("openssl", "path/to/nowhere")
304 //     .run(move |s| native::openssl(build, s.target));
305
306 #[derive(Serialize)]
307 pub struct Openssl<'a> {
308     pub target: &'a str,
309 }
310
311 impl<'a> Step<'a> for Openssl<'a> {
312     type Output = ();
313
314     fn should_run(_builder: &Builder, _path: &Path) -> bool {
315         false
316     }
317
318     fn run(self, builder: &Builder) {
319         let build = bulder.build;
320         let target = self.target;
321         let out = match build.openssl_dir(target) {
322             Some(dir) => dir,
323             None => return,
324         };
325
326         let stamp = out.join(".stamp");
327         let mut contents = String::new();
328         drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
329         if contents == OPENSSL_VERS {
330             return
331         }
332         t!(fs::create_dir_all(&out));
333
334         let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
335         let tarball = out.join(&name);
336         if !tarball.exists() {
337             let tmp = tarball.with_extension("tmp");
338             // originally from https://www.openssl.org/source/...
339             let url = format!("https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror/{}",
340                               name);
341             let mut ok = false;
342             for _ in 0..3 {
343                 let status = Command::new("curl")
344                                 .arg("-o").arg(&tmp)
345                                 .arg(&url)
346                                 .status()
347                                 .expect("failed to spawn curl");
348                 if status.success() {
349                     ok = true;
350                     break
351                 }
352             }
353             if !ok {
354                 panic!("failed to download openssl source")
355             }
356             let mut shasum = if target.contains("apple") {
357                 let mut cmd = Command::new("shasum");
358                 cmd.arg("-a").arg("256");
359                 cmd
360             } else {
361                 Command::new("sha256sum")
362             };
363             let output = output(&mut shasum.arg(&tmp));
364             let found = output.split_whitespace().next().unwrap();
365             if found != OPENSSL_SHA256 {
366                 panic!("downloaded openssl sha256 different\n\
367                         expected: {}\n\
368                         found:    {}\n", OPENSSL_SHA256, found);
369             }
370             t!(fs::rename(&tmp, &tarball));
371         }
372         let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
373         let dst = build.openssl_install_dir(target).unwrap();
374         drop(fs::remove_dir_all(&obj));
375         drop(fs::remove_dir_all(&dst));
376         build.run(Command::new("tar").arg("xf").arg(&tarball).current_dir(&out));
377
378         let mut configure = Command::new(obj.join("Configure"));
379         configure.arg(format!("--prefix={}", dst.display()));
380         configure.arg("no-dso");
381         configure.arg("no-ssl2");
382         configure.arg("no-ssl3");
383
384         let os = match target {
385             "aarch64-linux-android" => "linux-aarch64",
386             "aarch64-unknown-linux-gnu" => "linux-aarch64",
387             "arm-linux-androideabi" => "android",
388             "arm-unknown-linux-gnueabi" => "linux-armv4",
389             "arm-unknown-linux-gnueabihf" => "linux-armv4",
390             "armv7-linux-androideabi" => "android-armv7",
391             "armv7-unknown-linux-gnueabihf" => "linux-armv4",
392             "i686-apple-darwin" => "darwin-i386-cc",
393             "i686-linux-android" => "android-x86",
394             "i686-unknown-freebsd" => "BSD-x86-elf",
395             "i686-unknown-linux-gnu" => "linux-elf",
396             "i686-unknown-linux-musl" => "linux-elf",
397             "mips-unknown-linux-gnu" => "linux-mips32",
398             "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
399             "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
400             "mipsel-unknown-linux-gnu" => "linux-mips32",
401             "powerpc-unknown-linux-gnu" => "linux-ppc",
402             "powerpc64-unknown-linux-gnu" => "linux-ppc64",
403             "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
404             "s390x-unknown-linux-gnu" => "linux64-s390x",
405             "x86_64-apple-darwin" => "darwin64-x86_64-cc",
406             "x86_64-linux-android" => "linux-x86_64",
407             "x86_64-unknown-freebsd" => "BSD-x86_64",
408             "x86_64-unknown-linux-gnu" => "linux-x86_64",
409             "x86_64-unknown-linux-musl" => "linux-x86_64",
410             "x86_64-unknown-netbsd" => "BSD-x86_64",
411             _ => panic!("don't know how to configure OpenSSL for {}", target),
412         };
413         configure.arg(os);
414         configure.env("CC", build.cc(target));
415         for flag in build.cflags(target) {
416             configure.arg(flag);
417         }
418         // There is no specific os target for android aarch64 or x86_64,
419         // so we need to pass some extra cflags
420         if target == "aarch64-linux-android" || target == "x86_64-linux-android" {
421             configure.arg("-mandroid");
422             configure.arg("-fomit-frame-pointer");
423         }
424         // Make PIE binaries
425         // Non-PIE linker support was removed in Lollipop
426         // https://source.android.com/security/enhancements/enhancements50
427         if target == "i686-linux-android" {
428             configure.arg("no-asm");
429         }
430         configure.current_dir(&obj);
431         println!("Configuring openssl for {}", target);
432         build.run_quiet(&mut configure);
433         println!("Building openssl for {}", target);
434         build.run_quiet(Command::new("make").arg("-j1").current_dir(&obj));
435         println!("Installing openssl for {}", target);
436         build.run_quiet(Command::new("make").arg("install").current_dir(&obj));
437
438         let mut f = t!(File::create(&stamp));
439         t!(f.write_all(OPENSSL_VERS.as_bytes()));
440     }
441 }