]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/cc_detect.rs
Rollup merge of #60187 - tmandry:generator-optimization, r=eddyb
[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::{env, iter};
26 use std::path::{Path, PathBuf};
27 use std::process::Command;
28
29 use build_helper::output;
30
31 use crate::{Build, GitRepo};
32 use crate::config::Target;
33 use crate::cache::Interned;
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 {
49         let parent = cc.parent().unwrap();
50         let file = cc.file_name().unwrap().to_str().unwrap();
51         for suffix in &["gcc", "cc", "clang"] {
52             if let Some(idx) = file.rfind(suffix) {
53                 let mut file = file[..idx].to_owned();
54                 file.push_str("ar");
55                 return Some(parent.join(&file));
56             }
57         }
58         Some(parent.join(file))
59     }
60 }
61
62 pub fn find(build: &mut Build) {
63     // For all targets we're going to need a C compiler for building some shims
64     // and such as well as for being a linker for Rust code.
65     let targets = build.targets.iter().chain(&build.hosts).cloned().chain(iter::once(build.build))
66                                .collect::<HashSet<_>>();
67     for target in targets.into_iter() {
68         let mut cfg = cc::Build::new();
69         cfg.cargo_metadata(false).opt_level(2).warnings(false).debug(false)
70            .target(&target).host(&build.build);
71         match build.crt_static(target) {
72             Some(a) => { cfg.static_crt(a); }
73             None => {
74                 if target.contains("msvc") {
75                     cfg.static_crt(true);
76                 }
77                 if target.contains("musl") {
78                     cfg.static_flag(true);
79                 }
80             }
81         }
82
83         let config = build.config.target_config.get(&target);
84         if let Some(cc) = config.and_then(|c| c.cc.as_ref()) {
85             cfg.compiler(cc);
86         } else {
87             set_compiler(&mut cfg, Language::C, target, config, build);
88         }
89
90         let compiler = cfg.get_compiler();
91         let ar = if let ar @ Some(..) = config.and_then(|c| c.ar.clone()) {
92             ar
93         } else {
94             cc2ar(compiler.path(), &target)
95         };
96
97         build.cc.insert(target, compiler);
98         build.verbose(&format!("CC_{} = {:?}", &target, build.cc(target)));
99         build.verbose(&format!("CFLAGS_{} = {:?}", &target, build.cflags(target, GitRepo::Rustc)));
100         if let Some(ar) = ar {
101             build.verbose(&format!("AR_{} = {:?}", &target, ar));
102             build.ar.insert(target, ar);
103         }
104     }
105
106     // For all host triples we need to find a C++ compiler as well
107     let hosts = build.hosts.iter().cloned().chain(iter::once(build.build)).collect::<HashSet<_>>();
108     for host in hosts.into_iter() {
109         let mut cfg = cc::Build::new();
110         cfg.cargo_metadata(false).opt_level(2).warnings(false).debug(false).cpp(true)
111            .target(&host).host(&build.build);
112         let config = build.config.target_config.get(&host);
113         if let Some(cxx) = config.and_then(|c| c.cxx.as_ref()) {
114             cfg.compiler(cxx);
115         } else {
116             set_compiler(&mut cfg, Language::CPlusPlus, host, config, build);
117         }
118         let compiler = cfg.get_compiler();
119         build.verbose(&format!("CXX_{} = {:?}", host, compiler.path()));
120         build.cxx.insert(host, compiler);
121     }
122 }
123
124 fn set_compiler(cfg: &mut cc::Build,
125                 compiler: Language,
126                 target: Interned<String>,
127                 config: Option<&Target>,
128                 build: &Build) {
129     match &*target {
130         // When compiling for android we may have the NDK configured in the
131         // config.toml in which case we look there. Otherwise the default
132         // compiler already takes into account the triple in question.
133         t if t.contains("android") => {
134             if let Some(ndk) = config.and_then(|c| c.ndk.as_ref()) {
135                 let target = target.replace("armv7neon", "arm")
136                                    .replace("armv7", "arm")
137                                    .replace("thumbv7neon", "arm")
138                                    .replace("thumbv7", "arm");
139                 let compiler = format!("{}-{}", target, compiler.clang());
140                 cfg.compiler(ndk.join("bin").join(compiler));
141             }
142         }
143
144         // The default gcc version from OpenBSD may be too old, try using egcc,
145         // which is a gcc version from ports, if this is the case.
146         t if t.contains("openbsd") => {
147             let c = cfg.get_compiler();
148             let gnu_compiler = compiler.gcc();
149             if !c.path().ends_with(gnu_compiler) {
150                 return
151             }
152
153             let output = output(c.to_command().arg("--version"));
154             let i = match output.find(" 4.") {
155                 Some(i) => i,
156                 None => return,
157             };
158             match output[i + 3..].chars().next().unwrap() {
159                 '0' ..= '6' => {}
160                 _ => return,
161             }
162             let alternative = format!("e{}", gnu_compiler);
163             if Command::new(&alternative).output().is_ok() {
164                 cfg.compiler(alternative);
165             }
166         }
167
168         "mips-unknown-linux-musl" => {
169             if cfg.get_compiler().path().to_str() == Some("gcc") {
170                 cfg.compiler("mips-linux-musl-gcc");
171             }
172         }
173         "mipsel-unknown-linux-musl" => {
174             if cfg.get_compiler().path().to_str() == Some("gcc") {
175                 cfg.compiler("mipsel-linux-musl-gcc");
176             }
177         }
178
179         t if t.contains("musl") => {
180             if let Some(root) = build.musl_root(target) {
181                 let guess = root.join("bin/musl-gcc");
182                 if guess.exists() {
183                     cfg.compiler(guess);
184                 }
185             }
186         }
187
188         _ => {}
189     }
190 }
191
192 /// The target programming language for a native compiler.
193 enum Language {
194     /// The compiler is targeting C.
195     C,
196     /// The compiler is targeting C++.
197     CPlusPlus,
198 }
199
200 impl Language {
201     /// Obtains the name of a compiler in the GCC collection.
202     fn gcc(self) -> &'static str {
203         match self {
204             Language::C => "gcc",
205             Language::CPlusPlus => "g++",
206         }
207     }
208
209     /// Obtains the name of a compiler in the clang suite.
210     fn clang(self) -> &'static str {
211         match self {
212             Language::C => "clang",
213             Language::CPlusPlus => "clang++",
214         }
215     }
216 }