bootstrap/utils/
cc_detect.rs1use std::collections::HashSet;
25use std::iter;
26use std::path::{Path, PathBuf};
27
28use crate::core::config::flags::Subcommand;
29use crate::core::config::{CompressDebuginfo, TargetSelection};
30use crate::core::session::{CLang, GitRepo, Session};
31use crate::utils::exec::{BootstrapCommand, command};
32
33fn new_cc_build(sess: &Session, target: TargetSelection) -> cc::Build {
35 let mut cfg = cc::Build::new();
36 cfg.cargo_metadata(false)
37 .opt_level(2)
38 .warnings(false)
39 .debug(false)
40 .out_dir(sess.tempdir().join("cc-rs-out-dir"))
42 .target(&target.triple)
43 .host(&sess.host_target.triple);
44
45 match sess.config.compress_debuginfo(target) {
46 CompressDebuginfo::Zlib => {
47 cfg.flag_if_supported("-gz");
48 }
49 CompressDebuginfo::Off => {}
50 }
51
52 match sess.crt_static(target) {
53 Some(a) => {
54 cfg.static_crt(a);
55 }
56 None => {
57 if target.is_msvc() {
58 cfg.static_crt(true);
59 }
60 }
61 }
62 cfg
63}
64
65pub(crate) fn fill_compilers(sess: &mut Session) {
72 let mut targets: HashSet<_> = match sess.config.cmd {
73 Subcommand::Clean { .. }
75 | Subcommand::Check { .. }
76 | Subcommand::Format { .. }
77 | Subcommand::Setup { .. } => {
78 sess.hosts.iter().cloned().chain(iter::once(sess.host_target)).collect()
79 }
80
81 _ => {
82 sess.targets
85 .iter()
86 .chain(&sess.hosts)
87 .cloned()
88 .chain(iter::once(sess.host_target))
89 .collect()
90 }
91 };
92
93 if sess.config.wasm_proc_macros {
97 targets.insert(TargetSelection::from_user("wasm32-wasip2"));
98 }
99
100 for target in targets {
101 fill_target_compiler(sess, target);
102 }
103}
104
105fn fill_target_compiler(sess: &mut Session, target: TargetSelection) {
111 let mut cfg = new_cc_build(sess, target);
112 let config = sess.config.target_config.get(&target);
113 if let Some(cc) = config
114 .and_then(|c| c.cc.clone())
115 .or_else(|| default_compiler(&cfg, Language::C, target, sess))
116 {
117 cfg.compiler(cc);
118 }
119
120 let compiler = cfg.get_compiler();
121 let ar = config
122 .and_then(|c| c.ar.clone())
123 .or_else(|| cfg.try_get_archiver().map(|c| PathBuf::from(c.get_program())).ok());
124
125 sess.cc.insert(target, compiler.clone());
126 let mut cflags = sess.cc_handled_cflags(target, CLang::C);
127 cflags.extend(sess.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::C));
128
129 let mut cfg = new_cc_build(sess, target);
132 cfg.cpp(true);
133 let cxx_configured = if let Some(cxx) = config
134 .and_then(|c| c.cxx.clone())
135 .or_else(|| default_compiler(&cfg, Language::CPlusPlus, target, sess))
136 {
137 cfg.compiler(cxx);
138 true
139 } else {
140 cfg.try_get_compiler().is_ok()
142 };
143
144 if cxx_configured || target.contains("vxworks") {
146 let compiler = cfg.get_compiler();
147 sess.cxx.insert(target, compiler);
148 }
149
150 sess.do_if_verbose(|| println!("CC_{} = {:?}", target.triple, sess.cc(target)));
151 sess.do_if_verbose(|| println!("CFLAGS_{} = {cflags:?}", target.triple));
152 if let Ok(cxx) = sess.cxx(target) {
153 let mut cxxflags = sess.cc_handled_cflags(target, CLang::Cxx);
154 cxxflags.extend(sess.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::Cxx));
155 sess.do_if_verbose(|| println!("CXX_{} = {cxx:?}", target.triple));
156 sess.do_if_verbose(|| println!("CXXFLAGS_{} = {cxxflags:?}", target.triple));
157 }
158 if let Some(ar) = ar {
159 sess.do_if_verbose(|| println!("AR_{} = {ar:?}", target.triple));
160 sess.ar.insert(target, ar);
161 }
162
163 if let Some(ranlib) = config.and_then(|c| c.ranlib.clone()) {
164 sess.ranlib.insert(target, ranlib);
165 }
166}
167
168fn default_compiler(
171 cfg: &cc::Build,
172 compiler: Language,
173 target: TargetSelection,
174 sess: &Session,
175) -> Option<PathBuf> {
176 match &*target.triple {
177 t if t.contains("android") => {
181 sess.config.android_ndk.as_ref().map(|ndk| ndk_compiler(compiler, &target.triple, ndk))
182 }
183
184 t if t.contains("openbsd") => {
187 let c = cfg.get_compiler();
188 let gnu_compiler = compiler.gcc();
189 if !c.path().ends_with(gnu_compiler) {
190 return None;
191 }
192
193 let mut cmd = BootstrapCommand::from(c.to_command());
194 let output = cmd.arg("--version").run_capture_stdout(sess).stdout();
195 let i = output.find(" 4.")?;
196 match output[i + 3..].chars().next().unwrap() {
197 '0'..='6' => {}
198 _ => return None,
199 }
200 let alternative = format!("e{gnu_compiler}");
201 if command(&alternative).run_capture(sess).is_success() {
202 Some(PathBuf::from(alternative))
203 } else {
204 None
205 }
206 }
207
208 "mips-unknown-linux-musl" if compiler == Language::C => {
209 if cfg.get_compiler().path().to_str() == Some("gcc") {
210 Some(PathBuf::from("mips-linux-musl-gcc"))
211 } else {
212 None
213 }
214 }
215 "mipsel-unknown-linux-musl" if compiler == Language::C => {
216 if cfg.get_compiler().path().to_str() == Some("gcc") {
217 Some(PathBuf::from("mipsel-linux-musl-gcc"))
218 } else {
219 None
220 }
221 }
222
223 t if t.contains("musl") && compiler == Language::C => {
224 if let Some(root) = sess.musl_root(target) {
225 let guess = root.join("bin/musl-gcc");
226 if guess.exists() { Some(guess) } else { None }
227 } else {
228 None
229 }
230 }
231
232 t if t.contains("-wasi") => {
233 let root = if let Some(path) = sess.wasi_sdk_path.as_ref() {
234 path
235 } else {
236 if sess.config.is_running_on_ci() {
237 panic!("ERROR: WASI_SDK_PATH must be configured for a -wasi target on CI");
238 }
239 println!("WARNING: WASI_SDK_PATH not set, using default cc/cxx compiler");
240 return None;
241 };
242 let compiler = match compiler {
243 Language::C => format!("{t}-clang"),
244 Language::CPlusPlus => format!("{t}-clang++"),
245 };
246 let compiler = root.join("bin").join(compiler);
247 Some(compiler)
248 }
249
250 _ => None,
251 }
252}
253
254pub(crate) fn ndk_compiler(compiler: Language, triple: &str, ndk: &Path) -> PathBuf {
261 let mut triple_iter = triple.split('-');
262 let triple_translated = if let Some(arch) = triple_iter.next() {
263 let arch_new = match arch {
264 "arm" | "armv7" | "armv7neon" | "thumbv7" | "thumbv7neon" => "armv7a",
265 other => other,
266 };
267 std::iter::once(arch_new).chain(triple_iter).collect::<Vec<&str>>().join("-")
268 } else {
269 triple.to_string()
270 };
271
272 let api_level = "21";
274 let compiler = format!("{}{}-{}", triple_translated, api_level, compiler.clang());
275 let host_tag = if cfg!(target_os = "macos") {
276 "darwin-x86_64"
278 } else if cfg!(target_os = "windows") {
279 "windows-x86_64"
280 } else {
281 "linux-x86_64"
285 };
286 ndk.join("toolchains").join("llvm").join("prebuilt").join(host_tag).join("bin").join(compiler)
287}
288
289#[derive(PartialEq)]
295pub(crate) enum Language {
296 C,
298 CPlusPlus,
300}
301
302impl Language {
303 fn gcc(self) -> &'static str {
305 match self {
306 Language::C => "gcc",
307 Language::CPlusPlus => "g++",
308 }
309 }
310
311 fn clang(self) -> &'static str {
313 match self {
314 Language::C => "clang",
315 Language::CPlusPlus => "clang++",
316 }
317 }
318}
319
320#[cfg(test)]
321mod tests;