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