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