cc_detect.rs 8.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//! C-compiler probing and detection.
//!
//! This module will fill out the `cc` and `cxx` maps of `Build` by looking for
//! C and C++ compilers for each target configured. A compiler is found through
//! a number of vectors (in order of precedence)
//!
//! 1. Configuration via `target.$target.cc` in `config.toml`.
//! 2. Configuration via `target.$target.android-ndk` in `config.toml`, if
//!    applicable
//! 3. Special logic to probe on OpenBSD
//! 4. The `CC_$target` environment variable.
//! 5. The `CC` environment variable.
//! 6. "cc"
//!
//! Some of this logic is implemented here, but much of it is farmed out to the
A
Alex Crichton 已提交
16
//! `cc` crate itself, so we end up having the same fallbacks as there.
17 18 19 20 21 22 23
//! Similar logic is then used to find a C++ compiler, just some s/cc/c++/ is
//! used.
//!
//! It is intended that after this module has run no C/C++ compiler will
//! ever be probed for. Instead the compilers found here will be used for
//! everything.

24 25
use std::collections::HashSet;
use std::path::{Path, PathBuf};
A
Alex Crichton 已提交
26
use std::process::Command;
M
Mark Rousskov 已提交
27
use std::{env, iter};
A
Alex Crichton 已提交
28

29
use build_helper::output;
A
Alex Crichton 已提交
30

31
use crate::config::{Target, TargetSelection};
32
use crate::{Build, CLang, GitRepo};
A
Alex Crichton 已提交
33

34 35 36 37
// The `cc` crate doesn't provide a way to obtain a path to the detected archiver,
// so use some simplified logic here. First we respect the environment variable `AR`, then
// try to infer the archiver path from the C compiler path.
// In the future this logic should be replaced by calling into the `cc` crate.
38 39
fn cc2ar(cc: &Path, target: TargetSelection) -> Option<PathBuf> {
    if let Some(ar) = env::var_os(format!("AR_{}", target.triple.replace("-", "_"))) {
40 41
        Some(PathBuf::from(ar))
    } else if let Some(ar) = env::var_os("AR") {
42 43 44 45 46 47 48
        Some(PathBuf::from(ar))
    } else if target.contains("msvc") {
        None
    } else if target.contains("musl") {
        Some(PathBuf::from("ar"))
    } else if target.contains("openbsd") {
        Some(PathBuf::from("ar"))
B
Baoshan Pang 已提交
49
    } else if target.contains("vxworks") {
B
Baoshan Pang 已提交
50
        Some(PathBuf::from("wr-ar"))
51 52 53 54 55 56 57 58 59 60 61 62 63 64
    } else {
        let parent = cc.parent().unwrap();
        let file = cc.file_name().unwrap().to_str().unwrap();
        for suffix in &["gcc", "cc", "clang"] {
            if let Some(idx) = file.rfind(suffix) {
                let mut file = file[..idx].to_owned();
                file.push_str("ar");
                return Some(parent.join(&file));
            }
        }
        Some(parent.join(file))
    }
}

A
Alex Crichton 已提交
65 66 67
pub fn find(build: &mut Build) {
    // For all targets we're going to need a C compiler for building some shims
    // and such as well as for being a linker for Rust code.
M
Mark Rousskov 已提交
68 69 70 71 72 73 74
    let targets = build
        .targets
        .iter()
        .chain(&build.hosts)
        .cloned()
        .chain(iter::once(build.build))
        .collect::<HashSet<_>>();
75
    for target in targets.into_iter() {
A
Alex Crichton 已提交
76
        let mut cfg = cc::Build::new();
M
Mark Rousskov 已提交
77 78 79 80
        cfg.cargo_metadata(false)
            .opt_level(2)
            .warnings(false)
            .debug(false)
81 82
            .target(&target.triple)
            .host(&build.build.triple);
A
Alex Crichton 已提交
83
        match build.crt_static(target) {
M
Mark Rousskov 已提交
84 85 86
            Some(a) => {
                cfg.static_crt(a);
            }
A
Alex Crichton 已提交
87 88 89 90 91 92 93 94
            None => {
                if target.contains("msvc") {
                    cfg.static_crt(true);
                }
                if target.contains("musl") {
                    cfg.static_flag(true);
                }
            }
95
        }
A
Alex Crichton 已提交
96

97
        let config = build.config.target_config.get(&target);
A
Alex Crichton 已提交
98 99 100
        if let Some(cc) = config.and_then(|c| c.cc.as_ref()) {
            cfg.compiler(cc);
        } else {
101
            set_compiler(&mut cfg, Language::C, target, config, build);
A
Alex Crichton 已提交
102 103 104
        }

        let compiler = cfg.get_compiler();
105 106 107
        let ar = if let ar @ Some(..) = config.and_then(|c| c.ar.clone()) {
            ar
        } else {
108
            cc2ar(compiler.path(), target)
109 110
        };

111
        build.cc.insert(target, compiler.clone());
112
        let cflags = build.cflags(target, GitRepo::Rustc, CLang::C);
A
Alex Crichton 已提交
113

114 115
        // If we use llvm-libunwind, we will need a C++ compiler as well for all targets
        // We'll need one anyways if the target triple is also a host triple
116
        let mut cfg = cc::Build::new();
M
Mark Rousskov 已提交
117 118 119 120 121
        cfg.cargo_metadata(false)
            .opt_level(2)
            .warnings(false)
            .debug(false)
            .cpp(true)
122 123
            .target(&target.triple)
            .host(&build.build.triple);
124 125

        let cxx_configured = if let Some(cxx) = config.and_then(|c| c.cxx.as_ref()) {
A
Alex Crichton 已提交
126
            cfg.compiler(cxx);
127
            true
128
        } else if build.hosts.contains(&target) || build.build == target {
129 130
            set_compiler(&mut cfg, Language::CPlusPlus, target, config, build);
            true
A
Alex Crichton 已提交
131
        } else {
132 133
            // Use an auto-detected compiler (or one configured via `CXX_target_triple` env vars).
            cfg.try_get_compiler().is_ok()
134 135
        };

P
Pang, Baoshan 已提交
136 137
        // for VxWorks, record CXX compiler which will be used in lib.rs:linker()
        if cxx_configured || target.contains("vxworks") {
138 139
            let compiler = cfg.get_compiler();
            build.cxx.insert(target, compiler);
A
Alex Crichton 已提交
140
        }
141

142 143
        build.verbose(&format!("CC_{} = {:?}", &target.triple, build.cc(target)));
        build.verbose(&format!("CFLAGS_{} = {:?}", &target.triple, cflags));
144
        if let Ok(cxx) = build.cxx(target) {
145
            let cxxflags = build.cflags(target, GitRepo::Rustc, CLang::Cxx);
146
            build.verbose(&format!("CXX_{} = {:?}", &target.triple, cxx));
147
            build.verbose(&format!("CXXFLAGS_{} = {:?}", &target.triple, cxxflags));
148
        }
149
        if let Some(ar) = ar {
150
            build.verbose(&format!("AR_{} = {:?}", &target.triple, ar));
151 152
            build.ar.insert(target, ar);
        }
A
Alex Crichton 已提交
153 154 155
    }
}

