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