1 //! Compilation of native dependencies like LLVM.
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).
8 //! LLVM and compiler-rt are essentially just wired up to everything else to
9 //! ensure that they're always in place if needed.
12 use std::env::consts::EXE_EXTENSION;
13 use std::ffi::{OsStr, OsString};
14 use std::fs::{self, File};
16 use std::path::{Path, PathBuf};
17 use std::process::Command;
19 use crate::bolt::{instrument_with_bolt_inplace, optimize_library_with_bolt_inplace};
20 use crate::builder::{Builder, RunConfig, ShouldRun, Step};
22 use crate::config::{Config, TargetSelection};
23 use crate::util::get_clang_cl_resource_dir;
24 use crate::util::{self, exe, output, t, up_to_date};
25 use crate::{CLang, GitRepo};
27 use build_helper::ci::CiEnv;
30 pub struct LlvmResult {
31 /// Path to llvm-config binary.
32 /// NB: This is always the host llvm-config!
33 pub llvm_config: PathBuf,
34 /// Path to LLVM cmake directory for the target.
35 pub llvm_cmake_dir: PathBuf,
45 // Linker flags to pass to LLVM's CMake invocation.
46 #[derive(Debug, Clone, Default)]
48 // CMAKE_EXE_LINKER_FLAGS
50 // CMAKE_SHARED_LINKER_FLAGS
52 // CMAKE_MODULE_LINKER_FLAGS
57 fn push_all(&mut self, s: impl AsRef<OsStr>) {
61 self.shared.push(" ");
63 self.module.push(" ");
68 /// This returns whether we've already previously built LLVM.
70 /// It's used to avoid busting caches during x.py check -- if we've already built
71 /// LLVM, it's fine for us to not try to avoid doing so.
73 /// This will return the llvm-config if it can get it (but it will not build it
75 pub fn prebuilt_llvm_config(
76 builder: &Builder<'_>,
77 target: TargetSelection,
78 ) -> Result<LlvmResult, Meta> {
79 builder.config.maybe_download_ci_llvm();
81 // If we're using a custom LLVM bail out here, but we can only use a
82 // custom LLVM for the build triple.
83 if let Some(config) = builder.config.target_config.get(&target) {
84 if let Some(ref s) = config.llvm_config {
85 check_llvm_version(builder, s);
86 let llvm_config = s.to_path_buf();
87 let mut llvm_cmake_dir = llvm_config.clone();
90 llvm_cmake_dir.push("lib");
91 llvm_cmake_dir.push("cmake");
92 llvm_cmake_dir.push("llvm");
93 return Ok(LlvmResult { llvm_config, llvm_cmake_dir });
97 let root = "src/llvm-project/llvm";
98 let out_dir = builder.llvm_out(target);
100 let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build);
101 if !builder.config.build.contains("msvc") || builder.ninja() {
102 llvm_config_ret_dir.push("build");
104 llvm_config_ret_dir.push("bin");
105 let build_llvm_config = llvm_config_ret_dir.join(exe("llvm-config", builder.config.build));
106 let llvm_cmake_dir = out_dir.join("lib/cmake/llvm");
107 let res = LlvmResult { llvm_config: build_llvm_config, llvm_cmake_dir };
109 let stamp = out_dir.join("llvm-finished-building");
110 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
112 if builder.config.llvm_skip_rebuild && stamp.path.exists() {
115 Using a potentially stale build of LLVM; \
116 This may not behave well.",
122 if stamp.hash.is_none() {
124 "Could not determine the LLVM submodule commit hash. \
125 Assuming that an LLVM rebuild is not necessary.",
127 builder.info(&format!(
128 "To force LLVM to rebuild, remove the file `{}`",
135 Err(Meta { stamp, res, out_dir, root: root.into() })
138 /// This retrieves the LLVM sha we *want* to use, according to git history.
139 pub(crate) fn detect_llvm_sha(config: &Config, is_git: bool) -> String {
140 let llvm_sha = if is_git {
141 let mut rev_list = config.git();
143 PathBuf::from("rev-list"),
144 format!("--author={}", config.stage0_metadata.config.git_merge_commit_email).into(),
146 "--first-parent".into(),
149 config.src.join("src/llvm-project"),
150 config.src.join("src/bootstrap/download-ci-llvm-stamp"),
151 // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly`
152 config.src.join("src/version"),
154 output(&mut rev_list).trim().to_owned()
155 } else if let Some(info) = channel::read_commit_info_file(&config.src) {
156 info.sha.trim().to_owned()
162 eprintln!("error: could not find commit hash for downloading LLVM");
163 eprintln!("help: maybe your repository history is too shallow?");
164 eprintln!("help: consider disabling `download-ci-llvm`");
165 eprintln!("help: or fetch enough history to include one upstream commit");
172 /// Returns whether the CI-found LLVM is currently usable.
174 /// This checks both the build triple platform to confirm we're usable at all,
175 /// and then verifies if the current HEAD matches the detected LLVM SHA head,
176 /// in which case LLVM is indicated as not available.
177 pub(crate) fn is_ci_llvm_available(config: &Config, asserts: bool) -> bool {
178 // This is currently all tier 1 targets and tier 2 targets with host tools
179 // (since others may not have CI artifacts)
180 // https://doc.rust-lang.org/rustc/platform-support.html#tier-1
181 let supported_platforms = [
183 "aarch64-unknown-linux-gnu",
184 "i686-pc-windows-gnu",
185 "i686-pc-windows-msvc",
186 "i686-unknown-linux-gnu",
187 "x86_64-unknown-linux-gnu",
188 "x86_64-apple-darwin",
189 "x86_64-pc-windows-gnu",
190 "x86_64-pc-windows-msvc",
191 // tier 2 with host tools
192 "aarch64-apple-darwin",
193 "aarch64-pc-windows-msvc",
194 "aarch64-unknown-linux-musl",
195 "arm-unknown-linux-gnueabi",
196 "arm-unknown-linux-gnueabihf",
197 "armv7-unknown-linux-gnueabihf",
198 "mips-unknown-linux-gnu",
199 "mips64-unknown-linux-gnuabi64",
200 "mips64el-unknown-linux-gnuabi64",
201 "mipsel-unknown-linux-gnu",
202 "powerpc-unknown-linux-gnu",
203 "powerpc64-unknown-linux-gnu",
204 "powerpc64le-unknown-linux-gnu",
205 "riscv64gc-unknown-linux-gnu",
206 "s390x-unknown-linux-gnu",
207 "x86_64-unknown-freebsd",
208 "x86_64-unknown-illumos",
209 "x86_64-unknown-linux-musl",
210 "x86_64-unknown-netbsd",
212 if !supported_platforms.contains(&&*config.build.triple) {
216 let triple = &*config.build.triple;
217 if (triple == "aarch64-unknown-linux-gnu" || triple.contains("i686")) && asserts {
218 // No alt builder for aarch64-unknown-linux-gnu today.
223 // We assume we have access to git, so it's okay to unconditionally pass
225 let llvm_sha = detect_llvm_sha(config, true);
226 let head_sha = output(config.git().arg("rev-parse").arg("HEAD"));
227 let head_sha = head_sha.trim();
228 if llvm_sha == head_sha {
230 "Detected LLVM as non-available: running in CI and modified LLVM in this change"
239 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
241 pub target: TargetSelection,
245 type Output = LlvmResult;
247 const ONLY_HOSTS: bool = true;
249 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
250 run.path("src/llvm-project").path("src/llvm-project/llvm")
253 fn make_run(run: RunConfig<'_>) {
254 run.builder.ensure(Llvm { target: run.target });
257 /// Compile LLVM for `target`.
258 fn run(self, builder: &Builder<'_>) -> LlvmResult {
259 let target = self.target;
260 let target_native = if self.target.starts_with("riscv") {
261 // RISC-V target triples in Rust is not named the same as C compiler target triples.
262 // This converts Rust RISC-V target triples to C compiler triples.
263 let idx = target.triple.find('-').unwrap();
265 format!("riscv{}{}", &target.triple[5..7], &target.triple[idx..])
266 } else if self.target.starts_with("powerpc") && self.target.ends_with("freebsd") {
267 // FreeBSD 13 had incompatible ABI changes on all PowerPC platforms.
268 // Set the version suffix to 13.0 so the correct target details are used.
269 format!("{}{}", self.target, "13.0")
274 let Meta { stamp, res, out_dir, root } = match prebuilt_llvm_config(builder, target) {
279 builder.update_submodule(&Path::new("src").join("llvm-project"));
280 if builder.llvm_link_shared() && target.contains("windows") {
281 panic!("shared linking to LLVM is not currently supported on {}", target.triple);
284 builder.info(&format!("Building LLVM for {}", target));
286 let _time = util::timeit(&builder);
287 t!(fs::create_dir_all(&out_dir));
289 // https://llvm.org/docs/CMake.html
290 let mut cfg = cmake::Config::new(builder.src.join(root));
291 let mut ldflags = LdFlags::default();
293 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
294 (false, _) => "Debug",
295 (true, false) => "Release",
296 (true, true) => "RelWithDebInfo",
299 // NOTE: remember to also update `config.toml.example` when changing the
301 let llvm_targets = match &builder.config.llvm_targets {
304 "AArch64;ARM;BPF;Hexagon;MSP430;Mips;NVPTX;PowerPC;RISCV;\
305 Sparc;SystemZ;WebAssembly;X86"
309 let llvm_exp_targets = match builder.config.llvm_experimental_targets {
314 let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };
315 let plugins = if builder.config.llvm_plugins { "ON" } else { "OFF" };
316 let enable_tests = if builder.config.llvm_tests { "ON" } else { "OFF" };
318 cfg.out_dir(&out_dir)
320 .define("LLVM_ENABLE_ASSERTIONS", assertions)
321 .define("LLVM_ENABLE_PLUGINS", plugins)
322 .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
323 .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
324 .define("LLVM_INCLUDE_EXAMPLES", "OFF")
325 .define("LLVM_INCLUDE_DOCS", "OFF")
326 .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
327 .define("LLVM_INCLUDE_TESTS", enable_tests)
328 .define("LLVM_ENABLE_TERMINFO", "OFF")
329 .define("LLVM_ENABLE_LIBEDIT", "OFF")
330 .define("LLVM_ENABLE_BINDINGS", "OFF")
331 .define("LLVM_ENABLE_Z3_SOLVER", "OFF")
332 .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
333 .define("LLVM_TARGET_ARCH", target_native.split('-').next().unwrap())
334 .define("LLVM_DEFAULT_TARGET_TRIPLE", target_native);
336 // Parts of our test suite rely on the `FileCheck` tool, which is built by default in
337 // `build/$TARGET/llvm/build/bin` is but *not* then installed to `build/$TARGET/llvm/bin`.
338 // This flag makes sure `FileCheck` is copied in the final binaries directory.
339 cfg.define("LLVM_INSTALL_UTILS", "ON");
341 if builder.config.llvm_profile_generate {
342 cfg.define("LLVM_BUILD_INSTRUMENTED", "IR");
343 if let Ok(llvm_profile_dir) = std::env::var("LLVM_PROFILE_DIR") {
344 cfg.define("LLVM_PROFILE_DATA_DIR", llvm_profile_dir);
346 cfg.define("LLVM_BUILD_RUNTIME", "No");
348 if let Some(path) = builder.config.llvm_profile_use.as_ref() {
349 cfg.define("LLVM_PROFDATA_FILE", &path);
351 if builder.config.llvm_bolt_profile_generate
352 || builder.config.llvm_bolt_profile_use.is_some()
354 // Relocations are required for BOLT to work.
355 ldflags.push_all("-Wl,-q");
358 // Disable zstd to avoid a dependency on libzstd.so.
359 cfg.define("LLVM_ENABLE_ZSTD", "OFF");
361 if target != "aarch64-apple-darwin" && !target.contains("windows") {
362 cfg.define("LLVM_ENABLE_ZLIB", "ON");
364 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
367 // Are we compiling for iOS/tvOS/watchOS?
368 if target.contains("apple-ios")
369 || target.contains("apple-tvos")
370 || target.contains("apple-watchos")
372 // These two defines prevent CMake from automatically trying to add a MacOSX sysroot, which leads to a compiler error.
373 cfg.define("CMAKE_OSX_SYSROOT", "/");
374 cfg.define("CMAKE_OSX_DEPLOYMENT_TARGET", "");
375 // Prevent cmake from adding -bundle to CFLAGS automatically, which leads to a compiler error because "-bitcode_bundle" also gets added.
376 cfg.define("LLVM_ENABLE_PLUGINS", "OFF");
377 // Zlib fails to link properly, leading to a compiler error.
378 cfg.define("LLVM_ENABLE_ZLIB", "OFF");
381 // This setting makes the LLVM tools link to the dynamic LLVM library,
382 // which saves both memory during parallel links and overall disk space
383 // for the tools. We don't do this on every platform as it doesn't work
384 // equally well everywhere.
385 if builder.llvm_link_shared() {
386 cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
389 if target.starts_with("riscv") && !target.contains("freebsd") && !target.contains("openbsd")
391 // RISC-V GCC erroneously requires linking against
392 // `libatomic` when using 1-byte and 2-byte C++
393 // atomics but the LLVM build system check cannot
394 // detect this. Therefore it is set manually here.
395 // Some BSD uses Clang as its system compiler and
396 // provides no libatomic in its base system so does
398 ldflags.exe.push(" -latomic");
399 ldflags.shared.push(" -latomic");
402 if target.contains("msvc") {
403 cfg.define("LLVM_USE_CRT_DEBUG", "MT");
404 cfg.define("LLVM_USE_CRT_RELEASE", "MT");
405 cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
406 cfg.static_crt(true);
409 if target.starts_with("i686") {
410 cfg.define("LLVM_BUILD_32_BITS", "ON");
413 let mut enabled_llvm_projects = Vec::new();
415 if util::forcing_clang_based_tests() {
416 enabled_llvm_projects.push("clang");
417 enabled_llvm_projects.push("compiler-rt");
420 if builder.config.llvm_polly {
421 enabled_llvm_projects.push("polly");
424 if builder.config.llvm_clang {
425 enabled_llvm_projects.push("clang");
428 // We want libxml to be disabled.
429 // See https://github.com/rust-lang/rust/pull/50104
430 cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
432 if !enabled_llvm_projects.is_empty() {
433 enabled_llvm_projects.sort();
434 enabled_llvm_projects.dedup();
435 cfg.define("LLVM_ENABLE_PROJECTS", enabled_llvm_projects.join(";"));
438 if let Some(num_linkers) = builder.config.llvm_link_jobs {
440 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
444 // Workaround for ppc32 lld limitation
445 if target == "powerpc-unknown-freebsd" {
446 ldflags.exe.push(" -fuse-ld=bfd");
449 // https://llvm.org/docs/HowToCrossCompileLLVM.html
450 if target != builder.config.build {
451 let LlvmResult { llvm_config, .. } =
452 builder.ensure(Llvm { target: builder.config.build });
453 if !builder.config.dry_run() {
454 let llvm_bindir = output(Command::new(&llvm_config).arg("--bindir"));
455 let host_bin = Path::new(llvm_bindir.trim());
458 host_bin.join("llvm-tblgen").with_extension(EXE_EXTENSION),
460 // LLVM_NM is required for cross compiling using MSVC
461 cfg.define("LLVM_NM", host_bin.join("llvm-nm").with_extension(EXE_EXTENSION));
463 cfg.define("LLVM_CONFIG_PATH", llvm_config);
464 if builder.config.llvm_clang {
465 let build_bin = builder.llvm_out(builder.config.build).join("build").join("bin");
466 let clang_tblgen = build_bin.join("clang-tblgen").with_extension(EXE_EXTENSION);
467 if !builder.config.dry_run() && !clang_tblgen.exists() {
468 panic!("unable to find {}", clang_tblgen.display());
470 cfg.define("CLANG_TABLEGEN", clang_tblgen);
474 let llvm_version_suffix = if let Some(ref suffix) = builder.config.llvm_version_suffix {
475 // Allow version-suffix="" to not define a version suffix at all.
476 if !suffix.is_empty() { Some(suffix.to_string()) } else { None }
477 } else if builder.config.channel == "dev" {
478 // Changes to a version suffix require a complete rebuild of the LLVM.
479 // To avoid rebuilds during a time of version bump, don't include rustc
480 // release number on the dev channel.
481 Some("-rust-dev".to_string())
483 Some(format!("-rust-{}-{}", builder.version, builder.config.channel))
485 if let Some(ref suffix) = llvm_version_suffix {
486 cfg.define("LLVM_VERSION_SUFFIX", suffix);
489 configure_cmake(builder, target, &mut cfg, true, ldflags);
490 configure_llvm(builder, target, &mut cfg);
492 for (key, val) in &builder.config.llvm_build_config {
493 cfg.define(key, val);
496 // FIXME: we don't actually need to build all LLVM tools and all LLVM
497 // libraries here, e.g., we just want a few components and a few
498 // tools. Figure out how to filter them down and only build the right
499 // tools and libs on all platforms.
501 if builder.config.dry_run() {
507 // When building LLVM with LLVM_LINK_LLVM_DYLIB for macOS, an unversioned
508 // libLLVM.dylib will be built. However, llvm-config will still look
509 // for a versioned path like libLLVM-14.dylib. Manually create a symbolic
510 // link to make llvm-config happy.
511 if builder.llvm_link_shared() && target.contains("apple-darwin") {
512 let mut cmd = Command::new(&res.llvm_config);
513 let version = output(cmd.arg("--version"));
514 let major = version.split('.').next().unwrap();
515 let lib_name = match llvm_version_suffix {
516 Some(s) => format!("libLLVM-{}{}.dylib", major, s),
517 None => format!("libLLVM-{}.dylib", major),
520 let lib_llvm = out_dir.join("build").join("lib").join(lib_name);
521 if !lib_llvm.exists() {
522 t!(builder.symlink_file("libLLVM.dylib", &lib_llvm));
526 // After LLVM is built, we modify (instrument or optimize) the libLLVM.so library file
527 // in place. This is fine, because currently we do not support incrementally rebuilding
528 // LLVM after a configuration change, so to rebuild it the build files have to be removed,
529 // which will also remove these modified files.
530 if builder.config.llvm_bolt_profile_generate {
531 instrument_with_bolt_inplace(&get_built_llvm_lib_path(&res.llvm_config));
533 if let Some(path) = &builder.config.llvm_bolt_profile_use {
534 optimize_library_with_bolt_inplace(
535 &get_built_llvm_lib_path(&res.llvm_config),
546 /// Returns path to a built LLVM library (libLLVM.so).
547 /// Assumes that we have built LLVM into a single library file.
548 fn get_built_llvm_lib_path(llvm_config_path: &Path) -> PathBuf {
549 let mut cmd = Command::new(llvm_config_path);
550 cmd.arg("--libfiles");
551 PathBuf::from(output(&mut cmd).trim())
554 fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) {
555 if !builder.config.llvm_version_check {
559 if builder.config.dry_run() {
563 let mut cmd = Command::new(llvm_config);
564 let version = output(cmd.arg("--version"));
565 let mut parts = version.split('.').take(2).filter_map(|s| s.parse::<u32>().ok());
566 if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
571 panic!("\n\nbad LLVM version: {}, need >=13.0\n\n", version)
575 builder: &Builder<'_>,
576 target: TargetSelection,
577 cfg: &mut cmake::Config,
578 use_compiler_launcher: bool,
579 mut ldflags: LdFlags,
581 // Do not print installation messages for up-to-date files.
582 // LLVM and LLD builds can produce a lot of those and hit CI limits on log size.
583 cfg.define("CMAKE_INSTALL_MESSAGE", "LAZY");
585 // Do not allow the user's value of DESTDIR to influence where
586 // LLVM will install itself. LLVM must always be installed in our
587 // own build directories.
588 cfg.env("DESTDIR", "");
591 cfg.generator("Ninja");
593 cfg.target(&target.triple).host(&builder.config.build.triple);
595 if target != builder.config.build {
596 cfg.define("CMAKE_CROSSCOMPILING", "True");
598 if target.contains("netbsd") {
599 cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
600 } else if target.contains("freebsd") {
601 cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
602 } else if target.contains("windows") {
603 cfg.define("CMAKE_SYSTEM_NAME", "Windows");
604 } else if target.contains("haiku") {
605 cfg.define("CMAKE_SYSTEM_NAME", "Haiku");
606 } else if target.contains("solaris") || target.contains("illumos") {
607 cfg.define("CMAKE_SYSTEM_NAME", "SunOS");
609 // When cross-compiling we should also set CMAKE_SYSTEM_VERSION, but in
610 // that case like CMake we cannot easily determine system version either.
612 // Since, the LLVM itself makes rather limited use of version checks in
613 // CMakeFiles (and then only in tests), and so far no issues have been
614 // reported, the system version is currently left unset.
616 if target.contains("darwin") {
617 // Make sure that CMake does not build universal binaries on macOS.
618 // Explicitly specify the one single target architecture.
619 if target.starts_with("aarch64") {
620 // macOS uses a different name for building arm64
621 cfg.define("CMAKE_OSX_ARCHITECTURES", "arm64");
622 } else if target.starts_with("i686") {
623 // macOS uses a different name for building i386
624 cfg.define("CMAKE_OSX_ARCHITECTURES", "i386");
626 cfg.define("CMAKE_OSX_ARCHITECTURES", target.triple.split('-').next().unwrap());
631 let sanitize_cc = |cc: &Path| {
632 if target.contains("msvc") {
633 OsString::from(cc.to_str().unwrap().replace("\\", "/"))
635 cc.as_os_str().to_owned()
639 // MSVC with CMake uses msbuild by default which doesn't respect these
640 // vars that we'd otherwise configure. In that case we just skip this
642 if target.contains("msvc") && !builder.ninja() {
646 let (cc, cxx) = match builder.config.llvm_clang_cl {
647 Some(ref cl) => (cl.as_ref(), cl.as_ref()),
648 None => (builder.cc(target), builder.cxx(target).unwrap()),
651 // Handle msvc + ninja + ccache specially (this is what the bots use)
652 if target.contains("msvc") && builder.ninja() && builder.config.ccache.is_some() {
653 let mut wrap_cc = env::current_exe().expect("failed to get cwd");
654 wrap_cc.set_file_name("sccache-plus-cl.exe");
656 cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
657 .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
658 cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap())
659 .env("SCCACHE_TARGET", target.triple)
660 .env("SCCACHE_CC", &cc)
661 .env("SCCACHE_CXX", &cxx);
663 // Building LLVM on MSVC can be a little ludicrous at times. We're so far
664 // off the beaten path here that I'm not really sure this is even half
665 // supported any more. Here we're trying to:
667 // * Build LLVM on MSVC
668 // * Build LLVM with `clang-cl` instead of `cl.exe`
669 // * Build a project with `sccache`
670 // * Build for 32-bit as well
671 // * Build with Ninja
673 // For `cl.exe` there are different binaries to compile 32/64 bit which
674 // we use but for `clang-cl` there's only one which internally
675 // multiplexes via flags. As a result it appears that CMake's detection
676 // of a compiler's architecture and such on MSVC **doesn't** pass any
677 // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
678 // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
679 // definitely causes problems since all the env vars are pointing to
682 // To hack around this... again... we pass an argument that's
683 // unconditionally passed in the sccache shim. This'll get CMake to
684 // correctly diagnose it's doing a 32-bit compilation and LLVM will
685 // internally configure itself appropriately.
686 if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
687 cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
690 // If ccache is configured we inform the build a little differently how
691 // to invoke ccache while also invoking our compilers.
692 if use_compiler_launcher {
693 if let Some(ref ccache) = builder.config.ccache {
694 cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache)
695 .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache);
698 cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
699 .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx))
700 .define("CMAKE_ASM_COMPILER", sanitize_cc(cc));
703 cfg.build_arg("-j").build_arg(builder.jobs().to_string());
704 let mut cflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::C).join(" ").into();
705 if let Some(ref s) = builder.config.llvm_cflags {
709 // Some compiler features used by LLVM (such as thread locals) will not work on a min version below iOS 10.
710 if target.contains("apple-ios") {
711 if target.contains("86-") {
712 cflags.push(" -miphonesimulator-version-min=10.0");
714 cflags.push(" -miphoneos-version-min=10.0");
717 if builder.config.llvm_clang_cl.is_some() {
718 cflags.push(&format!(" --target={}", target));
720 cfg.define("CMAKE_C_FLAGS", cflags);
721 let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into();
722 if let Some(ref s) = builder.config.llvm_cxxflags {
726 if builder.config.llvm_clang_cl.is_some() {
727 cxxflags.push(&format!(" --target={}", target));
729 cfg.define("CMAKE_CXX_FLAGS", cxxflags);
730 if let Some(ar) = builder.ar(target) {
731 if ar.is_absolute() {
732 // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
733 // tries to resolve this path in the LLVM build directory.
734 cfg.define("CMAKE_AR", sanitize_cc(ar));
738 if let Some(ranlib) = builder.ranlib(target) {
739 if ranlib.is_absolute() {
740 // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
741 // tries to resolve this path in the LLVM build directory.
742 cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
746 if let Some(ref flags) = builder.config.llvm_ldflags {
747 ldflags.push_all(flags);
750 if let Some(flags) = get_var("LDFLAGS", &builder.config.build.triple, &target.triple) {
751 ldflags.push_all(&flags);
754 // For distribution we want the LLVM tools to be *statically* linked to libstdc++.
755 // We also do this if the user explicitly requested static libstdc++.
756 if builder.config.llvm_static_stdcpp {
757 if !target.contains("msvc") && !target.contains("netbsd") && !target.contains("solaris") {
758 if target.contains("apple") || target.contains("windows") {
759 ldflags.push_all("-static-libstdc++");
761 ldflags.push_all("-Wl,-Bsymbolic -static-libstdc++");
766 cfg.define("CMAKE_SHARED_LINKER_FLAGS", &ldflags.shared);
767 cfg.define("CMAKE_MODULE_LINKER_FLAGS", &ldflags.module);
768 cfg.define("CMAKE_EXE_LINKER_FLAGS", &ldflags.exe);
770 if env::var_os("SCCACHE_ERROR_LOG").is_some() {
771 cfg.env("RUSTC_LOG", "sccache=warn");
775 fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmake::Config) {
776 // ThinLTO is only available when building with LLVM, enabling LLD is required.
777 // Apple's linker ld64 supports ThinLTO out of the box though, so don't use LLD on Darwin.
778 if builder.config.llvm_thin_lto {
779 cfg.define("LLVM_ENABLE_LTO", "Thin");
780 if !target.contains("apple") {
781 cfg.define("LLVM_ENABLE_LLD", "ON");
785 if let Some(ref linker) = builder.config.llvm_use_linker {
786 cfg.define("LLVM_USE_LINKER", linker);
789 if builder.config.llvm_allow_old_toolchain {
790 cfg.define("LLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN", "YES");
794 // Adapted from https://github.com/alexcrichton/cc-rs/blob/fba7feded71ee4f63cfe885673ead6d7b4f2f454/src/lib.rs#L2347-L2365
795 fn get_var(var_base: &str, host: &str, target: &str) -> Option<OsString> {
796 let kind = if host == target { "HOST" } else { "TARGET" };
797 let target_u = target.replace("-", "_");
798 env::var_os(&format!("{}_{}", var_base, target))
799 .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u)))
800 .or_else(|| env::var_os(&format!("{}_{}", kind, var_base)))
801 .or_else(|| env::var_os(var_base))
804 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
806 pub target: TargetSelection,
810 type Output = PathBuf;
811 const ONLY_HOSTS: bool = true;
813 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
814 run.path("src/llvm-project/lld")
817 fn make_run(run: RunConfig<'_>) {
818 run.builder.ensure(Lld { target: run.target });
821 /// Compile LLD for `target`.
822 fn run(self, builder: &Builder<'_>) -> PathBuf {
823 if builder.config.dry_run() {
824 return PathBuf::from("lld-out-dir-test-gen");
826 let target = self.target;
828 let LlvmResult { llvm_config, llvm_cmake_dir } = builder.ensure(Llvm { target });
830 // The `dist` step packages LLD next to LLVM's binaries for download-ci-llvm. The root path
831 // we usually expect here is `./build/$triple/ci-llvm/`, with the binaries in its `bin`
832 // subfolder. We check if that's the case, and if LLD's binary already exists there next to
833 // `llvm-config`: if so, we can use it instead of building LLVM/LLD from source.
834 let ci_llvm_bin = llvm_config.parent().unwrap();
835 if ci_llvm_bin.is_dir() && ci_llvm_bin.file_name().unwrap() == "bin" {
836 let lld_path = ci_llvm_bin.join(exe("lld", target));
837 if lld_path.exists() {
838 // The following steps copying `lld` as `rust-lld` to the sysroot, expect it in the
839 // `bin` subfolder of this step's out dir.
840 return ci_llvm_bin.parent().unwrap().to_path_buf();
844 let out_dir = builder.lld_out(target);
845 let done_stamp = out_dir.join("lld-finished-building");
846 if done_stamp.exists() {
850 builder.info(&format!("Building LLD for {}", target));
851 let _time = util::timeit(&builder);
852 t!(fs::create_dir_all(&out_dir));
854 let mut cfg = cmake::Config::new(builder.src.join("src/llvm-project/lld"));
855 let mut ldflags = LdFlags::default();
857 // When building LLD as part of a build with instrumentation on windows, for example
858 // when doing PGO on CI, cmake or clang-cl don't automatically link clang's
859 // profiler runtime in. In that case, we need to manually ask cmake to do it, to avoid
860 // linking errors, much like LLVM's cmake setup does in that situation.
861 if builder.config.llvm_profile_generate && target.contains("msvc") {
862 if let Some(clang_cl_path) = builder.config.llvm_clang_cl.as_ref() {
863 // Find clang's runtime library directory and push that as a search path to the
864 // cmake linker flags.
865 let clang_rt_dir = get_clang_cl_resource_dir(clang_cl_path);
866 ldflags.push_all(&format!("/libpath:{}", clang_rt_dir.display()));
870 configure_cmake(builder, target, &mut cfg, true, ldflags);
871 configure_llvm(builder, target, &mut cfg);
873 // Re-use the same flags as llvm to control the level of debug information
874 // generated for lld.
875 let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
876 (false, _) => "Debug",
877 (true, false) => "Release",
878 (true, true) => "RelWithDebInfo",
881 cfg.out_dir(&out_dir)
883 .define("LLVM_CMAKE_DIR", llvm_cmake_dir)
884 .define("LLVM_INCLUDE_TESTS", "OFF");
886 if target != builder.config.build {
887 // Use the host llvm-tblgen binary.
890 llvm_config.with_file_name("llvm-tblgen").with_extension(EXE_EXTENSION),
896 t!(File::create(&done_stamp));
901 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
902 pub struct TestHelpers {
903 pub target: TargetSelection,
906 impl Step for TestHelpers {
909 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
910 run.path("tests/auxiliary/rust_test_helpers.c")
913 fn make_run(run: RunConfig<'_>) {
914 run.builder.ensure(TestHelpers { target: run.target })
917 /// Compiles the `rust_test_helpers.c` library which we used in various
918 /// `run-pass` tests for ABI testing.
919 fn run(self, builder: &Builder<'_>) {
920 if builder.config.dry_run() {
923 // The x86_64-fortanix-unknown-sgx target doesn't have a working C
924 // toolchain. However, some x86_64 ELF objects can be linked
925 // without issues. Use this hack to compile the test helpers.
926 let target = if self.target == "x86_64-fortanix-unknown-sgx" {
927 TargetSelection::from_user("x86_64-unknown-linux-gnu")
931 let dst = builder.test_helpers_out(target);
932 let src = builder.src.join("tests/auxiliary/rust_test_helpers.c");
933 if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
937 builder.info("Building test helpers");
938 t!(fs::create_dir_all(&dst));
939 let mut cfg = cc::Build::new();
940 // FIXME: Workaround for https://github.com/emscripten-core/emscripten/issues/9013
941 if target.contains("emscripten") {
945 // We may have found various cross-compilers a little differently due to our
946 // extra configuration, so inform cc of these compilers. Note, though, that
947 // on MSVC we still need cc's detection of env vars (ugh).
948 if !target.contains("msvc") {
949 if let Some(ar) = builder.ar(target) {
952 cfg.compiler(builder.cc(target));
954 cfg.cargo_metadata(false)
956 .target(&target.triple)
957 .host(&builder.config.build.triple)
961 .file(builder.src.join("tests/auxiliary/rust_test_helpers.c"))
962 .compile("rust_test_helpers");
966 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
967 pub struct Sanitizers {
968 pub target: TargetSelection,
971 impl Step for Sanitizers {
972 type Output = Vec<SanitizerRuntime>;
974 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
975 run.alias("sanitizers")
978 fn make_run(run: RunConfig<'_>) {
979 run.builder.ensure(Sanitizers { target: run.target });
982 /// Builds sanitizer runtime libraries.
983 fn run(self, builder: &Builder<'_>) -> Self::Output {
984 let compiler_rt_dir = builder.src.join("src/llvm-project/compiler-rt");
985 if !compiler_rt_dir.exists() {
989 let out_dir = builder.native_dir(self.target).join("sanitizers");
990 let runtimes = supported_sanitizers(&out_dir, self.target, &builder.config.channel);
991 if runtimes.is_empty() {
995 let LlvmResult { llvm_config, .. } = builder.ensure(Llvm { target: builder.config.build });
996 if builder.config.dry_run() {
1000 let stamp = out_dir.join("sanitizers-finished-building");
1001 let stamp = HashStamp::new(stamp, builder.in_tree_llvm_info.sha());
1003 if stamp.is_done() {
1004 if stamp.hash.is_none() {
1005 builder.info(&format!(
1006 "Rebuild sanitizers by removing the file `{}`",
1007 stamp.path.display()
1013 builder.info(&format!("Building sanitizers for {}", self.target));
1015 let _time = util::timeit(&builder);
1017 let mut cfg = cmake::Config::new(&compiler_rt_dir);
1018 cfg.profile("Release");
1019 cfg.define("CMAKE_C_COMPILER_TARGET", self.target.triple);
1020 cfg.define("COMPILER_RT_BUILD_BUILTINS", "OFF");
1021 cfg.define("COMPILER_RT_BUILD_CRT", "OFF");
1022 cfg.define("COMPILER_RT_BUILD_LIBFUZZER", "OFF");
1023 cfg.define("COMPILER_RT_BUILD_PROFILE", "OFF");
1024 cfg.define("COMPILER_RT_BUILD_SANITIZERS", "ON");
1025 cfg.define("COMPILER_RT_BUILD_XRAY", "OFF");
1026 cfg.define("COMPILER_RT_DEFAULT_TARGET_ONLY", "ON");
1027 cfg.define("COMPILER_RT_USE_LIBCXX", "OFF");
1028 cfg.define("LLVM_CONFIG_PATH", &llvm_config);
1030 // On Darwin targets the sanitizer runtimes are build as universal binaries.
1031 // Unfortunately sccache currently lacks support to build them successfully.
1032 // Disable compiler launcher on Darwin targets to avoid potential issues.
1033 let use_compiler_launcher = !self.target.contains("apple-darwin");
1034 configure_cmake(builder, self.target, &mut cfg, use_compiler_launcher, LdFlags::default());
1036 t!(fs::create_dir_all(&out_dir));
1037 cfg.out_dir(out_dir);
1039 for runtime in &runtimes {
1040 cfg.build_target(&runtime.cmake_target);
1049 #[derive(Clone, Debug)]
1050 pub struct SanitizerRuntime {
1051 /// CMake target used to build the runtime.
1052 pub cmake_target: String,
1053 /// Path to the built runtime library.
1055 /// Library filename that will be used rustc.
1059 /// Returns sanitizers available on a given target.
1060 fn supported_sanitizers(
1062 target: TargetSelection,
1064 ) -> Vec<SanitizerRuntime> {
1065 let darwin_libs = |os: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1068 .map(move |c| SanitizerRuntime {
1069 cmake_target: format!("clang_rt.{}_{}_dynamic", c, os),
1071 .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)),
1072 name: format!("librustc-{}_rt.{}.dylib", channel, c),
1077 let common_libs = |os: &str, arch: &str, components: &[&str]| -> Vec<SanitizerRuntime> {
1080 .map(move |c| SanitizerRuntime {
1081 cmake_target: format!("clang_rt.{}-{}", c, arch),
1082 path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)),
1083 name: format!("librustc-{}_rt.{}.a", channel, c),
1088 match &*target.triple {
1089 "aarch64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1090 "aarch64-unknown-fuchsia" => common_libs("fuchsia", "aarch64", &["asan"]),
1091 "aarch64-unknown-linux-gnu" => {
1092 common_libs("linux", "aarch64", &["asan", "lsan", "msan", "tsan", "hwasan"])
1094 "x86_64-apple-darwin" => darwin_libs("osx", &["asan", "lsan", "tsan"]),
1095 "x86_64-unknown-fuchsia" => common_libs("fuchsia", "x86_64", &["asan"]),
1096 "x86_64-unknown-freebsd" => common_libs("freebsd", "x86_64", &["asan", "msan", "tsan"]),
1097 "x86_64-unknown-netbsd" => {
1098 common_libs("netbsd", "x86_64", &["asan", "lsan", "msan", "tsan"])
1100 "x86_64-unknown-illumos" => common_libs("illumos", "x86_64", &["asan"]),
1101 "x86_64-pc-solaris" => common_libs("solaris", "x86_64", &["asan"]),
1102 "x86_64-unknown-linux-gnu" => {
1103 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1105 "x86_64-unknown-linux-musl" => {
1106 common_libs("linux", "x86_64", &["asan", "lsan", "msan", "tsan"])
1114 hash: Option<Vec<u8>>,
1118 fn new(path: PathBuf, hash: Option<&str>) -> Self {
1119 HashStamp { path, hash: hash.map(|s| s.as_bytes().to_owned()) }
1122 fn is_done(&self) -> bool {
1123 match fs::read(&self.path) {
1124 Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(),
1125 Err(e) if e.kind() == io::ErrorKind::NotFound => false,
1127 panic!("failed to read stamp file `{}`: {}", self.path.display(), e);
1132 fn remove(&self) -> io::Result<()> {
1133 match fs::remove_file(&self.path) {
1136 if e.kind() == io::ErrorKind::NotFound {
1145 fn write(&self) -> io::Result<()> {
1146 fs::write(&self.path, self.hash.as_deref().unwrap_or(b""))
1150 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1151 pub struct CrtBeginEnd {
1152 pub target: TargetSelection,
1155 impl Step for CrtBeginEnd {
1156 type Output = PathBuf;
1158 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1159 run.path("src/llvm-project/compiler-rt/lib/crt")
1162 fn make_run(run: RunConfig<'_>) {
1163 run.builder.ensure(CrtBeginEnd { target: run.target });
1166 /// Build crtbegin.o/crtend.o for musl target.
1167 fn run(self, builder: &Builder<'_>) -> Self::Output {
1168 let out_dir = builder.native_dir(self.target).join("crt");
1170 if builder.config.dry_run() {
1174 let crtbegin_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtbegin.c");
1175 let crtend_src = builder.src.join("src/llvm-project/compiler-rt/lib/crt/crtend.c");
1176 if up_to_date(&crtbegin_src, &out_dir.join("crtbegin.o"))
1177 && up_to_date(&crtend_src, &out_dir.join("crtendS.o"))
1182 builder.info("Building crtbegin.o and crtend.o");
1183 t!(fs::create_dir_all(&out_dir));
1185 let mut cfg = cc::Build::new();
1187 if let Some(ar) = builder.ar(self.target) {
1190 cfg.compiler(builder.cc(self.target));
1191 cfg.cargo_metadata(false)
1193 .target(&self.target.triple)
1194 .host(&builder.config.build.triple)
1201 // Those flags are defined in src/llvm-project/compiler-rt/lib/crt/CMakeLists.txt
1202 // Currently only consumer of those objects is musl, which use .init_array/.fini_array
1203 // instead of .ctors/.dtors
1204 cfg.flag("-std=c11")
1205 .define("CRT_HAS_INITFINI_ARRAY", None)
1206 .define("EH_USE_FRAME_REGISTRY", None);
1210 t!(fs::copy(out_dir.join("crtbegin.o"), out_dir.join("crtbeginS.o")));
1211 t!(fs::copy(out_dir.join("crtend.o"), out_dir.join("crtendS.o")));
1216 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1217 pub struct Libunwind {
1218 pub target: TargetSelection,
1221 impl Step for Libunwind {
1222 type Output = PathBuf;
1224 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1225 run.path("src/llvm-project/libunwind")
1228 fn make_run(run: RunConfig<'_>) {
1229 run.builder.ensure(Libunwind { target: run.target });
1232 /// Build linunwind.a
1233 fn run(self, builder: &Builder<'_>) -> Self::Output {
1234 if builder.config.dry_run() {
1235 return PathBuf::new();
1238 let out_dir = builder.native_dir(self.target).join("libunwind");
1239 let root = builder.src.join("src/llvm-project/libunwind");
1241 if up_to_date(&root, &out_dir.join("libunwind.a")) {
1245 builder.info(&format!("Building libunwind.a for {}", self.target.triple));
1246 t!(fs::create_dir_all(&out_dir));
1248 let mut cc_cfg = cc::Build::new();
1249 let mut cpp_cfg = cc::Build::new();
1252 cpp_cfg.cpp_set_stdlib(None);
1253 cpp_cfg.flag("-nostdinc++");
1254 cpp_cfg.flag("-fno-exceptions");
1255 cpp_cfg.flag("-fno-rtti");
1256 cpp_cfg.flag_if_supported("-fvisibility-global-new-delete-hidden");
1258 for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() {
1259 if let Some(ar) = builder.ar(self.target) {
1262 cfg.target(&self.target.triple);
1263 cfg.host(&builder.config.build.triple);
1264 cfg.warnings(false);
1266 // get_compiler() need set opt_level first.
1268 cfg.flag("-fstrict-aliasing");
1269 cfg.flag("-funwind-tables");
1270 cfg.flag("-fvisibility=hidden");
1271 cfg.define("_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS", None);
1272 cfg.include(root.join("include"));
1273 cfg.cargo_metadata(false);
1274 cfg.out_dir(&out_dir);
1276 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1277 cfg.static_flag(true);
1278 cfg.flag("-fno-stack-protector");
1279 cfg.flag("-ffreestanding");
1280 cfg.flag("-fexceptions");
1282 // easiest way to undefine since no API available in cc::Build to undefine
1283 cfg.flag("-U_FORTIFY_SOURCE");
1284 cfg.define("_FORTIFY_SOURCE", "0");
1285 cfg.define("RUST_SGX", "1");
1286 cfg.define("__NO_STRING_INLINES", None);
1287 cfg.define("__NO_MATH_INLINES", None);
1288 cfg.define("_LIBUNWIND_IS_BAREMETAL", None);
1289 cfg.define("__LIBUNWIND_IS_NATIVE_ONLY", None);
1290 cfg.define("NDEBUG", None);
1292 if self.target.contains("windows") {
1293 cfg.define("_LIBUNWIND_HIDE_SYMBOLS", "1");
1294 cfg.define("_LIBUNWIND_IS_NATIVE_ONLY", "1");
1298 cc_cfg.compiler(builder.cc(self.target));
1299 if let Ok(cxx) = builder.cxx(self.target) {
1300 cpp_cfg.compiler(cxx);
1302 cc_cfg.compiler(builder.cc(self.target));
1305 // Don't set this for clang
1306 // By default, Clang builds C code in GNU C17 mode.
1307 // By default, Clang builds C++ code according to the C++98 standard,
1308 // with many C++11 features accepted as extensions.
1309 if cc_cfg.get_compiler().is_like_gnu() {
1310 cc_cfg.flag("-std=c99");
1312 if cpp_cfg.get_compiler().is_like_gnu() {
1313 cpp_cfg.flag("-std=c++11");
1316 if self.target.contains("x86_64-fortanix-unknown-sgx") || self.target.contains("musl") {
1317 // use the same GCC C compiler command to compile C++ code so we do not need to setup the
1318 // C++ compiler env variables on the builders.
1319 // Don't set this for clang++, as clang++ is able to compile this without libc++.
1320 if cpp_cfg.get_compiler().is_like_gnu() {
1322 cpp_cfg.compiler(builder.cc(self.target));
1326 let mut c_sources = vec![
1328 "UnwindLevel1-gcc-ext.c",
1330 "UnwindRegistersRestore.S",
1331 "UnwindRegistersSave.S",
1334 let cpp_sources = vec!["Unwind-EHABI.cpp", "Unwind-seh.cpp", "libunwind.cpp"];
1335 let cpp_len = cpp_sources.len();
1337 if self.target.contains("x86_64-fortanix-unknown-sgx") {
1338 c_sources.push("UnwindRustSgx.c");
1341 for src in c_sources {
1342 cc_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1345 for src in &cpp_sources {
1346 cpp_cfg.file(root.join("src").join(src).canonicalize().unwrap());
1349 cpp_cfg.compile("unwind-cpp");
1351 // FIXME: https://github.com/alexcrichton/cc-rs/issues/545#issuecomment-679242845
1353 for entry in fs::read_dir(&out_dir).unwrap() {
1354 let file = entry.unwrap().path().canonicalize().unwrap();
1355 if file.is_file() && file.extension() == Some(OsStr::new("o")) {
1356 // file name starts with "Unwind-EHABI", "Unwind-seh" or "libunwind"
1357 let file_name = file.file_name().unwrap().to_str().expect("UTF-8 file name");
1358 if cpp_sources.iter().any(|f| file_name.starts_with(&f[..f.len() - 4])) {
1359 cc_cfg.object(&file);
1364 assert_eq!(cpp_len, count, "Can't get object files from {:?}", &out_dir);
1366 cc_cfg.compile("unwind");