M
Mark Rousskov 已提交
156 157 158
fn set_compiler(
    cfg: &mut cc::Build,
    compiler: Language,
159
    target: TargetSelection,
M
Mark Rousskov 已提交
160 161 162
    config: Option<&Target>,
    build: &Build,
) {
163
    match &*target.triple {
A
Alex Crichton 已提交
164 165 166 167 168
        // When compiling for android we may have the NDK configured in the
        // config.toml in which case we look there. Otherwise the default
        // compiler already takes into account the triple in question.
        t if t.contains("android") => {
            if let Some(ndk) = config.and_then(|c| c.ndk.as_ref()) {
M
Mark Rousskov 已提交
169
                let target = target
170
                    .triple
M
Mark Rousskov 已提交
171 172 173 174
                    .replace("armv7neon", "arm")
                    .replace("armv7", "arm")
                    .replace("thumbv7neon", "arm")
                    .replace("thumbv7", "arm");
175
                let compiler = format!("{}-{}", target, compiler.clang());
A
Alex Crichton 已提交
176 177 178 179 180 181 182 183
                cfg.compiler(ndk.join("bin").join(compiler));
            }
        }

        // The default gcc version from OpenBSD may be too old, try using egcc,
        // which is a gcc version from ports, if this is the case.
        t if t.contains("openbsd") => {
            let c = cfg.get_compiler();
184
            let gnu_compiler = compiler.gcc();
A
Alex Crichton 已提交
185
            if !c.path().ends_with(gnu_compiler) {
M
Mark Rousskov 已提交
186
                return;
A
Alex Crichton 已提交
187 188 189 190 191
            }

            let output = output(c.to_command().arg("--version"));
            let i = match output.find(" 4.") {
                Some(i) => i,
192
                None => return,
A
Alex Crichton 已提交
193 194
            };
            match output[i + 3..].chars().next().unwrap() {
M
Mark Rousskov 已提交
195
                '0'..='6' => {}
196
                _ => return,
A
Alex Crichton 已提交
197 198 199 200 201 202 203
            }
            let alternative = format!("e{}", gnu_compiler);
            if Command::new(&alternative).output().is_ok() {
                cfg.compiler(alternative);
            }
        }

204
        "mips-unknown-linux-musl" => {
205 206 207
            if cfg.get_compiler().path().to_str() == Some("gcc") {
                cfg.compiler("mips-linux-musl-gcc");
            }
208 209
        }
        "mipsel-unknown-linux-musl" => {
210 211 212
            if cfg.get_compiler().path().to_str() == Some("gcc") {
                cfg.compiler("mipsel-linux-musl-gcc");
            }
213 214 215 216 217 218 219 220 221 222 223
        }

        t if t.contains("musl") => {
            if let Some(root) = build.musl_root(target) {
                let guess = root.join("bin/musl-gcc");
                if guess.exists() {
                    cfg.compiler(guess);
                }
            }
        }

A
Alex Crichton 已提交
224 225 226
        _ => {}
    }
}
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

/// The target programming language for a native compiler.
enum Language {
    /// The compiler is targeting C.
    C,
    /// The compiler is targeting C++.
    CPlusPlus,
}

impl Language {
    /// Obtains the name of a compiler in the GCC collection.
    fn gcc(self) -> &'static str {
        match self {
            Language::C => "gcc",
            Language::CPlusPlus => "g++",
        }
    }

    /// Obtains the name of a compiler in the clang suite.
    fn clang(self) -> &'static str {
        match self {
            Language::C => "clang",
            Language::CPlusPlus => "clang++",
        }
    }
}