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