]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/cc_detect.rs
Rollup merge of #76069 - pickfire:patch-16, r=jyn514
[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         // for VxWorks, record CXX compiler which will be used in lib.rs:linker()
136         if cxx_configured || target.contains("vxworks") {
137             let compiler = cfg.get_compiler();
138             build.cxx.insert(target, compiler);
139         }
140
141         build.verbose(&format!("CC_{} = {:?}", &target.triple, build.cc(target)));
142         build.verbose(&format!("CFLAGS_{} = {:?}", &target.triple, cflags));
143         if let Ok(cxx) = build.cxx(target) {
144             build.verbose(&format!("CXX_{} = {:?}", &target.triple, cxx));
145             build.verbose(&format!("CXXFLAGS_{} = {:?}", &target.triple, cflags));
146         }
147         if let Some(ar) = ar {
148             build.verbose(&format!("AR_{} = {:?}", &target.triple, ar));
149             build.ar.insert(target, ar);
150         }
151     }
152 }
153
154 fn set_compiler(
155     cfg: &mut cc::Build,
156     compiler: Language,
157     target: TargetSelection,
158     config: Option<&Target>,
159     build: &Build,
160 ) {
161     match &*target.triple {
162         // When compiling for android we may have the NDK configured in the
163         // config.toml in which case we look there. Otherwise the default
164         // compiler already takes into account the triple in question.
165         t if t.contains("android") => {
166             if let Some(ndk) = config.and_then(|c| c.ndk.as_ref()) {
167                 let target = target
168                     .triple
169                     .replace("armv7neon", "arm")
170                     .replace("armv7", "arm")
171                     .replace("thumbv7neon", "arm")
172                     .replace("thumbv7", "arm");
173                 let compiler = format!("{}-{}", target, compiler.clang());
174                 cfg.compiler(ndk.join("bin").join(compiler));
175             }
176         }
177
178         // The default gcc version from OpenBSD may be too old, try using egcc,
179         // which is a gcc version from ports, if this is the case.
180         t if t.contains("openbsd") => {
181             let c = cfg.get_compiler();
182             let gnu_compiler = compiler.gcc();
183             if !c.path().ends_with(gnu_compiler) {
184                 return;
185             }
186
187             let output = output(c.to_command().arg("--version"));
188             let i = match output.find(" 4.") {
189                 Some(i) => i,
190                 None => return,
191             };
192             match output[i + 3..].chars().next().unwrap() {
193                 '0'..='6' => {}
194                 _ => return,
195             }
196             let alternative = format!("e{}", gnu_compiler);
197             if Command::new(&alternative).output().is_ok() {
198                 cfg.compiler(alternative);
199             }
200         }
201
202         "mips-unknown-linux-musl" => {
203             if cfg.get_compiler().path().to_str() == Some("gcc") {
204                 cfg.compiler("mips-linux-musl-gcc");
205             }
206         }
207         "mipsel-unknown-linux-musl" => {
208             if cfg.get_compiler().path().to_str() == Some("gcc") {
209                 cfg.compiler("mipsel-linux-musl-gcc");
210             }
211         }
212
213         t if t.contains("musl") => {
214             if let Some(root) = build.musl_root(target) {
215                 let guess = root.join("bin/musl-gcc");
216                 if guess.exists() {
217                     cfg.compiler(guess);
218                 }
219             }
220         }
221
222         _ => {}
223     }
224 }
225
226 /// The target programming language for a native compiler.
227 enum Language {
228     /// The compiler is targeting C.
229     C,
230     /// The compiler is targeting C++.
231     CPlusPlus,
232 }
233
234 impl Language {
235     /// Obtains the name of a compiler in the GCC collection.
236     fn gcc(self) -> &'static str {
237         match self {
238             Language::C => "gcc",
239             Language::CPlusPlus => "g++",
240         }
241     }
242
243     /// Obtains the name of a compiler in the clang suite.
244     fn clang(self) -> &'static str {
245         match self {
246             Language::C => "clang",
247             Language::CPlusPlus => "clang++",
248         }
249     }
250 }