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