bootstrap/utils/
cc_detect.rs

1//! C-compiler probing and detection.
2//!
3//! This module will fill out the `cc` and `cxx` maps of `Build` by looking for
4//! C and C++ compilers for each target configured. A compiler is found through
5//! a number of vectors (in order of precedence)
6//!
7//! 1. Configuration via `target.$target.cc` in `bootstrap.toml`.
8//! 2. Configuration via `target.$target.android-ndk` in `bootstrap.toml`, if
9//!    applicable
10//! 3. Special logic to probe on OpenBSD
11//! 4. The `CC_$target` environment variable.
12//! 5. The `CC` environment variable.
13//! 6. "cc"
14//!
15//! Some of this logic is implemented here, but much of it is farmed out to the
16//! `cc` crate itself, so we end up having the same fallbacks as there.
17//! Similar logic is then used to find a C++ compiler, just some s/cc/c++/ is
18//! used.
19//!
20//! It is intended that after this module has run no C/C++ compiler will
21//! ever be probed for. Instead the compilers found here will be used for
22//! everything.
23
24use std::collections::HashSet;
25use std::iter;
26use std::path::{Path, PathBuf};
27
28use crate::core::config::TargetSelection;
29use crate::utils::exec::{BootstrapCommand, command};
30use crate::{Build, CLang, GitRepo};
31
32/// Creates and configures a new [`cc::Build`] instance for the given target.
33fn new_cc_build(build: &Build, target: TargetSelection) -> cc::Build {
34    let mut cfg = cc::Build::new();
35    cfg.cargo_metadata(false)
36        .opt_level(2)
37        .warnings(false)
38        .debug(false)
39        // Compress debuginfo
40        .flag_if_supported("-gz")
41        .target(&target.triple)
42        .host(&build.host_target.triple);
43    match build.crt_static(target) {
44        Some(a) => {
45            cfg.static_crt(a);
46        }
47        None => {
48            if target.is_msvc() {
49                cfg.static_crt(true);
50            }
51            if target.contains("musl") {
52                cfg.static_flag(true);
53            }
54        }
55    }
56    cfg
57}
58
59/// Probes for C and C++ compilers and configures the corresponding entries in the [`Build`]
60/// structure.
61///
62/// This function determines which targets need a C compiler (and, if needed, a C++ compiler)
63/// by combining the primary build target, host targets, and any additional targets. For
64/// each target, it calls [`fill_target_compiler`] to configure the necessary compiler tools.
65pub fn fill_compilers(build: &mut Build) {
66    let targets: HashSet<_> = match build.config.cmd {
67        // We don't need to check cross targets for these commands.
68        crate::Subcommand::Clean { .. }
69        | crate::Subcommand::Check { .. }
70        | crate::Subcommand::Suggest { .. }
71        | crate::Subcommand::Format { .. }
72        | crate::Subcommand::Setup { .. } => {
73            build.hosts.iter().cloned().chain(iter::once(build.host_target)).collect()
74        }
75
76        _ => {
77            // For all targets we're going to need a C compiler for building some shims
78            // and such as well as for being a linker for Rust code.
79            build
80                .targets
81                .iter()
82                .chain(&build.hosts)
83                .cloned()
84                .chain(iter::once(build.host_target))
85                .collect()
86        }
87    };
88
89    for target in targets.into_iter() {
90        fill_target_compiler(build, target);
91    }
92}
93
94/// Probes and configures the C and C++ compilers for a single target.
95///
96/// This function uses both user-specified configuration (from `bootstrap.toml`) and auto-detection
97/// logic to determine the correct C/C++ compilers for the target. It also determines the appropriate
98/// archiver (`ar`) and sets up additional compilation flags (both handled and unhandled).
99pub fn fill_target_compiler(build: &mut Build, target: TargetSelection) {
100    let mut cfg = new_cc_build(build, target);
101    let config = build.config.target_config.get(&target);
102    if let Some(cc) = config
103        .and_then(|c| c.cc.clone())
104        .or_else(|| default_compiler(&mut cfg, Language::C, target, build))
105    {
106        cfg.compiler(cc);
107    }
108
109    let compiler = cfg.get_compiler();
110    let ar = if let ar @ Some(..) = config.and_then(|c| c.ar.clone()) {
111        ar
112    } else {
113        cfg.try_get_archiver().map(|c| PathBuf::from(c.get_program())).ok()
114    };
115
116    build.cc.insert(target, compiler.clone());
117    let mut cflags = build.cc_handled_clags(target, CLang::C);
118    cflags.extend(build.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::C));
119
120    // If we use llvm-libunwind, we will need a C++ compiler as well for all targets
121    // We'll need one anyways if the target triple is also a host triple
122    let mut cfg = new_cc_build(build, target);
123    cfg.cpp(true);
124    let cxx_configured = if let Some(cxx) = config
125        .and_then(|c| c.cxx.clone())
126        .or_else(|| default_compiler(&mut cfg, Language::CPlusPlus, target, build))
127    {
128        cfg.compiler(cxx);
129        true
130    } else {
131        // Use an auto-detected compiler (or one configured via `CXX_target_triple` env vars).
132        cfg.try_get_compiler().is_ok()
133    };
134
135    // for VxWorks, record CXX compiler which will be used in lib.rs:linker()
136    if cxx_configured || target.contains("vxworks") {
137        let compiler = cfg.get_compiler();
138        build.cxx.insert(target, compiler);
139    }
140
141    build.verbose(|| println!("CC_{} = {:?}", target.triple, build.cc(target)));
142    build.verbose(|| println!("CFLAGS_{} = {cflags:?}", target.triple));
143    if let Ok(cxx) = build.cxx(target) {
144        let mut cxxflags = build.cc_handled_clags(target, CLang::Cxx);
145        cxxflags.extend(build.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::Cxx));
146        build.verbose(|| println!("CXX_{} = {cxx:?}", target.triple));
147        build.verbose(|| println!("CXXFLAGS_{} = {cxxflags:?}", target.triple));
148    }
149    if let Some(ar) = ar {
150        build.verbose(|| println!("AR_{} = {ar:?}", target.triple));
151        build.ar.insert(target, ar);
152    }
153
154    if let Some(ranlib) = config.and_then(|c| c.ranlib.clone()) {
155        build.ranlib.insert(target, ranlib);
156    }
157}
158
159/// Determines the default compiler for a given target and language when not explicitly
160/// configured in `bootstrap.toml`.
161fn default_compiler(
162    cfg: &mut cc::Build,
163    compiler: Language,
164    target: TargetSelection,
165    build: &Build,
166) -> Option<PathBuf> {
167    match &*target.triple {
168        // When compiling for android we may have the NDK configured in the
169        // bootstrap.toml in which case we look there. Otherwise the default
170        // compiler already takes into account the triple in question.
171        t if t.contains("android") => {
172            build.config.android_ndk.as_ref().map(|ndk| ndk_compiler(compiler, &target.triple, ndk))
173        }
174
175        // The default gcc version from OpenBSD may be too old, try using egcc,
176        // which is a gcc version from ports, if this is the case.
177        t if t.contains("openbsd") => {
178            let c = cfg.get_compiler();
179            let gnu_compiler = compiler.gcc();
180            if !c.path().ends_with(gnu_compiler) {
181                return None;
182            }
183
184            let mut cmd = BootstrapCommand::from(c.to_command());
185            let output = cmd.arg("--version").run_capture_stdout(build).stdout();
186            let i = output.find(" 4.")?;
187            match output[i + 3..].chars().next().unwrap() {
188                '0'..='6' => {}
189                _ => return None,
190            }
191            let alternative = format!("e{gnu_compiler}");
192            if command(&alternative).run_capture(build).is_success() {
193                Some(PathBuf::from(alternative))
194            } else {
195                None
196            }
197        }
198
199        "mips-unknown-linux-musl" if compiler == Language::C => {
200            if cfg.get_compiler().path().to_str() == Some("gcc") {
201                Some(PathBuf::from("mips-linux-musl-gcc"))
202            } else {
203                None
204            }
205        }
206        "mipsel-unknown-linux-musl" if compiler == Language::C => {
207            if cfg.get_compiler().path().to_str() == Some("gcc") {
208                Some(PathBuf::from("mipsel-linux-musl-gcc"))
209            } else {
210                None
211            }
212        }
213
214        t if t.contains("musl") && compiler == Language::C => {
215            if let Some(root) = build.musl_root(target) {
216                let guess = root.join("bin/musl-gcc");
217                if guess.exists() { Some(guess) } else { None }
218            } else {
219                None
220            }
221        }
222
223        t if t.contains("-wasi") => {
224            let root = build
225                .wasi_sdk_path
226                .as_ref()
227                .expect("WASI_SDK_PATH mut be configured for a -wasi target");
228            let compiler = match compiler {
229                Language::C => format!("{t}-clang"),
230                Language::CPlusPlus => format!("{t}-clang++"),
231            };
232            let compiler = root.join("bin").join(compiler);
233            Some(compiler)
234        }
235
236        _ => None,
237    }
238}
239
240/// Constructs the path to the Android NDK compiler for the given target triple and language.
241///
242/// This helper function transform the target triple by converting certain architecture names
243/// (for example, translating "arm" to "arm7a"), appends the minimum API level (hardcoded as "21"
244/// for NDK r26d), and then constructs the full path based on the provided NDK directory and host
245/// platform.
246pub(crate) fn ndk_compiler(compiler: Language, triple: &str, ndk: &Path) -> PathBuf {
247    let mut triple_iter = triple.split('-');
248    let triple_translated = if let Some(arch) = triple_iter.next() {
249        let arch_new = match arch {
250            "arm" | "armv7" | "armv7neon" | "thumbv7" | "thumbv7neon" => "armv7a",
251            other => other,
252        };
253        std::iter::once(arch_new).chain(triple_iter).collect::<Vec<&str>>().join("-")
254    } else {
255        triple.to_string()
256    };
257
258    // The earliest API supported by NDK r26d is 21.
259    let api_level = "21";
260    let compiler = format!("{}{}-{}", triple_translated, api_level, compiler.clang());
261    let host_tag = if cfg!(target_os = "macos") {
262        // The NDK uses universal binaries, so this is correct even on ARM.
263        "darwin-x86_64"
264    } else if cfg!(target_os = "windows") {
265        "windows-x86_64"
266    } else {
267        // NDK r26d only has official releases for macOS, Windows and Linux.
268        // Try the Linux directory everywhere else, on the assumption that the OS has an
269        // emulation layer that can cope (e.g. BSDs).
270        "linux-x86_64"
271    };
272    ndk.join("toolchains").join("llvm").join("prebuilt").join(host_tag).join("bin").join(compiler)
273}
274
275/// Representing the target programming language for a native compiler.
276///
277/// This enum is used to indicate whether a particular compiler is intended for C or C++.
278/// It also provides helper methods for obtaining the standard executable names for GCC and
279/// clang-based compilers.
280#[derive(PartialEq)]
281pub(crate) enum Language {
282    /// The compiler is targeting C.
283    C,
284    /// The compiler is targeting C++.
285    CPlusPlus,
286}
287
288impl Language {
289    /// Returns the executable name for a GCC compiler corresponding to this language.
290    fn gcc(self) -> &'static str {
291        match self {
292            Language::C => "gcc",
293            Language::CPlusPlus => "g++",
294        }
295    }
296
297    /// Returns the executable name for a clang-based compiler corresponding to this language.
298    fn clang(self) -> &'static str {
299        match self {
300            Language::C => "clang",
301            Language::CPlusPlus => "clang++",
302        }
303    }
304}
305
306#[cfg(test)]
307mod tests;