]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/cc_detect.rs
Rollup merge of #68093 - GuillaumeGomez:fix-deref-impl-typedef, r=oli-obk
[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::cache::Interned;
32 use crate::config::Target;
33 use crate::{Build, GitRepo};
34
35 // The `cc` crate doesn't provide a way to obtain a path to the detected archiver,
36 // so use some simplified logic here. First we respect the environment variable `AR`, then
37 // try to infer the archiver path from the C compiler path.
38 // In the future this logic should be replaced by calling into the `cc` crate.
39 fn cc2ar(cc: &Path, target: &str) -> Option<PathBuf> {
40     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 pub fn find(build: &mut Build) {
65     // For all targets we're going to need a C compiler for building some shims
66     // and such as well as for being a linker for Rust code.
67     let targets = build
68         .targets
69         .iter()
70         .chain(&build.hosts)
71         .cloned()
72         .chain(iter::once(build.build))
73         .collect::<HashSet<_>>();
74     for target in targets.into_iter() {
75         let mut cfg = cc::Build::new();
76         cfg.cargo_metadata(false)
77             .opt_level(2)
78             .warnings(false)
79             .debug(false)
80             .target(&target)
81             .host(&build.build);
82         match build.crt_static(target) {
83             Some(a) => {
84                 cfg.static_crt(a);
85             }
86             None => {
87                 if target.contains("msvc") {
88                     cfg.static_crt(true);
89                 }
90                 if target.contains("musl") {
91                     cfg.static_flag(true);
92                 }
93             }
94         }
95
96         let config = build.config.target_config.get(&target);
97         if let Some(cc) = config.and_then(|c| c.cc.as_ref()) {
98             cfg.compiler(cc);
99         } else {
100             set_compiler(&mut cfg, Language::C, target, config, build);
101         }
102
103         let compiler = cfg.get_compiler();
104         let ar = if let ar @ Some(..) = config.and_then(|c| c.ar.clone()) {
105             ar
106         } else {
107             cc2ar(compiler.path(), &target)
108         };
109
110         build.cc.insert(target, compiler);
111         let cflags = build.cflags(target, GitRepo::Rustc);
112
113         // If we use llvm-libunwind, we will need a C++ compiler as well for all targets
114         // We'll need one anyways if the target triple is also a host triple
115         let mut cfg = cc::Build::new();
116         cfg.cargo_metadata(false)
117             .opt_level(2)
118             .warnings(false)
119             .debug(false)
120             .cpp(true)
121             .target(&target)
122             .host(&build.build);
123
124         let cxx_configured = if let Some(cxx) = config.and_then(|c| c.cxx.as_ref()) {
125             cfg.compiler(cxx);
126             true
127         } else if build.hosts.contains(&target) || build.build == target {
128             set_compiler(&mut cfg, Language::CPlusPlus, target, config, build);
129             true
130         } else {
131             false
132         };
133
134         if cxx_configured {
135             let compiler = cfg.get_compiler();
136             build.cxx.insert(target, compiler);
137         }
138
139         build.verbose(&format!("CC_{} = {:?}", &target, build.cc(target)));
140         build.verbose(&format!("CFLAGS_{} = {:?}", &target, cflags));
141         if let Ok(cxx) = build.cxx(target) {
142             build.verbose(&format!("CXX_{} = {:?}", &target, cxx));
143             build.verbose(&format!("CXXFLAGS_{} = {:?}", &target, cflags));
144         }
145         if let Some(ar) = ar {
146             build.verbose(&format!("AR_{} = {:?}", &target, ar));
147             build.ar.insert(target, ar);
148         }
149     }
150 }
151
152 fn set_compiler(
153     cfg: &mut cc::Build,
154     compiler: Language,
155     target: Interned<String>,
156     config: Option<&Target>,
157     build: &Build,
158 ) {
159     match &*target {
160         // When compiling for android we may have the NDK configured in the
161         // config.toml in which case we look there. Otherwise the default
162         // compiler already takes into account the triple in question.
163         t if t.contains("android") => {
164             if let Some(ndk) = config.and_then(|c| c.ndk.as_ref()) {
165                 let target = target
166                     .replace("armv7neon", "arm")
167                     .replace("armv7", "arm")
168                     .replace("thumbv7neon", "arm")
169                     .replace("thumbv7", "arm");
170                 let compiler = format!("{}-{}", target, compiler.clang());
171                 cfg.compiler(ndk.join("bin").join(compiler));
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 /// The target programming language for a native compiler.
224 enum Language {
225     /// The compiler is targeting C.
226     C,
227     /// The compiler is targeting C++.
228     CPlusPlus,
229 }
230
231 impl Language {
232     /// Obtains the name of a compiler in the GCC collection.
233     fn gcc(self) -> &'static str {
234         match self {
235             Language::C => "gcc",
236             Language::CPlusPlus => "g++",
237         }
238     }
239
240     /// Obtains the name of a compiler in the clang suite.
241     fn clang(self) -> &'static str {
242         match self {
243             Language::C => "clang",
244             Language::CPlusPlus => "clang++",
245         }
246     }
247 }