]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/cc_detect.rs
Rollup merge of #107740 - oli-obk:lock_tcx, r=petrochenkov
[rust.git] / src / bootstrap / 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 `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.
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
66 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         .target(&target.triple)
73         .host(&build.build.triple);
74     match build.crt_static(target) {
75         Some(a) => {
76             cfg.static_crt(a);
77         }
78         None => {
79             if target.contains("msvc") {
80                 cfg.static_crt(true);
81             }
82             if target.contains("musl") {
83                 cfg.static_flag(true);
84             }
85         }
86     }
87     cfg
88 }
89
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.
93     let targets = build
94         .targets
95         .iter()
96         .chain(&build.hosts)
97         .cloned()
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()) {
104             cfg.compiler(cc);
105         } else {
106             set_compiler(&mut cfg, Language::C, target, config, build);
107         }
108
109         let compiler = cfg.get_compiler();
110         let ar = if let ar @ Some(..) = config.and_then(|c| c.ar.clone()) {
111             ar
112         } else {
113             cc2ar(compiler.path(), target)
114         };
115
116         build.cc.insert(target, compiler.clone());
117         let cflags = build.cflags(target, GitRepo::Rustc, CLang::C);
118
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);
122         cfg.cpp(true);
123         let cxx_configured = if let Some(cxx) = config.and_then(|c| c.cxx.as_ref()) {
124             cfg.compiler(cxx);
125             true
126         } else if build.hosts.contains(&target) || build.build == target {
127             set_compiler(&mut cfg, Language::CPlusPlus, target, config, build);
128             true
129         } else {
130             // Use an auto-detected compiler (or one configured via `CXX_target_triple` env vars).
131             cfg.try_get_compiler().is_ok()
132         };
133
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);
138         }
139
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));
146         }
147         if let Some(ar) = ar {
148             build.verbose(&format!("AR_{} = {:?}", &target.triple, ar));
149             build.ar.insert(target, ar);
150         }
151
152         if let Some(ranlib) = config.and_then(|c| c.ranlib.clone()) {
153             build.ranlib.insert(target, ranlib);
154         }
155     }
156 }
157
158 fn set_compiler(
159     cfg: &mut cc::Build,
160     compiler: Language,
161     target: TargetSelection,
162     config: Option<&Target>,
163     build: &Build,
164 ) {
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                 cfg.compiler(ndk_compiler(compiler, &*target.triple, ndk));
172             }
173         }
174
175         // The default gcc version from OpenBSD may be too old, try using egcc,
176         // which is a gcc version from ports, if this is the case.
177         t if t.contains("openbsd") => {
178             let c = cfg.get_compiler();
179             let gnu_compiler = compiler.gcc();
180             if !c.path().ends_with(gnu_compiler) {
181                 return;
182             }
183
184             let output = output(c.to_command().arg("--version"));
185             let i = match output.find(" 4.") {
186                 Some(i) => i,
187                 None => return,
188             };
189             match output[i + 3..].chars().next().unwrap() {
190                 '0'..='6' => {}
191                 _ => return,
192             }
193             let alternative = format!("e{}", gnu_compiler);
194             if Command::new(&alternative).output().is_ok() {
195                 cfg.compiler(alternative);
196             }
197         }
198
199         "mips-unknown-linux-musl" => {
200             if cfg.get_compiler().path().to_str() == Some("gcc") {
201                 cfg.compiler("mips-linux-musl-gcc");
202             }
203         }
204         "mipsel-unknown-linux-musl" => {
205             if cfg.get_compiler().path().to_str() == Some("gcc") {
206                 cfg.compiler("mipsel-linux-musl-gcc");
207             }
208         }
209
210         t if t.contains("musl") => {
211             if let Some(root) = build.musl_root(target) {
212                 let guess = root.join("bin/musl-gcc");
213                 if guess.exists() {
214                     cfg.compiler(guess);
215                 }
216             }
217         }
218
219         _ => {}
220     }
221 }
222
223 pub(crate) fn ndk_compiler(compiler: Language, triple: &str, ndk: &Path) -> PathBuf {
224     let mut triple_iter = triple.split("-");
225     let triple_translated = if let Some(arch) = triple_iter.next() {
226         let arch_new = match arch {
227             "arm" | "armv7" | "armv7neon" | "thumbv7" | "thumbv7neon" => "armv7a",
228             other => other,
229         };
230         std::iter::once(arch_new).chain(triple_iter).collect::<Vec<&str>>().join("-")
231     } else {
232         triple.to_string()
233     };
234
235     // API 19 is the earliest API level supported by NDK r25b but AArch64 and x86_64 support
236     // begins at API level 21.
237     let api_level =
238         if triple.contains("aarch64") || triple.contains("x86_64") { "21" } else { "19" };
239     let compiler = format!("{}{}-{}", triple_translated, api_level, compiler.clang());
240     ndk.join("bin").join(compiler)
241 }
242
243 /// The target programming language for a native compiler.
244 pub(crate) enum Language {
245     /// The compiler is targeting C.
246     C,
247     /// The compiler is targeting C++.
248     CPlusPlus,
249 }
250
251 impl Language {
252     /// Obtains the name of a compiler in the GCC collection.
253     fn gcc(self) -> &'static str {
254         match self {
255             Language::C => "gcc",
256             Language::CPlusPlus => "g++",
257         }
258     }
259
260     /// Obtains the name of a compiler in the clang suite.
261     fn clang(self) -> &'static str {
262         match self {
263             Language::C => "clang",
264             Language::CPlusPlus => "clang++",
265         }
266     }
267 }