1 //! C-compiler probing and detection.
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)
7 //! 1. Configuration via `target.$target.cc` in `config.toml`.
8 //! 2. Configuration via `target.$target.android-ndk` in `config.toml`, if
10 //! 3. Special logic to probe on OpenBSD
11 //! 4. The `CC_$target` environment variable.
12 //! 5. The `CC` environment variable.
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
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
24 use std::collections::HashSet;
25 use std::path::{Path, PathBuf};
26 use std::process::Command;
29 use crate::config::{Target, TargetSelection};
30 use crate::util::output;
31 use crate::{Build, CLang, GitRepo};
33 // The `cc` crate doesn't provide a way to obtain a path to the detected archiver,
34 // so use some simplified logic here. First we respect the environment variable `AR`, then
35 // try to infer the archiver path from the C compiler path.
36 // In the future this logic should be replaced by calling into the `cc` crate.
37 fn cc2ar(cc: &Path, target: TargetSelection) -> Option<PathBuf> {
38 if let Some(ar) = env::var_os(format!("AR_{}", target.triple.replace("-", "_"))) {
39 Some(PathBuf::from(ar))
40 } else if let Some(ar) = env::var_os("AR") {
41 Some(PathBuf::from(ar))
42 } else if target.contains("msvc") {
44 } else if target.contains("musl") {
45 Some(PathBuf::from("ar"))
46 } else if target.contains("openbsd") {
47 Some(PathBuf::from("ar"))
48 } else if target.contains("vxworks") {
49 Some(PathBuf::from("wr-ar"))
50 } else if target.contains("android") {
51 Some(cc.parent().unwrap().join(PathBuf::from("llvm-ar")))
53 let parent = cc.parent().unwrap();
54 let file = cc.file_name().unwrap().to_str().unwrap();
55 for suffix in &["gcc", "cc", "clang"] {
56 if let Some(idx) = file.rfind(suffix) {
57 let mut file = file[..idx].to_owned();
59 return Some(parent.join(&file));
62 Some(parent.join(file))
66 fn new_cc_build(build: &Build, target: TargetSelection) -> cc::Build {
67 let mut cfg = cc::Build::new();
68 cfg.cargo_metadata(false)
72 .target(&target.triple)
73 .host(&build.build.triple);
74 match build.crt_static(target) {
79 if target.contains("msvc") {
82 if target.contains("musl") {
83 cfg.static_flag(true);
90 pub fn find(build: &mut Build) {
91 // For all targets we're going to need a C compiler for building some shims
92 // and such as well as for being a linker for Rust code.
98 .chain(iter::once(build.build))
99 .collect::<HashSet<_>>();
100 for target in targets.into_iter() {
101 let mut cfg = new_cc_build(build, target);
102 let config = build.config.target_config.get(&target);
103 if let Some(cc) = config.and_then(|c| c.cc.as_ref()) {
106 set_compiler(&mut cfg, Language::C, target, config, build);
109 let compiler = cfg.get_compiler();
110 let ar = if let ar @ Some(..) = config.and_then(|c| c.ar.clone()) {
113 cc2ar(compiler.path(), target)
116 build.cc.insert(target, compiler.clone());
117 let cflags = build.cflags(target, GitRepo::Rustc, CLang::C);
119 // If we use llvm-libunwind, we will need a C++ compiler as well for all targets
120 // We'll need one anyways if the target triple is also a host triple
121 let mut cfg = new_cc_build(build, target);
123 let cxx_configured = if let Some(cxx) = config.and_then(|c| c.cxx.as_ref()) {
126 } else if build.hosts.contains(&target) || build.build == target {
127 set_compiler(&mut cfg, Language::CPlusPlus, target, config, build);
130 // Use an auto-detected compiler (or one configured via `CXX_target_triple` env vars).
131 cfg.try_get_compiler().is_ok()
134 // for VxWorks, record CXX compiler which will be used in lib.rs:linker()
135 if cxx_configured || target.contains("vxworks") {
136 let compiler = cfg.get_compiler();
137 build.cxx.insert(target, compiler);
140 build.verbose(&format!("CC_{} = {:?}", &target.triple, build.cc(target)));
141 build.verbose(&format!("CFLAGS_{} = {:?}", &target.triple, cflags));
142 if let Ok(cxx) = build.cxx(target) {
143 let cxxflags = build.cflags(target, GitRepo::Rustc, CLang::Cxx);
144 build.verbose(&format!("CXX_{} = {:?}", &target.triple, cxx));
145 build.verbose(&format!("CXXFLAGS_{} = {:?}", &target.triple, cxxflags));
147 if let Some(ar) = ar {
148 build.verbose(&format!("AR_{} = {:?}", &target.triple, ar));
149 build.ar.insert(target, ar);
152 if let Some(ranlib) = config.and_then(|c| c.ranlib.clone()) {
153 build.ranlib.insert(target, ranlib);
161 target: TargetSelection,
162 config: Option<&Target>,
165 match &*target.triple {
166 // When compiling for android we may have the NDK configured in the
167 // config.toml in which case we look there. Otherwise the default
168 // compiler already takes into account the triple in question.
169 t if t.contains("android") => {
170 if let Some(ndk) = config.and_then(|c| c.ndk.as_ref()) {
171 let mut triple_iter = target.triple.split("-");
172 let triple_translated = if let Some(arch) = triple_iter.next() {
173 let arch_new = match arch {
174 "arm" | "armv7" | "armv7neon" | "thumbv7" | "thumbv7neon" => "armv7a",
177 std::iter::once(arch_new).chain(triple_iter).collect::<Vec<&str>>().join("-")
179 target.triple.to_string()
182 // API 19 is the earliest API level supported by NDK r25b but AArch64 and x86_64 support
183 // begins at API level 21.
185 if t.contains("aarch64") || t.contains("x86_64") { "21" } else { "19" };
186 let compiler = format!("{}{}-{}", triple_translated, api_level, compiler.clang());
187 cfg.compiler(ndk.join("bin").join(compiler));
191 // The default gcc version from OpenBSD may be too old, try using egcc,
192 // which is a gcc version from ports, if this is the case.
193 t if t.contains("openbsd") => {
194 let c = cfg.get_compiler();
195 let gnu_compiler = compiler.gcc();
196 if !c.path().ends_with(gnu_compiler) {
200 let output = output(c.to_command().arg("--version"));
201 let i = match output.find(" 4.") {
205 match output[i + 3..].chars().next().unwrap() {
209 let alternative = format!("e{}", gnu_compiler);
210 if Command::new(&alternative).output().is_ok() {
211 cfg.compiler(alternative);
215 "mips-unknown-linux-musl" => {
216 if cfg.get_compiler().path().to_str() == Some("gcc") {
217 cfg.compiler("mips-linux-musl-gcc");
220 "mipsel-unknown-linux-musl" => {
221 if cfg.get_compiler().path().to_str() == Some("gcc") {
222 cfg.compiler("mipsel-linux-musl-gcc");
226 t if t.contains("musl") => {
227 if let Some(root) = build.musl_root(target) {
228 let guess = root.join("bin/musl-gcc");
239 /// The target programming language for a native compiler.
241 /// The compiler is targeting C.
243 /// The compiler is targeting C++.
248 /// Obtains the name of a compiler in the GCC collection.
249 fn gcc(self) -> &'static str {
251 Language::C => "gcc",
252 Language::CPlusPlus => "g++",
256 /// Obtains the name of a compiler in the clang suite.
257 fn clang(self) -> &'static str {
259 Language::C => "clang",
260 Language::CPlusPlus => "clang++",