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::core::session::{CLang, GitRepo, Session};
31use crate::utils::exec::{BootstrapCommand, command};
32
33/// Creates and configures a new [`cc::Build`] instance for the given target.
34fn new_cc_build(sess: &Session, 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(sess.tempdir().join("cc-rs-out-dir"))
42        .target(&target.triple)
43        .host(&sess.host_target.triple);
44
45    match sess.config.compress_debuginfo(target) {
46        CompressDebuginfo::Zlib => {
47            cfg.flag_if_supported("-gz");
48        }
49        CompressDebuginfo::Off => {}
50    }
51
52    match sess.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 [`Session`]
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(crate) fn fill_compilers(sess: &mut Session) {
72    let mut targets: HashSet<_> = match sess.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            sess.hosts.iter().cloned().chain(iter::once(sess.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            sess.targets
85                .iter()
86                .chain(&sess.hosts)
87                .cloned()
88                .chain(iter::once(sess.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 sess.config.wasm_proc_macros {
97        targets.insert(TargetSelection::from_user("wasm32-wasip2"));
98    }
99
100    for target in targets {
101        fill_target_compiler(sess, 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).
110fn fill_target_compiler(sess: &mut Session, target: TargetSelection) {
111    let mut cfg = new_cc_build(sess, target);
112    let config = sess.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, sess))
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    sess.cc.insert(target, compiler.clone());
126    let mut cflags = sess.cc_handled_cflags(target, CLang::C);
127    cflags.extend(sess.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(sess, 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, sess))
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        sess.cxx.insert(target, compiler);
148    }
149
150    sess.do_if_verbose(|| println!("CC_{} = {:?}", target.triple, sess.cc(target)));
151    sess.do_if_verbose(|| println!("CFLAGS_{} = {cflags:?}", target.triple));
152    if let Ok(cxx) = sess.cxx(target) {
153        let mut cxxflags = sess.cc_handled_cflags(target, CLang::Cxx);
154        cxxflags.extend(sess.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::Cxx));
155        sess.do_if_verbose(|| println!("CXX_{} = {cxx:?}", target.triple));
156        sess.do_if_verbose(|| println!("CXXFLAGS_{} = {cxxflags:?}", target.triple));
157    }
158    if let Some(ar) = ar {
159        sess.do_if_verbose(|| println!("AR_{} = {ar:?}", target.triple));
160        sess.ar.insert(target, ar);
161    }
162
163    if let Some(ranlib) = config.and_then(|c| c.ranlib.clone()) {
164        sess.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    sess: &Session,
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            sess.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(sess).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(sess).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) = sess.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) = sess.wasi_sdk_path.as_ref() {
234                path
235            } else {
236                if sess.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;