Skip to main content

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