bootstrap/utils/
cc_detect.rs1use std::collections::HashSet;
25use std::iter;
26use std::path::{Path, PathBuf};
27
28use crate::core::config::{CompressDebuginfo, Subcommand, TargetSelection};
29use crate::utils::exec::{BootstrapCommand, command};
30use crate::{Build, CLang, GitRepo};
31
32fn new_cc_build(build: &Build, 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(build.tempdir().join("cc-rs-out-dir"))
41 .target(&target.triple)
42 .host(&build.host_target.triple);
43
44 match build.config.compress_debuginfo(target) {
45 CompressDebuginfo::Zlib => {
46 cfg.flag_if_supported("-gz");
47 }
48 CompressDebuginfo::Off => {}
49 }
50
51 match build.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 fn fill_compilers(build: &mut Build) {
71 let mut targets: HashSet<_> = match build.config.cmd {
72 Subcommand::Clean { .. }
74 | Subcommand::Check { .. }
75 | Subcommand::Format { .. }
76 | Subcommand::Setup { .. } => {
77 build.hosts.iter().cloned().chain(iter::once(build.host_target)).collect()
78 }
79
80 _ => {
81 build
84 .targets
85 .iter()
86 .chain(&build.hosts)
87 .cloned()
88 .chain(iter::once(build.host_target))
89 .collect()
90 }
91 };
92
93 if build.config.wasm_proc_macros {
97 targets.insert(TargetSelection::from_user("wasm32-wasip2"));
98 }
99
100 for target in targets {
101 fill_target_compiler(build, target);
102 }
103}
104
105pub fn fill_target_compiler(build: &mut Build, target: TargetSelection) {
111 let mut cfg = new_cc_build(build, target);
112 let config = build.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, build))
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 build.cc.insert(target, compiler.clone());
126 let mut cflags = build.cc_handled_cflags(target, CLang::C);
127 cflags.extend(build.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::C));
128
129 let mut cfg = new_cc_build(build, 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, build))
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 build.cxx.insert(target, compiler);
148 }
149
150 build.do_if_verbose(|| println!("CC_{} = {:?}", target.triple, build.cc(target)));
151 build.do_if_verbose(|| println!("CFLAGS_{} = {cflags:?}", target.triple));
152 if let Ok(cxx) = build.cxx(target) {
153 let mut cxxflags = build.cc_handled_cflags(target, CLang::Cxx);
154 cxxflags.extend(build.cc_unhandled_cflags(target, GitRepo::Rustc, CLang::Cxx));
155 build.do_if_verbose(|| println!("CXX_{} = {cxx:?}", target.triple));
156 build.do_if_verbose(|| println!("CXXFLAGS_{} = {cxxflags:?}", target.triple));
157 }
158 if let Some(ar) = ar {
159 build.do_if_verbose(|| println!("AR_{} = {ar:?}", target.triple));
160 build.ar.insert(target, ar);
161 }
162
163 if let Some(ranlib) = config.and_then(|c| c.ranlib.clone()) {
164 build.ranlib.insert(target, ranlib);
165 }
166}
167
168fn default_compiler(
171 cfg: &cc::Build,
172 compiler: Language,
173 target: TargetSelection,
174 build: &Build,
175) -> Option<PathBuf> {
176 match &*target.triple {
177 t if t.contains("android") => {
181 build.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(build).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(build).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) = build.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) = build.wasi_sdk_path.as_ref() {
234 path
235 } else {
236 if build.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;