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