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