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