]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[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::fs::{self, File};
22 use std::io::{Read, Write};
23 use std::path::Path;
24 use std::process::Command;
25
26 use build_helper::output;
27 use cmake;
28 use gcc;
29
30 use Build;
31 use util;
32 use build_helper::up_to_date;
33
34 /// Compile LLVM for `target`.
35 pub fn llvm(build: &Build, target: &str) {
36     // If we're using a custom LLVM bail out here, but we can only use a
37     // custom LLVM for the build triple.
38     if let Some(config) = build.config.target_config.get(target) {
39         if let Some(ref s) = config.llvm_config {
40             return check_llvm_version(build, s);
41         }
42     }
43
44     let rebuild_trigger = build.src.join("src/rustllvm/llvm-rebuild-trigger");
45     let mut rebuild_trigger_contents = String::new();
46     t!(t!(File::open(&rebuild_trigger)).read_to_string(&mut rebuild_trigger_contents));
47
48     let out_dir = build.llvm_out(target);
49     let done_stamp = out_dir.join("llvm-finished-building");
50     if done_stamp.exists() {
51         let mut done_contents = String::new();
52         t!(t!(File::open(&done_stamp)).read_to_string(&mut done_contents));
53
54         // If LLVM was already built previously and contents of the rebuild-trigger file
55         // didn't change from the previous build, then no action is required.
56         if done_contents == rebuild_trigger_contents {
57             return
58         }
59     }
60     if build.config.llvm_clean_rebuild {
61         drop(fs::remove_dir_all(&out_dir));
62     }
63
64     println!("Building LLVM for {}", target);
65     let _time = util::timeit();
66     t!(fs::create_dir_all(&out_dir));
67
68     // http://llvm.org/docs/CMake.html
69     let mut cfg = cmake::Config::new(build.src.join("src/llvm"));
70     if build.config.ninja {
71         cfg.generator("Ninja");
72     }
73
74     let profile = match (build.config.llvm_optimize, build.config.llvm_release_debuginfo) {
75         (false, _) => "Debug",
76         (true, false) => "Release",
77         (true, true) => "RelWithDebInfo",
78     };
79
80     // NOTE: remember to also update `config.toml.example` when changing the defaults!
81     let llvm_targets = match build.config.llvm_targets {
82         Some(ref s) => s,
83         None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;JSBackend;MSP430;Sparc;NVPTX",
84     };
85
86     let assertions = if build.config.llvm_assertions {"ON"} else {"OFF"};
87
88     cfg.target(target)
89        .host(&build.config.build)
90        .out_dir(&out_dir)
91        .profile(profile)
92        .define("LLVM_ENABLE_ASSERTIONS", assertions)
93        .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
94        .define("LLVM_INCLUDE_EXAMPLES", "OFF")
95        .define("LLVM_INCLUDE_TESTS", "OFF")
96        .define("LLVM_INCLUDE_DOCS", "OFF")
97        .define("LLVM_ENABLE_ZLIB", "OFF")
98        .define("WITH_POLLY", "OFF")
99        .define("LLVM_ENABLE_TERMINFO", "OFF")
100        .define("LLVM_ENABLE_LIBEDIT", "OFF")
101        .define("LLVM_PARALLEL_COMPILE_JOBS", build.jobs().to_string())
102        .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
103        .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
104
105     if target.contains("msvc") {
106         cfg.define("LLVM_USE_CRT_DEBUG", "MT");
107         cfg.define("LLVM_USE_CRT_RELEASE", "MT");
108         cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
109     }
110
111     if target.starts_with("i686") {
112         cfg.define("LLVM_BUILD_32_BITS", "ON");
113     }
114
115     if let Some(num_linkers) = build.config.llvm_link_jobs {
116         if num_linkers > 0 {
117             cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
118         }
119     }
120
121     // http://llvm.org/docs/HowToCrossCompileLLVM.html
122     if target != build.config.build {
123         // FIXME: if the llvm root for the build triple is overridden then we
124         //        should use llvm-tblgen from there, also should verify that it
125         //        actually exists most of the time in normal installs of LLVM.
126         let host = build.llvm_out(&build.config.build).join("bin/llvm-tblgen");
127         cfg.define("CMAKE_CROSSCOMPILING", "True")
128            .define("LLVM_TABLEGEN", &host);
129     }
130
131     // MSVC handles compiler business itself
132     if !target.contains("msvc") {
133         if let Some(ref ccache) = build.config.ccache {
134            cfg.define("CMAKE_C_COMPILER", ccache)
135               .define("CMAKE_C_COMPILER_ARG1", build.cc(target))
136               .define("CMAKE_CXX_COMPILER", ccache)
137               .define("CMAKE_CXX_COMPILER_ARG1", build.cxx(target));
138         } else {
139            cfg.define("CMAKE_C_COMPILER", build.cc(target))
140               .define("CMAKE_CXX_COMPILER", build.cxx(target));
141         }
142         cfg.build_arg("-j").build_arg(build.jobs().to_string());
143
144         cfg.define("CMAKE_C_FLAGS", build.cflags(target).join(" "));
145         cfg.define("CMAKE_CXX_FLAGS", build.cflags(target).join(" "));
146     }
147
148     // FIXME: we don't actually need to build all LLVM tools and all LLVM
149     //        libraries here, e.g. we just want a few components and a few
150     //        tools. Figure out how to filter them down and only build the right
151     //        tools and libs on all platforms.
152     cfg.build();
153
154     t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
155 }
156
157 fn check_llvm_version(build: &Build, llvm_config: &Path) {
158     if !build.config.llvm_version_check {
159         return
160     }
161
162     let mut cmd = Command::new(llvm_config);
163     let version = output(cmd.arg("--version"));
164     if version.starts_with("3.5") || version.starts_with("3.6") ||
165        version.starts_with("3.7") {
166         return
167     }
168     panic!("\n\nbad LLVM version: {}, need >=3.5\n\n", version)
169 }
170
171 /// Compiles the `rust_test_helpers.c` library which we used in various
172 /// `run-pass` test suites for ABI testing.
173 pub fn test_helpers(build: &Build, target: &str) {
174     let dst = build.test_helpers_out(target);
175     let src = build.src.join("src/rt/rust_test_helpers.c");
176     if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
177         return
178     }
179
180     println!("Building test helpers");
181     t!(fs::create_dir_all(&dst));
182     let mut cfg = gcc::Config::new();
183
184     // We may have found various cross-compilers a little differently due to our
185     // extra configuration, so inform gcc of these compilers. Note, though, that
186     // on MSVC we still need gcc's detection of env vars (ugh).
187     if !target.contains("msvc") {
188         if let Some(ar) = build.ar(target) {
189             cfg.archiver(ar);
190         }
191         cfg.compiler(build.cc(target));
192     }
193
194     cfg.cargo_metadata(false)
195        .out_dir(&dst)
196        .target(target)
197        .host(&build.config.build)
198        .opt_level(0)
199        .debug(false)
200        .file(build.src.join("src/rt/rust_test_helpers.c"))
201        .compile("librust_test_helpers.a");
202 }
203 const OPENSSL_VERS: &'static str = "1.0.2k";
204 const OPENSSL_SHA256: &'static str =
205     "6b3977c61f2aedf0f96367dcfb5c6e578cf37e7b8d913b4ecb6643c3cb88d8c0";
206
207 pub fn openssl(build: &Build, target: &str) {
208     let out = match build.openssl_dir(target) {
209         Some(dir) => dir,
210         None => return,
211     };
212
213     let stamp = out.join(".stamp");
214     let mut contents = String::new();
215     drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
216     if contents == OPENSSL_VERS {
217         return
218     }
219     t!(fs::create_dir_all(&out));
220
221     let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
222     let tarball = out.join(&name);
223     if !tarball.exists() {
224         let tmp = tarball.with_extension("tmp");
225         // originally from https://www.openssl.org/source/...
226         let url = format!("https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror/{}",
227                           name);
228         let mut ok = false;
229         for _ in 0..3 {
230             let status = Command::new("curl")
231                             .arg("-o").arg(&tmp)
232                             .arg(&url)
233                             .status()
234                             .expect("failed to spawn curl");
235             if status.success() {
236                 ok = true;
237                 break
238             }
239         }
240         if !ok {
241             panic!("failed to download openssl source")
242         }
243         let mut shasum = if target.contains("apple") {
244             let mut cmd = Command::new("shasum");
245             cmd.arg("-a").arg("256");
246             cmd
247         } else {
248             Command::new("sha256sum")
249         };
250         let output = output(&mut shasum.arg(&tmp));
251         let found = output.split_whitespace().next().unwrap();
252         if found != OPENSSL_SHA256 {
253             panic!("downloaded openssl sha256 different\n\
254                     expected: {}\n\
255                     found:    {}\n", OPENSSL_SHA256, found);
256         }
257         t!(fs::rename(&tmp, &tarball));
258     }
259     let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
260     let dst = build.openssl_install_dir(target).unwrap();
261     drop(fs::remove_dir_all(&obj));
262     drop(fs::remove_dir_all(&dst));
263     build.run(Command::new("tar").arg("xf").arg(&tarball).current_dir(&out));
264
265     let mut configure = Command::new(obj.join("Configure"));
266     configure.arg(format!("--prefix={}", dst.display()));
267     configure.arg("no-dso");
268     configure.arg("no-ssl2");
269     configure.arg("no-ssl3");
270
271     let os = match target {
272         "aarch64-unknown-linux-gnu" => "linux-aarch64",
273         "arm-unknown-linux-gnueabi" => "linux-armv4",
274         "arm-unknown-linux-gnueabihf" => "linux-armv4",
275         "armv7-unknown-linux-gnueabihf" => "linux-armv4",
276         "i686-apple-darwin" => "darwin-i386-cc",
277         "i686-unknown-freebsd" => "BSD-x86-elf",
278         "i686-unknown-linux-gnu" => "linux-elf",
279         "i686-unknown-linux-musl" => "linux-elf",
280         "mips-unknown-linux-gnu" => "linux-mips32",
281         "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
282         "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
283         "mipsel-unknown-linux-gnu" => "linux-mips32",
284         "powerpc-unknown-linux-gnu" => "linux-ppc",
285         "powerpc64-unknown-linux-gnu" => "linux-ppc64",
286         "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
287         "s390x-unknown-linux-gnu" => "linux64-s390x",
288         "x86_64-apple-darwin" => "darwin64-x86_64-cc",
289         "x86_64-unknown-freebsd" => "BSD-x86_64",
290         "x86_64-unknown-linux-gnu" => "linux-x86_64",
291         "x86_64-unknown-linux-musl" => "linux-x86_64",
292         "x86_64-unknown-netbsd" => "BSD-x86_64",
293         _ => panic!("don't know how to configure OpenSSL for {}", target),
294     };
295     configure.arg(os);
296     configure.env("CC", build.cc(target));
297     for flag in build.cflags(target) {
298         configure.arg(flag);
299     }
300     configure.current_dir(&obj);
301     println!("Configuring openssl for {}", target);
302     build.run_quiet(&mut configure);
303     println!("Building openssl for {}", target);
304     build.run_quiet(Command::new("make").current_dir(&obj));
305     println!("Installing openssl for {}", target);
306     build.run_quiet(Command::new("make").arg("install").current_dir(&obj));
307
308     let mut f = t!(File::create(&stamp));
309     t!(f.write_all(OPENSSL_VERS.as_bytes()));
310 }