• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 `config.toml`.
8 //! 2. Configuration via `target.$target.android-ndk` in `config.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 
24 use std::collections::HashSet;
25 use std::path::{Path, PathBuf};
26 use std::process::Command;
27 use std::{env, iter};
28 
29 use crate::config::{Target, TargetSelection};
30 use crate::util::output;
31 use crate::{Build, CLang, GitRepo};
32 
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.
cc2ar(cc: &Path, target: TargetSelection) -> Option<PathBuf>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") {
43         None
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")))
52     } else {
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();
58                 file.push_str("ar");
59                 return Some(parent.join(&file));
60             }
61         }
62         Some(parent.join(file))
63     }
64 }
65 
new_cc_build(build: &Build, target: TargetSelection) -> cc::Build66 fn new_cc_build(build: &Build, target: TargetSelection) -> cc::Build {
67     let mut cfg = cc::Build::new();
68     cfg.cargo_metadata(false)
69         .opt_level(2)
70         .warnings(false)
71         .debug(false)
72         // Compress debuginfo
73         .flag_if_supported("-gz")
74         .target(&target.triple)
75         .host(&build.build.triple);
76     match build.crt_static(target) {
77         Some(a) => {
78             cfg.static_crt(a);
79         }
80         None => {
81             if target.contains("msvc") {
82                 cfg.static_crt(true);
83             }
84             if target.contains("musl") {
85                 cfg.static_flag(true);
86             }
87         }
88     }
89     cfg
90 }
91 
find(build: &Build)92 pub fn find(build: &Build) {
93     // For all targets we're going to need a C compiler for building some shims
94     // and such as well as for being a linker for Rust code.
95     let targets = build
96         .targets
97         .iter()
98         .chain(&build.hosts)
99         .cloned()
100         .chain(iter::once(build.build))
101         .collect::<HashSet<_>>();
102     for target in targets.into_iter() {
103         find_target(build, target);
104     }
105 }
106 
find_target(build: &Build, target: TargetSelection)107 pub fn find_target(build: &Build, target: TargetSelection) {
108     let mut cfg = new_cc_build(build, target);
109     let config = build.config.target_config.get(&target);
110     if let Some(cc) = config.and_then(|c| c.cc.as_ref()) {
111         cfg.compiler(cc);
112     } else {
113         set_compiler(&mut cfg, Language::C, target, config, build);
114     }
115 
116     let compiler = cfg.get_compiler();
117     let ar = if let ar @ Some(..) = config.and_then(|c| c.ar.clone()) {
118         ar
119     } else {
120         cc2ar(compiler.path(), target)
121     };
122 
123     build.cc.borrow_mut().insert(target, compiler.clone());
124     let cflags = build.cflags(target, GitRepo::Rustc, CLang::C);
125 
126     // If we use llvm-libunwind, we will need a C++ compiler as well for all targets
127     // We'll need one anyways if the target triple is also a host triple
128     let mut cfg = new_cc_build(build, target);
129     cfg.cpp(true);
130     let cxx_configured = if let Some(cxx) = config.and_then(|c| c.cxx.as_ref()) {
131         cfg.compiler(cxx);
132         true
133     } else if build.hosts.contains(&target) || build.build == target {
134         set_compiler(&mut cfg, Language::CPlusPlus, target, config, build);
135         true
136     } else {
137         // Use an auto-detected compiler (or one configured via `CXX_target_triple` env vars).
138         cfg.try_get_compiler().is_ok()
139     };
140 
141     // for VxWorks, record CXX compiler which will be used in lib.rs:linker()
142     if cxx_configured || target.contains("vxworks") {
143         let compiler = cfg.get_compiler();
144         build.cxx.borrow_mut().insert(target, compiler);
145     }
146 
147     build.verbose(&format!("CC_{} = {:?}", &target.triple, build.cc(target)));
148     build.verbose(&format!("CFLAGS_{} = {:?}", &target.triple, cflags));
149     if let Ok(cxx) = build.cxx(target) {
150         let cxxflags = build.cflags(target, GitRepo::Rustc, CLang::Cxx);
151         build.verbose(&format!("CXX_{} = {:?}", &target.triple, cxx));
152         build.verbose(&format!("CXXFLAGS_{} = {:?}", &target.triple, cxxflags));
153     }
154     if let Some(ar) = ar {
155         build.verbose(&format!("AR_{} = {:?}", &target.triple, ar));
156         build.ar.borrow_mut().insert(target, ar);
157     }
158 
159     if let Some(ranlib) = config.and_then(|c| c.ranlib.clone()) {
160         build.ranlib.borrow_mut().insert(target, ranlib);
161     }
162 }
163 
set_compiler( cfg: &mut cc::Build, compiler: Language, target: TargetSelection, config: Option<&Target>, build: &Build, )164 fn set_compiler(
165     cfg: &mut cc::Build,
166     compiler: Language,
167     target: TargetSelection,
168     config: Option<&Target>,
169     build: &Build,
170 ) {
171     match &*target.triple {
172         // When compiling for android we may have the NDK configured in the
173         // config.toml in which case we look there. Otherwise the default
174         // compiler already takes into account the triple in question.
175         t if t.contains("android") => {
176             if let Some(ndk) = config.and_then(|c| c.ndk.as_ref()) {
177                 cfg.compiler(ndk_compiler(compiler, &*target.triple, ndk));
178             }
179         }
180 
181         // The default gcc version from OpenBSD may be too old, try using egcc,
182         // which is a gcc version from ports, if this is the case.
183         t if t.contains("openbsd") => {
184             let c = cfg.get_compiler();
185             let gnu_compiler = compiler.gcc();
186             if !c.path().ends_with(gnu_compiler) {
187                 return;
188             }
189 
190             let output = output(c.to_command().arg("--version"));
191             let i = match output.find(" 4.") {
192                 Some(i) => i,
193                 None => return,
194             };
195             match output[i + 3..].chars().next().unwrap() {
196                 '0'..='6' => {}
197                 _ => return,
198             }
199             let alternative = format!("e{}", gnu_compiler);
200             if Command::new(&alternative).output().is_ok() {
201                 cfg.compiler(alternative);
202             }
203         }
204 
205         "mips-unknown-linux-musl" => {
206             if cfg.get_compiler().path().to_str() == Some("gcc") {
207                 cfg.compiler("mips-linux-musl-gcc");
208             }
209         }
210         "mipsel-unknown-linux-musl" => {
211             if cfg.get_compiler().path().to_str() == Some("gcc") {
212                 cfg.compiler("mipsel-linux-musl-gcc");
213             }
214         }
215 
216         t if t.contains("musl") => {
217             if let Some(root) = build.musl_root(target) {
218                 let guess = root.join("bin/musl-gcc");
219                 if guess.exists() {
220                     cfg.compiler(guess);
221                 }
222             }
223         }
224 
225         _ => {}
226     }
227 }
228 
ndk_compiler(compiler: Language, triple: &str, ndk: &Path) -> PathBuf229 pub(crate) fn ndk_compiler(compiler: Language, triple: &str, ndk: &Path) -> PathBuf {
230     let mut triple_iter = triple.split("-");
231     let triple_translated = if let Some(arch) = triple_iter.next() {
232         let arch_new = match arch {
233             "arm" | "armv7" | "armv7neon" | "thumbv7" | "thumbv7neon" => "armv7a",
234             other => other,
235         };
236         std::iter::once(arch_new).chain(triple_iter).collect::<Vec<&str>>().join("-")
237     } else {
238         triple.to_string()
239     };
240 
241     // API 19 is the earliest API level supported by NDK r25b but AArch64 and x86_64 support
242     // begins at API level 21.
243     let api_level =
244         if triple.contains("aarch64") || triple.contains("x86_64") { "21" } else { "19" };
245     let compiler = format!("{}{}-{}", triple_translated, api_level, compiler.clang());
246     ndk.join("bin").join(compiler)
247 }
248 
249 /// The target programming language for a native compiler.
250 pub(crate) enum Language {
251     /// The compiler is targeting C.
252     C,
253     /// The compiler is targeting C++.
254     CPlusPlus,
255 }
256 
257 impl Language {
258     /// Obtains the name of a compiler in the GCC collection.
gcc(self) -> &'static str259     fn gcc(self) -> &'static str {
260         match self {
261             Language::C => "gcc",
262             Language::CPlusPlus => "g++",
263         }
264     }
265 
266     /// Obtains the name of a compiler in the clang suite.
clang(self) -> &'static str267     fn clang(self) -> &'static str {
268         match self {
269             Language::C => "clang",
270             Language::CPlusPlus => "clang++",
271         }
272     }
273 }
274