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