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