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