Skip to main content

cargo/util/
rustc.rs

1#![allow(deprecated)] // for SipHasher
2
3use std::collections::hash_map::{Entry, HashMap};
4use std::env;
5use std::hash::{Hash, Hasher, SipHasher};
6use std::path::{Path, PathBuf};
7use std::process::Stdio;
8use std::sync::Mutex;
9
10use log::{debug, info, warn};
11use serde::{Deserialize, Serialize};
12
13use crate::util::paths;
14use crate::util::{self, internal, profile, CargoResult, ProcessBuilder};
15
16/// Information on the `rustc` executable
17#[derive(Debug)]
18pub struct Rustc {
19    /// The location of the exe
20    pub path: PathBuf,
21    /// An optional program that will be passed the path of the rust exe as its first argument, and
22    /// rustc args following this.
23    pub wrapper: Option<PathBuf>,
24    /// Verbose version information (the output of `rustc -vV`)
25    pub verbose_version: String,
26    /// The host triple (arch-platform-OS), this comes from verbose_version.
27    pub host: String,
28    cache: Mutex<Cache>,
29}
30
31impl Rustc {
32    /// Run the compiler at `path` to learn various pieces of information about
33    /// it, with an optional wrapper.
34    ///
35    /// If successful this function returns a description of the compiler along
36    /// with a list of its capabilities.
37    pub fn new(
38        path: PathBuf,
39        wrapper: Option<PathBuf>,
40        rustup_rustc: &Path,
41        cache_location: Option<PathBuf>,
42    ) -> CargoResult<Rustc> {
43        let _p = profile::start("Rustc::new");
44
45        let mut cache = Cache::load(&path, rustup_rustc, cache_location);
46
47        let mut cmd = util::process(&path);
48        cmd.arg("-vV");
49        let verbose_version = cache.cached_output(&cmd)?.0;
50
51        let host = {
52            let triple = verbose_version
53                .lines()
54                .find(|l| l.starts_with("host: "))
55                .map(|l| &l[6..])
56                .ok_or_else(|| internal("rustc -v didn't have a line for `host:`"))?;
57            triple.to_string()
58        };
59
60        Ok(Rustc {
61            path,
62            wrapper,
63            verbose_version,
64            host,
65            cache: Mutex::new(cache),
66        })
67    }
68
69    /// Get a process builder set up to use the found rustc version, with a wrapper if Some
70    pub fn process(&self) -> ProcessBuilder {
71        match self.wrapper {
72            Some(ref wrapper) if !wrapper.as_os_str().is_empty() => {
73                let mut cmd = util::process(wrapper);
74                cmd.arg(&self.path);
75                cmd
76            }
77            _ => self.process_no_wrapper(),
78        }
79    }
80
81    pub fn process_no_wrapper(&self) -> ProcessBuilder {
82        util::process(&self.path)
83    }
84
85    pub fn cached_output(&self, cmd: &ProcessBuilder) -> CargoResult<(String, String)> {
86        self.cache.lock().unwrap().cached_output(cmd)
87    }
88
89    pub fn cached_success(&self, cmd: &ProcessBuilder) -> CargoResult<bool> {
90        self.cache.lock().unwrap().cached_success(cmd)
91    }
92}
93
94/// It is a well known that `rustc` is not the fastest compiler in the world.
95/// What is less known is that even `rustc --version --verbose` takes about a
96/// hundred milliseconds! Because we need compiler version info even for no-op
97/// builds, we cache it here, based on compiler's mtime and rustup's current
98/// toolchain.
99///
100/// https://github.com/rust-lang/cargo/issues/5315
101/// https://github.com/rust-lang/rust/issues/49761
102#[derive(Debug)]
103struct Cache {
104    cache_location: Option<PathBuf>,
105    dirty: bool,
106    data: CacheData,
107}
108
109#[derive(Serialize, Deserialize, Debug, Default)]
110struct CacheData {
111    rustc_fingerprint: u64,
112    outputs: HashMap<u64, (String, String)>,
113    successes: HashMap<u64, bool>,
114}
115
116impl Cache {
117    fn load(rustc: &Path, rustup_rustc: &Path, cache_location: Option<PathBuf>) -> Cache {
118        match (cache_location, rustc_fingerprint(rustc, rustup_rustc)) {
119            (Some(cache_location), Ok(rustc_fingerprint)) => {
120                let empty = CacheData {
121                    rustc_fingerprint,
122                    outputs: HashMap::new(),
123                    successes: HashMap::new(),
124                };
125                let mut dirty = true;
126                let data = match read(&cache_location) {
127                    Ok(data) => {
128                        if data.rustc_fingerprint == rustc_fingerprint {
129                            info!("reusing existing rustc info cache");
130                            dirty = false;
131                            data
132                        } else {
133                            info!("different compiler, creating new rustc info cache");
134                            empty
135                        }
136                    }
137                    Err(e) => {
138                        info!("failed to read rustc info cache: {}", e);
139                        empty
140                    }
141                };
142                return Cache {
143                    cache_location: Some(cache_location),
144                    dirty,
145                    data,
146                };
147
148                fn read(path: &Path) -> CargoResult<CacheData> {
149                    let json = paths::read(path)?;
150                    Ok(serde_json::from_str(&json)?)
151                }
152            }
153            (_, fingerprint) => {
154                if let Err(e) = fingerprint {
155                    warn!("failed to calculate rustc fingerprint: {}", e);
156                }
157                info!("rustc info cache disabled");
158                Cache {
159                    cache_location: None,
160                    dirty: false,
161                    data: CacheData::default(),
162                }
163            }
164        }
165    }
166
167    fn cached_output(&mut self, cmd: &ProcessBuilder) -> CargoResult<(String, String)> {
168        let key = process_fingerprint(cmd);
169        match self.data.outputs.entry(key) {
170            Entry::Occupied(entry) => {
171                info!("rustc info cache hit");
172                Ok(entry.get().clone())
173            }
174            Entry::Vacant(entry) => {
175                info!("rustc info cache miss");
176                let output = cmd.exec_with_output()?;
177                let stdout = String::from_utf8(output.stdout)
178                    .map_err(|_| internal("rustc didn't return utf8 output"))?;
179                let stderr = String::from_utf8(output.stderr)
180                    .map_err(|_| internal("rustc didn't return utf8 output"))?;
181                let output = (stdout, stderr);
182                entry.insert(output.clone());
183                self.dirty = true;
184                Ok(output)
185            }
186        }
187    }
188
189    fn cached_success(&mut self, cmd: &ProcessBuilder) -> CargoResult<bool> {
190        let key = process_fingerprint(cmd);
191        match self.data.successes.entry(key) {
192            Entry::Occupied(entry) => {
193                info!("rustc info cache hit");
194                Ok(*entry.get())
195            }
196            Entry::Vacant(entry) => {
197                info!("rustc info cache miss");
198                let success = cmd
199                    .build_command()
200                    .stdout(Stdio::null())
201                    .stderr(Stdio::null())
202                    .status()?
203                    .success();
204                entry.insert(success);
205                self.dirty = true;
206                Ok(success)
207            }
208        }
209    }
210}
211
212impl Drop for Cache {
213    fn drop(&mut self) {
214        if !self.dirty {
215            return;
216        }
217        if let Some(ref path) = self.cache_location {
218            let json = serde_json::to_string(&self.data).unwrap();
219            match paths::write(path, json.as_bytes()) {
220                Ok(()) => info!("updated rustc info cache"),
221                Err(e) => warn!("failed to update rustc info cache: {}", e),
222            }
223        }
224    }
225}
226
227fn rustc_fingerprint(path: &Path, rustup_rustc: &Path) -> CargoResult<u64> {
228    let mut hasher = SipHasher::new_with_keys(0, 0);
229
230    let path = paths::resolve_executable(path)?;
231    path.hash(&mut hasher);
232
233    paths::mtime(&path)?.hash(&mut hasher);
234
235    // Rustup can change the effective compiler without touching
236    // the `rustc` binary, so we try to account for this here.
237    // If we see rustup's env vars, we mix them into the fingerprint,
238    // but we also mix in the mtime of the actual compiler (and not
239    // the rustup shim at `~/.cargo/bin/rustup`), because `RUSTUP_TOOLCHAIN`
240    // could be just `stable-x86_64-unknown-linux-gnu`, i.e, it could
241    // not mention the version of Rust at all, which changes after
242    // `rustup update`.
243    //
244    // If we don't see rustup env vars, but it looks like the compiler
245    // is managed by rustup, we conservatively bail out.
246    let maybe_rustup = rustup_rustc == path;
247    match (
248        maybe_rustup,
249        env::var("RUSTUP_HOME"),
250        env::var("RUSTUP_TOOLCHAIN"),
251    ) {
252        (_, Ok(rustup_home), Ok(rustup_toolchain)) => {
253            debug!("adding rustup info to rustc fingerprint");
254            rustup_toolchain.hash(&mut hasher);
255            rustup_home.hash(&mut hasher);
256            let real_rustc = Path::new(&rustup_home)
257                .join("toolchains")
258                .join(rustup_toolchain)
259                .join("bin")
260                .join("rustc")
261                .with_extension(env::consts::EXE_EXTENSION);
262            paths::mtime(&real_rustc)?.hash(&mut hasher);
263        }
264        (true, _, _) => failure::bail!("probably rustup rustc, but without rustup's env vars"),
265        _ => (),
266    }
267
268    Ok(hasher.finish())
269}
270
271fn process_fingerprint(cmd: &ProcessBuilder) -> u64 {
272    let mut hasher = SipHasher::new_with_keys(0, 0);
273    cmd.get_args().hash(&mut hasher);
274    let mut env = cmd.get_envs().iter().collect::<Vec<_>>();
275    env.sort_unstable();
276    env.hash(&mut hasher);
277    hasher.finish()
278}