]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
Remove the source archive functionality of ArchiveWriter
[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::{OsStr, 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 crate::builder::{Builder, RunConfig, ShouldRun, Step};
20 use crate::config::TargetSelection;
21 use crate::util::{self, exe, output, program_out_of_date, t, up_to_date};
22 use crate::{CLang, GitRepo};
23
24 pub struct Meta {
25     stamp: HashStamp,
26     build_llvm_config: PathBuf,
27     out_dir: PathBuf,
28     root: String,
29 }
30
31 // Linker flags to pass to LLVM's CMake invocation.
32 #[derive(Debug, Clone, Default)]
33 struct LdFlags {
34     // CMAKE_EXE_LINKER_FLAGS
35     exe: OsString,
36     // CMAKE_SHARED_LINKER_FLAGS
37     shared: OsString,
38     // CMAKE_MODULE_LINKER_FLAGS
39     module: OsString,
40 }
41
42 impl LdFlags {
43     fn push_all(&mut self, s: impl AsRef<OsStr>) {
44         let s = s.as_ref();
45         self.exe.push(" ");
46         self.exe.push(s);
47         self.shared.push(" ");
48         self.shared.push(s);
49         self.module.push(" ");
50         self.module.push(s);
51     }
52 }
53
54 // This returns whether we've already previously built LLVM.
55 //
56 // It's used to avoid busting caches during x.py check -- if we've already built
57 // LLVM, it's fine for us to not try to avoid doing so.
58 //
59 // This will return the llvm-config if it can get it (but it will not build it
60 // if not).
61 pub fn prebuilt_llvm_config(
62     builder: &Builder<'_>,
63     target: TargetSelection,
64 ) -> Result<PathBuf, Meta> {
65     maybe_download_ci_llvm(builder);
66
67     // If we're using a custom LLVM bail out here, but we can only use a
68     // custom LLVM for the build triple.
69     if let Some(config) = builder.config.target_config.get(&target) {
70         if let Some(ref s) = config.llvm_config {
71             check_llvm_version(builder, s);
72             return Ok(s.to_path_buf());
73         }
74     }
75
76     let root = "src/llvm-project/llvm";
77     let out_dir = builder.llvm_out(target);
78
79     let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
80     if !builder.config.build.contains("msvc") || builder.ninja() {
81         llvm_config_ret_dir.push("build");
82     }
83     llvm_config_ret_dir.push("bin");
84
85     let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
86
87     let stamp = out_dir.join("llvm-finished-building");
88     let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
89
90     if builder.config.llvm_skip_rebuild && stamp.path.exists() {
91         builder.info(
92             "Warning: \
93                 Using a potentially stale build of LLVM; \
94                 This may not behave well.",
95         );
96         return Ok(build_llvm_config);
97     }
98
99     if stamp.is_done() {
100         if stamp.hash.is_none() {
101             builder.info(
102                 "Could not determine the LLVM submodule commit hash. \
103                      Assuming that an LLVM rebuild is not necessary.",
104             );
105             builder.info(&format!(
106                 "To force LLVM to rebuild, remove the file `{}`",
107                 stamp.path.display()
108             ));
109         }
110         return Ok(build_llvm_config);
111     }
112
113     Err(Meta { stamp, build_llvm_config, out_dir, root: root.into() })
114 }
115
116 pub(crate) fn maybe_download_ci_llvm(builder: &Builder<'_>) {
117     let config = &builder.config;
118     if !config.llvm_from_ci {
119         return;
120     }
121     let mut rev_list = Command::new("git");
122     rev_list.args(&[
123         PathBuf::from("rev-list"),
124         "--author=bors@rust-lang.org".into(),
125         "-n1".into(),
126         "--first-parent".into(),
127         "HEAD".into(),
128         "--".into(),
129         builder.src.join("src/llvm-project"),
130         builder.src.join("src/bootstrap/download-ci-llvm-stamp"),
131         // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
132         builder.src.join("src/version"),
133     ]);
134     let llvm_sha = output(&mut rev_list);
135     let llvm_sha = llvm_sha.trim();
136
137     if llvm_sha == "" {
138         eprintln!("error: could not find commit hash for downloading LLVM");
139         eprintln!("help: maybe your repository history is too shallow?");
140         eprintln!("help: consider disabling `download-ci-llvm`");
141         eprintln!("help: or fetch enough history to include one upstream commit");
142         panic!();
143     }
144
145     let llvm_root = config.ci_llvm_root();
146     let llvm_stamp = llvm_root.join(".llvm-stamp");
147     let key = format!("{}{}", llvm_sha, config.llvm_assertions);
148     if program_out_of_date(&llvm_stamp, &key) && !config.dry_run {
149         download_ci_llvm(builder, &llvm_sha);
150         for binary in ["llvm-config", "FileCheck"] {
151             builder.fix_bin_or_dylib(&llvm_root.join("bin").join(binary));
152         }
153         let llvm_lib = llvm_root.join("lib");
154         for entry in t!(fs::read_dir(&llvm_lib)) {
155             let lib = t!(entry).path();
156             if lib.extension().map_or(false, |ext| ext == "so") {
157                 builder.fix_bin_or_dylib(&lib);
158             }
159         }
160         t!(fs::write(llvm_stamp, key));
161     }
162 }
163
164 fn download_ci_llvm(builder: &Builder<'_>, llvm_sha: &str) {
165     let llvm_assertions = builder.config.llvm_assertions;
166
167     let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions);
168     let cache_dst = builder.out.join("cache");
169     let rustc_cache = cache_dst.join(cache_prefix);
170     if !rustc_cache.exists() {
171         t!(fs::create_dir_all(&rustc_cache));
172     }
173     let base = "https://ci-artifacts.rust-lang.org";
174     let url = if llvm_assertions {
175         format!("rustc-builds-alt/{}", llvm_sha)
176     } else {
177         format!("rustc-builds/{}", llvm_sha)
178     };
179     let filename = format!("rust-dev-nightly-{}.tar.xz", builder.build.build.triple);
180     let tarball = rustc_cache.join(&filename);
181     if !tarball.exists() {
182         let help_on_error = "error: failed to download llvm from ci
183
184 help: old builds get deleted after a certain time
185 help: if trying to compile an old commit of rustc, disable `download-ci-llvm` in config.toml:
186
187 [llvm]
188 download-ci-llvm = false
189 ";
190         builder.download_component(base, &format!("{}/{}", url, filename), &tarball, help_on_error);
191     }
192     let llvm_root = builder.config.ci_llvm_root();
193     builder.unpack(&tarball, &llvm_root, "rust-dev");
194 }
195
196 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
197 pub struct Llvm {
198     pub target: TargetSelection,
199 }
200
201 impl Step for Llvm {
202     type Output = PathBuf; // path to llvm-config
203
204     const ONLY_HOSTS: bool = true;
205
206     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
207         run.path("src/llvm-project").path("src/llvm-project/llvm")
208     }
209
210     fn make_run(run: RunConfig<'_>) {
211         run.builder.ensure(Llvm { target: run.target });
212     }
213
214     /// Compile LLVM for `target`.
215     fn run(self, builder: &Builder<'_>) -> PathBuf {
216         let target = self.target;
217         let target_native = if self.target.starts_with("riscv") {
218             // RISC-V target triples in Rust is not named the same as C compiler target triples.
219             // This converts Rust RISC-V target triples to C compiler triples.
220             let idx = target.triple.find('-').unwrap();
221
222             format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
223         } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
224             // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
225             // Set the version suffix to 13.0 so the correct target details are used.
226             format!("{}{}", self.target, "13.0")
227         } else {
228             target.to_string()
229         };
230
231         let Meta { stamp, build_llvm_config, out_dir, root } =
232             match prebuilt_llvm_config(builder, target) {
233                 Ok(p) => return p,
234                 Err(m) => m,
235             };
236
237         builder.update_submodule(&Path::new("src").join("llvm-project"));
238         if builder.llvm_link_shared()
239             && (target.contains("windows") || target.contains("apple-darwin"))
240         {
241             panic!("shared linking to LLVM is not currently supported on {}", target.triple);
242         }
243
244         builder.info(&format!("Building LLVM for {}", target));
245         t!(stamp.remove());
246         let _time = util::timeit(&builder);
247         t!(fs::create_dir_all(&out_dir));
248
249         // https://llvm.org/docs/CMake.html
250         let mut cfg = cmake::Config::new(builder.src.join(root));
251         let mut ldflags = LdFlags::default();
252
253         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
254             (false, _) => "Debug",
255             (true, false) => "Release",
256             (true, true) => "RelWithDebInfo",
257         };
258
259         // NOTE: remember to also update `config.toml.example` when changing the
260         // defaults!
261         let llvm_targets = match &builder.config.llvm_targets {
262             Some(s) => s,
263             None => {
264                 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
265                      Sparc;SystemZ;WebAssembly;X86"
266             }
267         };
268
269         let llvm_exp_targets = match builder.config.llvm_experimental_targets {
270             Some(ref s) => s,
271             None => "AVR;M68k",
272         };
273
274         let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
275         let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
276         let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
277
278         cfg.out_dir(&out_dir)
279             .profile(profile)
280             .define("LLVM_ENABLE_ASSERTIONS", assertions)
281             .define("LLVM_ENABLE_PLUGINS", plugins)
282             .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
283             .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
284             .define("LLVM_INCLUDE_EXAMPLES", "OFF")
285             .define("LLVM_INCLUDE_DOCS", "OFF")
286             .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
287             .define("LLVM_INCLUDE_TESTS", enable_tests)
288             .define("LLVM_ENABLE_TERMINFO", "OFF")
289             .define("LLVM_ENABLE_LIBEDIT", "OFF")
290             .define("LLVM_ENABLE_BINDINGS", "OFF")
291             .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
292             .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
293             .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
294             .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
295
296         // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
297         // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
298         // This flag makes sure `FileCheck` is copied in the final binaries directory.
299         cfg.define("LLVM_INSTALL_UTILS", "ON");
300
301         if builder.config.llvm_profile_generate {
302             cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
303             if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
304                 cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
305             }
306             cfg.define("LLVM_BUILD_RUNTIME", "No");
307         }
308         if let Some(path) = builder.config.llvm_profile_use.as_ref() {
309             cfg.define("LLVM_PROFDATA_FILE", &path);
310         }
311
312         if target != "aarch64-apple-darwin" && !target.contains("windows") {
313             cfg.define("LLVM_ENABLE_ZLIB", "ON");
314         } else {
315             cfg.define("LLVM_ENABLE_ZLIB", "OFF");
316         }
317
318         // Are we compiling for iOS/tvOS/watchOS?
319         if target.contains("apple-ios")
320             || target.contains("apple-tvos")
321             || target.contains("apple-watchos")
322         {
323             // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
324             cfg.define("CMAKE_OSX_SYSROOT", "/");
325             cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
326             // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
327             cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
328             // Zlib fails to link properly, leading to a compiler error.
329             cfg.define("LLVM_ENABLE_ZLIB", "OFF");
330         }
331
332         if builder.config.llvm_thin_lto {
333             cfg.define("LLVM_ENABLE_LTO", "Thin");
334             if !target.contains("apple") {
335                 cfg.define("LLVM_ENABLE_LLD", "ON");
336             }
337         }
338
339         // This setting makes the LLVM tools link to the dynamic LLVM library,
340         // which saves both memory during parallel links and overall disk space
341         // for the tools. We don't do this on every platform as it doesn't work
342         // equally well everywhere.
343         //
344         // If we're not linking rustc to a dynamic LLVM, though, then don't link
345         // tools to it.
346         if builder.llvm_link_tools_dynamically(target) && builder.llvm_link_shared() {
347             cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
348         }
349
350         if target.starts_with("riscv") && !target.contains("freebsd") {
351             // RISC-V GCC erroneously requires linking against
352             // `libatomic` when using 1-byte and 2-byte C++
353             // atomics but the LLVM build system check cannot
354             // detect this. Therefore it is set manually here.
355             // FreeBSD uses Clang as its system compiler and
356             // provides no libatomic in its base system so does
357             // not want this.
358             ldflags.exe.push(" -latomic");
359             ldflags.shared.push(" -latomic");
360         }
361
362         if target.contains("msvc") {
363             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
364             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
365             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
366             cfg.static_crt(true);
367         }
368
369         if target.starts_with("i686") {
370             cfg.define("LLVM_BUILD_32_BITS", "ON");
371         }
372
373         let mut enabled_llvm_projects = Vec::new();
374
375         if util::forcing_clang_based_tests() {
376             enabled_llvm_projects.push("clang");
377             enabled_llvm_projects.push("compiler-rt");
378         }
379
380         if builder.config.llvm_polly {
381             enabled_llvm_projects.push("polly");
382         }
383
384         if builder.config.llvm_clang {
385             enabled_llvm_projects.push("clang");
386         }
387
388         // We want libxml to be disabled.
389         // See https://github.com/rust-lang/rust/pull/50104
390         cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
391
392         if !enabled_llvm_projects.is_empty() {
393             enabled_llvm_projects.sort();
394             enabled_llvm_projects.dedup();
395             cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
396         }
397
398         if let Some(num_linkers) = builder.config.llvm_link_jobs {
399             if num_linkers > 0 {
400                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
401             }
402         }
403
404         // Workaround for ppc32 lld limitation
405         if target == "powerpc-unknown-freebsd" {
406             ldflags.exe.push(" -fuse-ld=bfd");
407         }
408
409         // https://llvm.org/docs/HowToCrossCompileLLVM.html
410         if target != builder.config.build {
411             builder.ensure(Llvm { target: builder.config.build });
412             // FIXME: if the llvm root for the build triple is overridden then we
413             //        should use llvm-tblgen from there, also should verify that it
414             //        actually exists most of the time in normal installs of LLVM.
415             let host_bin = builder.llvm_out(builder.config.build).join("bin");
416             cfg.define("CMAKE_CROSSCOMPILING", "True");
417             cfg.define("LLVM_TABLEGEN", host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION));
418             cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
419             cfg.define(
420                 "LLVM_CONFIG_PATH",
421                 host_bin.join("llvm-config").with_extension(EXE_EXTENSION),
422             );
423         }
424
425         if let Some(ref suffix) = builder.config.llvm_version_suffix {
426             // Allow version-suffix="" to not define a version suffix at all.
427             if !suffix.is_empty() {
428                 cfg.define("LLVM_VERSION_SUFFIX", suffix);
429             }
430         } else if builder.config.channel == "dev" {
431             // Changes to a version suffix require a complete rebuild of the LLVM.
432             // To avoid rebuilds during a time of version bump, don't include rustc
433             // release number on the dev channel.
434             cfg.define("LLVM_VERSION_SUFFIX", "-rust-dev");
435         } else {
436             let suffix = format!("-rust-{}-{}", builder.version, builder.config.channel);
437             cfg.define("LLVM_VERSION_SUFFIX", suffix);
438         }
439
440         if let Some(ref linker) = builder.config.llvm_use_linker {
441             cfg.define("LLVM_USE_LINKER", linker);
442         }
443
444         if builder.config.llvm_allow_old_toolchain {
445             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
446         }
447
448         configure_cmake(builder, target, &mut cfg, true, ldflags);
449
450         for (key, val) in &builder.config.llvm_build_config {
451             cfg.define(key, val);
452         }
453
454         // FIXME: we don't actually need to build all LLVM tools and all LLVM
455         //        libraries here, e.g., we just want a few components and a few
456         //        tools. Figure out how to filter them down and only build the right
457         //        tools and libs on all platforms.
458
459         if builder.config.dry_run {
460             return build_llvm_config;
461         }
462
463         cfg.build();
464
465         t!(stamp.write());
466
467         build_llvm_config
468     }
469 }
470
471 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
472     if !builder.config.llvm_version_check {
473         return;
474     }
475
476     if builder.config.dry_run {
477         return;
478     }
479
480     let mut cmd = Command::new(llvm_config);
481     let version = output(cmd.arg("--version"));
482     let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
483     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
484         if major >= 12 {
485             return;
486         }
487     }
488     panic!("\n\nbad LLVM version: {}, need >=12.0\n\n", version)
489 }
490
491 fn configure_cmake(
492     builder: &Builder<'_>,
493     target: TargetSelection,
494     cfg: &mut cmake::Config,
495     use_compiler_launcher: bool,
496     mut ldflags: LdFlags,
497 ) {
498     // Do not print installation messages for up-to-date files.
499     // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
500     cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
501
502     // Do not allow the user's value of DESTDIR to influence where
503     // LLVM will install itself. LLVM must always be installed in our
504     // own build directories.
505     cfg.env("DESTDIR", "");
506
507     if builder.ninja() {
508         cfg.generator("Ninja");
509     }
510     cfg.target(&target.triple).host(&builder.config.build.triple);
511
512     if target != builder.config.build {
513         if target.contains("netbsd") {
514             cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
515         } else if target.contains("freebsd") {
516             cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
517         } else if target.contains("windows") {
518             cfg.define("CMAKE_SYSTEM_NAME", "Windows");
519         } else if target.contains("haiku") {
520             cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
521         } else if target.contains("solaris") || target.contains("illumos") {
522             cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
523         }
524         // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
525         // that case like CMake we cannot easily determine system version either.
526         //
527         // Since, the LLVM itself makes rather limited use of version checks in
528         // CMakeFiles (and then only in tests), and so far no issues have been
529         // reported, the system version is currently left unset.
530     }
531
532     let sanitize_cc = |cc: &Path| {
533         if target.contains("msvc") {
534             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
535         } else {
536             cc.as_os_str().to_owned()
537         }
538     };
539
540     // MSVC with CMake uses msbuild by default which doesn't respect these
541     // vars that we'd otherwise configure. In that case we just skip this
542     // entirely.
543     if target.contains("msvc") && !builder.ninja() {
544         return;
545     }
546
547     let (cc, cxx) = match builder.config.llvm_clang_cl {
548         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
549         None => (builder.cc(target), builder.cxx(target).unwrap()),
550     };
551
552     // Handle msvc + ninja + ccache specially (this is what the bots use)
553     if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
554         let mut wrap_cc = env::current_exe().expect("failed to get cwd");
555         wrap_cc.set_file_name("sccache-plus-cl.exe");
556
557         cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
558             .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
559         cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
560             .env("SCCACHE_TARGET", target.triple)
561             .env("SCCACHE_CC", &cc)
562             .env("SCCACHE_CXX", &cxx);
563
564         // Building LLVM on MSVC can be a little ludicrous at times. We're so far
565         // off the beaten path here that I'm not really sure this is even half
566         // supported any more. Here we're trying to:
567         //
568         // * Build LLVM on MSVC
569         // * Build LLVM with `clang-cl` instead of `cl.exe`
570         // * Build a project with `sccache`
571         // * Build for 32-bit as well
572         // * Build with Ninja
573         //
574         // For `cl.exe` there are different binaries to compile 32/64 bit which
575         // we use but for `clang-cl` there's only one which internally
576         // multiplexes via flags. As a result it appears that CMake's detection
577         // of a compiler's architecture and such on MSVC **doesn't** pass any
578         // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
579         // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
580         // definitely causes problems since all the env vars are pointing to
581         // 32-bit libraries.
582         //
583         // To hack around this... again... we pass an argument that's
584         // unconditionally passed in the sccache shim. This'll get CMake to
585         // correctly diagnose it's doing a 32-bit compilation and LLVM will
586         // internally configure itself appropriately.
587         if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
588             cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
589         }
590     } else {
591         // If ccache is configured we inform the build a little differently how
592         // to invoke ccache while also invoking our compilers.
593         if use_compiler_launcher {
594             if let Some(ref ccache) = builder.config.ccache {
595                 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
596                     .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
597             }
598         }
599         cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
600             .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
601             .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
602     }
603
604     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
605     let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
606     if let Some(ref s) = builder.config.llvm_cflags {
607         cflags.push(" ");
608         cflags.push(s);
609     }
610     // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
611     if target.contains("apple-ios") {
612         if target.contains("86-") {
613             cflags.push(" -miphonesimulator-version-min=10.0");
614         } else {
615             cflags.push(" -miphoneos-version-min=10.0");
616         }
617     }
618     if builder.config.llvm_clang_cl.is_some() {
619         cflags.push(&format!(" --target={}", target));
620     }
621     cfg.define("CMAKE_C_FLAGS", cflags);
622     let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
623     if let Some(ref s) = builder.config.llvm_cxxflags {
624         cxxflags.push(" ");
625         cxxflags.push(s);
626     }
627     if builder.config.llvm_clang_cl.is_some() {
628         cxxflags.push(&format!(" --target={}", target));
629     }
630     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
631     if let Some(ar) = builder.ar(target) {
632         if ar.is_absolute() {
633             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
634             // tries to resolve this path in the LLVM build directory.
635             cfg.define("CMAKE_AR", sanitize_cc(ar));
636         }
637     }
638
639     if let Some(ranlib) = builder.ranlib(target) {
640         if ranlib.is_absolute() {
641             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
642             // tries to resolve this path in the LLVM build directory.
643             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
644         }
645     }
646
647     if let Some(ref flags) = builder.config.llvm_ldflags {
648         ldflags.push_all(flags);
649     }
650
651     if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
652         ldflags.push_all(&flags);
653     }
654
655     // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
656     // We also do this if the user explicitly requested static libstdc++.
657     if builder.config.llvm_static_stdcpp {
658         if !target.contains("msvc") && !target.contains("netbsd") {
659             if target.contains("apple") || target.contains("windows") {
660                 ldflags.push_all("-static-libstdc++");
661             } else {
662                 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
663             }
664         }
665     }
666
667     cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
668     cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
669     cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
670
671     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
672         cfg.env("RUSTC_LOG", "sccache=warn");
673     }
674 }
675
676 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
677 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
678     let kind = if host == target { "HOST" } else { "TARGET" };
679     let target_u = target.replace("-", "_");
680     env::var_os(&format!("{}_{}", var_base, target))
681         .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
682         .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
683         .or_else(|| env::var_os(var_base))
684 }
685
686 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
687 pub struct Lld {
688     pub target: TargetSelection,
689 }
690
691 impl Step for Lld {
692     type Output = PathBuf;
693     const ONLY_HOSTS: bool = true;
694
695     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
696         run.path("src/llvm-project/lld")
697     }
698
699     fn make_run(run: RunConfig<'_>) {
700         run.builder.ensure(Lld { target: run.target });
701     }
702
703     /// Compile LLD for `target`.
704     fn run(self, builder: &Builder<'_>) -> PathBuf {
705         if builder.config.dry_run {
706             return PathBuf::from("lld-out-dir-test-gen");
707         }
708         let target = self.target;
709
710         let llvm_config = builder.ensure(Llvm { target: self.target });
711
712         let out_dir = builder.lld_out(target);
713         let done_stamp = out_dir.join("lld-finished-building");
714         if done_stamp.exists() {
715             return out_dir;
716         }
717
718         builder.info(&format!("Building LLD for {}", target));
719         let _time = util::timeit(&builder);
720         t!(fs::create_dir_all(&out_dir));
721
722         let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
723         configure_cmake(builder, target, &mut cfg, true, LdFlags::default());
724
725         // This is an awful, awful hack. Discovered when we migrated to using
726         // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
727         // tree, will execute `llvm-config --cmakedir` and then tell CMake about
728         // that directory for later processing. Unfortunately if this path has
729         // forward slashes in it (which it basically always does on Windows)
730         // then CMake will hit a syntax error later on as... something isn't
731         // escaped it seems?
732         //
733         // Instead of attempting to fix this problem in upstream CMake and/or
734         // LLVM/LLD we just hack around it here. This thin wrapper will take the
735         // output from llvm-config and replace all instances of `\` with `/` to
736         // ensure we don't hit the same bugs with escaping. It means that you
737         // can't build on a system where your paths require `\` on Windows, but
738         // there's probably a lot of reasons you can't do that other than this.
739         let llvm_config_shim = env::current_exe().unwrap().with_file_name("llvm-config-wrapper");
740
741         // Re-use the same flags as llvm to control the level of debug information
742         // generated for lld.
743         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
744             (false, _) => "Debug",
745             (true, false) => "Release",
746             (true, true) => "RelWithDebInfo",
747         };
748
749         cfg.out_dir(&out_dir)
750             .profile(profile)
751             .env("LLVM_CONFIG_REAL", &llvm_config)
752             .define("LLVM_CONFIG_PATH", llvm_config_shim)
753             .define("LLVM_INCLUDE_TESTS", "OFF");
754
755         if builder.config.llvm_allow_old_toolchain {
756             cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
757         }
758
759         // While we're using this horrible workaround to shim the execution of
760         // llvm-config, let's just pile on more. I can't seem to figure out how
761         // to build LLD as a standalone project and also cross-compile it at the
762         // same time. It wants a natively executable `llvm-config` to learn
763         // about LLVM, but then it learns about all the host configuration of
764         // LLVM and tries to link to host LLVM libraries.
765         //
766         // To work around that we tell our shim to replace anything with the
767         // build target with the actual target instead. This'll break parts of
768         // LLD though which try to execute host tools, such as llvm-tblgen, so
769         // we specifically tell it where to find those. This is likely super
770         // brittle and will break over time. If anyone knows better how to
771         // cross-compile LLD it would be much appreciated to fix this!
772         if target != builder.config.build {
773             cfg.env("LLVM_CONFIG_SHIM_REPLACE", &builder.config.build.triple)
774                 .env("LLVM_CONFIG_SHIM_REPLACE_WITH", &target.triple)
775                 .define(
776                     "LLVM_TABLEGEN_EXE",
777                     llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
778                 );
779         }
780
781         // Explicitly set C++ standard, because upstream doesn't do so
782         // for standalone builds.
783         cfg.define("CMAKE_CXX_STANDARD", "14");
784
785         cfg.build();
786
787         t!(File::create(&done_stamp));
788         out_dir
789     }
790 }
791
792 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
793 pub struct TestHelpers {
794     pub target: TargetSelection,
795 }
796
797 impl Step for TestHelpers {
798     type Output = ();
799
800     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
801         run.path("src/test/auxiliary/rust_test_helpers.c")
802     }
803
804     fn make_run(run: RunConfig<'_>) {
805         run.builder.ensure(TestHelpers { target: run.target })
806     }
807
808     /// Compiles the `rust_test_helpers.c` library which we used in various
809     /// `run-pass` tests for ABI testing.
810     fn run(self, builder: &Builder<'_>) {
811         if builder.config.dry_run {
812             return;
813         }
814         // The x86_64-fortanix-unknown-sgx target doesn't have a working C
815         // toolchain. However, some x86_64 ELF objects can be linked
816         // without issues. Use this hack to compile the test helpers.
817         let target = if self.target == "x86_64-fortanix-unknown-sgx" {
818             TargetSelection::from_user("x86_64-unknown-linux-gnu")
819         } else {
820             self.target
821         };
822         let dst = builder.test_helpers_out(target);
823         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
824         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
825             return;
826         }
827
828         builder.info("Building test helpers");
829         t!(fs::create_dir_all(&dst));
830         let mut cfg = cc::Build::new();
831         // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
832         if target.contains("emscripten") {
833             cfg.pic(false);
834         }
835
836         // We may have found various cross-compilers a little differently due to our
837         // extra configuration, so inform cc of these compilers. Note, though, that
838         // on MSVC we still need cc's detection of env vars (ugh).
839         if !target.contains("msvc") {
840             if let Some(ar) = builder.ar(target) {
841                 cfg.archiver(ar);
842             }
843             cfg.compiler(builder.cc(target));
844         }
845         cfg.cargo_metadata(false)
846             .out_dir(&dst)
847             .target(&target.triple)
848             .host(&builder.config.build.triple)
849             .opt_level(0)
850             .warnings(false)
851             .debug(false)
852             .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
853             .compile("rust_test_helpers");
854     }
855 }
856
857 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
858 pub struct Sanitizers {
859     pub target: TargetSelection,
860 }
861
862 impl Step for Sanitizers {
863     type Output = Vec<SanitizerRuntime>;
864
865     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
866         run.alias("sanitizers")
867     }
868
869     fn make_run(run: RunConfig<'_>) {
870         run.builder.ensure(Sanitizers { target: run.target });
871     }
872
873     /// Builds sanitizer runtime libraries.
874     fn run(self, builder: &Builder<'_>) -> Self::Output {
875         let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
876         if !compiler_rt_dir.exists() {
877             return Vec::new();
878         }
879
880         let out_dir = builder.native_dir(self.target).join("sanitizers");
881         let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
882         if runtimes.is_empty() {
883             return runtimes;
884         }
885
886         let llvm_config = builder.ensure(Llvm { target: builder.config.build });
887         if builder.config.dry_run {
888             return runtimes;
889         }
890
891         let stamp = out_dir.join("sanitizers-finished-building");
892         let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
893
894         if stamp.is_done() {
895             if stamp.hash.is_none() {
896                 builder.info(&format!(
897                     "Rebuild sanitizers by removing the file `{}`",
898                     stamp.path.display()
899                 ));
900             }
901             return runtimes;
902         }
903
904         builder.info(&format!("Building sanitizers for {}", self.target));
905         t!(stamp.remove());
906         let _time = util::timeit(&builder);
907
908         let mut cfg = cmake::Config::new(&compiler_rt_dir);
909         cfg.profile("Release");
910         cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
911         cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
912         cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
913         cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
914         cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
915         cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
916         cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
917         cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
918         cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
919         cfg.define("LLVM_CONFIG_PATH", &llvm_config);
920
921         // On Darwin targets the sanitizer runtimes are build as universal binaries.
922         // Unfortunately sccache currently lacks support to build them successfully.
923         // Disable compiler launcher on Darwin targets to avoid potential issues.
924         let use_compiler_launcher = !self.target.contains("apple-darwin");
925         configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
926
927         t!(fs::create_dir_all(&out_dir));
928         cfg.out_dir(out_dir);
929
930         for runtime in &runtimes {
931             cfg.build_target(&runtime.cmake_target);
932             cfg.build();
933         }
934         t!(stamp.write());
935
936         runtimes
937     }
938 }
939
940 #[derive(Clone, Debug)]
941 pub struct SanitizerRuntime {
942     /// CMake target used to build the runtime.
943     pub cmake_target: String,
944     /// Path to the built runtime library.
945     pub path: PathBuf,
946     /// Library filename that will be used rustc.
947     pub name: String,
948 }
949
950 /// Returns sanitizers available on a given target.
951 fn supported_sanitizers(
952     out_dir: &Path,
953     target: TargetSelection,
954     channel: &str,
955 ) -> Vec<SanitizerRuntime> {
956     let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
957         components
958             .iter()
959             .map(move |c| SanitizerRuntime {
960                 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
961                 path: out_dir
962                     .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
963                 name: format!("librustc-{}_rt.{}.dylib", channel, c),
964             })
965             .collect()
966     };
967
968     let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
969         components
970             .iter()
971             .map(move |c| SanitizerRuntime {
972                 cmake_target: format!("clang_rt.{}-{}", c, arch),
973                 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
974                 name: format!("librustc-{}_rt.{}.a", channel, c),
975             })
976             .collect()
977     };
978
979     match &*target.triple {
980         "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
981         "aarch64-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
982         "aarch64-unknown-linux-gnu" => {
983             common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
984         }
985         "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
986         "x86_64-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
987         "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
988         "x86_64-unknown-netbsd" => {
989             common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
990         }
991         "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
992         "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
993         "x86_64-unknown-linux-gnu" => {
994             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
995         }
996         "x86_64-unknown-linux-musl" => {
997             common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
998         }
999         _ => Vec::new(),
1000     }
1001 }
1002
1003 struct HashStamp {
1004     path: PathBuf,
1005     hash: Option<Vec<u8>>,
1006 }
1007
1008 impl HashStamp {
1009     fn new(path: PathBuf, hash: Option<&str>) -> Self {
1010         HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
1011     }
1012
1013     fn is_done(&self) -> bool {
1014         match fs::read(&self.path) {
1015             Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
1016             Err(e) if e.kind() == io::ErrorKind::NotFound => false,
1017             Err(e) => {
1018                 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
1019             }
1020         }
1021     }
1022
1023     fn remove(&self) -> io::Result<()> {
1024         match fs::remove_file(&self.path) {
1025             Ok(()) => Ok(()),
1026             Err(e) => {
1027                 if e.kind() == io::ErrorKind::NotFound {
1028                     Ok(())
1029                 } else {
1030                     Err(e)
1031                 }
1032             }
1033         }
1034     }
1035
1036     fn write(&self) -> io::Result<()> {
1037         fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
1038     }
1039 }
1040
1041 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1042 pub struct CrtBeginEnd {
1043     pub target: TargetSelection,
1044 }
1045
1046 impl Step for CrtBeginEnd {
1047     type Output = PathBuf;
1048
1049     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1050         run.path("src/llvm-project/compiler-rt/lib/crt")
1051     }
1052
1053     fn make_run(run: RunConfig<'_>) {
1054         run.builder.ensure(CrtBeginEnd { target: run.target });
1055     }
1056
1057     /// Build crtbegin.o/crtend.o for musl target.
1058     fn run(self, builder: &Builder<'_>) -> Self::Output {
1059         let out_dir = builder.native_dir(self.target).join("crt");
1060
1061         if builder.config.dry_run {
1062             return out_dir;
1063         }
1064
1065         let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
1066         let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
1067         if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
1068             && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1069         {
1070             return out_dir;
1071         }
1072
1073         builder.info("Building crtbegin.o and crtend.o");
1074         t!(fs::create_dir_all(&out_dir));
1075
1076         let mut cfg = cc::Build::new();
1077
1078         if let Some(ar) = builder.ar(self.target) {
1079             cfg.archiver(ar);
1080         }
1081         cfg.compiler(builder.cc(self.target));
1082         cfg.cargo_metadata(false)
1083             .out_dir(&out_dir)
1084             .target(&self.target.triple)
1085             .host(&builder.config.build.triple)
1086             .warnings(false)
1087             .debug(false)
1088             .opt_level(3)
1089             .file(crtbegin_src)
1090             .file(crtend_src);
1091
1092         // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1093         // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1094         // instead of .ctors/.dtors
1095         cfg.flag("-std=c11")
1096             .define("CRT_HAS_INITFINI_ARRAY", None)
1097             .define("EH_USE_FRAME_REGISTRY", None);
1098
1099         cfg.compile("crt");
1100
1101         t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1102         t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1103         out_dir
1104     }
1105 }
1106
1107 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1108 pub struct Libunwind {
1109     pub target: TargetSelection,
1110 }
1111
1112 impl Step for Libunwind {
1113     type Output = PathBuf;
1114
1115     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1116         run.path("src/llvm-project/libunwind")
1117     }
1118
1119     fn make_run(run: RunConfig<'_>) {
1120         run.builder.ensure(Libunwind { target: run.target });
1121     }
1122
1123     /// Build linunwind.a
1124     fn run(self, builder: &Builder<'_>) -> Self::Output {
1125         if builder.config.dry_run {
1126             return PathBuf::new();
1127         }
1128
1129         let out_dir = builder.native_dir(self.target).join("libunwind");
1130         let root = builder.src.join("src/llvm-project/libunwind");
1131
1132         if up_to_date(&root, &out_dir.join("libunwind.a")) {
1133             return out_dir;
1134         }
1135
1136         builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1137         t!(fs::create_dir_all(&out_dir));
1138
1139         let mut cc_cfg = cc::Build::new();
1140         let mut cpp_cfg = cc::Build::new();
1141
1142         cpp_cfg.cpp(true);
1143         cpp_cfg.cpp_set_stdlib(None);
1144         cpp_cfg.flag("-nostdinc++");
1145         cpp_cfg.flag("-fno-exceptions");
1146         cpp_cfg.flag("-fno-rtti");
1147         cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1148
1149         for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1150             if let Some(ar) = builder.ar(self.target) {
1151                 cfg.archiver(ar);
1152             }
1153             cfg.target(&self.target.triple);
1154             cfg.host(&builder.config.build.triple);
1155             cfg.warnings(false);
1156             cfg.debug(false);
1157             // get_compiler() need set opt_level first.
1158             cfg.opt_level(3);
1159             cfg.flag("-fstrict-aliasing");
1160             cfg.flag("-funwind-tables");
1161             cfg.flag("-fvisibility=hidden");
1162             cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1163             cfg.include(root.join("include"));
1164             cfg.cargo_metadata(false);
1165             cfg.out_dir(&out_dir);
1166
1167             if self.target.contains("x86_64-fortanix-unknown-sgx") {
1168                 cfg.static_flag(true);
1169                 cfg.flag("-fno-stack-protector");
1170                 cfg.flag("-ffreestanding");
1171                 cfg.flag("-fexceptions");
1172
1173                 // easiest way to undefine since no API available in cc::Build to undefine
1174                 cfg.flag("-U_FORTIFY_SOURCE");
1175                 cfg.define("_FORTIFY_SOURCE", "0");
1176                 cfg.define("RUST_SGX", "1");
1177                 cfg.define("__NO_STRING_INLINES", None);
1178                 cfg.define("__NO_MATH_INLINES", None);
1179                 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1180                 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1181                 cfg.define("NDEBUG", None);
1182             }
1183             if self.target.contains("windows") {
1184                 cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1185                 cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1186             }
1187         }
1188
1189         cc_cfg.compiler(builder.cc(self.target));
1190         if let Ok(cxx) = builder.cxx(self.target) {
1191             cpp_cfg.compiler(cxx);
1192         } else {
1193             cc_cfg.compiler(builder.cc(self.target));
1194         }
1195
1196         // Don't set this for clang
1197         // By default, Clang builds C code in GNU C17 mode.
1198         // By default, Clang builds C++ code according to the C++98 standard,
1199         // with many C++11 features accepted as extensions.
1200         if cc_cfg.get_compiler().is_like_gnu() {
1201             cc_cfg.flag("-std=c99");
1202         }
1203         if cpp_cfg.get_compiler().is_like_gnu() {
1204             cpp_cfg.flag("-std=c++11");
1205         }
1206
1207         if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1208             // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1209             // C++ compiler env variables on the builders.
1210             // Don't set this for clang++, as clang++ is able to compile this without libc++.
1211             if cpp_cfg.get_compiler().is_like_gnu() {
1212                 cpp_cfg.cpp(false);
1213                 cpp_cfg.compiler(builder.cc(self.target));
1214             }
1215         }
1216
1217         let mut c_sources = vec![
1218             "Unwind-sjlj.c",
1219             "UnwindLevel1-gcc-ext.c",
1220             "UnwindLevel1.c",
1221             "UnwindRegistersRestore.S",
1222             "UnwindRegistersSave.S",
1223         ];
1224
1225         let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1226         let cpp_len = cpp_sources.len();
1227
1228         if self.target.contains("x86_64-fortanix-unknown-sgx") {
1229             c_sources.push("UnwindRustSgx.c");
1230         }
1231
1232         for src in c_sources {
1233             cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1234         }
1235
1236         for src in &cpp_sources {
1237             cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1238         }
1239
1240         cpp_cfg.compile("unwind-cpp");
1241
1242         // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1243         let mut count = 0;
1244         for entry in fs::read_dir(&out_dir).unwrap() {
1245             let file = entry.unwrap().path().canonicalize().unwrap();
1246             if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1247                 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1248                 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1249                 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1250                     cc_cfg.object(&file);
1251                     count += 1;
1252                 }
1253             }
1254         }
1255         assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1256
1257         cc_cfg.compile("unwind");
1258         out_dir
1259     }
1260 }