]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/cc_detect.rs
Simplify Cache wrapper to single type, impl Deref on it, fix all compilation errors...
[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 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.targets.iter().chain(&build.hosts).cloned().chain(iter::once(build.build))
68                                .collect::<HashSet<_>>();
69     for target in targets.into_iter() {
70         let mut cfg = cc::Build::new();
71         cfg.cargo_metadata(false).opt_level(2).warnings(false).debug(false)
72            .target(&target).host(&build.build);
73         match build.crt_static(target) {
74             Some(a) => { cfg.static_crt(a); }
75             None => {
76                 if target.contains("msvc") {
77                     cfg.static_crt(true);
78                 }
79                 if target.contains("musl") {
80                     cfg.static_flag(true);
81                 }
82             }
83         }
84
85         let config = build.config.target_config.get(&target);
86         if let Some(cc) = config.and_then(|c| c.cc.as_ref()) {
87             cfg.compiler(cc);
88         } else {
89             set_compiler(&mut cfg, Language::C, target, config, build);
90         }
91
92         let compiler = cfg.get_compiler();
93         let ar = if let ar @ Some(..) = config.and_then(|c| c.ar.clone()) {
94             ar
95         } else {
96             cc2ar(compiler.path(), &target)
97         };
98
99         build.cc.insert(target, compiler);
100         let cflags = build.cflags(target, GitRepo::Rustc);
101
102         // If we use llvm-libunwind, we will need a C++ compiler as well for all targets
103         // We'll need one anyways if the target triple is also a host triple
104         let mut cfg = cc::Build::new();
105         cfg.cargo_metadata(false).opt_level(2).warnings(false).debug(false).cpp(true)
106             .target(&target).host(&build.build);
107
108         let cxx_configured = if let Some(cxx) = config.and_then(|c| c.cxx.as_ref()) {
109             cfg.compiler(cxx);
110             true
111         } else if build.hosts.contains(&target) || build.build == target {
112             set_compiler(&mut cfg, Language::CPlusPlus, target, config, build);
113             true
114         } else {
115             false
116         };
117
118         if cxx_configured {
119             let compiler = cfg.get_compiler();
120             build.cxx.insert(target, compiler);
121         }
122
123         build.verbose(&format!("CC_{} = {:?}", &target, build.cc(target)));
124         build.verbose(&format!("CFLAGS_{} = {:?}", &target, cflags));
125         if let Ok(cxx) = build.cxx(target) {
126             build.verbose(&format!("CXX_{} = {:?}", &target, cxx));
127             build.verbose(&format!("CXXFLAGS_{} = {:?}", &target, cflags));
128         }
129         if let Some(ar) = ar {
130             build.verbose(&format!("AR_{} = {:?}", &target, ar));
131             build.ar.insert(target, ar);
132         }
133     }
134 }
135
136 fn set_compiler(cfg: &mut cc::Build,
137                 compiler: Language,
138                 target: Interned<String>,
139                 config: Option<&Target>,
140                 build: &Build) {
141     match &*target {
142         // When compiling for android we may have the NDK configured in the
143         // config.toml in which case we look there. Otherwise the default
144         // compiler already takes into account the triple in question.
145         t if t.contains("android") => {
146             if let Some(ndk) = config.and_then(|c| c.ndk.as_ref()) {
147                 let target = target.replace("armv7neon", "arm")
148                                    .replace("armv7", "arm")
149                                    .replace("thumbv7neon", "arm")
150                                    .replace("thumbv7", "arm");
151                 let compiler = format!("{}-{}", target, compiler.clang());
152                 cfg.compiler(ndk.join("bin").join(compiler));
153             }
154         }
155
156         // The default gcc version from OpenBSD may be too old, try using egcc,
157         // which is a gcc version from ports, if this is the case.
158         t if t.contains("openbsd") => {
159             let c = cfg.get_compiler();
160             let gnu_compiler = compiler.gcc();
161             if !c.path().ends_with(gnu_compiler) {
162                 return
163             }
164
165             let output = output(c.to_command().arg("--version"));
166             let i = match output.find(" 4.") {
167                 Some(i) => i,
168                 None => return,
169             };
170             match output[i + 3..].chars().next().unwrap() {
171                 '0' ..= '6' => {}
172                 _ => return,
173             }
174             let alternative = format!("e{}", gnu_compiler);
175             if Command::new(&alternative).output().is_ok() {
176                 cfg.compiler(alternative);
177             }
178         }
179
180         "mips-unknown-linux-musl" => {
181             if cfg.get_compiler().path().to_str() == Some("gcc") {
182                 cfg.compiler("mips-linux-musl-gcc");
183             }
184         }
185         "mipsel-unknown-linux-musl" => {
186             if cfg.get_compiler().path().to_str() == Some("gcc") {
187                 cfg.compiler("mipsel-linux-musl-gcc");
188             }
189         }
190
191         t if t.contains("musl") => {
192             if let Some(root) = build.musl_root(target) {
193                 let guess = root.join("bin/musl-gcc");
194                 if guess.exists() {
195                     cfg.compiler(guess);
196                 }
197             }
198         }
199
200         _ => {}
201     }
202 }
203
204 /// The target programming language for a native compiler.
205 enum Language {
206     /// The compiler is targeting C.
207     C,
208     /// The compiler is targeting C++.
209     CPlusPlus,
210 }
211
212 impl Language {
213     /// Obtains the name of a compiler in the GCC collection.
214     fn gcc(self) -> &'static str {
215         match self {
216             Language::C => "gcc",
217             Language::CPlusPlus => "g++",
218         }
219     }
220
221     /// Obtains the name of a compiler in the clang suite.
222     fn clang(self) -> &'static str {
223         match self {
224             Language::C => "clang",
225             Language::CPlusPlus => "clang++",
226         }
227     }
228 }