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