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