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