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