]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
0f39e33c5f46a2e346da835235bb25015ef2502a
[rust.git] / src / bootstrap / native.rs
1 //! Compilation of native dependencies like LLVM.
2 //!
3 //! Native projects like LLVM unfortunately aren't suited just yet for
4 //! compilation in build scripts that Cargo has. This is because the
5 //! compilation takes a *very* long time but also because we don't want to
6 //! compile LLVM 3 times as part of a normal bootstrap (we want it cached).
7 //!
8 //! LLVM and compiler-rt are essentially just wired up to everything else to
9 //! ensure that they're always in place if needed.
10
11 use std::env;
12 use std::ffi::OsString;
13 use std::fs::{self, File};
14 use std::io;
15 use std::path::{Path, PathBuf};
16 use std::process::Command;
17
18 use build_helper::{output, t};
19
20 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
21 use crate::cache::Interned;
22 use crate::channel;
23 use crate::util::{self, exe};
24 use crate::GitRepo;
25 use build_helper::up_to_date;
26
27 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
28 pub struct Llvm {
29     pub target: Interned<String>,
30 }
31
32 impl Step for Llvm {
33     type Output = PathBuf; // path to llvm-config
34
35     const ONLY_HOSTS: bool = true;
36
37     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
38         run.path("src/llvm-project").path("src/llvm-project/llvm").path("src/llvm")
39     }
40
41     fn make_run(run: RunConfig<'_>) {
42         run.builder.ensure(Llvm { target: run.target });
43     }
44
45     /// Compile LLVM for `target`.
46     fn run(self, builder: &Builder<'_>) -> PathBuf {
47         let target = self.target;
48
49         // If we're using a custom LLVM bail out here, but we can only use a
50         // custom LLVM for the build triple.
51         if let Some(config) = builder.config.target_config.get(&target) {
52             if let Some(ref s) = config.llvm_config {
53                 check_llvm_version(builder, s);
54                 return s.to_path_buf();
55             }
56         }
57
58         let root = "src/llvm-project/llvm";
59         let out_dir = builder.llvm_out(target);
60         let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
61         if !builder.config.build.contains("msvc") || builder.config.ninja {
62             llvm_config_ret_dir.push("build");
63         }
64         llvm_config_ret_dir.push("bin");
65
66         let build_llvm_config =
67             llvm_config_ret_dir.join(exe("llvm-config", &*builder.config.build));
68
69         let stamp = out_dir.join("llvm-finished-building");
70         let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
71
72         if builder.config.llvm_skip_rebuild && stamp.path.exists() {
73             builder.info(
74                 "Warning: \
75                 Using a potentially stale build of LLVM; \
76                 This may not behave well.",
77             );
78             return build_llvm_config;
79         }
80
81         if stamp.is_done() {
82             if stamp.hash.is_none() {
83                 builder.info(
84                     "Could not determine the LLVM submodule commit hash. \
85                      Assuming that an LLVM rebuild is not necessary.",
86                 );
87                 builder.info(&format!(
88                     "To force LLVM to rebuild, remove the file `{}`",
89                     stamp.path.display()
90                 ));
91             }
92             return build_llvm_config;
93         }
94
95         builder.info(&format!("Building LLVM for {}", target));
96         t!(stamp.remove());
97         let _time = util::timeit(&builder);
98         t!(fs::create_dir_all(&out_dir));
99
100         // http://llvm.org/docs/CMake.html
101         let mut cfg = cmake::Config::new(builder.src.join(root));
102
103         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
104             (false, _) => "Debug",
105             (true, false) => "Release",
106             (true, true) => "RelWithDebInfo",
107         };
108
109         // NOTE: remember to also update `config.toml.example` when changing the
110         // defaults!
111         let llvm_targets = match &builder.config.llvm_targets {
112             Some(s) => s,
113             None => {
114                 "AArch64;ARM;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
115                      Sparc;SystemZ;WebAssembly;X86"
116             }
117         };
118
119         let llvm_exp_targets = match builder.config.llvm_experimental_targets {
120             Some(ref s) => s,
121             None => "",
122         };
123
124         let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
125
126         cfg.out_dir(&out_dir)
127             .profile(profile)
128             .define("LLVM_ENABLE_ASSERTIONS", assertions)
129             .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
130             .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
131             .define("LLVM_INCLUDE_EXAMPLES", "OFF")
132             .define("LLVM_INCLUDE_TESTS", "OFF")
133             .define("LLVM_INCLUDE_DOCS", "OFF")
134             .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
135             .define("LLVM_ENABLE_ZLIB", "OFF")
136             .define("WITH_POLLY", "OFF")
137             .define("LLVM_ENABLE_TERMINFO", "OFF")
138             .define("LLVM_ENABLE_LIBEDIT", "OFF")
139             .define("LLVM_ENABLE_BINDINGS", "OFF")
140             .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
141             .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
142             .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
143             .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
144
145         if builder.config.llvm_thin_lto {
146             cfg.define("LLVM_ENABLE_LTO", "Thin");
147             if !target.contains("apple") {
148                 cfg.define("LLVM_ENABLE_LLD", "ON");
149             }
150         }
151
152         // This setting makes the LLVM tools link to the dynamic LLVM library,
153         // which saves both memory during parallel links and overall disk space
154         // for the tools. We don't do this on every platform as it doesn't work
155         // equally well everywhere.
156         if builder.llvm_link_tools_dynamically(target) {
157             cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
158         }
159
160         // For distribution we want the LLVM tools to be *statically* linked to libstdc++
161         if builder.config.llvm_tools_enabled || builder.config.lldb_enabled {
162             if !target.contains("msvc") {
163                 if target.contains("apple") {
164                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
165                 } else {
166                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
167                 }
168             }
169         }
170
171         if target.contains("msvc") {
172             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
173             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
174             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
175             cfg.static_crt(true);
176         }
177
178         if target.starts_with("i686") {
179             cfg.define("LLVM_BUILD_32_BITS", "ON");
180         }
181
182         let mut enabled_llvm_projects = Vec::new();
183
184         if util::forcing_clang_based_tests() {
185             enabled_llvm_projects.push("clang");
186             enabled_llvm_projects.push("compiler-rt");
187         }
188
189         if builder.config.lldb_enabled {
190             enabled_llvm_projects.push("clang");
191             enabled_llvm_projects.push("lldb");
192             // For the time being, disable code signing.
193             cfg.define("LLDB_CODESIGN_IDENTITY", "");
194             cfg.define("LLDB_NO_DEBUGSERVER", "ON");
195         } else {
196             // LLDB requires libxml2; but otherwise we want it to be disabled.
197             // See https://github.com/rust-lang/rust/pull/50104
198             cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
199         }
200
201         if !enabled_llvm_projects.is_empty() {
202             enabled_llvm_projects.sort();
203             enabled_llvm_projects.dedup();
204             cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
205         }
206
207         if let Some(num_linkers) = builder.config.llvm_link_jobs {
208             if num_linkers > 0 {
209                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
210             }
211         }
212
213         // http://llvm.org/docs/HowToCrossCompileLLVM.html
214         if target != builder.config.build {
215             builder.ensure(Llvm { target: builder.config.build });
216             // FIXME: if the llvm root for the build triple is overridden then we
217             //        should use llvm-tblgen from there, also should verify that it
218             //        actually exists most of the time in normal installs of LLVM.
219             let host = builder.llvm_out(builder.config.build).join("bin/llvm-tblgen");
220             cfg.define("CMAKE_CROSSCOMPILING", "True").define("LLVM_TABLEGEN", &host);
221
222             if target.contains("netbsd") {
223                 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
224             } else if target.contains("freebsd") {
225                 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
226             } else if target.contains("windows") {
227                 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
228             }
229
230             cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
231         }
232
233         if let Some(ref suffix) = builder.config.llvm_version_suffix {
234             // Allow version-suffix="" to not define a version suffix at all.
235             if !suffix.is_empty() {
236                 cfg.define("LLVM_VERSION_SUFFIX", suffix);
237             }
238         } else if builder.config.channel == "dev" {
239             // Changes to a version suffix require a complete rebuild of the LLVM.
240             // To avoid rebuilds during a time of version bump, don't include rustc
241             // release number on the dev channel.
242             cfg.define("LLVM_VERSION_SUFFIX", "-rust-dev");
243         } else {
244             let suffix = format!("-rust-{}-{}", channel::CFG_RELEASE_NUM, builder.config.channel);
245             cfg.define("LLVM_VERSION_SUFFIX", suffix);
246         }
247
248         if let Some(ref linker) = builder.config.llvm_use_linker {
249             cfg.define("LLVM_USE_LINKER", linker);
250         }
251
252         if let Some(true) = builder.config.llvm_allow_old_toolchain {
253             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
254         }
255
256         if let Some(ref python) = builder.config.python {
257             cfg.define("PYTHON_EXECUTABLE", python);
258         }
259
260         configure_cmake(builder, target, &mut cfg, true);
261
262         // FIXME: we don't actually need to build all LLVM tools and all LLVM
263         //        libraries here, e.g., we just want a few components and a few
264         //        tools. Figure out how to filter them down and only build the right
265         //        tools and libs on all platforms.
266
267         if builder.config.dry_run {
268             return build_llvm_config;
269         }
270
271         cfg.build();
272
273         t!(stamp.write());
274
275         build_llvm_config
276     }
277 }
278
279 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
280     if !builder.config.llvm_version_check {
281         return;
282     }
283
284     if builder.config.dry_run {
285         return;
286     }
287
288     let mut cmd = Command::new(llvm_config);
289     let version = output(cmd.arg("--version"));
290     let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
291     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
292         if major >= 8 {
293             return;
294         }
295     }
296     panic!("\n\nbad LLVM version: {}, need >=8.0\n\n", version)
297 }
298
299 fn configure_cmake(
300     builder: &Builder<'_>,
301     target: Interned<String>,
302     cfg: &mut cmake::Config,
303     use_compiler_launcher: bool,
304 ) {
305     // Do not print installation messages for up-to-date files.
306     // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
307     cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
308
309     if builder.config.ninja {
310         cfg.generator("Ninja");
311     }
312     cfg.target(&target).host(&builder.config.build);
313
314     let sanitize_cc = |cc: &Path| {
315         if target.contains("msvc") {
316             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
317         } else {
318             cc.as_os_str().to_owned()
319         }
320     };
321
322     // MSVC with CMake uses msbuild by default which doesn't respect these
323     // vars that we'd otherwise configure. In that case we just skip this
324     // entirely.
325     if target.contains("msvc") && !builder.config.ninja {
326         return;
327     }
328
329     let (cc, cxx) = match builder.config.llvm_clang_cl {
330         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
331         None => (builder.cc(target), builder.cxx(target).unwrap()),
332     };
333
334     // Handle msvc + ninja + ccache specially (this is what the bots use)
335     if target.contains("msvc") && builder.config.ninja && builder.config.ccache.is_some() {
336         let mut wrap_cc = env::current_exe().expect("failed to get cwd");
337         wrap_cc.set_file_name("sccache-plus-cl.exe");
338
339         cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
340             .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
341         cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
342             .env("SCCACHE_TARGET", target)
343             .env("SCCACHE_CC", &cc)
344             .env("SCCACHE_CXX", &cxx);
345
346         // Building LLVM on MSVC can be a little ludicrous at times. We're so far
347         // off the beaten path here that I'm not really sure this is even half
348         // supported any more. Here we're trying to:
349         //
350         // * Build LLVM on MSVC
351         // * Build LLVM with `clang-cl` instead of `cl.exe`
352         // * Build a project with `sccache`
353         // * Build for 32-bit as well
354         // * Build with Ninja
355         //
356         // For `cl.exe` there are different binaries to compile 32/64 bit which
357         // we use but for `clang-cl` there's only one which internally
358         // multiplexes via flags. As a result it appears that CMake's detection
359         // of a compiler's architecture and such on MSVC **doesn't** pass any
360         // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
361         // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
362         // definitely causes problems since all the env vars are pointing to
363         // 32-bit libraries.
364         //
365         // To hack around this... again... we pass an argument that's
366         // unconditionally passed in the sccache shim. This'll get CMake to
367         // correctly diagnose it's doing a 32-bit compilation and LLVM will
368         // internally configure itself appropriately.
369         if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
370             cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
371         }
372     } else {
373         // If ccache is configured we inform the build a little differently how
374         // to invoke ccache while also invoking our compilers.
375         if use_compiler_launcher {
376             if let Some(ref ccache) = builder.config.ccache {
377                 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
378                     .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
379             }
380         }
381         cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
382             .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
383     }
384
385     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
386     let mut cflags = builder.cflags(target, GitRepo::Llvm).join(" ");
387     if let Some(ref s) = builder.config.llvm_cflags {
388         cflags.push_str(&format!(" {}", s));
389     }
390     cfg.define("CMAKE_C_FLAGS", cflags);
391     let mut cxxflags = builder.cflags(target, GitRepo::Llvm).join(" ");
392     if builder.config.llvm_static_stdcpp && !target.contains("msvc") && !target.contains("netbsd") {
393         cxxflags.push_str(" -static-libstdc++");
394     }
395     if let Some(ref s) = builder.config.llvm_cxxflags {
396         cxxflags.push_str(&format!(" {}", s));
397     }
398     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
399     if let Some(ar) = builder.ar(target) {
400         if ar.is_absolute() {
401             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
402             // tries to resolve this path in the LLVM build directory.
403             cfg.define("CMAKE_AR", sanitize_cc(ar));
404         }
405     }
406
407     if let Some(ranlib) = builder.ranlib(target) {
408         if ranlib.is_absolute() {
409             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
410             // tries to resolve this path in the LLVM build directory.
411             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
412         }
413     }
414
415     if let Some(ref s) = builder.config.llvm_ldflags {
416         cfg.define("CMAKE_SHARED_LINKER_FLAGS", s);
417         cfg.define("CMAKE_MODULE_LINKER_FLAGS", s);
418         cfg.define("CMAKE_EXE_LINKER_FLAGS", s);
419     }
420
421     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
422         cfg.env("RUSTC_LOG", "sccache=warn");
423     }
424 }
425
426 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
427 pub struct Lld {
428     pub target: Interned<String>,
429 }
430
431 impl Step for Lld {
432     type Output = PathBuf;
433     const ONLY_HOSTS: bool = true;
434
435     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
436         run.path("src/llvm-project/lld").path("src/tools/lld")
437     }
438
439     fn make_run(run: RunConfig<'_>) {
440         run.builder.ensure(Lld { target: run.target });
441     }
442
443     /// Compile LLVM for `target`.
444     fn run(self, builder: &Builder<'_>) -> PathBuf {
445         if builder.config.dry_run {
446             return PathBuf::from("lld-out-dir-test-gen");
447         }
448         let target = self.target;
449
450         let llvm_config = builder.ensure(Llvm { target: self.target });
451
452         let out_dir = builder.lld_out(target);
453         let done_stamp = out_dir.join("lld-finished-building");
454         if done_stamp.exists() {
455             return out_dir;
456         }
457
458         builder.info(&format!("Building LLD for {}", target));
459         let _time = util::timeit(&builder);
460         t!(fs::create_dir_all(&out_dir));
461
462         let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
463         configure_cmake(builder, target, &mut cfg, true);
464
465         // This is an awful, awful hack. Discovered when we migrated to using
466         // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
467         // tree, will execute `llvm-config --cmakedir` and then tell CMake about
468         // that directory for later processing. Unfortunately if this path has
469         // forward slashes in it (which it basically always does on Windows)
470         // then CMake will hit a syntax error later on as... something isn't
471         // escaped it seems?
472         //
473         // Instead of attempting to fix this problem in upstream CMake and/or
474         // LLVM/LLD we just hack around it here. This thin wrapper will take the
475         // output from llvm-config and replace all instances of `\` with `/` to
476         // ensure we don't hit the same bugs with escaping. It means that you
477         // can't build on a system where your paths require `\` on Windows, but
478         // there's probably a lot of reasons you can't do that other than this.
479         let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
480         cfg.out_dir(&out_dir)
481             .profile("Release")
482             .env("LLVM_CONFIG_REAL", &llvm_config)
483             .define("LLVM_CONFIG_PATH", llvm_config_shim)
484             .define("LLVM_INCLUDE_TESTS", "OFF");
485
486         // While we're using this horrible workaround to shim the execution of
487         // llvm-config, let's just pile on more. I can't seem to figure out how
488         // to build LLD as a standalone project and also cross-compile it at the
489         // same time. It wants a natively executable `llvm-config` to learn
490         // about LLVM, but then it learns about all the host configuration of
491         // LLVM and tries to link to host LLVM libraries.
492         //
493         // To work around that we tell our shim to replace anything with the
494         // build target with the actual target instead. This'll break parts of
495         // LLD though which try to execute host tools, such as llvm-tblgen, so
496         // we specifically tell it where to find those. This is likely super
497         // brittle and will break over time. If anyone knows better how to
498         // cross-compile LLD it would be much appreciated to fix this!
499         if target != builder.config.build {
500             cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build)
501                 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target)
502                 .define("LLVM_TABLEGEN_EXE", llvm_config.with_file_name("llvm-tblgen"));
503         }
504
505         cfg.build();
506
507         t!(File::create(&done_stamp));
508         out_dir
509     }
510 }
511
512 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
513 pub struct TestHelpers {
514     pub target: Interned<String>,
515 }
516
517 impl Step for TestHelpers {
518     type Output = ();
519
520     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
521         run.path("src/test/auxiliary/rust_test_helpers.c")
522     }
523
524     fn make_run(run: RunConfig<'_>) {
525         run.builder.ensure(TestHelpers { target: run.target })
526     }
527
528     /// Compiles the `rust_test_helpers.c` library which we used in various
529     /// `run-pass` tests for ABI testing.
530     fn run(self, builder: &Builder<'_>) {
531         if builder.config.dry_run {
532             return;
533         }
534         let target = self.target;
535         let dst = builder.test_helpers_out(target);
536         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
537         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
538             return;
539         }
540
541         builder.info("Building test helpers");
542         t!(fs::create_dir_all(&dst));
543         let mut cfg = cc::Build::new();
544         // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
545         if target.contains("emscripten") {
546             cfg.pic(false);
547         }
548
549         // We may have found various cross-compilers a little differently due to our
550         // extra configuration, so inform gcc of these compilers. Note, though, that
551         // on MSVC we still need gcc's detection of env vars (ugh).
552         if !target.contains("msvc") {
553             if let Some(ar) = builder.ar(target) {
554                 cfg.archiver(ar);
555             }
556             cfg.compiler(builder.cc(target));
557         }
558
559         cfg.cargo_metadata(false)
560             .out_dir(&dst)
561             .target(&target)
562             .host(&builder.config.build)
563             .opt_level(0)
564             .warnings(false)
565             .debug(false)
566             .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
567             .compile("rust_test_helpers");
568     }
569 }
570
571 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
572 pub struct Sanitizers {
573     pub target: Interned<String>,
574 }
575
576 impl Step for Sanitizers {
577     type Output = Vec<SanitizerRuntime>;
578
579     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
580         run.path("src/llvm-project/compiler-rt").path("src/sanitizers")
581     }
582
583     fn make_run(run: RunConfig<'_>) {
584         run.builder.ensure(Sanitizers { target: run.target });
585     }
586
587     /// Builds sanitizer runtime libraries.
588     fn run(self, builder: &Builder<'_>) -> Self::Output {
589         let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
590         if !compiler_rt_dir.exists() {
591             return Vec::new();
592         }
593
594         let out_dir = builder.native_dir(self.target).join("sanitizers");
595         let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
596         if runtimes.is_empty() {
597             return runtimes;
598         }
599
600         let llvm_config = builder.ensure(Llvm { target: builder.config.build });
601         if builder.config.dry_run {
602             return runtimes;
603         }
604
605         let stamp = out_dir.join("sanitizers-finished-building");
606         let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
607
608         if stamp.is_done() {
609             if stamp.hash.is_none() {
610                 builder.info(&format!(
611                     "Rebuild sanitizers by removing the file `{}`",
612                     stamp.path.display()
613                 ));
614             }
615             return runtimes;
616         }
617
618         builder.info(&format!("Building sanitizers for {}", self.target));
619         t!(stamp.remove());
620         let _time = util::timeit(&builder);
621
622         let mut cfg = cmake::Config::new(&compiler_rt_dir);
623         cfg.profile("Release");
624         cfg.define("CMAKE_C_COMPILER_TARGET", self.target);
625         cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
626         cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
627         cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
628         cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
629         cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
630         cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
631         cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
632         cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
633         cfg.define("LLVM_CONFIG_PATH", &llvm_config);
634
635         // On Darwin targets the sanitizer runtimes are build as universal binaries.
636         // Unfortunately sccache currently lacks support to build them successfully.
637         // Disable compiler launcher on Darwin targets to avoid potential issues.
638         let use_compiler_launcher = !self.target.contains("apple-darwin");
639         configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher);
640
641         t!(fs::create_dir_all(&out_dir));
642         cfg.out_dir(out_dir);
643
644         for runtime in &runtimes {
645             cfg.build_target(&runtime.cmake_target);
646             cfg.build();
647         }
648         t!(stamp.write());
649
650         runtimes
651     }
652 }
653
654 #[derive(Clone, Debug)]
655 pub struct SanitizerRuntime {
656     /// CMake target used to build the runtime.
657     pub cmake_target: String,
658     /// Path to the built runtime library.
659     pub path: PathBuf,
660     /// Library filename that will be used rustc.
661     pub name: String,
662 }
663
664 /// Returns sanitizers available on a given target.
665 fn supported_sanitizers(
666     out_dir: &Path,
667     target: Interned<String>,
668     channel: &str,
669 ) -> Vec<SanitizerRuntime> {
670     let mut result = Vec::new();
671     match &*target {
672         "x86_64-apple-darwin" => {
673             for s in &["asan", "lsan", "tsan"] {
674                 result.push(SanitizerRuntime {
675                     cmake_target: format!("clang_rt.{}_osx_dynamic", s),
676                     path: out_dir
677                         .join(&format!("build/lib/darwin/libclang_rt.{}_osx_dynamic.dylib", s)),
678                     name: format!("librustc-{}_rt.{}.dylib", channel, s),
679                 });
680             }
681         }
682         "x86_64-unknown-linux-gnu" => {
683             for s in &["asan", "lsan", "msan", "tsan"] {
684                 result.push(SanitizerRuntime {
685                     cmake_target: format!("clang_rt.{}-x86_64", s),
686                     path: out_dir.join(&format!("build/lib/linux/libclang_rt.{}-x86_64.a", s)),
687                     name: format!("librustc-{}_rt.{}.a", channel, s),
688                 });
689             }
690         }
691         "x86_64-fuchsia" => {
692             for s in &["asan"] {
693                 result.push(SanitizerRuntime {
694                     cmake_target: format!("clang_rt.{}-x86_64", s),
695                     path: out_dir.join(&format!("build/lib/fuchsia/libclang_rt.{}-x86_64.a", s)),
696                     name: format!("librustc-{}_rt.{}.a", channel, s),
697                 });
698             }
699         }
700         "aarch64-fuchsia" => {
701             for s in &["asan"] {
702                 result.push(SanitizerRuntime {
703                     cmake_target: format!("clang_rt.{}-aarch64", s),
704                     path: out_dir.join(&format!("build/lib/fuchsia/libclang_rt.{}-aarch64.a", s)),
705                     name: format!("librustc-{}_rt.{}.a", channel, s),
706                 });
707             }
708         }
709         _ => {}
710     }
711     result
712 }
713
714 struct HashStamp {
715     path: PathBuf,
716     hash: Option<Vec<u8>>,
717 }
718
719 impl HashStamp {
720     fn new(path: PathBuf, hash: Option<&str>) -> Self {
721         HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
722     }
723
724     fn is_done(&self) -> bool {
725         match fs::read(&self.path) {
726             Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
727             Err(e) if e.kind() == io::ErrorKind::NotFound => false,
728             Err(e) => {
729                 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
730             }
731         }
732     }
733
734     fn remove(&self) -> io::Result<()> {
735         match fs::remove_file(&self.path) {
736             Ok(()) => Ok(()),
737             Err(e) => {
738                 if e.kind() == io::ErrorKind::NotFound {
739                     Ok(())
740                 } else {
741                     Err(e)
742                 }
743             }
744         }
745     }
746
747     fn write(&self) -> io::Result<()> {
748         fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
749     }
750 }