Skip to main content

cargo/core/compiler/build_context/
target_info.rs

1use std::cell::RefCell;
2use std::collections::hash_map::{Entry, HashMap};
3use std::path::PathBuf;
4use std::str::{self, FromStr};
5
6use super::env_args;
7use super::Kind;
8use crate::core::TargetKind;
9use crate::util::{CargoResult, CargoResultExt, Cfg, Config, ProcessBuilder, Rustc};
10
11#[derive(Clone)]
12pub struct TargetInfo {
13    crate_type_process: Option<ProcessBuilder>,
14    crate_types: RefCell<HashMap<String, Option<(String, String)>>>,
15    cfg: Option<Vec<Cfg>>,
16    pub sysroot_libdir: Option<PathBuf>,
17}
18
19/// Type of each file generated by a Unit.
20#[derive(Copy, Clone, PartialEq, Eq, Debug)]
21pub enum FileFlavor {
22    /// Not a special file type.
23    Normal,
24    /// It is something you can link against (e.g. a library)
25    Linkable,
26    /// It is a piece of external debug information (e.g. *.dSYM and *.pdb)
27    DebugInfo,
28}
29
30pub struct FileType {
31    pub flavor: FileFlavor,
32    suffix: String,
33    prefix: String,
34    // wasm bin target will generate two files in deps such as
35    // "web-stuff.js" and "web_stuff.wasm". Note the different usages of
36    // "-" and "_". should_replace_hyphens is a flag to indicate that
37    // we need to convert the stem "web-stuff" to "web_stuff", so we
38    // won't miss "web_stuff.wasm".
39    should_replace_hyphens: bool,
40}
41
42impl FileType {
43    pub fn filename(&self, stem: &str) -> String {
44        let stem = if self.should_replace_hyphens {
45            stem.replace("-", "_")
46        } else {
47            stem.to_string()
48        };
49        format!("{}{}{}", self.prefix, stem, self.suffix)
50    }
51}
52
53impl TargetInfo {
54    pub fn new(
55        config: &Config,
56        requested_target: &Option<String>,
57        rustc: &Rustc,
58        kind: Kind,
59    ) -> CargoResult<TargetInfo> {
60        let rustflags = env_args(
61            config,
62            requested_target,
63            &rustc.host,
64            None,
65            kind,
66            "RUSTFLAGS",
67        )?;
68        let mut process = rustc.process();
69        process
70            .arg("-")
71            .arg("--crate-name")
72            .arg("___")
73            .arg("--print=file-names")
74            .args(&rustflags)
75            .env_remove("RUST_LOG");
76
77        let target_triple = requested_target
78            .as_ref()
79            .map(|s| s.as_str())
80            .unwrap_or(&rustc.host);
81        if kind == Kind::Target {
82            process.arg("--target").arg(target_triple);
83        }
84
85        let crate_type_process = process.clone();
86        const KNOWN_CRATE_TYPES: &[&str] =
87            &["bin", "rlib", "dylib", "cdylib", "staticlib", "proc-macro"];
88        for crate_type in KNOWN_CRATE_TYPES.iter() {
89            process.arg("--crate-type").arg(crate_type);
90        }
91
92        let mut with_cfg = process.clone();
93        with_cfg.arg("--print=sysroot");
94        with_cfg.arg("--print=cfg");
95
96        let mut has_cfg_and_sysroot = true;
97        let (output, error) = rustc
98            .cached_output(&with_cfg)
99            .or_else(|_| {
100                has_cfg_and_sysroot = false;
101                rustc.cached_output(&process)
102            })
103            .chain_err(|| "failed to run `rustc` to learn about target-specific information")?;
104
105        let mut lines = output.lines();
106        let mut map = HashMap::new();
107        for crate_type in KNOWN_CRATE_TYPES {
108            let out = parse_crate_type(crate_type, &error, &mut lines)?;
109            map.insert(crate_type.to_string(), out);
110        }
111
112        let mut sysroot_libdir = None;
113        if has_cfg_and_sysroot {
114            let line = match lines.next() {
115                Some(line) => line,
116                None => failure::bail!(
117                    "output of --print=sysroot missing when learning about \
118                     target-specific information from rustc"
119                ),
120            };
121            let mut rustlib = PathBuf::from(line);
122            if kind == Kind::Host {
123                if cfg!(windows) {
124                    rustlib.push("bin");
125                } else {
126                    rustlib.push("lib");
127                }
128                sysroot_libdir = Some(rustlib);
129            } else {
130                rustlib.push("lib");
131                rustlib.push("rustlib");
132                rustlib.push(target_triple);
133                rustlib.push("lib");
134                sysroot_libdir = Some(rustlib);
135            }
136        }
137
138        let cfg = if has_cfg_and_sysroot {
139            Some(lines.map(Cfg::from_str).collect::<CargoResult<_>>()?)
140        } else {
141            None
142        };
143
144        Ok(TargetInfo {
145            crate_type_process: Some(crate_type_process),
146            crate_types: RefCell::new(map),
147            cfg,
148            sysroot_libdir,
149        })
150    }
151
152    pub fn cfg(&self) -> Option<&[Cfg]> {
153        self.cfg.as_ref().map(|v| v.as_ref())
154    }
155
156    pub fn file_types(
157        &self,
158        crate_type: &str,
159        flavor: FileFlavor,
160        kind: &TargetKind,
161        target_triple: &str,
162    ) -> CargoResult<Option<Vec<FileType>>> {
163        let mut crate_types = self.crate_types.borrow_mut();
164        let entry = crate_types.entry(crate_type.to_string());
165        let crate_type_info = match entry {
166            Entry::Occupied(o) => &*o.into_mut(),
167            Entry::Vacant(v) => {
168                let value = self.discover_crate_type(v.key())?;
169                &*v.insert(value)
170            }
171        };
172        let (prefix, suffix) = match *crate_type_info {
173            Some((ref prefix, ref suffix)) => (prefix, suffix),
174            None => return Ok(None),
175        };
176        let mut ret = vec![FileType {
177            suffix: suffix.clone(),
178            prefix: prefix.clone(),
179            flavor,
180            should_replace_hyphens: false,
181        }];
182
183        // rust-lang/cargo#4500
184        if target_triple.ends_with("pc-windows-msvc")
185            && crate_type.ends_with("dylib")
186            && suffix == ".dll"
187        {
188            ret.push(FileType {
189                suffix: ".dll.lib".to_string(),
190                prefix: prefix.clone(),
191                flavor: FileFlavor::Normal,
192                should_replace_hyphens: false,
193            })
194        }
195
196        // rust-lang/cargo#4535
197        if target_triple.starts_with("wasm32-") && crate_type == "bin" && suffix == ".js" {
198            ret.push(FileType {
199                suffix: ".wasm".to_string(),
200                prefix: prefix.clone(),
201                flavor: FileFlavor::Normal,
202                should_replace_hyphens: true,
203            })
204        }
205
206        // rust-lang/cargo#4490, rust-lang/cargo#4960
207        //  - only uplift debuginfo for binaries.
208        //    tests are run directly from target/debug/deps/
209        //    and examples are inside target/debug/examples/ which already have symbols next to them
210        //    so no need to do anything.
211        if *kind == TargetKind::Bin {
212            if target_triple.contains("-apple-") {
213                ret.push(FileType {
214                    suffix: ".dSYM".to_string(),
215                    prefix: prefix.clone(),
216                    flavor: FileFlavor::DebugInfo,
217                    should_replace_hyphens: false,
218                })
219            } else if target_triple.ends_with("-msvc") {
220                ret.push(FileType {
221                    suffix: ".pdb".to_string(),
222                    prefix: prefix.clone(),
223                    flavor: FileFlavor::DebugInfo,
224                    should_replace_hyphens: false,
225                })
226            }
227        }
228
229        Ok(Some(ret))
230    }
231
232    fn discover_crate_type(&self, crate_type: &str) -> CargoResult<Option<(String, String)>> {
233        let mut process = self.crate_type_process.clone().unwrap();
234
235        process.arg("--crate-type").arg(crate_type);
236
237        let output = process.exec_with_output().chain_err(|| {
238            format!(
239                "failed to run `rustc` to learn about \
240                 crate-type {} information",
241                crate_type
242            )
243        })?;
244
245        let error = str::from_utf8(&output.stderr).unwrap();
246        let output = str::from_utf8(&output.stdout).unwrap();
247        Ok(parse_crate_type(crate_type, error, &mut output.lines())?)
248    }
249}
250
251/// Takes rustc output (using specialized command line args), and calculates the file prefix and
252/// suffix for the given crate type, or returns None if the type is not supported. (e.g. for a
253/// rust library like libcargo.rlib, prefix = "lib", suffix = "rlib").
254///
255/// The caller needs to ensure that the lines object is at the correct line for the given crate
256/// type: this is not checked.
257// This function can not handle more than 1 file per type (with wasm32-unknown-emscripten, there
258// are 2 files for bin (.wasm and .js))
259fn parse_crate_type(
260    crate_type: &str,
261    error: &str,
262    lines: &mut str::Lines<'_>,
263) -> CargoResult<Option<(String, String)>> {
264    let not_supported = error.lines().any(|line| {
265        (line.contains("unsupported crate type") || line.contains("unknown crate type"))
266            && line.contains(crate_type)
267    });
268    if not_supported {
269        return Ok(None);
270    }
271    let line = match lines.next() {
272        Some(line) => line,
273        None => failure::bail!(
274            "malformed output when learning about \
275             crate-type {} information",
276            crate_type
277        ),
278    };
279    let mut parts = line.trim().split("___");
280    let prefix = parts.next().unwrap();
281    let suffix = match parts.next() {
282        Some(part) => part,
283        None => failure::bail!(
284            "output of --print=file-names has changed in \
285             the compiler, cannot parse"
286        ),
287    };
288
289    Ok(Some((prefix.to_string(), suffix.to_string())))
290}