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