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