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